Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ Please make sure you make a backup of your database before updating any version
* Fixed: the user_logged_in property followed the "Authors and categories" option instead of "Logged-in user status".
* Fixed: the user_logged_in value for logged-out visitors is no longer translated.
* Fixed: PHP warning when a Contact Form 7 form outside the loop (e.g. in a widget) is submitted.
* Improved: the proxy's endpoint is no longer listed in the WordPress REST API and only accepts events for your site's domain(s), sent from your site.

= 2.6.4 =
* Improved: the proxy now also forwards the visitor's Accept-Language and User-Agent Client Hints (Sec-CH-UA*) headers to Plausible Analytics, so its bot detection works for proxied requests, too.
Expand Down
190 changes: 187 additions & 3 deletions src/Proxy.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use WP_Error;
use WP_HTTP_Response;
use WP_REST_Request;
use WP_REST_Response;
use WP_REST_Server;

class Proxy {
Expand All @@ -33,6 +34,11 @@ class Proxy {
'HTTP_CLIENT_IP',
];

/**
* Maximum size (in bytes) of an event's body. Leaves room for long URLs and 30 custom properties.
*/
const MAX_BODY_BYTES = 102400;

/**
* API namespace
*
Expand Down Expand Up @@ -87,6 +93,8 @@ private function init( $init ) {
// No need to continue if Proxy isn't enabled .
if ( Helpers::proxy_enabled( $settings ) ) {
add_action( 'rest_api_init', [ $this, 'register_route' ] );
add_filter( 'rest_index', [ $this, 'hide_from_index' ] );
add_filter( 'rest_pre_dispatch', [ $this, 'hide_namespace_index' ], 10, 3 );
}

add_filter( 'rest_post_dispatch', [ $this, 'force_http_response_code' ], null, 3 );
Expand Down Expand Up @@ -257,14 +265,186 @@ public function register_route() {
[
'methods' => 'POST',
'callback' => [ $this, 'send_event' ],
// There's no reason not to allow access to this API.
'permission_callback' => '__return_true',
'permission_callback' => [ $this, 'validate_request' ],
'show_in_index' => false,
],
'schema' => null,
]
);
}

/**
* Removes the proxy's namespace from the REST API index (/wp-json/), so the endpoint can't be discovered there.
*
* @since v2.6.5
*
* @param WP_REST_Response $response
*
* @return WP_REST_Response
*/
public function hide_from_index( $response ) {
$data = $response->get_data();

if ( isset( $data['namespaces'] ) ) {
$data['namespaces'] = array_values( array_diff( $data['namespaces'], [ $this->namespace ] ) );
}

unset( $data['routes'][ '/' . $this->namespace ] );

$response->set_data( $data );

return $response;
}

/**
* Returns a 404 for the index of the proxy's namespace, because it lists the endpoint.
*
* @since v2.6.5
*
* @param mixed $result
* @param WP_REST_Server $server
* @param WP_REST_Request $request
*
* @return mixed
*/
public function hide_namespace_index( $result, $server, $request ) {
if ( strtolower( untrailingslashit( $request->get_route() ) ) !== '/' . $this->namespace ) {
return $result;
}

return $this->no_route_error();
}

/**
* Checks if the request is an event sent by the tracker on this site. All requests rejected here get the same
* response, so it doesn't reveal which check failed.
*
* @since v2.6.5
*
* @param WP_REST_Request $request
*
* @return true|WP_Error
*/
public function validate_request( $request ) {
$body = (string) $request->get_body();
// Only limits what's forwarded: PHP has already read the body, so limiting request sizes is up to the web server.
$max_bytes = (int) apply_filters( 'plausible_analytics_proxy_max_body_bytes', self::MAX_BODY_BYTES );

if ( strlen( $body ) > $max_bytes ) {
return $this->no_route_error();
}

// The tracker sends its JSON as text/plain, so the request's JSON params aren't available.
$event = json_decode( $body, true );

if ( ! is_array( $event ) || ! $this->is_valid_event( $event ) || ! $this->is_same_site( $request ) ) {
return $this->no_route_error();
}

return true;
}

/**
* Checks the properties each event should have: a name, (one of) this site's Plausible domain(s) and a URL on this site.
*
* @param array $event
*
* @return bool
*/
private function is_valid_event( $event ) {
// The 404 event's name is sent as a number.
if ( isset( $event['n'] ) && is_int( $event['n'] ) ) {
$event['n'] = (string) $event['n'];
}

foreach ( [ 'n', 'd', 'u' ] as $key ) {
if ( empty( $event[ $key ] ) || ! is_string( $event[ $key ] ) ) {
return false;
}
}

return in_array( $this->normalize_domain( $event['d'] ), $this->get_allowed_domains(), true ) && $this->is_allowed_host( $event['u'] );
}

/**
* Checks if the Origin header, or the Referer header if there's no (valid) Origin, matches this site.
*
* @param WP_REST_Request $request
*
* @return bool
*/
private function is_same_site( $request ) {
if ( ! apply_filters( 'plausible_analytics_proxy_require_same_site', true ) ) {
return true;
}

return $this->is_allowed_host( (string) $request->get_header( 'origin' ) ) || $this->is_allowed_host( (string) $request->get_header( 'referer' ) );
}

/**
* Returns all Plausible domains configured for this site. The multilingual plugins might not be loaded in proxy
* requests, so the domains of all languages are allowed.
*
* @return array
*/
private function get_allowed_domains() {
$domains = (array) Helpers::get_settings()['domain_name'];
$domains[] = Helpers::get_domain();
$domains = (array) apply_filters( 'plausible_analytics_proxy_allowed_domains', array_values( array_filter( $domains ) ) );

return array_map( [ $this, 'normalize_domain' ], $domains );
}

/**
* Checks if the host of $url is one this site is served from.
*
* @param string $url
*
* @return bool
*/
private function is_allowed_host( $url ) {
$host = wp_parse_url( $url, PHP_URL_HOST );

if ( ! $host ) {
return false;
}

$hosts = [
wp_parse_url( get_option( 'home' ), PHP_URL_HOST ),
wp_parse_url( get_option( 'siteurl' ), PHP_URL_HOST ),
wp_parse_url( 'http://' . ( $_SERVER['HTTP_HOST'] ?? '' ), PHP_URL_HOST ),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
];

foreach ( $this->get_allowed_domains() as $domain ) {
$hosts[] = wp_parse_url( 'http://' . $domain, PHP_URL_HOST );
}

$hosts = (array) apply_filters( 'plausible_analytics_proxy_allowed_hosts', array_values( array_filter( $hosts ) ) );

return in_array( $this->normalize_domain( $host ), array_map( [ $this, 'normalize_domain' ], $hosts ), true );
}

/**
* Strips the scheme, www. and trailing slashes/dots, so domains can be compared.
*
* @param string $domain
*
* @return string
*/
private function normalize_domain( $domain ) {
return rtrim( preg_replace( '/^(https?:\/\/)?(www\.)?/', '', strtolower( trim( (string) $domain ) ) ), '/.' );
}

/**
* The same error WordPress returns for routes that don't exist.
*
* @return WP_Error
*/
private function no_route_error() {
// phpcs:ignore WordPress.WP.I18n.MissingArgDomain
return new WP_Error( 'rest_no_route', __( 'No route was found matching the URL and request method.' ), [ 'status' => 404 ] );
}

/**
* Make sure our response code is returned, instead of the default 200 on success.
*
Expand All @@ -282,7 +462,11 @@ public function force_http_response_code( $response, $server, $request ) {
}

$response_code = wp_remote_retrieve_response_code( $response->get_data() );
$response->set_status( $response_code );

// Errors already have the correct status.
if ( $response_code ) {
$response->set_status( $response_code );
}

return $response;
}
Expand Down
145 changes: 145 additions & 0 deletions tests/integration/ProxyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
namespace Plausible\Analytics\Tests\Integration;

use Plausible\Analytics\Tests\TestCase;
use Plausible\Analytics\WP\Helpers;
use Plausible\Analytics\WP\Proxy;

class ProxyTest extends TestCase {
Expand Down Expand Up @@ -94,4 +95,148 @@ public function testSendEventForwardsHeaders() {
unset( $_SERVER['HTTP_ACCEPT_LANGUAGE'], $_SERVER['HTTP_SEC_CH_UA_MOBILE'] );
}
}

/**
* @see Proxy::validate_request()
* @return void
*/
public function testValidateRequest() {
add_filter( 'plausible_analytics_settings', [ $this, 'setLanguageDomains' ] );

$_SERVER['HTTP_HOST'] = 'alias.test';

$event = [ 'n' => 'pageview', 'd' => 'test.dev', 'u' => 'http://example.org/page', 'v' => 35, 'p' => [ 'a' => 'b' ] ];

try {
$this->assertTrue( $this->isValid( $event ) );
$this->assertTrue( $this->isValid( [ 'd' => 'es.test.dev', 'u' => 'https://www.es.test.dev/' ] + $event, [ 'origin' => 'https://es.test.dev' ] ) );
$this->assertTrue( $this->isValid( [ 'u' => 'https://alias.test/' ] + $event, [ 'origin' => 'https://alias.test:8443' ] ) );
$this->assertTrue( $this->isValid( $event, [ 'referer' => 'http://example.org/page' ] ) );
$this->assertTrue( $this->isValid( $event, [ 'origin' => 'null', 'referer' => 'http://example.org/page' ] ) );
$this->assertTrue( $this->isValid( [ 'n' => 404 ] + $event ) );
$this->assertTrue( $this->isValid( [ 'p' => array_fill( 0, 30, str_repeat( 'a', 2000 ) ) ] + $event ) );

// Invalid events.
$this->assertFalse( $this->isValid( [ 'd' => 'evil.test' ] + $event ) );
$this->assertFalse( $this->isValid( [ 'd' => [ 'test.dev' ] ] + $event ) );
$this->assertFalse( $this->isValid( [ 'n' => '' ] + $event ) );
$this->assertFalse( $this->isValid( [ 'n' => [ 'pageview' ] ] + $event ) );
$this->assertFalse( $this->isValid( [ 'u' => 'http://evil.test/' ] + $event ) );
$this->assertFalse( $this->isValid( [ 'u' => 'http://example.org.evil.test/' ] + $event ) );
$this->assertFalse( $this->isValid( [ 'u' => '/page' ] + $event ) );
$this->assertFalse( $this->isValid( [ 'p' => [ 'a' => str_repeat( 'a', Proxy::MAX_BODY_BYTES ) ] ] + $event ) );
$this->assertFalse( $this->isValid( 'not-json' ) );

// Invalid sources.
$this->assertFalse( $this->isValid( $event, [] ) );
$this->assertFalse( $this->isValid( $event, [ 'origin' => 'http://evil.test' ] ) );

add_filter( 'plausible_analytics_proxy_require_same_site', '__return_false' );

$this->assertTrue( $this->isValid( $event, [] ) );
} finally {
remove_filter( 'plausible_analytics_proxy_require_same_site', '__return_false' );
remove_filter( 'plausible_analytics_settings', [ $this, 'setLanguageDomains' ] );
unset( $_SERVER['HTTP_HOST'] );
}
}

/**
* Dispatches requests through the REST server to verify that the endpoint is hidden, and which status it returns.
*
* @see Proxy::hide_from_index()
* @see Proxy::hide_namespace_index()
* @see Proxy::force_http_response_code()
* @return void
*/
public function testEndpointIsHidden() {
add_filter( 'plausible_analytics_settings', [ $this, 'enableProxy' ] );
add_filter( 'plausible_analytics_settings', [ $this, 'setDomain' ] );

$accept = function () {
return [ 'headers' => [], 'body' => 'ok', 'response' => [ 'code' => 202, 'message' => 'Accepted' ], 'cookies' => [] ];
};

add_filter( 'pre_http_request', $accept );

global $wp_rest_server;

$original_server = $wp_rest_server;
$wp_rest_server = null;
$route = substr( Helpers::get_rest_endpoint( false ), strlen( '/' . rest_get_url_prefix() ) );
$namespace = Helpers::get_proxy_resource( 'namespace' ) . '/v1';

new Proxy();

try {
$server = rest_get_server();

$this->assertArrayHasKey( $route, $server->get_routes() );

$index = $server->dispatch( new \WP_REST_Request( 'GET', '/' ) )->get_data();

$this->assertNotEmpty( $index['routes'] );
$this->assertStringNotContainsString( Helpers::get_proxy_resource( 'namespace' ), (string) wp_json_encode( [ $index['namespaces'], array_keys( $index['routes'] ) ] ) );
$this->assertTrue( array_values( $index['namespaces'] ) === $index['namespaces'] );

$response = $server->dispatch( new \WP_REST_Request( 'GET', "/$namespace" ) );

// Older WordPress versions don't convert errors returned by the rest_pre_dispatch filter.
if ( is_wp_error( $response ) ) {
$response = rest_convert_error_to_response( $response );
}

$this->assertEquals( 404, $response->get_status() );

// Rejected requests keep their status.
$request = new \WP_REST_Request( 'POST', $route );
$response = apply_filters( 'rest_post_dispatch', $server->dispatch( $request ), $server, $request );

$this->assertEquals( 404, $response->get_status() );

// Events sent by the tracker are forwarded.
$request->set_header( 'content-type', 'text/plain' );
$request->set_header( 'origin', 'http://example.org' );
$request->set_body( wp_json_encode( [ 'n' => 'pageview', 'd' => 'test.dev', 'u' => 'http://example.org/' ] ) );
$response = apply_filters( 'rest_post_dispatch', $server->dispatch( $request ), $server, $request );

$this->assertEquals( 202, $response->get_status() );
} finally {
$wp_rest_server = $original_server;

$this->removeAction( 'rest_api_init', 'register_route' );
$this->removeAction( 'rest_index', 'hide_from_index' );
$this->removeAction( 'rest_pre_dispatch', 'hide_namespace_index' );
remove_filter( 'pre_http_request', $accept );
remove_filter( 'plausible_analytics_settings', [ $this, 'enableProxy' ] );
remove_filter( 'plausible_analytics_settings', [ $this, 'setDomain' ] );
}
}

/**
* @param array $settings
*
* @return array
*/
public function setLanguageDomains( $settings ) {
$settings['domain_name'] = [ 'default' => 'test.dev', 'es' => 'es.test.dev' ];

return $settings;
}

/**
* @param array|string $event
* @param array $headers
*
* @return bool
*/
private function isValid( $event, $headers = [ 'origin' => 'http://example.org' ] ) {
$proxy = new Proxy( false );
$request = new \WP_REST_Request( 'POST' );

$request->set_body( is_array( $event ) ? wp_json_encode( $event ) : $event );
$request->set_headers( [ 'content-type' => 'text/plain' ] + $headers );

return $proxy->validate_request( $request ) === true;
}
}
Loading