diff --git a/README.md b/README.md index 4c7fd94a6..e52e7680c 100644 --- a/README.md +++ b/README.md @@ -66,6 +66,35 @@ It also checks the shared `--prpl-*` names against `tokens.json` in at a checkout of it (`export YOUR_BRANDING_DIR=~/path/to/branding-api`). A name the plugin reads must be listed there; without the variable the check is skipped. +## Authentication transport rollout + +The compatibility release accepts `X-Progress-Planner-Token` on `/get-stats` and +`/tasks`, while retaining the legacy stats URLs (`/get-stats/token/` and +`/get-stats/`) and `token` query parameter. A supplied custom header takes +precedence: an empty or incorrect header is rejected even with a valid URL token. +`Authorization: Bearer` is not used for Progress Planner authentication. + +1. Ship this compatibility release first and verify its installation on every + site the server will switch. Old server requests must continue to work, and a + header-only statistics request must succeed without a key in the URL. An + unreachable or older site is not ready for the switch. +2. Deploy the server security and custom-header changes together + ([server #68](https://github.com/ProgressPlanner/progress-planner-server/pull/68) + and [server #69](https://github.com/ProgressPlanner/progress-planner-server/pull/69)). + Verify statistics retrieval through the server. If it fails, the server can + return to its previous URL transport while the compatibility plugin is installed. +3. After all server callers use the custom header, ship the strict plugin changes + ([#802](https://github.com/ProgressPlanner/progress-planner/pull/802) and + [#803](https://github.com/ProgressPlanner/progress-planner/pull/803)). Remove the + URL fallback and legacy route, and change the compatibility tests to expect + legacy authentication to fail. Reconcile these overlapping REST changes when + updating those branches. After this stage, reverting the server to URL tokens + requires restoring the compatibility plugin first. + +This is a transport bridge, not key rotation or the full security release. +Existing credentials are unchanged. Preparing this branch does not deploy it or +establish that installed sites have received it. + ## Branches on this repository We use a couple of branches in this repository to keep things clean: diff --git a/classes/rest/class-base.php b/classes/rest/class-base.php index be58f286b..4a20969b7 100644 --- a/classes/rest/class-base.php +++ b/classes/rest/class-base.php @@ -12,11 +12,65 @@ */ abstract class Base { + /** + * HTTP header shared with the server's new credential transport. + */ + const TOKEN_HEADER = 'X-Progress-Planner-Token'; + + /** + * REST namespace of the token-authenticated endpoints. + */ + const REST_NAMESPACE = '/progress-planner/v1'; + + /** + * Route of the endpoint, relative to the namespace. Empty means no route. + */ + const ROUTE = ''; + /** * Constructor. */ public function __construct() { \add_action( 'rest_api_init', [ $this, 'register_rest_endpoint' ] ); + \add_filter( 'rest_post_dispatch', [ $this, 'prevent_caching' ], 10, 3 ); + } + + /** + * Keep responses of this endpoint out of every cache. + * + * With header authentication every caller requests the same URL. A cache + * that stored an authenticated response would hand it to anyone requesting + * that URL, and the server would get stale data back. WordPress only sends + * no-cache headers to logged-in users, and the server is not logged in. + * Runs for successful and rejected requests alike. + * + * @param mixed $response The response. + * @param mixed $server The REST server. + * @param mixed $request The request. + * + * @return mixed + */ + public function prevent_caching( $response, $server, $request ) { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.FoundAfterLastUsed + if ( '' === static::ROUTE + || ! $response instanceof \WP_HTTP_Response + || ! $request instanceof \WP_REST_Request + ) { + return $response; + } + + $route = self::REST_NAMESPACE . static::ROUTE; + if ( $route !== $request->get_route() && 0 !== \strpos( $request->get_route(), $route . '/' ) ) { + return $response; + } + + $response->header( 'Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0, private' ); + $response->header( 'Expires', 'Wed, 11 Jan 1984 05:00:00 GMT' ); + + // LiteSpeed Cache caches REST responses for guests by default and sends + // its own cache header, so the headers above alone do not stop it. + \do_action( 'litespeed_control_set_nocache', 'Progress Planner token-authenticated endpoint' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- LiteSpeed Cache's public API. + + return $response; } /** @@ -59,13 +113,45 @@ protected function get_client_ip() { } /** - * Validate the token. + * Authenticate with the new header or a legacy URL token during rollout. + * + * An explicitly supplied header always wins, including an empty or invalid one. + * Remove the URL fallback after the server and installed plugins use the header. + * + * @param \WP_REST_Request $request The REST request. + * @return bool + */ + public function permissions_check( $request ) { + $token = $request->get_header( self::TOKEN_HEADER ); + if ( null !== $token ) { + return $this->validate_token( \trim( $token ) ); + } + + $token = $request->get_param( 'token' ); + if ( ! \is_string( $token ) ) { + return false; + } + + // The old stats route captures "token/" as one route parameter. + if ( 0 === \strpos( $token, 'token/' ) ) { + $token = \substr( $token, 6 ); + } + + return $this->validate_token( $token ); + } + + /** + * Validate the complete credential, without transport-specific prefixes. * - * @param string $token The token. + * @param mixed $token The token. * * @return bool */ public function validate_token( $token ) { + if ( ! \is_string( $token ) || '' === $token ) { + return false; + } + // Rate limiting: Check for too many failed attempts. $ip_address = $this->get_client_ip(); $rate_limit_key = 'prpl_api_rate_limit_' . \md5( $ip_address ); @@ -76,8 +162,6 @@ public function validate_token( $token ) { return false; } - $token = \str_replace( 'token/', '', $token ); - // Check test token first (use hash_equals to prevent timing attacks). $test_token = \get_option( 'progress_planner_test_token', '' ); if ( ! empty( $test_token ) && \hash_equals( $test_token, $token ) ) { diff --git a/classes/rest/class-stats.php b/classes/rest/class-stats.php index 5ff4217bb..ce12097a8 100644 --- a/classes/rest/class-stats.php +++ b/classes/rest/class-stats.php @@ -3,7 +3,8 @@ * Progress_Planner REST-API. * * Adds a REST-API endpoint to get stats, in a URL like: - * /wp-json/progress-planner/v1/get-stats/token/ + * /wp-json/progress-planner/v1/get-stats (X-Progress-Planner-Token header) + * Legacy URLs with a token remain available during the transport rollout. * * The token is generated and saved in the settings. * @@ -19,29 +20,30 @@ */ class Stats extends Base { + /** + * Route of the endpoint, relative to the namespace. + */ + const ROUTE = '/get-stats'; + /** * Register the REST-API endpoint. * * @return void */ public function register_rest_endpoint() { - \register_rest_route( - 'progress-planner/v1', - '/get-stats/(?P\S+)', - [ + foreach ( [ '/get-stats', '/get-stats/(?P\S+)' ] as $route ) { + \register_rest_route( + 'progress-planner/v1', + $route, [ - 'methods' => 'GET', - 'callback' => [ $this, 'get_stats' ], - 'permission_callback' => '__return_true', - 'args' => [ - 'token' => [ - 'required' => true, - 'validate_callback' => [ $this, 'validate_token' ], - ], + [ + 'methods' => 'GET', + 'callback' => [ $this, 'get_stats' ], + 'permission_callback' => [ $this, 'permissions_check' ], ], - ], - ] - ); + ] + ); + } } /** diff --git a/classes/rest/class-tasks.php b/classes/rest/class-tasks.php index 7e4849320..c0883178d 100644 --- a/classes/rest/class-tasks.php +++ b/classes/rest/class-tasks.php @@ -15,6 +15,11 @@ */ class Tasks extends Base { + /** + * Route of the endpoint, relative to the namespace. + */ + const ROUTE = '/tasks'; + /** * Register the REST-API endpoint. * @@ -28,13 +33,7 @@ public function register_rest_endpoint() { [ 'methods' => 'GET', 'callback' => [ $this, 'get_tasks' ], - 'permission_callback' => '__return_true', - 'args' => [ - 'token' => [ - 'required' => true, - 'validate_callback' => [ $this, 'validate_token' ], - ], - ], + 'permission_callback' => [ $this, 'permissions_check' ], ], ] ); diff --git a/tests/phpunit/test-class-rest-base.php b/tests/phpunit/test-class-rest-base.php index 38af0aead..5b4eabdab 100644 --- a/tests/phpunit/test-class-rest-base.php +++ b/tests/phpunit/test-class-rest-base.php @@ -250,7 +250,7 @@ public function test_validate_token_test_token() { } /** - * Test validate_token with token containing "token/" prefix. + * Token validation does not strip a transport prefix from the credential. * * @return void */ @@ -270,7 +270,7 @@ public function test_validate_token_with_prefix() { $result = $this->rest_instance->validate_token( $token ); - $this->assertTrue( $result ); + $this->assertFalse( $result ); } /** diff --git a/tests/phpunit/test-rest-token-compatibility.php b/tests/phpunit/test-rest-token-compatibility.php new file mode 100644 index 000000000..d2fce186c --- /dev/null +++ b/tests/phpunit/test-rest-token-compatibility.php @@ -0,0 +1,172 @@ +getMockBuilder( $is_stats ? Stats::class : Tasks::class ) + ->disableOriginalConstructor() + ->onlyMethods( [ $callback ] ) + ->getMock(); + $api->expects( 200 === $status ? $this->once() : $this->never() ) + ->method( $callback ) + ->willReturn( new \WP_REST_Response( [ 'authenticated' => true ] ) ); + $register = function () use ( $api ) { + global $wp_rest_server; + // Keep only this fixture's routes, while still registering on the real hook. + $wp_rest_server = new \WP_REST_Server(); + $api->register_rest_endpoint(); + }; + \add_action( 'rest_api_init', $register, PHP_INT_MAX ); + + $request = new \WP_REST_Request( 'GET', '/progress-planner/v1' . $route ); + $request->set_query_params( $query ); + foreach ( $headers as $name => $value ) { + $request->set_header( $name, $value ); + } + + try { + \do_action( 'rest_api_init', $wp_rest_server ); + $response = $wp_rest_server->dispatch( $request ); + $this->assertSame( $status, $response->get_status() ); + if ( 200 === $status ) { + $this->assertSame( [ 'authenticated' => true ], $response->get_data() ); + } else { + $this->assertSame( 'rest_forbidden', $response->get_data()['code'] ); + } + + // Accepted and rejected responses alike must stay out of caches. + $litespeed = \did_action( 'litespeed_control_set_nocache' ); + $headers = $api->prevent_caching( $response, $wp_rest_server, $request )->get_headers(); + $this->assertStringContainsString( 'no-store', $headers['Cache-Control'] ?? '' ); + $this->assertStringContainsString( 'private', $headers['Cache-Control'] ?? '' ); + $this->assertSame( $litespeed + 1, \did_action( 'litespeed_control_set_nocache' ) ); + } finally { + \remove_action( 'rest_api_init', $register, PHP_INT_MAX ); + $wp_rest_server = $previous_server; + } + } + + /** + * Requests used by the legacy server, the new server and invalid callers. + * + * @return array + */ + public static function authentication_cases() { + $cases = [ + 'legacy stats path' => [ '/get-stats/token/fixture-key', [], [], 200 ], + 'legacy bare stats path' => [ '/get-stats/fixture-key', [], [], 200 ], + 'invalid legacy stats path' => [ '/get-stats/token/wrong', [], [], 401 ], + 'header wins over path' => [ '/get-stats/token/wrong', [], [ 'X-Progress-Planner-Token' => 'fixture-key' ], 200 ], + 'bad header with valid path' => [ '/get-stats/token/fixture-key', [], [ 'X-Progress-Planner-Token' => 'wrong' ], 401 ], + ]; + foreach ( [ '/get-stats', '/tasks' ] as $route ) { + $cases[ $route . ' header' ] = [ $route, [], [ 'X-Progress-Planner-Token' => 'fixture-key' ], 200 ]; + $cases[ $route . ' lowercase header' ] = [ $route, [], [ 'x-progress-planner-token' => ' fixture-key ' ], 200 ]; + $cases[ $route . ' query' ] = [ $route, [ 'token' => 'fixture-key' ], [], 200 ]; + $cases[ $route . ' missing' ] = [ $route, [], [], 401 ]; + $cases[ $route . ' wrong query' ] = [ $route, [ 'token' => 'wrong' ], [], 401 ]; + $cases[ $route . ' array query' ] = [ $route, [ 'token' => [ 'fixture-key' ] ], [], 401 ]; + $cases[ $route . ' bearer alone' ] = [ $route, [], [ 'Authorization' => 'Bearer fixture-key' ], 401 ]; + $cases[ $route . ' unrelated bearer' ] = [ + $route, + [], + [ + 'Authorization' => 'Bearer other-plugin', + 'X-Progress-Planner-Token' => 'fixture-key', + ], + 200, + ]; + $cases[ $route . ' invalid header precedence' ] = [ $route, [ 'token' => 'fixture-key' ], [ 'X-Progress-Planner-Token' => 'wrong' ], 401 ]; + $cases[ $route . ' empty header precedence' ] = [ $route, [ 'token' => 'fixture-key' ], [ 'X-Progress-Planner-Token' => '' ], 401 ]; + $cases[ $route . ' valid header precedence' ] = [ $route, [ 'token' => [ 'wrong' ] ], [ 'X-Progress-Planner-Token' => 'fixture-key' ], 200 ]; + $cases[ $route . ' prefixed header rejected' ] = [ $route, [], [ 'X-Progress-Planner-Token' => 'token/fixture-key' ], 401 ]; + } + return $cases; + } + + /** + * Both endpoints register the no-cache filter when the plugin boots. + * + * @return void + */ + public function test_prevent_caching_is_registered() { + $this->assertNotFalse( \has_filter( 'rest_post_dispatch', [ \progress_planner()->get_rest__stats(), 'prevent_caching' ] ) ); + $this->assertNotFalse( \has_filter( 'rest_post_dispatch', [ \progress_planner()->get_rest__tasks(), 'prevent_caching' ] ) ); + } + + /** + * Other routes, including look-alikes, keep their own cache headers. + * + * @dataProvider other_routes + * + * @param string $class_name The endpoint class. + * @param string $route The requested route. + * + * @return void + */ + public function test_prevent_caching_leaves_other_routes_alone( $class_name, $route ) { + $api = $this->getMockBuilder( $class_name ) + ->disableOriginalConstructor() + ->onlyMethods( [] ) + ->getMock(); + + $litespeed = \did_action( 'litespeed_control_set_nocache' ); + $response = $api->prevent_caching( + new \WP_REST_Response( [] ), + \rest_get_server(), + new \WP_REST_Request( 'GET', $route ) + ); + + $this->assertArrayNotHasKey( 'Cache-Control', $response->get_headers() ); + $this->assertSame( $litespeed, \did_action( 'litespeed_control_set_nocache' ) ); + } + + /** + * Routes the no-cache filter must not touch. + * + * @return array + */ + public static function other_routes() { + return [ + 'core posts route' => [ Stats::class, '/wp/v2/posts' ], + 'other plugin route' => [ Stats::class, '/progress-planner/v1/recommendations' ], + 'look-alike stats route' => [ Stats::class, '/progress-planner/v1/get-stats-extra' ], + 'look-alike tasks route' => [ Tasks::class, '/progress-planner/v1/tasks-extra' ], + 'other endpoint route' => [ Tasks::class, '/progress-planner/v1/get-stats' ], + ]; + } +}