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
81 changes: 61 additions & 20 deletions classes/rest/class-base.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,65 @@
*/
abstract class Base {

/**
* HTTP header that carries the site token.
*/
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;
}

/**
Expand All @@ -40,31 +94,18 @@ protected function get_client_ip() {
}

/**
* Authenticate a request using a bearer token, never a URL parameter.
* Authenticate a request using the site token header, never a URL parameter.
*
* A dedicated header, not `Authorization: Bearer`: bearer-auth plugins (JWT
* and OAuth) try to decode every bearer token and reject the request before
* this check runs, and some Apache setups strip `Authorization` entirely.
*
* @param \WP_REST_Request $request The REST request.
* @return bool
*/
public function permissions_check( $request ) {
$authorization = $request->get_header( 'authorization' );
// Apache may expose Authorization only through its original request headers
// when WordPress's rewrite rules have not populated HTTP_AUTHORIZATION.
if ( null === $authorization ) {
$headers = \array_change_key_case( $this->get_http_request_headers(), CASE_LOWER );
$authorization = $headers['authorization'] ?? null;
}
return \is_string( $authorization )
&& 1 === \preg_match( '/^Bearer ([^\s]+)$/iD', $authorization, $matches )
&& $this->validate_token( $matches[1] );
}

/**
* Read original HTTP headers when the web server exposes them separately.
*
* @return array
*/
protected function get_http_request_headers() {
return \function_exists( 'getallheaders' ) ? \getallheaders() : [];
$token = $request->get_header( self::TOKEN_HEADER );
return \is_string( $token ) && $this->validate_token( \trim( $token ) );
}

