is_connected ) : ?>
+
@@ -194,4 +203,20 @@ private static function format_stored_date( string $value ): string {
return $date->format( get_option( 'date_format' ) . ' @ ' . get_option( 'time_format' ) );
}
+
+ /**
+ * What a scope lets Scanfully do, as the settings page says it.
+ *
+ * @param string $scope The scope.
+ *
+ * @return string
+ */
+ public static function scope_label( string $scope ): string {
+ switch ( $scope ) {
+ case OAuth::SCOPE_READ:
+ return __( 'Read site data: health, plugins and themes, and activity', 'scanfully' );
+ default:
+ return $scope;
+ }
+ }
}
diff --git a/src/Cron/Controller.php b/src/Cron/Controller.php
index 78a3574..5b5ee0b 100644
--- a/src/Cron/Controller.php
+++ b/src/Cron/Controller.php
@@ -420,6 +420,30 @@ private static function refresh_access_token_if_needed(): void {
}
}
+ /**
+ * Whether the access token expires within two days, or the connection is
+ * still a legacy one. An expiry date that cannot be parsed also needs a
+ * refresh, which stores a fresh one.
+ *
+ * @param Options\Options $options The current options.
+ *
+ * @return bool
+ */
+ private static function token_needs_refresh( Options\Options $options ): bool {
+ return self::moves_to_oauth() || self::token_expires_soon( $options );
+ }
+
+ /**
+ * Whether a connection from before 1.11 moves to the OAuth server now:
+ * one refresh there, whatever its expiry. After a failure there, the next
+ * try is a day later.
+ *
+ * @return bool
+ */
+ private static function moves_to_oauth(): bool {
+ return 'oauth' !== Options\Controller::get_option( 'flow' ) && false === get_transient( Connect\Controller::OAUTH_UNAVAILABLE_TRANSIENT );
+ }
+
/**
* Whether the access token expires within two days. An expiry date that
* cannot be parsed also needs a refresh, which stores a fresh one.
@@ -428,7 +452,7 @@ private static function refresh_access_token_if_needed(): void {
*
* @return bool
*/
- private static function token_needs_refresh( Options\Options $options ): bool {
+ private static function token_expires_soon( Options\Options $options ): bool {
try {
$refresh_after = new \DateTime( $options->expires, new \DateTimeZone( 'UTC' ) );
} catch ( \Exception $e ) {
@@ -447,8 +471,15 @@ private static function token_needs_refresh( Options\Options $options ): bool {
* @return void
*/
private static function refresh_access_token( Options\Options $options ): void {
- $tokens = Connect\Controller::refresh_access_token( $options->refresh_token, $options->site_id );
+ // a move to the OAuth server of tokens that still work: a failure is
+ // no broken connection, the move is tried again tomorrow.
+ $moving = ! self::token_expires_soon( $options );
+ $tokens = Connect\Controller::refresh_access_token( $options->refresh_token, $options->site_id, ! $moving );
+ if ( $moving && ! self::is_valid_token_response( $tokens ) ) {
+ set_transient( Connect\Controller::OAUTH_UNAVAILABLE_TRANSIENT, 1, DAY_IN_SECONDS );
+ return;
+ }
if ( ! self::is_valid_token_response( $tokens ) ) {
self::record_refresh_failure( 'Token refresh request failed. The Scanfully API may be unreachable or the refresh token may be invalid.' );
return;
diff --git a/src/Main.php b/src/Main.php
index 2e095c1..2d8e739 100644
--- a/src/Main.php
+++ b/src/Main.php
@@ -88,6 +88,28 @@ public static function get_connect_url(): string {
return apply_filters( 'scanfully_connect_url', self::CONNECT_URL );
}
+ /**
+ * Get the address of Scanfully's OAuth server: the origin of the API URL,
+ * such as https://api.scanfully.com.
+ *
+ * @return string
+ */
+ public static function get_oauth_url(): string {
+ $parts = wp_parse_url( self::get_api_url() );
+ $origin = ( $parts['scheme'] ?? 'https' ) . '://' . ( $parts['host'] ?? '' ) . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' );
+
+ return apply_filters( 'scanfully_oauth_url', $origin );
+ }
+
+ /**
+ * Get the resource the plugin's tokens are for on the OAuth server.
+ *
+ * @return string
+ */
+ public static function get_site_resource(): string {
+ return self::get_oauth_url() . '/v1/sites';
+ }
+
/**
* Set up the plugin.
*
diff --git a/src/Options/Controller.php b/src/Options/Controller.php
index d6f2752..2376e03 100644
--- a/src/Options/Controller.php
+++ b/src/Options/Controller.php
@@ -144,6 +144,9 @@ public static function clear() {
delete_option( self::$db_prefix . 'last_used' );
delete_option( self::$db_prefix . 'date_connected' );
delete_option( self::$db_prefix . 'last_request_error' );
+ delete_option( self::$db_prefix . 'scopes' );
+ delete_option( self::$db_prefix . 'flow' );
+ delete_transient( 'scanfully_oauth_unavailable' );
// Email deliverability sub-feature: per-site secret + cached state.
delete_option( self::$db_prefix . 'email_deliverability_enabled' );
diff --git a/src/Sync/Controller.php b/src/Sync/Controller.php
index d175dac..9c76ad3 100644
--- a/src/Sync/Controller.php
+++ b/src/Sync/Controller.php
@@ -75,9 +75,11 @@ public static function register_routes(): void {
}
/**
- * Only the Scanfully API may trigger a sync: the request must carry the
- * site's current access token. Unauthenticated requests are rejected
- * before they can consume the rate-limit budget.
+ * Only the Scanfully API may trigger a sync: the request carries a token
+ * Scanfully signed for this site (SignedRequest), or, from an API that
+ * still keeps the plugin's tokens, the site's current access token.
+ * Unauthenticated requests are rejected before they can consume the
+ * rate-limit budget.
*
* @param \WP_REST_Request $request The request.
*
@@ -85,13 +87,19 @@ public static function register_routes(): void {
*/
public static function check_permission( \WP_REST_Request $request ): bool {
$options = Options\Controller::get_options();
- if ( ! $options->is_connected || '' === $options->access_token ) {
+ if ( ! $options->is_connected ) {
return false;
}
$token = self::get_request_token( $request );
+ if ( '' === $token ) {
+ return false;
+ }
+ if ( SignedRequest::looks_signed( $token ) ) {
+ return SignedRequest::verify( $token, $options->site_id, 'sync', \Scanfully\Connect\OAuth::SCOPE_READ );
+ }
- return '' !== $token && hash_equals( $options->access_token, $token );
+ return '' !== $options->access_token && hash_equals( $options->access_token, $token );
}
/**
diff --git a/src/Sync/SignedRequest.php b/src/Sync/SignedRequest.php
new file mode 100644
index 0000000..aed1b6c
--- /dev/null
+++ b/src/Sync/SignedRequest.php
@@ -0,0 +1,240 @@
+ $now + self::LEEWAY )
+ || ! isset( $claims['jti'] ) || ! is_string( $claims['jti'] ) || '' === $claims['jti'] ) {
+ return false;
+ }
+
+ // each request once: a copy of it, seen in a log, does nothing.
+ $seen = 'scanfully_jti_' . md5( $claims['jti'] );
+ if ( false !== get_transient( $seen ) ) {
+ return false;
+ }
+ set_transient( $seen, 1, max( 60, (int) $claims['exp'] - $now + self::LEEWAY ) );
+
+ return true;
+ }
+
+ /**
+ * The public key with the id, as PEM, from the cached key set, or from a
+ * fresh one when the cache does not have it.
+ *
+ * @param string $kid The key id.
+ *
+ * @return string|null
+ */
+ private static function key( string $kid ): ?string {
+ $keys = get_transient( self::KEYS_TRANSIENT );
+ if ( is_array( $keys ) && isset( $keys[ $kid ] ) ) {
+ return $keys[ $kid ];
+ }
+ if ( is_array( $keys ) && false !== get_transient( self::REFETCH_TRANSIENT ) ) {
+ return null;
+ }
+ $keys = self::fetch_keys();
+ if ( null === $keys ) {
+ return null;
+ }
+ set_transient( self::KEYS_TRANSIENT, $keys, DAY_IN_SECONDS );
+ set_transient( self::REFETCH_TRANSIENT, 1, 5 * MINUTE_IN_SECONDS );
+
+ return $keys[ $kid ] ?? null;
+ }
+
+ /**
+ * Fetch Scanfully's public keys.
+ *
+ * @return array
|null The keys by id, as PEM, or null when they could not be read.
+ */
+ private static function fetch_keys(): ?array {
+ $resp = wp_remote_get(
+ Main::get_oauth_url() . self::KEYS_PATH,
+ [
+ 'timeout' => 5,
+ 'sslverify' => Main::get_sslverify(),
+ ]
+ );
+ if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) {
+ return null;
+ }
+
+ return self::parse_keys( (string) wp_remote_retrieve_body( $resp ) );
+ }
+
+ /**
+ * The RSA signing keys of a JWK set, by id, as PEM.
+ *
+ * @param string $json The key set.
+ *
+ * @return array|null
+ */
+ public static function parse_keys( string $json ): ?array {
+ $set = json_decode( $json, true );
+ if ( ! is_array( $set ) || ! isset( $set['keys'] ) || ! is_array( $set['keys'] ) ) {
+ return null;
+ }
+ $keys = [];
+ foreach ( $set['keys'] as $jwk ) {
+ if ( ! is_array( $jwk ) || ( $jwk['kty'] ?? '' ) !== 'RSA' || ! isset( $jwk['kid'], $jwk['n'], $jwk['e'] )
+ || ! is_string( $jwk['kid'] ) || ! is_string( $jwk['n'] ) || ! is_string( $jwk['e'] ) ) {
+ continue;
+ }
+ $keys[ $jwk['kid'] ] = self::rsa_pem( self::b64url_decode( $jwk['n'] ), self::b64url_decode( $jwk['e'] ) );
+ }
+
+ return $keys;
+ }
+
+ /**
+ * A public key as PEM from its modulus and exponent (a SubjectPublicKeyInfo in DER).
+ *
+ * @param string $modulus The modulus, big-endian bytes.
+ * @param string $exponent The exponent, big-endian bytes.
+ *
+ * @return string
+ */
+ public static function rsa_pem( string $modulus, string $exponent ): string {
+ $rsa = self::der( 0x30, self::der_integer( $modulus ) . self::der_integer( $exponent ) );
+ $algorithm = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00"; // rsaEncryption, no parameters.
+ $spki = self::der( 0x30, $algorithm . self::der( 0x03, "\x00" . $rsa ) );
+
+ return "-----BEGIN PUBLIC KEY-----\n" . chunk_split( base64_encode( $spki ), 64, "\n" ) . "-----END PUBLIC KEY-----\n"; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- PEM is base64.
+ }
+
+ /**
+ * A DER integer: positive, so a leading 0 when the high bit is set.
+ *
+ * @param string $bytes Big-endian bytes.
+ *
+ * @return string
+ */
+ private static function der_integer( string $bytes ): string {
+ $bytes = ltrim( $bytes, "\x00" );
+ if ( '' === $bytes || ord( $bytes[0] ) > 0x7f ) {
+ $bytes = "\x00" . $bytes;
+ }
+
+ return self::der( 0x02, $bytes );
+ }
+
+ /**
+ * A DER element of a tag and its content.
+ *
+ * @param int $tag The tag.
+ * @param string $content The content.
+ *
+ * @return string
+ */
+ private static function der( int $tag, string $content ): string {
+ $length = strlen( $content );
+ if ( $length < 0x80 ) {
+ return chr( $tag ) . chr( $length ) . $content;
+ }
+ $encoded = ltrim( pack( 'N', $length ), "\x00" );
+
+ return chr( $tag ) . chr( 0x80 | strlen( $encoded ) ) . $encoded . $content;
+ }
+
+ /**
+ * Decode base64url without padding.
+ *
+ * @param string $value The encoded value.
+ *
+ * @return string The bytes, or an empty string when it is not base64url.
+ */
+ private static function b64url_decode( string $value ): string {
+ $decoded = base64_decode( strtr( $value, '-_', '+/' ), true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- JWTs are base64url.
+
+ return false === $decoded ? '' : $decoded;
+ }
+}
diff --git a/tests/Unit/API/RequestTlsTest.php b/tests/Unit/API/RequestTlsTest.php
index 2123834..305e6eb 100644
--- a/tests/Unit/API/RequestTlsTest.php
+++ b/tests/Unit/API/RequestTlsTest.php
@@ -29,6 +29,9 @@ final class RequestTlsTest extends TestCase {
protected function setUp(): void {
parent::setUp();
+ Functions\when( 'get_transient' )->justReturn( false );
+ Functions\when( 'set_transient' )->justReturn( true );
+ Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
$this->captured = [];
$capture = function ( string $url, array $args ) {
@@ -90,7 +93,8 @@ private function send_all(): void {
public function test_every_api_request_verifies_tls_by_default(): void {
$this->send_all();
- $this->assertCount( 4, $this->captured );
+ // the refresh of a connection that has not moved tries the OAuth server, then the legacy route.
+ $this->assertCount( 5, $this->captured );
foreach ( $this->captured as $args ) {
$this->assertTrue( $args['sslverify'] );
}
diff --git a/tests/Unit/Connect/OAuthTest.php b/tests/Unit/Connect/OAuthTest.php
new file mode 100644
index 0000000..9efaa93
--- /dev/null
+++ b/tests/Unit/Connect/OAuthTest.php
@@ -0,0 +1,156 @@
+
+ */
+ private array $transients = [];
+
+ /**
+ * The token requests sent, with their arguments.
+ *
+ * @var array}>
+ */
+ private array $posts = [];
+
+ /**
+ * The next answer of the token endpoint: status and body.
+ *
+ * @var array{int, string}
+ */
+ private array $answer = [ 200, '' ];
+
+ protected function setUp(): void {
+ parent::setUp();
+ Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
+ Functions\when( 'admin_url' )->alias( static fn( $path = '' ) => 'https://wp.scanfully.com/wp-admin/' . $path );
+ Functions\when( 'home_url' )->justReturn( 'https://wp.scanfully.com' );
+ Functions\when( 'add_query_arg' )->alias(
+ static function ( $key, $value, $url ) {
+ return $url . ( false === strpos( $url, '?' ) ? '?' : '&' ) . $key . '=' . $value;
+ }
+ );
+ Functions\when( 'get_current_user_id' )->justReturn( 3 );
+ Functions\when( 'wp_generate_password' )->alias( static fn( $length ) => str_repeat( 'v', $length ) );
+ Functions\when( 'set_transient' )->alias(
+ function ( string $key, $value ) {
+ $this->transients[ $key ] = $value;
+ return true;
+ }
+ );
+ Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false );
+ Functions\when( 'is_wp_error' )->justReturn( false );
+ Functions\when( 'wp_remote_post' )->alias(
+ function ( string $url, array $args ) {
+ $this->posts[] = [ $url, $args ];
+ return $this->answer;
+ }
+ );
+ Functions\when( 'wp_remote_retrieve_response_code' )->alias( static fn( $response ) => $response[0] );
+ Functions\when( 'wp_remote_retrieve_body' )->alias( static fn( $response ) => $response[1] );
+ }
+
+ public function test_a_connection_starts_on_scanfully_oauth_server(): void {
+ $url = OAuth::authorize_url();
+ $this->assertStringStartsWith( 'https://api.scanfully.com/oauth/authorize?', $url );
+ parse_str( (string) parse_url( $url, PHP_URL_QUERY ), $query );
+
+ $this->assertSame( 'wordpress-plugin', $query['client_id'] );
+ $this->assertSame( 'code', $query['response_type'] );
+ $this->assertSame( 'https://api.scanfully.com/v1/sites', $query['resource'] );
+ $this->assertSame( 'wordpress:read', $query['scope'] );
+ $this->assertSame( 'https://wp.scanfully.com', $query['site'] );
+ $this->assertSame( OAuth::redirect_uri(), $query['redirect_uri'] );
+ $this->assertStringStartsWith( 'https://wp.scanfully.com/wp-admin/', $query['redirect_uri'] );
+ $this->assertStringContainsString( 'scanfully-oauth=1', $query['redirect_uri'] );
+ $this->assertSame( 'S256', $query['code_challenge_method'] );
+ $this->assertSame( Controller::code_challenge( Controller::get_code_verifier() ), $query['code_challenge'] );
+ $this->assertSame( Controller::get_state(), $query['state'] );
+ }
+
+ public function test_a_code_is_exchanged_with_its_verifier_and_return_address(): void {
+ $this->answer = [
+ 200,
+ (string) json_encode(
+ [
+ 'access_token' => 'sfy_sat_a',
+ 'refresh_token' => 'sfy_srt_r',
+ 'expires_in' => 2419200,
+ 'scope' => 'wordpress:read',
+ 'site_id' => 'site-1',
+ ]
+ ),
+ ];
+
+ $tokens = OAuth::exchange_code( 'the-code', 'the-verifier' );
+
+ [ $url, $args ] = $this->posts[0];
+ $this->assertSame( 'https://api.scanfully.com/oauth/token', $url );
+ $this->assertSame( 'application/x-www-form-urlencoded', $args['headers']['Content-Type'] );
+ $this->assertSame( 'authorization_code', $args['body']['grant_type'] );
+ $this->assertSame( 'the-verifier', $args['body']['code_verifier'] );
+ $this->assertSame( OAuth::redirect_uri(), $args['body']['redirect_uri'] );
+ $this->assertSame( 'site-1', $tokens['site_id'] );
+ $this->assertSame( [ 'wordpress:read' ], $tokens['scopes'] );
+ $this->assertEqualsWithDelta( time() + 2419200, strtotime( $tokens['expires'] ), 5 );
+ }
+
+ public function test_an_answer_without_tokens_or_expiry_is_nothing(): void {
+ $this->assertSame(
+ [],
+ OAuth::normalize(
+ [
+ 'access_token' => 'a',
+ 'refresh_token' => 'r',
+ ]
+ )
+ );
+ $this->assertSame(
+ [],
+ OAuth::normalize(
+ [
+ 'access_token' => 'a',
+ 'expires_in' => 60,
+ ]
+ )
+ );
+ $this->assertSame(
+ [],
+ OAuth::normalize(
+ [
+ 'access_token' => 'a',
+ 'refresh_token' => 'r',
+ 'expires_in' => 0,
+ ]
+ )
+ );
+ }
+
+ public function test_a_refresh_tells_an_api_without_the_plugin_client_from_a_failure(): void {
+ $this->answer = [ 400, '{"error":"invalid_client"}' ];
+ $this->assertNull( OAuth::refresh( 'r', 'site-1' ) );
+ $this->answer = [ 404, '' ];
+ $this->assertNull( OAuth::refresh( 'r', 'site-1' ) );
+ $this->answer = [ 400, '{"error":"invalid_grant"}' ];
+ $this->assertSame( [], OAuth::refresh( 'r', 'site-1' ) );
+ $this->assertSame( 'site-1', $this->posts[2][1]['body']['site_id'] );
+ }
+}
diff --git a/tests/Unit/Cron/TokenRefreshTest.php b/tests/Unit/Cron/TokenRefreshTest.php
index ad613b5..93d9539 100644
--- a/tests/Unit/Cron/TokenRefreshTest.php
+++ b/tests/Unit/Cron/TokenRefreshTest.php
@@ -49,6 +49,13 @@ final class TokenRefreshTest extends TestCase {
*/
private array $api_response = [ 200, '' ];
+ /**
+ * The addresses of the token requests.
+ *
+ * @var string[]
+ */
+ private array $urls = [];
+
/**
* Runs inside the fake API call, to simulate another process.
*
@@ -77,6 +84,8 @@ protected function setUp(): void {
'scanfully_connect_expires' => gmdate( 'Y-m-d H:i:s', time() + HOUR_IN_SECONDS ),
'scanfully_connect_last_used' => '',
'scanfully_connect_date_connected' => '',
+ // a connection on the OAuth server; the move from a legacy one has tests of its own.
+ 'scanfully_connect_flow' => 'oauth',
];
$this->api_response = [ 200, $this->token_body( 'new-access', 'new-refresh' ) ];
$this->token_requests = 0;
@@ -90,6 +99,7 @@ function ( string $name, $value ) {
}
);
Functions\when( 'wp_cache_delete' )->justReturn( true );
+ Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false );
Functions\when( 'set_transient' )->alias(
function ( string $key, $value ) {
@@ -106,8 +116,9 @@ function ( string $key ) {
Functions\when( 'wp_json_encode' )->alias( static fn( $data ) => json_encode( $data ) ); // phpcs:ignore WordPress.WP.AlternativeFunctions.json_encode_json_encode -- WordPress is not loaded in unit tests.
Functions\when( 'is_wp_error' )->justReturn( false );
Functions\when( 'wp_remote_post' )->alias(
- function () {
+ function ( string $url ) {
++$this->token_requests;
+ $this->urls[] = $url;
if ( null !== $this->during_request ) {
( $this->during_request )();
}
@@ -136,6 +147,9 @@ private function token_body( string $access, string $refresh ): string {
[
'access_token' => $access,
'refresh_token' => $refresh,
+ // the OAuth server's answer, and the legacy route's expiry.
+ 'expires_in' => 28 * DAY_IN_SECONDS,
+ 'scope' => 'wordpress:read',
'expires' => gmdate( 'Y-m-d\TH:i:s\Z', time() + 28 * DAY_IN_SECONDS ),
'site_id' => 'site-1',
]
@@ -253,7 +267,7 @@ public function provide_failed_responses(): array {
}
public function test_the_site_id_falls_back_to_the_stored_one(): void {
- $this->api_response = [ 200, '{"access_token":"a","refresh_token":"r","expires":"2030-01-01T00:00:00Z"}' ];
+ $this->api_response = [ 200, '{"access_token":"a","refresh_token":"r","expires_in":2419200,"expires":"2030-01-01T00:00:00Z"}' ];
$this->refresh();
@@ -269,6 +283,75 @@ public function test_an_unparsable_stored_expiry_triggers_a_refresh(): void {
$this->assertSame( 1, $this->token_requests );
$this->assertSame( 'new-access', $this->options['scanfully_connect_access_token'] );
}
+
+ public function test_a_legacy_connection_moves_to_the_oauth_server_once(): void {
+ unset( $this->options['scanfully_connect_flow'] );
+ $this->options['scanfully_connect_expires'] = gmdate( 'Y-m-d H:i:s', time() + 10 * DAY_IN_SECONDS );
+
+ $this->refresh();
+
+ $this->assertSame( 1, $this->token_requests );
+ $this->assertStringEndsWith( '/oauth/token', $this->urls[0] );
+ $this->assertSame( 'new-access', $this->options['scanfully_connect_access_token'] );
+ $this->assertSame( 'oauth', $this->options['scanfully_connect_flow'] );
+ $this->assertSame( 'wordpress:read', $this->options['scanfully_connect_scopes'] );
+
+ $this->refresh();
+ $this->assertSame( 1, $this->token_requests, 'moved: no refresh until the token expires' );
+ }
+
+ public function test_a_failed_move_keeps_the_tokens_and_is_no_broken_connection(): void {
+ unset( $this->options['scanfully_connect_flow'] );
+ $this->options['scanfully_connect_expires'] = gmdate( 'Y-m-d H:i:s', time() + 10 * DAY_IN_SECONDS );
+ $this->api_response = [ 502, '' ];
+
+ $this->refresh();
+
+ $this->assertSame( 'old-access', $this->options['scanfully_connect_access_token'] );
+ $this->assertArrayNotHasKey( 'scanfully_refresh_failures', $this->transients );
+ $this->assertArrayHasKey( 'scanfully_oauth_unavailable', $this->transients );
+
+ $this->refresh();
+ $this->assertSame( 1, $this->token_requests, 'the move waits a day' );
+ }
+
+ public function test_a_legacy_connection_the_oauth_server_refuses_refreshes_on_the_legacy_route_when_expiring(): void {
+ unset( $this->options['scanfully_connect_flow'] );
+ $replies = [ [ 400, '{"error":"invalid_grant"}' ], [ 200, $this->token_body( 'legacy-access', 'legacy-refresh' ) ] ];
+ $this->during_request = function () use ( &$replies ) {
+ $this->api_response = array_shift( $replies );
+ };
+
+ $this->refresh();
+
+ $this->assertSame( 2, $this->token_requests );
+ $this->assertSame( 'legacy-access', $this->options['scanfully_connect_access_token'] );
+ }
+
+ public function test_a_moved_connection_the_oauth_server_refuses_is_a_failure(): void {
+ $this->api_response = [ 400, '{"error":"invalid_grant"}' ];
+
+ $this->refresh();
+
+ $this->assertSame( 1, $this->token_requests );
+ $this->assertSame( 1, $this->transients['scanfully_refresh_failures'] ?? 0 );
+ }
+
+ public function test_an_api_without_the_plugin_client_refreshes_an_expiring_token_on_the_legacy_route(): void {
+ unset( $this->options['scanfully_connect_flow'] );
+ $replies = [ [ 400, '{"error":"invalid_client"}' ], [ 200, $this->token_body( 'legacy-access', 'legacy-refresh' ) ] ];
+ $this->during_request = function () use ( &$replies ) {
+ $this->api_response = array_shift( $replies );
+ };
+
+ $this->refresh();
+
+ $this->assertSame( 2, $this->token_requests );
+ $this->assertStringEndsWith( '/oauth/token', $this->urls[0] );
+ $this->assertStringEndsWith( '/connect/token', $this->urls[1] );
+ $this->assertSame( 'legacy-access', $this->options['scanfully_connect_access_token'] );
+ $this->assertArrayNotHasKey( 'scanfully_connect_flow', $this->options );
+ }
}
/**
diff --git a/tests/Unit/Sync/SignedRequestTest.php b/tests/Unit/Sync/SignedRequestTest.php
new file mode 100644
index 0000000..f72676a
--- /dev/null
+++ b/tests/Unit/Sync/SignedRequestTest.php
@@ -0,0 +1,209 @@
+
+ */
+ private array $transients = [];
+
+ /**
+ * How often the key set was fetched.
+ *
+ * @var int
+ */
+ private int $fetches = 0;
+
+ public static function setUpBeforeClass(): void {
+ parent::setUpBeforeClass();
+ self::$key = openssl_pkey_new(
+ [
+ 'private_key_bits' => 2048,
+ 'private_key_type' => OPENSSL_KEYTYPE_RSA,
+ ]
+ );
+ $details = openssl_pkey_get_details( self::$key );
+ self::$jwks = (string) json_encode(
+ [
+ 'keys' => [
+ [
+ 'kty' => 'RSA',
+ 'use' => 'sig',
+ 'alg' => 'RS256',
+ 'kid' => 'key-1',
+ 'n' => self::b64url( $details['rsa']['n'] ),
+ 'e' => self::b64url( $details['rsa']['e'] ),
+ ],
+ ],
+ ]
+ );
+ }
+
+ protected function setUp(): void {
+ parent::setUp();
+ Functions\when( 'wp_parse_url' )->alias( 'parse_url' );
+ Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false );
+ Functions\when( 'set_transient' )->alias(
+ function ( string $key, $value ) {
+ $this->transients[ $key ] = $value;
+ return true;
+ }
+ );
+ Functions\when( 'is_wp_error' )->justReturn( false );
+ Functions\when( 'wp_remote_get' )->alias(
+ function ( string $url ) {
+ $this->assertSame( self::ISSUER . SignedRequest::KEYS_PATH, $url );
+ ++$this->fetches;
+ return [ 'body' => self::$jwks ];
+ }
+ );
+ Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 200 );
+ Functions\when( 'wp_remote_retrieve_body' )->alias( fn( $resp ) => $resp['body'] );
+ }
+
+ private static function b64url( string $bytes ): string {
+ return rtrim( strtr( base64_encode( $bytes ), '+/', '-_' ), '=' );
+ }
+
+ /**
+ * A request signed as the API signs it, with claims changed.
+ *
+ * @param array $claims Claims to change.
+ * @param string $kid The key id.
+ */
+ private function signed( array $claims = [], string $kid = 'key-1' ): string {
+ $now = time();
+ $header = self::b64url(
+ (string) json_encode(
+ [
+ 'alg' => 'RS256',
+ 'typ' => 'JWT',
+ 'kid' => $kid,
+ ]
+ )
+ );
+ $payload = self::b64url(
+ (string) json_encode(
+ array_merge(
+ [
+ 'iss' => self::ISSUER,
+ 'sub' => 'sync',
+ 'aud' => [ self::SITE ],
+ 'iat' => $now,
+ 'nbf' => $now - 60,
+ 'exp' => $now + 300,
+ 'jti' => bin2hex( random_bytes( 8 ) ),
+ 'scope' => 'wordpress:read',
+ ],
+ $claims
+ )
+ )
+ );
+ openssl_sign( $header . '.' . $payload, $signature, self::$key, OPENSSL_ALGO_SHA256 );
+
+ return $header . '.' . $payload . '.' . self::b64url( $signature );
+ }
+
+ private function verify( string $token ): bool {
+ return SignedRequest::verify( $token, self::SITE, 'sync', 'wordpress:read' );
+ }
+
+ public function test_a_request_scanfully_signed_for_the_site_passes_once(): void {
+ $token = $this->signed();
+ $this->assertTrue( SignedRequest::looks_signed( $token ) );
+ $this->assertTrue( $this->verify( $token ) );
+ $this->assertFalse( $this->verify( $token ), 'a replayed request' );
+ $this->assertTrue( $this->verify( $this->signed() ) );
+ $this->assertSame( 1, $this->fetches, 'the key set is cached' );
+ }
+
+ public function test_a_request_for_another_site_action_or_scope_fails(): void {
+ $this->assertFalse( $this->verify( $this->signed( [ 'aud' => [ 'site-2' ] ] ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [ 'sub' => 'login' ] ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [ 'scope' => 'wordpress:update' ] ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [ 'iss' => 'https://evil.scanfully.dev' ] ) ) );
+ $this->assertTrue( $this->verify( $this->signed( [ 'aud' => self::SITE ] ) ), 'a single audience' );
+ }
+
+ public function test_times_allow_some_clock_skew_only(): void {
+ $this->assertTrue( $this->verify( $this->signed( [ 'exp' => time() - 60 ] ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [ 'exp' => time() - SignedRequest::LEEWAY - 60 ] ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [ 'nbf' => time() + SignedRequest::LEEWAY + 60 ] ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [ 'jti' => '' ] ) ) );
+ }
+
+ public function test_a_forged_or_tampered_request_fails(): void {
+ $token = $this->signed();
+ [ $header, $payload, $signature ] = explode( '.', $token );
+ $other = self::b64url(
+ (string) json_encode(
+ [
+ 'iss' => self::ISSUER,
+ 'sub' => 'sync',
+ 'aud' => self::SITE,
+ 'exp' => time() + 60,
+ 'jti' => 'x',
+ 'scope' => 'wordpress:read',
+ ]
+ )
+ );
+ $this->assertFalse( $this->verify( $header . '.' . $other . '.' . $signature ), 'another payload' );
+ $none = self::b64url(
+ (string) json_encode(
+ [
+ 'alg' => 'none',
+ 'kid' => 'key-1',
+ ]
+ )
+ );
+ $this->assertFalse( $this->verify( $none . '.' . $payload . '.' ), 'alg none' );
+ $this->assertFalse( $this->verify( 'not.a.token' ) );
+ }
+
+ public function test_an_unknown_key_is_fetched_again_a_few_minutes_apart(): void {
+ $this->assertTrue( $this->verify( $this->signed() ) );
+ $this->assertFalse( $this->verify( $this->signed( [], 'key-2' ) ) );
+ $this->assertFalse( $this->verify( $this->signed( [], 'key-3' ) ) );
+ $this->assertSame( 1, $this->fetches, 'one fetch, then the refetch waits' );
+ }
+
+ public function test_the_key_set_becomes_pem_keys(): void {
+ $keys = SignedRequest::parse_keys( self::$jwks );
+ $this->assertArrayHasKey( 'key-1', $keys );
+ $this->assertNotFalse( openssl_pkey_get_public( $keys['key-1'] ) );
+ $this->assertNull( SignedRequest::parse_keys( 'not json' ) );
+ }
+}