diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..d92e756 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,5 @@ +# scanfully-plugin + +Repository instructions, shared with VS Code Copilot: + +@.github/copilot-instructions.md diff --git a/readme.txt b/readme.txt index d367c30..a0c322b 100644 --- a/readme.txt +++ b/readme.txt @@ -4,7 +4,7 @@ Donate link: https://scanfully.com Tags: monitoring, site health, broken links, broken media, activity log Requires at least: 6.0 Tested up to: 7.1.0 -Stable tag: 1.7.0 +Stable tag: 1.8.0 License: GPLv3 or later License URI: http://www.gnu.org/licenses/gpl-3.0.html Requires PHP: 7.4 @@ -131,7 +131,7 @@ This helps you detect problems affecting contact forms, password resets, WooComm Scanfully notifies you when monitored events need your attention. -You decide where those notifications should go using [notification channels](https://scanfully.com/docs/channels/). +You decide where those notifications should go using [notification channels](https://docs.scanfully.com/notifications/). Scanfully currently supports email, Slack, Discord, and Pushover. @@ -206,6 +206,13 @@ Scanfully is designed to keep monitoring work away from frontend page loads. The == Changelog == += 1.8.0: October 13, 2026 = +* Added: site data includes each plugin's latest version from WordPress's own update check, so Scanfully can show which plugins have an update +* Changed: help center and notification channels links now point to docs.scanfully.com +* Fixed: a sync requested from the dashboard now runs right away instead of waiting for the next visit to the site or for the pending regular syncs +* Fixed: jobs scheduled within ten minutes of an uninstall being stored under the deleted Action Scheduler group +* Security: the connect flow uses PKCE, so an authorization code that ends up anywhere else cannot be exchanged for tokens + = 1.7.0: September 21, 2026 = * Added: WooCommerce checkout monitoring support. * Added: PHPCS, PHPStan, PHPUnit and wp-env tooling with composer scripts and QA workflow diff --git a/scanfully.php b/scanfully.php index 933c66d..4ff45c7 100644 --- a/scanfully.php +++ b/scanfully.php @@ -8,7 +8,7 @@ * * @wordpress-plugin * Plugin Name: Scanfully - * Version: 1.7.0 + * Version: 1.8.0 * Plugin URI: https://scanfully.com/wp-plugin * Description: Scanfully is your favorite WordPress performance and health monitoring tool. * Author: Scanfully @@ -68,7 +68,7 @@ function Scanfully(): \Scanfully\Main { // phpcs:ignore WordPress.NamingConventi function () { // meta. define( 'SCANFULLY_PLUGIN_FILE', __FILE__ ); - define( 'SCANFULLY_VERSION', '1.7.0' ); + define( 'SCANFULLY_VERSION', '1.8.0' ); // boot. require __DIR__ . '/vendor/autoload.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/src/Connect/Page.php b/src/Connect/Page.php index d64970c..301d79b 100644 --- a/src/Connect/Page.php +++ b/src/Connect/Page.php @@ -165,7 +165,7 @@ public static function render_page(): void { '.' === $folder ? basename( $basename, '.php' ) : $folder, 'url' => $plugin['PluginURI'], 'version' => $plugin['Version'], + 'latest_version' => self::get_latest_version( $updates, $plugin_path ), 'description' => $plugin['Description'], 'author' => $plugin['Author'], 'author_uri' => $plugin['AuthorURI'], @@ -400,6 +402,34 @@ private static function get_plugins(): array { return $map; } + /** + * Get the latest version of a plugin as WordPress's own update check knows + * it, which covers premium plugins with their own updater too. + * + * @param mixed $updates The update_plugins site transient. + * @param string $plugin_path The plugin's file, relative to the plugins folder. + * + * @return string|null The latest version, or null when WordPress does not know it. + */ + private static function get_latest_version( $updates, string $plugin_path ): ?string { + if ( ! is_object( $updates ) ) { + return null; + } + + // "response" holds the plugins with an update, "no_update" the ones + // that are up to date. + foreach ( [ 'response', 'no_update' ] as $list ) { + $item = $updates->{$list}[ $plugin_path ] ?? null; + // Some third-party updaters add an array instead of an object. + $version = is_array( $item ) ? ( $item['new_version'] ?? null ) : ( is_object( $item ) ? ( $item->new_version ?? null ) : null ); + if ( is_scalar( $version ) && '' !== (string) $version ) { + return (string) $version; + } + } + + return null; + } + /** * Get the site data sent to Scanfully. * diff --git a/src/Sync/Controller.php b/src/Sync/Controller.php index ae9b5d7..7053ff8 100644 --- a/src/Sync/Controller.php +++ b/src/Sync/Controller.php @@ -113,7 +113,8 @@ private static function get_request_token( \WP_REST_Request $request ): string { /** * Handle an on-demand sync request. Schedules the existing health and - * directory syncs to run as soon as possible and returns immediately. + * directory syncs, starts the queue runner so they run now, and returns + * immediately. * * @return \WP_REST_Response */ @@ -137,6 +138,7 @@ public static function handle_sync(): \WP_REST_Response { set_transient( self::RATE_LIMIT_TRANSIENT, time(), self::RATE_LIMIT_WINDOW ); self::schedule_syncs(); + self::run_queue_now(); return new \WP_REST_Response( [ 'status' => 'scheduled' ], 202 ); } @@ -153,8 +155,32 @@ private static function schedule_syncs(): void { return; } - // Unique: parallel requests can't queue duplicate syncs. - as_schedule_single_action( time(), Cron\Controller::ACTION_SYNC_SITE_HEALTH, [], self::AS_GROUP, true ); - as_schedule_single_action( time(), Cron\Controller::ACTION_SYNC_DIRECTORIES, [], self::AS_GROUP, true ); + // Not unique: a unique action is skipped while another one with the + // same hook is pending, and the recurring syncs always are, so the + // request would queue nothing. The rate limit bounds the duplicates. + as_schedule_single_action( time(), Cron\Controller::ACTION_SYNC_SITE_HEALTH, [], self::AS_GROUP ); + as_schedule_single_action( time(), Cron\Controller::ACTION_SYNC_DIRECTORIES, [], self::AS_GROUP ); + } + + /** + * Start Action Scheduler's queue runner now, with the non-blocking + * loopback request (admin-ajax) it sends itself on admin pages. Without + * it the syncs wait for WP-Cron, which only runs on a later visit, so a + * quiet site would not sync until someone loads a page. The runner still + * decides for itself: it only runs with actions due, below its limit of + * concurrent batches, and when no filter turned async requests off. + * + * @return void + */ + private static function run_queue_now(): void { + if ( ! class_exists( 'ActionScheduler' ) || ! class_exists( 'ActionScheduler_AsyncRequest_QueueRunner' ) ) { + return; + } + + // The lock keeps the admin shutdown hook from dispatching a second + // runner within its minute; a runner it already started picks up the + // new actions or dispatches again when it finishes. + \ActionScheduler::lock()->set( 'async-request-runner' ); + ( new \ActionScheduler_AsyncRequest_QueueRunner( \ActionScheduler::store() ) )->maybe_dispatch(); } } diff --git a/tests/Integration/CleanupTest.php b/tests/Integration/CleanupTest.php index e4c3ab9..f7c0700 100644 --- a/tests/Integration/CleanupTest.php +++ b/tests/Integration/CleanupTest.php @@ -173,6 +173,24 @@ public function test_uninstall_removes_options_transients_jobs_and_the_probe_use delete_option( 'unrelated_option_kept' ); } + /** + * Action Scheduler caches group ids, so a job scheduled after uninstall (a + * reinstall, or the next test) must not reuse the deleted group's id. + * + * @depends test_uninstall_keeps_an_account_that_is_not_the_probe_user + */ + public function test_jobs_scheduled_after_uninstall_are_found_by_their_group(): void { + $this->schedule_jobs(); + + scanfully_uninstall_site(); + $this->schedule_jobs(); + + $this->assertSame( 2, $this->pending_jobs() ); + + as_unschedule_all_actions( '', [], 'scanfully' ); + $this->assertSame( 0, $this->pending_jobs() ); + } + /** * @depends test_uninstall_keeps_an_account_that_is_not_the_probe_user */ diff --git a/tests/Integration/EventSendFailureTest.php b/tests/Integration/EventSendFailureTest.php index 37f4f60..b020ae1 100644 --- a/tests/Integration/EventSendFailureTest.php +++ b/tests/Integration/EventSendFailureTest.php @@ -75,6 +75,7 @@ public function test_a_server_error_marks_the_job_failed_and_queues_a_retry(): v [ 'hook' => EventsController::ACTION_SEND_EVENT, 'args' => [ 'PostSaved', [ 'id' => 1 ], [ 'id' => 2 ], 1 ], + 'group' => 'scanfully', 'status' => \ActionScheduler_Store::STATUS_PENDING, 'per_page' => -1, ], diff --git a/tests/Integration/SyncEndpointTest.php b/tests/Integration/SyncEndpointTest.php index 023233a..9e4d3d2 100644 --- a/tests/Integration/SyncEndpointTest.php +++ b/tests/Integration/SyncEndpointTest.php @@ -28,6 +28,7 @@ protected function setUp(): void { update_option( 'scanfully_connect_is_connected', 'yes' ); update_option( 'scanfully_connect_access_token', self::TOKEN ); delete_transient( 'scanfully_sync_last_run' ); + $this->unschedule_syncs(); } protected function tearDown(): void { @@ -35,10 +36,23 @@ protected function tearDown(): void { delete_option( 'scanfully_connect_is_connected' ); delete_option( 'scanfully_connect_access_token' ); delete_transient( 'scanfully_sync_last_run' ); + $this->unschedule_syncs(); } parent::tearDown(); } + /** + * Remove the sync jobs every accepted request queues. + * + * @return void + */ + private function unschedule_syncs(): void { + if ( function_exists( 'as_unschedule_all_actions' ) ) { + as_unschedule_all_actions( 'scanfully_sync_site_health', [], 'scanfully' ); + as_unschedule_all_actions( 'scanfully_sync_directories', [], 'scanfully' ); + } + } + /** * Dispatch a POST to the sync route. * @@ -69,4 +83,88 @@ public function test_the_access_token_is_accepted(): void { public function test_the_fallback_header_is_accepted(): void { $this->assertSame( 202, $this->post_sync( [ 'X-Scanfully-Token' => self::TOKEN ] ) ); } + + public function test_a_sync_queues_jobs_due_now_while_the_recurring_syncs_are_pending(): void { + if ( ! function_exists( 'as_schedule_recurring_action' ) ) { + $this->markTestSkipped( 'Action Scheduler not loaded.' ); + } + + // A connected site always has these pending, hours ahead. + as_schedule_recurring_action( time() + HOUR_IN_SECONDS, 3 * HOUR_IN_SECONDS, 'scanfully_sync_site_health', [], 'scanfully', true ); + as_schedule_recurring_action( time() + HOUR_IN_SECONDS, DAY_IN_SECONDS, 'scanfully_sync_directories', [], 'scanfully', true ); + + $block = static fn() => [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 200, + 'message' => 'OK', + ], + 'cookies' => [], + ]; + add_filter( 'pre_http_request', $block ); + + $due = static fn( string $hook ): int => count( + as_get_scheduled_actions( + [ + 'hook' => $hook, + 'group' => 'scanfully', + 'status' => \ActionScheduler_Store::STATUS_PENDING, + 'date' => gmdate( 'Y-m-d H:i:s', time() + 60 ), + 'date_compare' => '<=', + 'per_page' => -1, + ], + 'ids' + ) + ); + + try { + $this->assertSame( 202, $this->post_sync( [ 'Authorization' => 'Bearer ' . self::TOKEN ] ) ); + + foreach ( [ 'scanfully_sync_site_health', 'scanfully_sync_directories' ] as $hook ) { + $this->assertSame( 1, $due( $hook ), $hook . ' must run now, not with the recurring sync.' ); + } + } finally { + remove_filter( 'pre_http_request', $block ); + } + } + + public function test_an_accepted_sync_starts_the_queue_runner_now(): void { + if ( ! class_exists( \ActionScheduler::class ) ) { + $this->markTestSkipped( 'Action Scheduler not loaded.' ); + } + + // Catch the runner's loopback request instead of sending it. + $requests = []; + $catch = static function ( $response, array $args, string $url ) use ( &$requests ) { + $requests[] = [ + 'url' => $url, + 'args' => $args, + ]; + return [ + 'headers' => [], + 'body' => '', + 'response' => [ + 'code' => 200, + 'message' => 'OK', + ], + 'cookies' => [], + ]; + }; + add_filter( 'pre_http_request', $catch, 10, 3 ); + \ActionScheduler::lock()->set( 'async-request-runner' ); // as if an admin page just started a runner. + + try { + $this->assertSame( 202, $this->post_sync( [ 'Authorization' => 'Bearer ' . self::TOKEN ] ) ); + } finally { + remove_filter( 'pre_http_request', $catch, 10 ); + } + + $runners = array_filter( + $requests, + static fn( array $request ) => false !== strpos( $request['url'], 'admin-ajax.php' ) && false !== strpos( $request['url'], 'as_async_request_queue_runner' ) + ); + $this->assertCount( 1, $runners, 'The sync must start the queue runner, not wait for WP-Cron.' ); + $this->assertFalse( reset( $runners )['args']['blocking'], 'The runner request must not hold up the response.' ); + } } 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 ); + } +} diff --git a/tests/Unit/Health/LatestVersionTest.php b/tests/Unit/Health/LatestVersionTest.php new file mode 100644 index 0000000..58416f6 --- /dev/null +++ b/tests/Unit/Health/LatestVersionTest.php @@ -0,0 +1,104 @@ +> + */ + private function plugins( $updates ): array { + Functions\when( 'get_plugins' )->justReturn( + [ + 'akismet/akismet.php' => $this->header( 'Akismet', '5.3' ), + 'premium/premium.php' => $this->header( 'Premium', '2.0' ), + 'hello.php' => $this->header( 'Hello Dolly', '1.7.2' ), + 'custom-plugin/custom.php' => $this->header( 'Custom', '1.0' ), + ] + ); + Functions\when( 'get_site_transient' )->justReturn( $updates ); + Functions\when( 'plugin_basename' )->returnArg(); + Functions\when( 'is_plugin_active' )->justReturn( true ); + + $method = new ReflectionMethod( Controller::class, 'get_plugins' ); + $method->setAccessible( true ); + + return array_column( $method->invoke( null ), null, 'slug' ); + } + + /** + * A plugin header as get_plugins() returns it. + * + * @param string $name Name. + * @param string $version Version. + * + * @return array + */ + private function header( string $name, string $version ): array { + return [ + 'Name' => $name, + 'PluginURI' => '', + 'Version' => $version, + 'Description' => '', + 'Author' => '', + 'AuthorURI' => '', + ]; + } + + public function test_the_latest_version_comes_from_the_update_check(): void { + $updates = (object) [ + 'response' => [ + 'akismet/akismet.php' => (object) [ 'new_version' => '5.7.2' ], + // A third-party updater that adds an array. + 'premium/premium.php' => [ 'new_version' => '2.1' ], + ], + 'no_update' => [ + 'hello.php' => (object) [ 'new_version' => '1.7.2' ], + ], + ]; + + $plugins = $this->plugins( $updates ); + + $this->assertSame( '5.7.2', $plugins['akismet']['latest_version'] ); + $this->assertSame( '2.1', $plugins['premium']['latest_version'] ); + $this->assertSame( '1.7.2', $plugins['hello']['latest_version'], 'An up-to-date plugin reports its own version as the latest.' ); + $this->assertNull( $plugins['custom-plugin']['latest_version'], 'A plugin the update check does not know has no latest version.' ); + } + + public function test_without_an_update_check_no_latest_version_is_reported(): void { + foreach ( $this->plugins( false ) as $plugin ) { + $this->assertNull( $plugin['latest_version'] ); + } + } + + public function test_an_empty_or_odd_new_version_is_ignored(): void { + $updates = (object) [ + 'response' => [ + 'akismet/akismet.php' => (object) [ 'new_version' => '' ], + 'premium/premium.php' => (object) [ 'new_version' => [ '2.1' ] ], + 'hello.php' => 'not an object', + ], + ]; + + foreach ( $this->plugins( $updates ) as $plugin ) { + $this->assertNull( $plugin['latest_version'] ); + } + } +} diff --git a/tests/Unit/Sync/ControllerTest.php b/tests/Unit/Sync/ControllerTest.php index 48b7fa1..3e9e22c 100644 --- a/tests/Unit/Sync/ControllerTest.php +++ b/tests/Unit/Sync/ControllerTest.php @@ -58,6 +58,10 @@ function ( string $key, $value ) { return true; } ); + $GLOBALS['scanfully_test_action_scheduler'] = [ + 'locks' => [], + 'dispatched' => [], + ]; Functions\when( 'as_schedule_single_action' )->alias( function ( ...$args ) { $this->scheduled[] = $args; @@ -114,7 +118,7 @@ public function test_an_empty_stored_token_never_matches(): void { $this->assertFalse( Controller::check_permission( $this->request( [ 'X-Scanfully-Token' => '' ] ) ) ); } - public function test_a_sync_schedules_unique_health_and_directory_jobs(): void { + public function test_a_sync_schedules_health_and_directory_jobs_beside_the_recurring_ones(): void { $response = Controller::handle_sync(); $this->assertSame( 202, $response->get_status() ); @@ -123,10 +127,17 @@ public function test_a_sync_schedules_unique_health_and_directory_jobs(): void { $this->assertContains( CronController::ACTION_SYNC_SITE_HEALTH, $hooks ); $this->assertContains( CronController::ACTION_SYNC_DIRECTORIES, $hooks ); foreach ( $this->scheduled as $args ) { - $this->assertTrue( $args[4], 'Sync jobs must be scheduled as unique.' ); + $this->assertFalse( $args[4] ?? false, 'A unique job is skipped while the recurring sync is pending.' ); } } + public function test_a_sync_starts_the_queue_runner_now(): void { + Controller::handle_sync(); + + $this->assertCount( 1, $GLOBALS['scanfully_test_action_scheduler']['dispatched'], 'The syncs must not wait for WP-Cron.' ); + $this->assertSame( [ 'async-request-runner' ], $GLOBALS['scanfully_test_action_scheduler']['locks'] ); + } + public function test_a_second_sync_within_the_window_is_rate_limited(): void { Controller::handle_sync(); $response = Controller::handle_sync(); @@ -134,5 +145,6 @@ public function test_a_second_sync_within_the_window_is_rate_limited(): void { $this->assertSame( 429, $response->get_status() ); $this->assertArrayHasKey( 'Retry-After', $response->get_headers() ); $this->assertCount( 2, $this->scheduled ); + $this->assertCount( 1, $GLOBALS['scanfully_test_action_scheduler']['dispatched'], 'A refused sync starts no runner.' ); } } diff --git a/tests/stubs.php b/tests/stubs.php index db5fbea..44fc196 100644 --- a/tests/stubs.php +++ b/tests/stubs.php @@ -208,6 +208,71 @@ abstract class WC_Payment_Gateway { public $supports = [ 'products' ]; } } + + if ( ! class_exists( 'ActionScheduler' ) ) { + /** + * Stub of Action Scheduler's facade, for the lock and store the sync + * endpoint uses to start the queue runner. The stubs record what they + * are asked in $GLOBALS['scanfully_test_action_scheduler']. + */ + class ActionScheduler { + /** + * The lock. + * + * @return ActionScheduler_Lock + */ + public static function lock() { + return new ActionScheduler_Lock(); + } + + /** + * The store. + * + * @return null + */ + public static function store() { + return null; + } + } + + /** + * Stub of Action Scheduler's lock. + */ + class ActionScheduler_Lock { + /** + * Set a lock. + * + * @param string $lock_type The lock type. + * + * @return bool + */ + public function set( $lock_type ) { + $GLOBALS['scanfully_test_action_scheduler']['locks'][] = $lock_type; + return true; + } + } + + /** + * Stub of Action Scheduler's async queue runner. + */ + class ActionScheduler_AsyncRequest_QueueRunner { + /** + * Constructor. + * + * @param mixed $store The store. + */ + public function __construct( $store ) {} + + /** + * Dispatch a runner. + * + * @return void + */ + public function maybe_dispatch() { + $GLOBALS['scanfully_test_action_scheduler']['dispatched'][] = true; + } + } + } } namespace Automattic\WooCommerce\Blocks\Payments\Integrations { diff --git a/uninstall.php b/uninstall.php index 56aef83..e814976 100644 --- a/uninstall.php +++ b/uninstall.php @@ -125,6 +125,11 @@ function scanfully_uninstall_scheduled_actions(): void { $wpdb->delete( $actions, [ 'group_id' => $group_id ], [ '%d' ] ); $wpdb->delete( $groups, [ 'group_id' => $group_id ], [ '%d' ] ); // phpcs:enable WordPress.DB.DirectDatabaseQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared + + // Action Scheduler 4.1+ caches group ids for ten minutes. Drop the cached id + // so jobs scheduled after a reinstall create the group again instead of + // pointing at the deleted row. + wp_cache_delete( 'scanfully', 'action_scheduler_groups' ); } /**