/**
Expand Down
7 changes: 6 additions & 1 deletion classes/rest/class-stats.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Progress_Planner REST-API.
*
* Adds a REST-API endpoint to get stats, in a URL like:
* <site-url>/wp-json/progress-planner/v1/get-stats (Authorization: Bearer <site-token>)
* <site-url>/wp-json/progress-planner/v1/get-stats (X-Progress-Planner-Token: <site-token>)
*
* The token is generated and saved in the settings.
*
Expand All @@ -19,6 +19,11 @@
*/
class Stats extends Base {

/**
* Route of the endpoint, relative to the namespace.
*/
const ROUTE = '/get-stats';

/**
* Register the REST-API endpoint.
*
Expand Down
5 changes: 5 additions & 0 deletions classes/rest/class-tasks.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,11 @@
*/
class Tasks extends Base {

/**
* Route of the endpoint, relative to the namespace.
*/
const ROUTE = '/tasks';

/**
* Register the REST-API endpoint.
*
Expand Down
2 changes: 1 addition & 1 deletion tests/e2e/api/tasks.api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export class TasksApi {
{
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${ testToken }`,
'X-Progress-Planner-Token': testToken,
},
}
);
Expand Down
6 changes: 3 additions & 3 deletions tests/phpunit/integration/test-rest-api-stats-integration.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public function test_get_stats_endpoint_with_valid_token() {
'/progress-planner/v1/get-stats',
'GET',
[],
[ 'Authorization' => 'Bearer ' . $license_key ]
[ 'X-Progress-Planner-Token' => $license_key ]
);

$this->assertNotInstanceOf( \WP_Error::class, $response );
Expand Down Expand Up @@ -62,7 +62,7 @@ public function test_get_stats_endpoint_with_invalid_token() {
'/progress-planner/v1/get-stats',
'GET',
[],
[ 'Authorization' => 'Bearer invalid-token' ]
[ 'X-Progress-Planner-Token' => 'invalid-token' ]
);

// Should return error due to validation failure.
Expand All @@ -89,7 +89,7 @@ public function test_get_stats_endpoint_includes_system_data() {
'/progress-planner/v1/get-stats',
'GET',
[],
[ 'Authorization' => 'Bearer ' . $license_key ]
[ 'X-Progress-Planner-Token' => $license_key ]
);

$this->assertInstanceOf( \WP_REST_Response::class, $response );
Expand Down
6 changes: 3 additions & 3 deletions tests/phpunit/integration/test-rest-api-tasks-integration.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public function test_get_tasks_endpoint_with_valid_token() {
'/progress-planner/v1/tasks',
'GET',
[],
[ 'Authorization' => 'Bearer ' . $license_key ]
[ 'X-Progress-Planner-Token' => $license_key ]
);

$this->assertNotInstanceOf( \WP_Error::class, $response );
Expand Down Expand Up @@ -63,7 +63,7 @@ public function test_get_tasks_endpoint_with_invalid_token() {
'/progress-planner/v1/tasks',
'GET',
[],
[ 'Authorization' => 'Bearer invalid-token' ]
[ 'X-Progress-Planner-Token' => 'invalid-token' ]
);

// Missing or invalid credentials must not expose tasks.
Expand Down Expand Up @@ -105,7 +105,7 @@ public function test_get_tasks_endpoint_includes_all_statuses() {
'/progress-planner/v1/tasks',
'GET',
[],
[ 'Authorization' => 'Bearer ' . $license_key ]
[ 'X-Progress-Planner-Token' => $license_key ]
);

$this->assertInstanceOf( \WP_REST_Response::class, $response );
Expand Down
2 changes: 1 addition & 1 deletion tests/phpunit/test-class-api-get-stats.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ public function tearDown(): void {
*/
public function testEndpoint() {
$request = new WP_REST_Request( 'GET', '/progress-planner/v1/get-stats' );
$request->set_header( 'Authorization', 'Bearer ' . $this->token );
$request->set_header( 'X-Progress-Planner-Token', $this->token );
$response = $this->server->dispatch( $request );

// Check if the response is successful.
Expand Down
42 changes: 10 additions & 32 deletions tests/phpunit/test-class-rest-base.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,44 +33,22 @@ public function setUp(): void {
}

/**
* Apache's original headers authenticate only when REST has no header.
* Only the dedicated token header authenticates; a bearer token is never read,
* so bearer-auth plugins and the site token cannot interfere with each other.
*
* @return void
*/
public function test_original_authorization_header_fallback() {
public function test_only_the_token_header_authenticates() {
\update_option( 'progress_planner_license_key', 'fixture-license' );
\delete_transient( 'prpl_api_rate_limit_' . \md5( '0.0.0.0' ) );
unset( $_SERVER['REMOTE_ADDR'] );
$api = $this->getMockBuilder( Tasks::class )
->disableOriginalConstructor()
->onlyMethods( [ 'get_http_request_headers' ] )
->getMock();
$api->method( 'get_http_request_headers' )->willReturn( [ 'aUtHoRiZaTiOn' => 'Bearer fixture-license' ] );
$request = new \WP_REST_Request( 'GET', '/progress-planner/v1/tasks' );
$this->assertTrue( $api->permissions_check( $request ) );
$request->set_header( 'Authorization', 'Bearer wrong-key' );
$this->assertFalse( $api->permissions_check( $request ) );
}

/**
* A raw header fallback still rejects a bad token and URL credentials.
*
* @return void
*/
public function test_original_headers_do_not_bypass_token_validation() {
\update_option( 'progress_planner_license_key', 'fixture-license' );
$api = $this->getMockBuilder( Tasks::class )
->disableOriginalConstructor()
->onlyMethods( [ 'get_http_request_headers' ] )
->getMock();
$api->method( 'get_http_request_headers' )->willReturnOnConsecutiveCalls(
[ 'Authorization' => 'Bearer wrong-key' ],
[]
);
$request = new \WP_REST_Request( 'GET', '/progress-planner/v1/tasks' );
$request->set_param( 'token', 'fixture-license' );
$this->assertFalse( $api->permissions_check( $request ) );
$this->assertFalse( $api->permissions_check( $request ) );
$request->set_header( 'Authorization', 'Bearer fixture-license' );
$this->assertFalse( $this->rest_instance->permissions_check( $request ) );
$request->set_header( 'x-progress-planner-token', 'fixture-license' );
$this->assertTrue( $this->rest_instance->permissions_check( $request ) );
$request->set_header( 'X-Progress-Planner-Token', 'wrong-key' );
$this->assertFalse( $this->rest_instance->permissions_check( $request ) );
}

/**
Expand Down Expand Up @@ -291,7 +269,7 @@ public function test_validate_token_test_token() {
}

/**
* Token validation compares the entire bearer token, including any prefix.
* Token validation compares the entire token, including any prefix.
*
* @return void
*/
Expand Down
8 changes: 4 additions & 4 deletions tests/phpunit/test-class-security-review.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,19 +89,19 @@ public function test_spoofed_headers_cannot_bypass_rate_limit() {
}

/**
* Bearer authentication works without credentials in the URL.
* Header authentication works without credentials in the URL.
*
* @return void
*/
public function test_bearer_authentication() {
public function test_token_header_authentication() {
\update_option( 'progress_planner_license_key', 'fixture-license' );
\wp_set_current_user( 0 );
foreach ( [ '/tasks', '/get-stats' ] as $endpoint ) {
$request = new \WP_REST_Request( 'GET', '/progress-planner/v1' . $endpoint );
$this->assertSame( 401, \rest_do_request( $request )->get_status() );
$request->set_header( 'Authorization', 'Bearer fixture-license' );
$request->set_header( 'X-Progress-Planner-Token', 'fixture-license' );
$this->assertSame( 200, \rest_do_request( $request )->get_status() );
$request->set_header( 'Authorization', 'Bearer incorrect' );
$request->set_header( 'X-Progress-Planner-Token', 'incorrect' );
$request->set_param( 'token', 'fixture-license' );
$this->assertSame( 401, \rest_do_request( $request )->get_status() );
}
Expand Down
Loading
Loading