From 6c0560e6034b6ec6ddbf62ace7be6c3f8ac4fe41 Mon Sep 17 00:00:00 2001 From: Barry Kooij Date: Thu, 1 Oct 2026 22:52:04 +0200 Subject: [PATCH] Security: the connect request carries a PKCE challenge and the code exchange its verifier, so an authorization code that ends up anywhere else cannot be exchanged for tokens --- src/Connect/Controller.php | 100 +++++++++++--- tests/Unit/Connect/ControllerPkceTest.php | 153 ++++++++++++++++++++++ 2 files changed, 237 insertions(+), 16 deletions(-) create mode 100644 tests/Unit/Connect/ControllerPkceTest.php diff --git a/src/Connect/Controller.php b/src/Connect/Controller.php index 5dc668c..355a7bb 100644 --- a/src/Connect/Controller.php +++ b/src/Connect/Controller.php @@ -96,9 +96,11 @@ private static function handle_connect_start(): void { // the WordPress installation URL (which may be in a subdirectory). $connect_url = add_query_arg( [ - 'redirect_uri' => rawurlencode( Page::get_page_url() ), - 'site' => rawurlencode( home_url() ), - 'state' => self::generate_state(), + 'redirect_uri' => rawurlencode( Page::get_page_url() ), + 'site' => rawurlencode( home_url() ), + 'state' => self::generate_state(), + 'code_challenge' => self::code_challenge( self::generate_code_verifier() ), + 'code_challenge_method' => 'S256', ], Main::get_connect_url() ); @@ -157,9 +159,11 @@ private static function handle_reconnect(): void { // build the connect URL and redirect directly into the connect flow. $connect_url = add_query_arg( [ - 'redirect_uri' => rawurlencode( Page::get_page_url() ), - 'site' => rawurlencode( home_url() ), - 'state' => self::generate_state(), + 'redirect_uri' => rawurlencode( Page::get_page_url() ), + 'site' => rawurlencode( home_url() ), + 'state' => self::generate_state(), + 'code_challenge' => self::code_challenge( self::generate_code_verifier() ), + 'code_challenge_method' => 'S256', ], Main::get_connect_url() ); @@ -198,13 +202,18 @@ private static function handle_request_connect_success(): void { $code = sanitize_text_field( wp_unslash( $_GET['code'] ) ); $site = sanitize_text_field( wp_unslash( $_GET['site'] ) ); + // the PKCE verifier proves to the API that this site started the + // connect request; like the state, it is single use. + $verifier = self::get_code_verifier(); + self::delete_code_verifier(); + // the site ID ends up in API URL paths, so only allow plain ID characters. if ( 1 !== preg_match( '/^[A-Za-z0-9_-]{1,64}\z/', $site ) ) { wp_die( 'Invalid Scanfully connect parameters' ); } // exchange authorization code for access token. - $tokens = self::exchange_authorization_code( $code, $site ); + $tokens = self::exchange_authorization_code( $code, $site, $verifier ); // validate token response so we fail gracefully if the API is unreachable or returned an error. if ( empty( $tokens['access_token'] ) @@ -307,11 +316,21 @@ function () use ( $message, $type ) { * Exchange the authorization code for an access and refresh token. * * @param string $code The authorization code. - * @param string $site The Scanfully site ID. + * @param string $site The Scanfully site ID. + * @param string $verifier The PKCE code verifier of the connect request, or an empty string without one. * * @return array The token response (access_token, refresh_token, expires), or an empty array on failure. */ - private static function exchange_authorization_code( string $code, string $site ): array { + private static function exchange_authorization_code( string $code, string $site, string $verifier ): array { + + $body = [ + 'grant_type' => 'authorization_code', + 'code' => $code, + 'site_id' => $site, + ]; + if ( '' !== $verifier ) { + $body['code_verifier'] = $verifier; + } // request arguments for the requests. $request_args = [ @@ -320,13 +339,7 @@ private static function exchange_authorization_code( string $code, string $site 'blocking' => true, 'httpversion' => '1.0', 'sslverify' => Main::get_sslverify(), - 'body' => wp_json_encode( - [ - 'grant_type' => 'authorization_code', - 'code' => $code, - 'site_id' => $site, - ] - ), + 'body' => wp_json_encode( $body ), ]; // later check if post failed and show a notice to admins. @@ -482,4 +495,59 @@ public static function delete_state(): void { private static function get_state_key(): string { return 'scanfully_connect_state_' . get_current_user_id(); } + + /** + * Generate and store the PKCE code verifier (RFC 7636) for a connect + * request of the current user. The API only exchanges the code for a + * request that started with its challenge for the verifier, so a code + * that ends up elsewhere is worthless. + * + * @return string The verifier: 64 random letters and digits. + */ + public static function generate_code_verifier(): string { + $verifier = wp_generate_password( 64, false, false ); + set_transient( self::get_code_verifier_key(), $verifier, 15 * MINUTE_IN_SECONDS ); + + return $verifier; + } + + /** + * Get the stored PKCE code verifier of the current user. + * + * @return string The verifier, or an empty string when there is none. + */ + public static function get_code_verifier(): string { + $verifier = get_transient( self::get_code_verifier_key() ); + + return is_string( $verifier ) ? $verifier : ''; + } + + /** + * Delete the stored PKCE code verifier of the current user. + * + * @return void + */ + public static function delete_code_verifier(): void { + delete_transient( self::get_code_verifier_key() ); + } + + /** + * The S256 challenge of a code verifier: its SHA-256, base64url without padding. + * + * @param string $verifier The code verifier. + * + * @return string + */ + public static function code_challenge( string $verifier ): string { + return rtrim( strtr( base64_encode( hash( 'sha256', $verifier, true ) ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- base64url is the encoding RFC 7636 requires. + } + + /** + * Get the transient key holding the PKCE code verifier for the current user. + * + * @return string + */ + private static function get_code_verifier_key(): string { + return 'scanfully_connect_verifier_' . get_current_user_id(); + } } \ No newline at end of file diff --git a/tests/Unit/Connect/ControllerPkceTest.php b/tests/Unit/Connect/ControllerPkceTest.php new file mode 100644 index 0000000..4056559 --- /dev/null +++ b/tests/Unit/Connect/ControllerPkceTest.php @@ -0,0 +1,153 @@ + + */ + private array $transients = []; + + /** + * Transient lifetimes, keyed by transient name. + * + * @var array + */ + private array $expirations = []; + + protected function setUp(): void { + parent::setUp(); + $_GET = []; + + Functions\when( 'get_current_user_id' )->justReturn( 7 ); + Functions\when( 'current_user_can' )->justReturn( true ); + Functions\when( 'wp_unslash' )->returnArg(); + Functions\when( 'sanitize_text_field' )->returnArg(); + Functions\when( 'wp_json_encode' )->alias( 'json_encode' ); + Functions\when( 'set_transient' )->alias( + function ( string $key, $value, int $expiration ) { + $this->transients[ $key ] = $value; + $this->expirations[ $key ] = $expiration; + return true; + } + ); + Functions\when( 'get_transient' )->alias( fn( string $key ) => $this->transients[ $key ] ?? false ); + Functions\when( 'delete_transient' )->alias( + function ( string $key ) { + unset( $this->transients[ $key ] ); + return true; + } + ); + Functions\when( 'wp_die' )->alias( + static function ( $message ) { + throw new RuntimeException( (string) $message ); + } + ); + } + + protected function tearDown(): void { + $_GET = []; + parent::tearDown(); + } + + public function test_the_verifier_is_64_random_characters_per_user_for_fifteen_minutes(): void { + Functions\when( 'wp_generate_password' )->alias( static fn( $length ) => str_repeat( 'b', $length ) ); + + $verifier = Controller::generate_code_verifier(); + + $this->assertSame( 64, strlen( $verifier ) ); + $this->assertSame( $verifier, $this->transients['scanfully_connect_verifier_7'] ); + $this->assertSame( 15 * MINUTE_IN_SECONDS, $this->expirations['scanfully_connect_verifier_7'] ); + $this->assertSame( $verifier, Controller::get_code_verifier() ); + } + + public function test_the_challenge_is_the_s256_of_rfc_7636(): void { + $this->assertSame( + 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + Controller::code_challenge( 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' ) + ); + } + + public function test_the_exchange_sends_the_verifier_once(): void { + $this->transients['scanfully_connect_state_7'] = 'the-state'; + $this->transients['scanfully_connect_verifier_7'] = 'the-verifier'; + + $sent = null; + Functions\expect( 'wp_remote_post' )->once()->andReturnUsing( + static function ( $url, $args ) use ( &$sent ) { + $sent = json_decode( $args['body'], true ); + return [ 'response' => [ 'code' => 400 ] ]; + } + ); + Functions\when( 'is_wp_error' )->justReturn( false ); + Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 400 ); + + $_GET = [ + 'scanfully-connect-success' => 'true', + 'state' => 'the-state', + 'code' => 'the-code', + 'site' => 'site-1', + ]; + try { + Controller::catch_connect_requests(); + $this->fail( 'A refused exchange did not stop the request.' ); + } catch ( RuntimeException $e ) { + $this->assertStringContainsString( 'Could not complete Scanfully connection', $e->getMessage() ); + } + + $this->assertSame( + [ + 'grant_type' => 'authorization_code', + 'code' => 'the-code', + 'site_id' => 'site-1', + 'code_verifier' => 'the-verifier', + ], + $sent + ); + $this->assertArrayNotHasKey( 'scanfully_connect_verifier_7', $this->transients ); + } + + public function test_without_a_stored_verifier_the_exchange_sends_none(): void { + $this->transients['scanfully_connect_state_7'] = 'the-state'; + + $sent = null; + Functions\expect( 'wp_remote_post' )->once()->andReturnUsing( + static function ( $url, $args ) use ( &$sent ) { + $sent = json_decode( $args['body'], true ); + return [ 'response' => [ 'code' => 400 ] ]; + } + ); + Functions\when( 'is_wp_error' )->justReturn( false ); + Functions\when( 'wp_remote_retrieve_response_code' )->justReturn( 400 ); + + $_GET = [ + 'scanfully-connect-success' => 'true', + 'state' => 'the-state', + 'code' => 'the-code', + 'site' => 'site-1', + ]; + try { + Controller::catch_connect_requests(); + } catch ( RuntimeException $e ) { + // The refused exchange stops the request. + } + + $this->assertArrayNotHasKey( 'code_verifier', (array) $sent ); + } +}