From edb1e89f7ba32790ff5809d86f676451cd544da2 Mon Sep 17 00:00:00 2001 From: Alt-Charlie Date: Mon, 9 Nov 2026 10:19:32 +0000 Subject: [PATCH 1/6] Give each kind of change its own applier, and report site setup on /health Appliers share an interface so alt text, links, robots.txt and structured data can each have one, and /health assembles its checks from them. One that throws is left out rather than stopping the answer. Classes now load on demand, and the test database can be named and placed through the environment. --- altimiser.php | 19 +++++------- src/Applier.php | 20 +++++++++++++ src/ChangeDispatcher.php | 13 +------- src/InactiveSeoPlugin.php | 30 +++++++++++++++++++ src/Receiver.php | 63 ++++++++++++++++++++++++++++++++++----- src/YoastApplier.php | 8 +---- tests/wp-tests-config.php | 4 +-- 7 files changed, 118 insertions(+), 39 deletions(-) create mode 100644 src/Applier.php create mode 100644 src/InactiveSeoPlugin.php diff --git a/altimiser.php b/altimiser.php index 5b7e0ba..ee0e467 100644 --- a/altimiser.php +++ b/altimiser.php @@ -20,17 +20,14 @@ defined('ABSPATH') || exit; -require_once __DIR__.'/src/ChangeDispatcher.php'; -require_once __DIR__.'/src/ChangeRequest.php'; -require_once __DIR__.'/src/ChangeResult.php'; -require_once __DIR__.'/src/ContentResolver.php'; -require_once __DIR__.'/src/ControlPanel.php'; -require_once __DIR__.'/src/PageCache.php'; -require_once __DIR__.'/src/Receiver.php'; -require_once __DIR__.'/src/ReviewQueuePage.php'; -require_once __DIR__.'/src/Updater.php'; -require_once __DIR__.'/src/Yoast.php'; -require_once __DIR__.'/src/YoastApplier.php'; +spl_autoload_register(static function (string $class): void { + $namespace = 'AltDesign\\Altimiser\\'; + $file = __DIR__.'/src/'.str_replace('\\', '/', substr($class, strlen($namespace))).'.php'; + + if (str_starts_with($class, $namespace) && is_file($file)) { + require $file; + } +}); add_action('rest_api_init', static function (): void { (new Receiver(__FILE__, defined('WPSEO_VERSION') ? new Yoast() : null))->registerRoutes(); diff --git a/src/Applier.php b/src/Applier.php new file mode 100644 index 0000000..f25f8f4 --- /dev/null +++ b/src/Applier.php @@ -0,0 +1,20 @@ + + */ + public function checks(): array; + + public function supports(string $check): bool; + + /** + * @return array + */ + public function apply(ChangeRequest $change, bool $dryRun): array; +} diff --git a/src/ChangeDispatcher.php b/src/ChangeDispatcher.php index 3495a87..f226816 100644 --- a/src/ChangeDispatcher.php +++ b/src/ChangeDispatcher.php @@ -7,7 +7,7 @@ class ChangeDispatcher { /** - * @param array $appliers + * @param array $appliers */ public function __construct(private array $appliers, private PageCache $pageCache) {} @@ -66,21 +66,10 @@ private function outOfRoom(int $attempted, int $batchSize, float $startedAt, flo } /** - * Failed rather than skipped with no applier, because Altimiser withdraws the - * approval on a skip, and this one comes out differently once Yoast SEO is back. - * * @return array */ private function applyOne(ChangeRequest $change, bool $dryRun): array { - if ($this->appliers === []) { - return ChangeResult::failed( - $change->id, - 'seo_plugin_inactive', - 'Yoast SEO is not active on this site, so nothing was attempted. The change stays approved for the next apply.', - ); - } - foreach ($this->appliers as $applier) { if (! $applier->supports($change->check)) { continue; diff --git a/src/InactiveSeoPlugin.php b/src/InactiveSeoPlugin.php new file mode 100644 index 0000000..26ab61a --- /dev/null +++ b/src/InactiveSeoPlugin.php @@ -0,0 +1,30 @@ +id, + 'seo_plugin_inactive', + 'Yoast SEO is not active on this site, so nothing was attempted. The change stays approved for the next apply.', + ); + } +} diff --git a/src/Receiver.php b/src/Receiver.php index 751db70..2eda350 100644 --- a/src/Receiver.php +++ b/src/Receiver.php @@ -2,6 +2,7 @@ namespace AltDesign\Altimiser; +use Throwable; use WP_Error; use WP_REST_Request; use WP_REST_Response; @@ -53,22 +54,66 @@ public function verifySignature(WP_REST_Request $request): bool|WP_Error public function health(): WP_REST_Response { - $checks = array_merge([], ...array_map( - static fn (YoastApplier $applier): array => $applier->checks(), - $this->appliers(), - )); + $checks = $this->advertisedChecks(); return $this->uncached([ 'receiver' => 'wordpress', 'receiver_version' => get_file_data($this->pluginFile, ['version' => 'Version'])['version'], 'cms_version' => get_bloginfo('version'), - 'capabilities' => $checks === [] ? [] : ['content.update'], + 'capabilities' => $this->capabilities($checks), 'checks' => $checks, 'integrations' => ['yoast' => $this->yoastState()], + 'setup' => $this->setup(), 'site_url' => home_url(), ]); } + /** + * An applier that throws is left out rather than stopping the answer, so a fault + * in Yoast costs its own checks and not the connection. + * + * @return array + */ + private function advertisedChecks(): array + { + $checks = []; + + foreach ($this->appliers() as $applier) { + try { + $checks = [...$checks, ...$applier->checks()]; + } catch (Throwable $exception) { + error_log("Altimiser left out the checks of one applier: {$exception->getMessage()}"); + } + } + + return array_values(array_unique($checks)); + } + + /** + * @param array $checks + * @return array + */ + private function capabilities(array $checks): array + { + return array_keys(array_filter([ + 'content.update' => $checks !== [], + 'content.link' => in_array('link.opportunity', $checks, true), + ])); + } + + /** + * Settings that stop fixes from counting, which Altimiser reports as findings. + * + * @return array + */ + private function setup(): array + { + return [ + 'search_engines_discouraged' => (string) get_option('blog_public', '1') === '0', + 'plain_permalinks' => (string) get_option('permalink_structure') === '', + ]; + } + public function changes(WP_REST_Request $request): WP_REST_Response|WP_Error { $payload = json_decode($request->get_body(), true); @@ -105,11 +150,15 @@ public function changes(WP_REST_Request $request): WP_REST_Response|WP_Error } /** - * @return array + * @return array */ private function appliers(): array { - return $this->yoast === null ? [] : [new YoastApplier($this->yoast, new ContentResolver())]; + $content = new ContentResolver(); + + return [ + $this->yoast === null ? new InactiveSeoPlugin() : new YoastApplier($this->yoast, $content), + ]; } /** diff --git a/src/YoastApplier.php b/src/YoastApplier.php index 6be249c..b94f958 100644 --- a/src/YoastApplier.php +++ b/src/YoastApplier.php @@ -5,13 +5,10 @@ use WP_Post; use WP_Term; -class YoastApplier +class YoastApplier implements Applier { public function __construct(private Yoast $yoast, private ContentResolver $content) {} - /** - * @return array - */ public function checks(): array { $checks = [ @@ -35,9 +32,6 @@ public function supports(string $check): bool return in_array($check, $this->checks(), true); } - /** - * @return array - */ public function apply(ChangeRequest $change, bool $dryRun): array { if (trim($change->suggestedValue ?? '') === '') { diff --git a/tests/wp-tests-config.php b/tests/wp-tests-config.php index 9ac3324..23d84f5 100644 --- a/tests/wp-tests-config.php +++ b/tests/wp-tests-config.php @@ -2,10 +2,10 @@ define('ABSPATH', dirname(__DIR__).'/wordpress/'); -define('DB_NAME', 'altimiser_wordpress_tests'); +define('DB_NAME', getenv('WP_TESTS_DB_NAME') ?: 'altimiser_wordpress_tests'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); -define('DB_HOST', '127.0.0.1'); +define('DB_HOST', getenv('WP_TESTS_DB_HOST') ?: '127.0.0.1'); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', ''); From 5225c474dfa501844bdbde982ebfe44d50b9d6cf Mon Sep 17 00:00:00 2001 From: Alt-Charlie Date: Mon, 9 Nov 2026 10:32:03 +0000 Subject: [PATCH 2/6] Prepare the plugin for its first client trial Releases only publish once the tests pass and the tag is on main, and the workflow parses again. Page caches are purged for the pages that changed rather than whole, where the cache plugin can do that, and the altimiser_purge_urls action lets a host or edge cache be purged too. The secret has to be at least 32 characters, and can come from the environment or a settings page as well as wp-config.php, which gives each site on a network its own. Refused signed requests and failed writes are logged. A fault in Yoast no longer stops /health answering, and the tests also run against Yoast 24.0, the oldest release supported. Only posts whose type has public pages are written to, so a menu item answering ?p=N under plain permalinks is left alone. The review count waits two seconds at most and is asked for by one page at a time, and the widget shows what is approved and what Altimiser can fix here. Admin text is translatable, the queue's styles are enqueued, and uninstalling removes what the plugin keeps. --- .github/workflows/release.yml | 19 +++- .github/workflows/tests.yml | 7 ++ README.md | 99 ++++++++++++------ altimiser.php | 6 ++ src/ChangeDispatcher.php | 51 +++++++-- src/ContentResolver.php | 7 +- src/ControlPanel.php | 55 +++++++--- src/PageCache.php | 63 +++++++++++- src/Receiver.php | 41 ++++++-- src/ReviewQueuePage.php | 115 ++++++++++++++++++--- src/Settings.php | 65 ++++++++++++ src/SettingsPage.php | 142 ++++++++++++++++++++++++++ tests/ChangeRequestHandlingTest.php | 13 +++ tests/ControlPanelTest.php | 8 +- tests/HealthTest.php | 41 ++++++++ tests/PageCacheTest.php | 69 +++++++++++-- tests/ReceiverTestCase.php | 2 +- tests/ReviewQueuePageTest.php | 39 ++++++- tests/SecretSourcesTest.php | 64 ++++++++++++ tests/SettingsPageTest.php | 102 ++++++++++++++++++ tests/SignatureTest.php | 16 +++ tests/bootstrap.php | 2 + tests/fixtures/page-cache-plugins.php | 19 ++++ uninstall.php | 26 +++++ 24 files changed, 967 insertions(+), 104 deletions(-) create mode 100644 src/Settings.php create mode 100644 src/SettingsPage.php create mode 100644 tests/SecretSourcesTest.php create mode 100644 tests/SettingsPageTest.php create mode 100644 uninstall.php diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bb8c3ca..d84a09c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -5,20 +5,33 @@ on: tags: ['v*'] permissions: - contents: write + contents: read jobs: + tests: + uses: ./.github/workflows/tests.yml + release: + needs: tests runs-on: ubuntu-latest + permissions: + contents: write + steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check the tag is on main + run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main - name: Check the tag matches the plugin's version - run: grep -Fxq " * Version: ${GITHUB_REF_NAME#v}" altimiser.php + run: | + grep -Fxq " * Version: ${GITHUB_REF_NAME#v}" altimiser.php - name: Build the zip - run: git archive --prefix=altimiser/ -o altimiser.zip HEAD altimiser.php src README.md + run: git archive --prefix=altimiser/ -o altimiser.zip HEAD altimiser.php uninstall.php src README.md - name: Publish the release run: gh release create "$GITHUB_REF_NAME" altimiser.zip --generate-notes diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c105f47..117f7e5 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -4,6 +4,7 @@ on: push: branches: [main] pull_request: + workflow_call: permissions: contents: read @@ -21,6 +22,11 @@ jobs: matrix: php: ['8.1', '8.2', '8.3', '8.4'] wordpress: ['6.8.*', '*'] + yoast: ['*'] + include: + - php: '8.1' + wordpress: '6.8.*' + yoast: '24.0' services: mysql: @@ -51,6 +57,7 @@ jobs: composer require --dev --no-interaction --no-progress --prefer-dist --with-all-dependencies "roots/wordpress:${{ matrix.wordpress }}" "wp-phpunit/wp-phpunit:${{ matrix.wordpress }}" + "wpackagist-plugin/wordpress-seo:${{ matrix.yoast }}" - name: Run tests run: vendor/bin/phpunit diff --git a/README.md b/README.md index 3d7c328..8b9d6c9 100644 --- a/README.md +++ b/README.md @@ -1,30 +1,39 @@ # Altimiser for WordPress -Connects a WordPress site to Altimiser. It implements the [receiver protocol](https://github.com/alt-design/altimiser/blob/main/docs/receiver-protocol.md), and it is held to that document rather than to the [Statamic receiver](https://github.com/alt-design/altimiser-statamic), with which it shares no code. +Connects a WordPress site to Altimiser. It implements Altimiser's receiver protocol, which is kept with Altimiser itself, and it is held to that document rather than to the [Statamic receiver](https://github.com/alt-design/altimiser-statamic), with which it shares no code. -It applies the changes Altimiser sends to titles, meta descriptions and Open Graph text, by writing to Yoast SEO's own fields. Without Yoast SEO active a site can still connect, but `GET /health` advertises no checks, Altimiser reports the gap as `receiver.no_seo_plugin`, and nothing on the site is changed. +It applies the changes Altimiser sends to titles, meta descriptions and Open Graph text, by writing to Yoast SEO's own fields. Without Yoast SEO active a site can still connect, but `GET /health` advertises none of those checks, Altimiser reports the gap as `receiver.no_seo_plugin`, and none of those fields is changed. ## Requirements -WordPress 6.8 or newer, PHP 8.1 or newer, and Yoast SEO for anything to be applied. The plugin has no runtime Composer dependencies, because vendor classes in a plugin can collide with another plugin's copies. +WordPress 6.8 or newer, PHP 8.1 or newer, and Yoast SEO 24.0 or newer for titles, descriptions and Open Graph text. The tests run against Yoast SEO 24.0 as well as the latest release. The plugin has no runtime Composer dependencies, because vendor classes in a plugin can collide with another plugin's copies. ## Installing -Put this repository in `wp-content/plugins/altimiser` and activate the plugin. +Install from `altimiser.zip` on the latest GitHub release, through **Plugins > Add New > Upload Plugin**, and activate it. A clone in a folder not named `altimiser` gets a second copy on its first update. -Then add a shared secret to `wp-config.php`, above the line that says to stop editing: +Then give the site a shared secret of at least 32 characters. Every request is refused until there is one, and while it is shorter than that, so an install without one is inert rather than open. There are three places to put it, and the first one found wins: -```php -define('ALTIMISER_SECRET', 'a long random string'); -``` +1. A constant in `wp-config.php`, above the line that says to stop editing: -With WP-CLI, this generates one and writes it there: + ```php + define('ALTIMISER_SECRET', 'a long random string'); + ``` -```bash -wp config set ALTIMISER_SECRET "$(openssl rand -hex 32)" -``` + With WP-CLI, this generates one and writes it there: + + ```bash + wp config set ALTIMISER_SECRET "$(openssl rand -hex 32)" + ``` + +2. An `ALTIMISER_SECRET` environment variable, for hosts that manage configuration that way. +3. **Settings > Altimiser**, for administrators. The field never shows a saved secret, and leaving it blank keeps the one saved. -Every request is refused until the secret is set, so an install without one is inert rather than open. +The settings page also shows the receiver address to give Altimiser, and says whether the site will accept its requests. + +### Multisite + +Each site on a network has its own **Settings > Altimiser** page, and so its own secret and its own connection in Altimiser. A constant in `wp-config.php` or an environment variable applies to every site on the network at once, so use the settings page there. Multisite has not yet been tried on a running network. ## Connecting @@ -40,6 +49,8 @@ A successful connection shows the receiver as `wordpress` with the plugin's vers Connect again after activating Yoast SEO, so Altimiser reads what the site can now apply. +`GET /health` also reports two settings under `setup`, which Altimiser turns into findings because they stop fixes from counting: **Discourage search engines** under **Settings > Reading**, and plain permalinks. + ## What gets changed | Checks | Yoast SEO field | @@ -48,7 +59,7 @@ Connect again after activating Yoast SEO, so Altimiser reads what the site can n | `meta_description.missing`, `too_short`, `too_long`, `irrelevant`, `duplicate` | Meta description | | `open_graph.missing` for `og:title` and `og:description`, while Yoast SEO's social tags are switched on | Social title and description | -These are written to the post, page, custom post type or taxonomy term the URL belongs to. A shared template is never edited and a meta title is never written to `post_title`. +These are written to the post, page, custom post type or taxonomy term the URL belongs to, as long as its type has public pages. A shared template is never edited and a meta title is never written to `post_title`. `canonical.missing` is left to a developer. Yoast SEO prints a canonical itself except on noindex pages, so a missing one points to something else on the site. @@ -58,34 +69,41 @@ A change is refused rather than guessed at, and the finding goes to a person: | --- | --- | | `value_changed` | The field no longer holds what the scan saw, usually because an editor has been in since | | `ambiguous` | The page has no value of its own and its template does not produce what the scan saw. A renamed page does this, and so does a `wpseo_title` or `wpseo_metadesc` filter, so a site using those filters gets inherited values refused | -| `not_found` | Nothing editable answers to the URL. This covers a blog home listing latest posts, post type and author archives, term pages on plain permalinks, and a page's address with a query on the end, such as a search or a campaign link | +| `not_found` | Nothing editable answers to the URL. This covers a blog home listing latest posts, post type and author archives, term pages on plain permalinks, a type with no pages of its own such as a menu item, and a page's address with a query on the end, such as a search or a campaign link | | `no_suggestion` | There is no replacement value, as with `og:image` | | `no_field` | Yoast SEO has no text field for that tag | -If Yoast SEO is not active when a change arrives, nothing is attempted and the change comes back as `failed` with the reason `seo_plugin_inactive`. That keeps its approval, so it goes out again on the next apply. +If Yoast SEO is not active when one of its changes arrives, nothing is attempted and the change comes back as `failed` with the reason `seo_plugin_inactive`. That keeps its approval, so it goes out again on the next apply. -A page that inherits from a template goes back to inheriting when the change is reverted, rather than keeping a copy of the template's text. +A page that inherited from a template goes back to inheriting when the change is reverted, as long as the template still produces what the scan saw. A field that was empty with nothing to inherit is not reverted, because Altimiser has no earlier value to send back, so it keeps the new value until someone clears it in the editor. Each request attempts up to 10 changes within 45 seconds and hands the rest back as `deferred`, for Altimiser to send again. The `altimiser_batch_size` and `altimiser_time_budget` filters change those numbers. The time budget is also held to half of `max_execution_time`. ## Page caches -A request that applies something, or finds it already in place, purges the page cache once, during the request, after Yoast has rebuilt what the page prints. A dry run never does. +A request that applies something, or finds it already in place, purges the pages it changed, once, during the request, after Yoast has rebuilt what the page prints. A dry run never does. -| Plugin | How it was checked | -| --- | --- | -| Breeze 2.6.4 and 2.1.11 | Live: a cached page rendered afresh after an apply | -| W3 Total Cache 2.11.0 | Live: an apply carried out its page cache flush. A page coming back afresh was not observed, because it did not serve cached pages on the local install | -| WP Super Cache 3.1.5 | The purge function exists with the plugin active, and the call is tested. Purging was not observed, because it did not serve cached pages on the local install | -| WP Rocket, LiteSpeed Cache | From reading their source, and not from testing on a running site | +| Plugin | What is purged | How it was checked | +| --- | --- | --- | +| WP Rocket | Each changed page, with `rocket_clean_files()` | From reading its source | +| W3 Total Cache | Each changed page, with `w3tc_flush_url()` | From reading its source. 2.11.0 carried out a whole cache flush live on a local install | +| WP Super Cache | Each changed page, with `wpsc_delete_url_cache()`, and the whole cache for the home page or an address with a query, which it will not delete by address | From reading its source | +| LiteSpeed Cache | Each changed page, through its `litespeed_purge_url` action | From reading its source | +| Breeze | The whole cache, because it offers no purge by address | Live on 2.6.4 and 2.1.11: a cached page rendered afresh after an apply | -Any other page cache is not purged, so a change appears there once the cache expires. +Any other cache, including one run by the host or a CDN, is not purged, so a change appears there once it expires. To purge one, listen for the `altimiser_purge_urls` action, which receives the addresses and whether the whole site changed: + +```php +add_action('altimiser_purge_urls', function (array $urls, bool $everything): void { + // Purge $urls, or everything when $everything is true. +}, 10, 2); +``` `GET /health` is marked as uncacheable, because a cached copy would answer later requests without checking their signature. Breeze 2.1.11 ignores the usual signals on REST responses, so the plugin also makes the check that one version does make come out as not cacheable. Without that, a signed request left a cache file behind on a local install. ## The review queue in wp-admin -This is optional. Add Altimiser's address to `wp-config.php`, and an Altimiser item appears in the admin menu for editors and administrators: +This is optional. Add Altimiser's address on **Settings > Altimiser**, or in `wp-config.php`, and an Altimiser item appears in the admin menu for editors and administrators: ```php define('ALTIMISER_URL', 'https://altimiser.example.com'); @@ -93,7 +111,7 @@ define('ALTIMISER_URL', 'https://altimiser.example.com'); The page shows the queue in a frame that fills the space beside the menu. Altimiser only allows framing by the origin of the site's URL, so the queue will not load for an admin served from another origin, or in a browser that refuses the frame. The frame's link is signed on the server, carries the email address of whoever is signed in, which is who an approval gets recorded against, and expires. Reloading the page gets a new one. -The menu item and a dashboard widget show how many changes are waiting for review. The number is kept for five minutes, so it can lag behind the queue. If Altimiser cannot be reached the number is left out, and it is not asked again for five minutes, so one admin page waits at most five seconds rather than all of them. +The menu item shows how many changes are waiting for review. The dashboard widget shows the same, along with how many approved changes are waiting to be applied and how many of the site's open findings Altimiser can fix here. The counts are kept for five minutes, so they can lag behind the queue. Altimiser is given two seconds to answer, and only one admin page asks at a time. If it cannot be reached the counts are left out, and it is not asked again for five minutes. Two more constants are available: @@ -102,13 +120,27 @@ Two more constants are available: | `ALTIMISER_SITE_URL` | The address the site was added to Altimiser under, where that differs from WordPress's home URL | | `ALTIMISER_LINK_MINUTES` | How long a review link lasts. The default is 30 | +## What is sent where + +The plugin sends nothing on its own. Altimiser scans the site's public pages from outside, and what it does with them, including sending text and images to AI model providers to write suggestions, is covered by the agreement with the client rather than by this plugin. + +Altimiser sends the site the changes that were approved: page addresses, the values the scan saw, and the values to write. The site answers with what it did. + +With the review queue switched on, the site asks Altimiser for its counts, naming only the site. The frame's link carries the signed in editor's email address to Altimiser, because approvals are recorded against it. Tell the client this before switching it on. + +Refused requests that carried a signature, and changes that could not be written, are logged to PHP's error log, which is `wp-content/debug.log` when `WP_DEBUG_LOG` is on. The log names the route or the page address, and holds no secrets or personal data. + ## Updates WordPress's own updater offers new versions, from the latest release on GitHub. The **View details** link in the update notice says the plugin was not found, because it is not in the WordPress directory. The update itself works. A site that keeps its plugins in git should commit the update instead, or the next deploy puts the old version back. -To publish a release, change `Version` in `altimiser.php`, then push a tag naming that version, such as `v0.2.0`. The release workflow builds `altimiser.zip` and publishes it, and fails if the tag and the version disagree. +To publish a release, change `Version` in `altimiser.php` on `main`, then push a tag naming that version, such as `v0.2.0`. The release workflow runs the tests, checks that the tag is on `main` and matches the version, and only then builds `altimiser.zip` and publishes it. The updater trusts the latest release, so keep the ability to push tags to people who need it. + +## Uninstalling + +Deleting the plugin removes its settings and the counts it keeps, on every site of a network. Changes it applied are the site's content by then, and stay. ## When the connection fails @@ -116,8 +148,9 @@ To publish a release, change `Version` in `altimiser.php`, then push a tag namin | What Altimiser reports | What it means | What to check | | --- | --- | --- | -| `401` Altimiser is not configured on this site | `ALTIMISER_SECRET` is missing, empty or not a string | That `wp-config.php` on this server defines the constant, with a non empty string as its value | -| `401` Signature does not match | The two ends hold different secrets | Connect again passing the value from `wp-config.php` | +| `401` Altimiser is not configured on this site | No secret is set, or it is empty or not a string | **Settings > Altimiser**, which says where the secret is expected and whether one is found | +| `401` The Altimiser secret on this site is shorter than 32 characters | A secret is set and too short to accept | Replace it with a longer one, in the same place, and connect again with the new value | +| `401` Signature does not match | The two ends hold different secrets | Connect again passing the value the site holds | | `401` Signature timestamp is outside the accepted window | The timestamp was more than five minutes out, or never arrived | The clocks on both servers. Something in front of the site may also be removing the `X-Altimiser-*` headers | | `404` `rest_no_route` | WordPress answered and has no such route | That the plugin is active, and that the receiver URL ends in `/altimiser/v1` | | `200` followed by HTML | The address is not reaching the REST API. On plain permalinks `/wp-json` is not routed, so WordPress answers with an ordinary page | Choose any other permalink structure, or use `https://example.com/?rest_route=/altimiser/v1` as the receiver URL | @@ -130,7 +163,7 @@ Two common security plugins need nothing doing. From reading their source, and n ## Testing -The tests run against a real WordPress, which Composer installs into `wordpress/`, and a real Yoast SEO from wpackagist, in `vendor/wp-plugins/`. They need MySQL at `127.0.0.1` as `root` with no password. +The tests run against a real WordPress, which Composer installs into `wordpress/`, and a real Yoast SEO from wpackagist, in `vendor/wp-plugins/`. They need MySQL as `root` with no password, at `127.0.0.1` unless `WP_TESTS_DB_HOST` says otherwise, in a database named `altimiser_wordpress_tests` unless `WP_TESTS_DB_NAME` says otherwise. ```bash composer install @@ -138,8 +171,8 @@ mysql -h127.0.0.1 -uroot -e "CREATE DATABASE IF NOT EXISTS altimiser_wordpress_t vendor/bin/phpunit ``` -GitHub Actions runs them on PHP 8.1 to 8.4, against WordPress 6.8 and the latest release. +GitHub Actions runs them on PHP 8.1 to 8.4, against WordPress 6.8 and the latest release, with the latest Yoast SEO, and once more on PHP 8.1 and WordPress 6.8 with Yoast SEO 24.0. Anything the plugin logs during the tests goes to `altimiser-tests.log` in the system's temporary directory. `SignatureTest` computes the signature from the protocol document rather than taking it from the plugin or from Altimiser, and checks that calculation against the document's worked examples. Requests go through WordPress's own REST server, so `permission_callback` is what is under test. -`NoSecretTest` runs each test in a process of its own, because a constant cannot be undefined or redefined. `PageCacheTest` does the same, and defines stand-ins for the cache plugins' purge functions in `tests/fixtures/page-cache-plugins.php`. +`NoSecretTest`, `SecretSourcesTest` and `SettingsPageTest` run each test in a process of its own, because a constant cannot be undefined or redefined. `PageCacheTest` does the same where it defines stand-ins for the cache plugins' purge functions, in `tests/fixtures/page-cache-plugins.php`. diff --git a/altimiser.php b/altimiser.php index ee0e467..8cebc6c 100644 --- a/altimiser.php +++ b/altimiser.php @@ -10,11 +10,13 @@ * Author: Alt Design * Author URI: https://alt-design.net * Update URI: https://github.com/alt-design/altimiser-wordpress + * Text Domain: altimiser */ use AltDesign\Altimiser\ControlPanel; use AltDesign\Altimiser\Receiver; use AltDesign\Altimiser\ReviewQueuePage; +use AltDesign\Altimiser\SettingsPage; use AltDesign\Altimiser\Updater; use AltDesign\Altimiser\Yoast; @@ -34,6 +36,10 @@ }); add_action('plugins_loaded', static function (): void { + if (is_admin()) { + (new SettingsPage())->register(); + } + $controlPanel = ControlPanel::configured(); if ($controlPanel !== null) { diff --git a/src/ChangeDispatcher.php b/src/ChangeDispatcher.php index f226816..e1aca69 100644 --- a/src/ChangeDispatcher.php +++ b/src/ChangeDispatcher.php @@ -18,8 +18,9 @@ public function __construct(private array $appliers, private PageCache $pageCach * * The purge happens here and not at the end of the request because W3 Total Cache * carries a flush out on the shutdown action, so one asked for later is not acted on. - * A change already in place purges too: the request that wrote it may have died before - * getting this far, and being sent the change again is the only chance left to do it. + * A change already in place purges its page too: the request that wrote it may have + * died before getting this far, and being sent the change again is the only chance + * left to do it. * * @param array $changes * @return array> @@ -31,6 +32,8 @@ public function dispatch(array $changes, bool $dryRun): array $budget = $this->timeBudget(); $results = []; + $landed = []; + foreach ($changes as $change) { if ($results !== [] && $this->outOfRoom(count($results), $batchSize, $startedAt, $budget)) { $results[] = ChangeResult::deferred($change->id); @@ -38,16 +41,44 @@ public function dispatch(array $changes, bool $dryRun): array continue; } - $results[] = $this->applyOne($change, $dryRun); + $result = $this->applyOne($change, $dryRun); + $results[] = $result; + + if (in_array($result['status'], ['applied', 'already_applied'], true)) { + $landed[] = [$change->url, $result['location'] ?? []]; + } } - if (! $dryRun && array_intersect(['applied', 'already_applied'], array_column($results, 'status')) !== []) { - $this->pageCache->purge(); + if (! $dryRun) { + $this->purge($landed); } return $results; } + /** + * A change stored as a default shows on every page of its kind, so it clears the + * whole cache. Anything else clears the page it was made for. + * + * @param array}> $landed + */ + private function purge(array $landed): void + { + if ($landed === []) { + return; + } + + foreach ($landed as [, $location]) { + if (($location['default'] ?? false) === true) { + $this->pageCache->purgeEverything(); + + return; + } + } + + $this->pageCache->purge(array_column($landed, 0)); + } + /** * Half the limit, because a request killed mid-change leaves it unrecorded, and * one change can take a while once it has been started. @@ -76,10 +107,16 @@ private function applyOne(ChangeRequest $change, bool $dryRun): array } try { - return $applier->apply($change, $dryRun); + $result = $applier->apply($change, $dryRun); } catch (Throwable $exception) { - return ChangeResult::failed($change->id, 'write_failed', $exception->getMessage()); + $result = ChangeResult::failed($change->id, 'write_failed', $exception->getMessage()); + } + + if (($result['reason'] ?? null) === 'write_failed') { + error_log("Altimiser could not apply {$change->check} to {$change->url}: {$result['message']}"); } + + return $result; } return ChangeResult::skipped( diff --git a/src/ContentResolver.php b/src/ContentResolver.php index ef9e988..59a707e 100644 --- a/src/ContentResolver.php +++ b/src/ContentResolver.php @@ -22,7 +22,8 @@ public function find(string $url): WP_Post|WP_Term|null * url_to_postid() answers for unpublished records and revisions, for the addresses * beneath a page, such as its feed or its second page, and ignores the query, so * /?s=anything answers as a static home page. A suggestion made for one of those - * does not belong on the page itself. + * does not belong on the page itself. Under plain permalinks it also answers + * ?p=N for a menu item or any other type with no page of its own. */ private function isPublishedAt(string $url, int $postId): bool { @@ -30,6 +31,10 @@ private function isPublishedAt(string $url, int $postId): bool return false; } + if (! is_post_type_viewable((string) get_post_type($postId))) { + return false; + } + return $this->address(get_permalink($postId)) === $this->address($url); } diff --git a/src/ControlPanel.php b/src/ControlPanel.php index 02ac0be..1fd2945 100644 --- a/src/ControlPanel.php +++ b/src/ControlPanel.php @@ -13,19 +13,19 @@ public function __construct( public static function configured(): ?self { - $altimiserUrl = defined('ALTIMISER_URL') ? constant('ALTIMISER_URL') : null; - $secret = defined('ALTIMISER_SECRET') ? constant('ALTIMISER_SECRET') : null; + $altimiserUrl = Settings::altimiserUrl(); + $secret = Settings::secret(); - if (! is_string($altimiserUrl) || trim($altimiserUrl) === '') { + if ($altimiserUrl === null || $secret === null) { return null; } - if (! is_string($secret) || trim($secret) === '') { + if (! Settings::secretIsLongEnough($secret)) { return null; } return new self( - rtrim($altimiserUrl, '/'), + $altimiserUrl, rtrim(defined('ALTIMISER_SITE_URL') ? (string) constant('ALTIMISER_SITE_URL') : home_url(), '/'), $secret, defined('ALTIMISER_LINK_MINUTES') ? (int) constant('ALTIMISER_LINK_MINUTES') : 30, @@ -49,35 +49,52 @@ public function reviewUrl(string $user, int $expires): string return "{$url}&signature=".hash_hmac('sha256', $url, $this->secret); } + public function awaitingReview(): ?int + { + return $this->summary()['awaiting_review'] ?? null; + } + /** * Read on every admin page, so an unreachable Altimiser is remembered as well. - * Asking again each time would put the timeout in front of every screen. + * Asking again each time would put the timeout in front of every screen, and the + * lock keeps the screens opened while one request waits from asking as well. + * + * @return ?array */ - public function awaitingReview(): ?int + public function summary(): ?array { - $cached = get_transient('altimiser_awaiting_review'); + $cached = get_transient('altimiser_summary'); if (is_array($cached)) { - return $cached['count']; + return $cached['summary']; + } + + if (get_transient('altimiser_summary_lock') !== false) { + return null; } - $count = $this->fetchAwaitingReview(); + set_transient('altimiser_summary_lock', true, 30); + + $summary = $this->fetchSummary(); - set_transient('altimiser_awaiting_review', ['count' => $count], 5 * MINUTE_IN_SECONDS); + set_transient('altimiser_summary', ['summary' => $summary], 5 * MINUTE_IN_SECONDS); + delete_transient('altimiser_summary_lock'); - return $count; + return $summary; } /** * Redirects are not followed, because the signature would be sent on to wherever - * they lead. + * they lead. Only whole numbers are kept, and the badge's count has to be one of them. + * + * @return ?array */ - private function fetchAwaitingReview(): ?int + private function fetchSummary(): ?array { $timestamp = time(); $response = wp_remote_get("{$this->altimiserUrl}/api/summary?".http_build_query(['site' => $this->siteUrl]), [ - 'timeout' => 5, + 'timeout' => 2, 'redirection' => 0, 'headers' => [ 'X-Altimiser-Timestamp' => (string) $timestamp, @@ -90,8 +107,12 @@ private function fetchAwaitingReview(): ?int return null; } - $count = json_decode(wp_remote_retrieve_body($response), true)['awaiting_review'] ?? null; + $body = json_decode(wp_remote_retrieve_body($response), true); + + if (! is_int($body['awaiting_review'] ?? null)) { + return null; + } - return is_int($count) ? $count : null; + return array_filter($body, 'is_int'); } } diff --git a/src/PageCache.php b/src/PageCache.php index bdea2c8..4d3e8ef 100644 --- a/src/PageCache.php +++ b/src/PageCache.php @@ -4,14 +4,40 @@ use Throwable; +/** + * Altimiser scans again a few minutes after applying, and a cached page would hand a + * fix that landed back as one that did not. A failure here is logged and not returned, + * because the changes it follows have already been written. + * + * Each plugin's function was checked in its own source: WP Rocket's rocket_clean_files(), + * W3 Total Cache's w3tc_flush_url(), WP Super Cache's wpsc_delete_url_cache() and + * LiteSpeed's litespeed_purge_url action. Breeze offers no purge by address, so it is + * cleared whole. A host or edge cache can listen for altimiser_purge_urls. + */ class PageCache { /** - * Altimiser scans again a few minutes after applying, and a cached page would - * hand a fix that landed back as one that did not. A failure here is logged and - * not returned, because the changes it follows have already been written. + * @param array $urls */ - public function purge(): void + public function purge(array $urls): void + { + $urls = array_values(array_unique($urls)); + + if ($urls === []) { + return; + } + + try { + $this->purgeAddresses($urls); + } catch (Throwable $exception) { + error_log("Altimiser could not purge the page cache: {$exception->getMessage()}"); + } + } + + /** + * For a change that shows on every page of a kind, such as a default for a post type. + */ + public function purgeEverything(): void { try { if (function_exists('rocket_clean_domain')) { @@ -28,8 +54,37 @@ public function purge(): void do_action('litespeed_purge_all'); do_action('breeze_clear_all_cache'); + do_action('altimiser_purge_urls', [home_url('/')], true); } catch (Throwable $exception) { error_log("Altimiser could not purge the page cache: {$exception->getMessage()}"); } } + + /** + * WP Super Cache will not delete its home page or an address with a query by + * address, and says so by returning false, so it is cleared whole for those. + * + * @param array $urls + */ + private function purgeAddresses(array $urls): void + { + if (function_exists('rocket_clean_files')) { + rocket_clean_files($urls); + } + + if (function_exists('w3tc_flush_url')) { + array_map('w3tc_flush_url', $urls); + } + + if (function_exists('wpsc_delete_url_cache') && in_array(false, array_map('wpsc_delete_url_cache', $urls), true)) { + wp_cache_clear_cache(); + } + + foreach ($urls as $url) { + do_action('litespeed_purge_url', $url); + } + + do_action('breeze_clear_all_cache'); + do_action('altimiser_purge_urls', $urls, false); + } } diff --git a/src/Receiver.php b/src/Receiver.php index 2eda350..28882ff 100644 --- a/src/Receiver.php +++ b/src/Receiver.php @@ -29,27 +29,51 @@ public function registerRoutes(): void ]); } + /** + * A refused request that carried a signature is logged, because it is most likely + * Altimiser with the wrong secret or a clock out of step. Ones without are left out, + * since anything probing the route would fill the log. + */ public function verifySignature(WP_REST_Request $request): bool|WP_Error { - $secret = defined('ALTIMISER_SECRET') ? constant('ALTIMISER_SECRET') : null; + $refusal = $this->refusal($request); + + if ($refusal === null) { + return true; + } - if (! is_string($secret) || trim($secret) === '') { - return $this->refuse('Altimiser is not configured on this site.'); + if ($request->get_header('X-Altimiser-Signature') !== null) { + error_log("Altimiser refused a signed request to {$request->get_route()}: {$refusal}"); + } + + return new WP_Error('altimiser_refused', $refusal, ['status' => 401]); + } + + private function refusal(WP_REST_Request $request): ?string + { + $secret = Settings::secret(); + + if ($secret === null) { + return 'Altimiser is not configured on this site.'; + } + + if (! Settings::secretIsLongEnough($secret)) { + return 'The Altimiser secret on this site is shorter than 32 characters, so requests are refused until it is replaced with a longer one.'; } $timestamp = (int) $request->get_header('X-Altimiser-Timestamp'); if (abs(time() - $timestamp) > $this->toleranceInSeconds) { - return $this->refuse('Signature timestamp is outside the accepted window.'); + return 'Signature timestamp is outside the accepted window.'; } $expected = 'sha256='.hash_hmac('sha256', "{$timestamp}\n{$request->get_body()}", $secret); if (! hash_equals($expected, (string) $request->get_header('X-Altimiser-Signature'))) { - return $this->refuse('Signature does not match.'); + return 'Signature does not match.'; } - return true; + return null; } public function health(): WP_REST_Response @@ -195,9 +219,4 @@ private function uncached(array $body): WP_REST_Response return new WP_REST_Response($body, 200, array_filter(wp_get_nocache_headers())); } - - private function refuse(string $message): WP_Error - { - return new WP_Error('altimiser_refused', $message, ['status' => 401]); - } } diff --git a/src/ReviewQueuePage.php b/src/ReviewQueuePage.php index e120214..5f6caf3 100644 --- a/src/ReviewQueuePage.php +++ b/src/ReviewQueuePage.php @@ -12,6 +12,7 @@ public function register(): void { add_action('admin_menu', [$this, 'addMenuItem']); add_action('wp_dashboard_setup', [$this, 'addDashboardWidget']); + add_action('admin_enqueue_scripts', [$this, 'addStyles']); } public function addMenuItem(): void @@ -20,7 +21,14 @@ public function addMenuItem(): void return; } - add_menu_page('Altimiser', 'Altimiser'.$this->badge(), $this->capability, 'altimiser', [$this, 'render'], $this->icon()); + add_menu_page( + __('Altimiser', 'altimiser'), + __('Altimiser', 'altimiser').$this->badge(), + $this->capability, + 'altimiser', + [$this, 'render'], + $this->icon(), + ); } /** @@ -44,25 +52,57 @@ public function addDashboardWidget(): void return; } - wp_add_dashboard_widget('altimiser', 'Altimiser', [$this, 'renderWidget']); + wp_add_dashboard_widget('altimiser', __('Altimiser', 'altimiser'), [$this, 'renderWidget']); + } + + /** + * The queue fills the screen below the admin bar, with WordPress's own padding and + * footer taken away around it. + */ + public function addStyles(string $hook): void + { + if ($hook !== 'toplevel_page_altimiser') { + return; + } + + wp_register_style('altimiser-review-queue', false, [], null); + wp_enqueue_style('altimiser-review-queue'); + wp_add_inline_style( + 'altimiser-review-queue', + '.wp-admin #wpcontent{padding:0}#wpbody-content{padding-bottom:0}#wpfooter{display:none}' + .'.altimiser-review-queue{display:block;width:100%;height:calc(100vh - var(--wp-admin--admin-bar--height,32px));border:0}', + ); } public function render(): void { printf( - '' - .'', esc_url($this->panel->reviewUrl(wp_get_current_user()->user_email, $this->panel->linkExpiry())), + esc_attr__('Altimiser review queue', 'altimiser'), ); } public function renderWidget(): void { + $summary = $this->panel->summary(); + + printf('

%s

', esc_html($this->describe($summary['awaiting_review'] ?? null))); + + $details = array_filter([$this->pending($summary), $this->handled($summary)]); + + if ($details !== []) { + printf('
    %s
', implode('', array_map( + static fn (string $detail): string => '
  • '.esc_html($detail).'
  • ', + $details, + ))); + } + printf( - '

    %s

    Open the review queue

    ', - esc_html($this->describe($this->panel->awaitingReview())), + '

    %s

    ', esc_url(admin_url('admin.php?page=altimiser')), + esc_html__('Open the review queue', 'altimiser'), ); } @@ -75,18 +115,67 @@ private function badge(): string } return sprintf( - ' %1$d waiting for review', + ' %2$s', $count, + esc_html(sprintf( + /* translators: %d: how many changes are waiting for review */ + _n('%d waiting for review', '%d waiting for review', $count, 'altimiser'), + $count, + )), ); } private function describe(?int $count): string { - return match ($count) { - null => 'The count is not available right now, but the review queue should still open.', - 0 => 'Nothing is waiting for review.', - 1 => '1 change is waiting for review.', - default => "{$count} changes are waiting for review.", - }; + if ($count === null) { + return __('The count is not available right now, but the review queue should still open.', 'altimiser'); + } + + if ($count === 0) { + return __('Nothing is waiting for review.', 'altimiser'); + } + + return sprintf( + /* translators: %d: how many changes are waiting for review */ + _n('%d change is waiting for review.', '%d changes are waiting for review.', $count, 'altimiser'), + $count, + ); + } + + /** + * @param ?array $summary + */ + private function pending(?array $summary): ?string + { + $pending = $summary['pending'] ?? 0; + + if ($pending === 0) { + return null; + } + + return sprintf( + /* translators: %d: how many approved changes have not been applied yet */ + _n('%d approved change is waiting to be applied.', '%d approved changes are waiting to be applied.', $pending, 'altimiser'), + $pending, + ); + } + + /** + * @param ?array $summary + */ + private function handled(?array $summary): ?string + { + $outstanding = $summary['outstanding'] ?? 0; + + if ($outstanding === 0) { + return null; + } + + return sprintf( + /* translators: 1: findings this plugin can fix, 2: all open findings */ + _n('Altimiser can apply fixes for %1$d of the %2$d open finding on this site.', 'Altimiser can apply fixes for %1$d of the %2$d open findings on this site.', $outstanding, 'altimiser'), + $summary['handled'] ?? 0, + $outstanding, + ); } } diff --git a/src/Settings.php b/src/Settings.php new file mode 100644 index 0000000..6bc3cd3 --- /dev/null +++ b/src/Settings.php @@ -0,0 +1,65 @@ += self::$minimumSecretLength; + } + + /** + * Whether a value is fixed outside the settings page, which then shows it as set + * elsewhere rather than offering a field that would be ignored. + */ + public static function definedOutsideSettings(string $constant): bool + { + return self::fromCode($constant) !== null; + } + + /** + * @return array{secret?: string, altimiser_url?: string} + */ + public static function stored(): array + { + $stored = get_option(self::$option, []); + + return is_array($stored) ? $stored : []; + } + + private static function read(string $constant, string $key): ?string + { + $value = self::fromCode($constant) ?? (self::stored()[$key] ?? null); + + return is_string($value) && trim($value) !== '' ? trim($value) : null; + } + + private static function fromCode(string $constant): ?string + { + $value = defined($constant) ? constant($constant) : getenv($constant); + + return is_string($value) && trim($value) !== '' ? $value : null; + } +} diff --git a/src/SettingsPage.php b/src/SettingsPage.php new file mode 100644 index 0000000..6ea6ae1 --- /dev/null +++ b/src/SettingsPage.php @@ -0,0 +1,142 @@ +page, + [$this, 'render'], + ); + } + + public function registerSetting(): void + { + register_setting($this->page, Settings::$option, [ + 'type' => 'object', + 'sanitize_callback' => [$this, 'sanitise'], + 'show_in_rest' => false, + 'default' => [], + ]); + } + + /** + * A blank secret keeps the one saved, because the field never shows it, and a short + * one is turned away with the saved one kept, since saving it would stop the site + * accepting anything from Altimiser. + * + * @return array + */ + public function sanitise(mixed $input): array + { + $input = is_array($input) ? $input : []; + $saved = Settings::stored()['secret'] ?? ''; + $secret = trim((string) ($input['secret'] ?? '')); + + if ($secret !== '' && ! Settings::secretIsLongEnough($secret)) { + add_settings_error(Settings::$option, 'altimiser_secret_too_short', sprintf( + /* translators: %d: the minimum number of characters */ + __('The secret needs at least %d characters, so the one already saved was kept.', 'altimiser'), + Settings::$minimumSecretLength, + )); + + $secret = ''; + } + + return array_filter([ + 'altimiser_url' => esc_url_raw(trim((string) ($input['altimiser_url'] ?? '')), ['https', 'http']), + 'secret' => $secret === '' ? $saved : $secret, + ]); + } + + public function render(): void + { + if (! current_user_can('manage_options')) { + return; + } + + $stored = Settings::stored(); + + echo '

    '.esc_html__('Altimiser', 'altimiser').'

    '; + printf('

    %s

    ', esc_html($this->status())); + printf( + '

    %s %s

    ', + esc_html__('Give Altimiser this receiver address when adding the site:', 'altimiser'), + esc_html(rest_url('altimiser/v1')), + ); + + echo '
    '; + settings_fields($this->page); + echo ''; + + $this->row('altimiser_url', __('Altimiser address', 'altimiser'), 'ALTIMISER_URL', sprintf( + '', + esc_attr(Settings::$option), + esc_attr($stored['altimiser_url'] ?? ''), + ), __('Where the review queue and its count come from.', 'altimiser')); + + $this->row('altimiser_secret', __('Secret', 'altimiser'), 'ALTIMISER_SECRET', sprintf( + '', + esc_attr(Settings::$option), + esc_attr(isset($stored['secret']) ? __('A secret is saved. Leave blank to keep it.', 'altimiser') : ''), + ), sprintf( + /* translators: %d: the minimum number of characters */ + __('The secret Altimiser shows when the site is added, at least %d characters.', 'altimiser'), + Settings::$minimumSecretLength, + )); + + echo ''; + submit_button(); + echo '
    '; + } + + private function row(string $id, string $label, string $constant, string $field, string $description): void + { + $control = Settings::definedOutsideSettings($constant) + ? '

    '.esc_html(sprintf( + /* translators: %s: the name of a PHP constant */ + __('Set by %s in wp-config.php or the server environment.', 'altimiser'), + $constant, + )).'

    ' + : $field.'

    '.esc_html($description).'

    '; + + printf( + '%s', + esc_attr($id), + esc_html($label), + $control, + ); + } + + private function status(): string + { + $secret = Settings::secret(); + + if ($secret === null) { + return __('No secret is set, so this site turns away every request from Altimiser.', 'altimiser'); + } + + if (! Settings::secretIsLongEnough($secret)) { + return sprintf( + /* translators: %d: the minimum number of characters */ + __('The secret is shorter than %d characters, so this site turns away every request from Altimiser until it is replaced.', 'altimiser'), + Settings::$minimumSecretLength, + ); + } + + return __('A secret is set, and this site accepts signed requests from Altimiser.', 'altimiser'); + } +} diff --git a/tests/ChangeRequestHandlingTest.php b/tests/ChangeRequestHandlingTest.php index 3132ae5..2a3364b 100644 --- a/tests/ChangeRequestHandlingTest.php +++ b/tests/ChangeRequestHandlingTest.php @@ -127,6 +127,19 @@ public function test_skips_a_url_that_maps_to_nothing_editable(): void $this->assertSame('not_found', $result['reason']); } + public function test_skips_a_published_post_of_a_type_with_no_page_of_its_own(): void + { + $this->set_permalink_structure(''); + + $menuItem = self::factory()->post->create(['post_type' => 'nav_menu_item', 'post_status' => 'publish']); + + $result = $this->sendOne(['url' => home_url("/?p={$menuItem}")]); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('not_found', $result['reason']); + $this->assertSame('', get_post_meta($menuItem, '_yoast_wpseo_metadesc', true)); + } + public function test_reports_a_write_that_threw_as_failed_and_carries_on(): void { $failOnce = static function (): void { diff --git a/tests/ControlPanelTest.php b/tests/ControlPanelTest.php index 89cb259..ede421a 100644 --- a/tests/ControlPanelTest.php +++ b/tests/ControlPanelTest.php @@ -64,7 +64,7 @@ public function test_reads_the_count_with_a_request_signed_over_the_empty_body() $this->assertSame('https://altimiser.example.com/api/summary?site=https%3A%2F%2Fexample.com', $url); $this->assertSame('sha256='.hash_hmac('sha256', "{$timestamp}\n", 'shared-secret'), $args['headers']['X-Altimiser-Signature']); $this->assertEqualsWithDelta(time(), (int) $timestamp, 2); - $this->assertSame(5, $args['timeout']); + $this->assertSame(2, $args['timeout']); $this->assertSame(0, $args['redirection']); } @@ -124,7 +124,7 @@ public function test_remembers_altimiser_being_unreachable_so_only_one_page_wait */ public function test_needs_altimisers_address_before_it_can_link_to_it(): void { - define('ALTIMISER_SECRET', 'shared-secret'); + define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); $this->assertNull(ControlPanel::configured()); } @@ -149,7 +149,7 @@ public function test_needs_the_secret_before_it_can_sign_anything(): void public function test_names_the_site_by_its_own_address_with_no_trailing_slash(): void { define('ALTIMISER_URL', 'https://altimiser.example.com/'); - define('ALTIMISER_SECRET', 'shared-secret'); + define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); add_filter('home_url', static fn (): string => 'https://client.example.com/'); $url = ControlPanel::configured()->reviewUrl('', 1769558400); @@ -166,7 +166,7 @@ public function test_names_the_site_by_its_own_address_with_no_trailing_slash(): public function test_takes_the_sites_address_from_a_constant_where_the_two_disagree(): void { define('ALTIMISER_URL', 'https://altimiser.example.com'); - define('ALTIMISER_SECRET', 'shared-secret'); + define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); define('ALTIMISER_SITE_URL', 'https://www.client.example.com/'); define('ALTIMISER_LINK_MINUTES', 10); diff --git a/tests/HealthTest.php b/tests/HealthTest.php index e5d2213..d792f98 100644 --- a/tests/HealthTest.php +++ b/tests/HealthTest.php @@ -149,6 +149,47 @@ public function test_sends_no_header_without_a_value(): void $this->assertNotContains(false, $this->dispatch($this->signedRequest())->get_headers()); } + public function test_reports_settings_that_stop_fixes_from_counting(): void + { + update_option('blog_public', '0'); + $this->set_permalink_structure(''); + + $setup = $this->dispatch($this->signedRequest())->get_data()['setup']; + + update_option('blog_public', '1'); + + $this->assertSame(['search_engines_discouraged' => true, 'plain_permalinks' => true], $setup); + } + + public function test_reports_a_site_set_up_to_be_found(): void + { + $this->set_permalink_structure('/%postname%/'); + + $setup = $this->dispatch($this->signedRequest())->get_data()['setup']; + + $this->assertSame(['search_engines_discouraged' => false, 'plain_permalinks' => false], $setup); + } + + public function test_still_answers_when_yoast_throws_and_leaves_out_only_its_checks(): void + { + $failing = static function (): never { + throw new RuntimeException('Yoast could not read its options.'); + }; + + add_filter('pre_option_wpseo_social', $failing); + WPSEO_Options::clear_cache(); + + $logged = ini_set('error_log', '/dev/null'); + $response = $this->dispatch($this->signedRequest()); + + ini_set('error_log', (string) $logged); + remove_filter('pre_option_wpseo_social', $failing); + WPSEO_Options::clear_cache(); + + $this->assertSame(200, $response->get_status()); + $this->assertNotContains('title.too_long', $response->get_data()['checks']); + } + public function test_says_nothing_about_the_site_to_an_unsigned_request(): void { $response = $this->dispatch($this->request()); diff --git a/tests/PageCacheTest.php b/tests/PageCacheTest.php index 1a8fd6f..800a7e3 100644 --- a/tests/PageCacheTest.php +++ b/tests/PageCacheTest.php @@ -24,11 +24,11 @@ public function set_up(): void private function purges(callable $request): int { - $before = did_action('litespeed_purge_all'); + $before = did_action('altimiser_purge_urls'); $request(); - return did_action('litespeed_purge_all') - $before; + return did_action('altimiser_purge_urls') - $before; } private function descriptionYoastPrints(): ?string @@ -49,11 +49,11 @@ public function test_purges_once_yoast_has_rebuilt_what_the_page_prints(): void $printedAtPurge = $this->descriptionYoastPrints(); }; - add_action('litespeed_purge_all', $recordWhatIsPrinted); + add_action('litespeed_purge_url', $recordWhatIsPrinted); $this->sendOne(); - remove_action('litespeed_purge_all', $recordWhatIsPrinted); + remove_action('litespeed_purge_url', $recordWhatIsPrinted); $this->assertSame('How our studio works, and who we build for.', $printedAtPurge); } @@ -104,31 +104,82 @@ public function test_purges_when_the_fix_was_already_in_place_because_the_reques * * @preserveGlobalState disabled */ - public function test_reaches_each_plugin_that_is_active(): void + public function test_reaches_each_plugin_that_is_active_by_address(): void { require __DIR__.'/fixtures/page-cache-plugins.php'; + $page = home_url('/about/'); $beforeBreeze = did_action('breeze_clear_all_cache'); + $beforeLiteSpeed = did_action('litespeed_purge_url'); - (new AltDesign\Altimiser\PageCache())->purge(); + (new AltDesign\Altimiser\PageCache())->purge([$page, $page]); - $this->assertSame(['rocket', 'w3tc', 'super-cache'], $GLOBALS['altimiser_purged']); + $this->assertSame([['rocket', [$page]], ['w3tc', $page], ['super-cache', $page]], $GLOBALS['altimiser_purged']); + $this->assertSame($beforeLiteSpeed + 1, did_action('litespeed_purge_url')); $this->assertSame($beforeBreeze + 1, did_action('breeze_clear_all_cache')); } + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_clears_wp_super_cache_whole_for_the_home_page_it_will_not_delete_by_address(): void + { + require __DIR__.'/fixtures/page-cache-plugins.php'; + + (new AltDesign\Altimiser\PageCache())->purge([home_url('/')]); + + $this->assertContains('super-cache', $GLOBALS['altimiser_purged']); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_clears_everything_on_request(): void + { + require __DIR__.'/fixtures/page-cache-plugins.php'; + + $beforeLiteSpeed = did_action('litespeed_purge_all'); + + (new AltDesign\Altimiser\PageCache())->purgeEverything(); + + $this->assertSame(['rocket', 'w3tc', 'super-cache'], $GLOBALS['altimiser_purged']); + $this->assertSame($beforeLiteSpeed + 1, did_action('litespeed_purge_all')); + } + + public function test_purges_only_the_page_the_change_was_made_for(): void + { + $purged = []; + + $record = static function (array $urls, bool $everything) use (&$purged): void { + $purged[] = [$urls, $everything]; + }; + + add_action('altimiser_purge_urls', $record, 10, 2); + + $this->sendOne(); + + remove_action('altimiser_purge_urls', $record); + + $this->assertSame([[[home_url('/about/')], false]], $purged); + } + public function test_reports_success_even_when_the_purge_fails_because_the_changes_have_landed(): void { $failing = static function (): void { throw new RuntimeException('The cache directory is read only.'); }; - add_action('litespeed_purge_all', $failing); + add_action('litespeed_purge_url', $failing); $logged = ini_set('error_log', '/dev/null'); $result = $this->sendOne(); ini_set('error_log', (string) $logged); - remove_action('litespeed_purge_all', $failing); + remove_action('litespeed_purge_url', $failing); $this->assertSame('applied', $result['status']); } diff --git a/tests/ReceiverTestCase.php b/tests/ReceiverTestCase.php index b04644a..6798a01 100644 --- a/tests/ReceiverTestCase.php +++ b/tests/ReceiverTestCase.php @@ -9,7 +9,7 @@ */ abstract class ReceiverTestCase extends WP_UnitTestCase { - protected static string $secret = 'shared-secret'; + protected static string $secret = 'a-shared-secret-of-at-least-32-characters'; protected static function configureSecret(): void { diff --git a/tests/ReviewQueuePageTest.php b/tests/ReviewQueuePageTest.php index 19c0b07..1816bf2 100644 --- a/tests/ReviewQueuePageTest.php +++ b/tests/ReviewQueuePageTest.php @@ -186,7 +186,7 @@ public function test_frames_a_link_signed_for_whoever_is_signed_in(): void $html = html_entity_decode($this->renderedPage(), ENT_QUOTES); - preg_match('/', - esc_url($this->panel->reviewUrl(wp_get_current_user()->user_email, $this->panel->linkExpiry())), + esc_url($this->panel->reviewUrl(wp_get_current_user()->user_email, $this->panel->linkExpiry(), $connection)), esc_attr__('Altimiser review queue', 'altimiser'), ); } + /** + * Counts are shown only once the editor has connected their account, so nothing about + * the queue appears to someone Altimiser has not given the site. + */ public function renderWidget(): void { + if (Connections::live(get_current_user_id()) === null) { + printf('

    %s

    ', esc_html__('Connect your Altimiser account to see what is waiting for review.', 'altimiser')); + $this->renderOpenButton(__('Connect your account', 'altimiser')); + + return; + } + $summary = $this->panel->summary(); printf('

    %s

    ', esc_html($this->describe($summary['awaiting_review'] ?? null))); @@ -99,16 +161,21 @@ public function renderWidget(): void ))); } + $this->renderOpenButton(__('Open the review queue', 'altimiser')); + } + + private function renderOpenButton(string $label): void + { printf( '

    %s

    ', esc_url(admin_url('admin.php?page=altimiser')), - esc_html__('Open the review queue', 'altimiser'), + esc_html($label), ); } private function badge(): string { - $count = $this->panel->awaitingReview(); + $count = Connections::live(get_current_user_id()) === null ? null : $this->panel->awaitingReview(); if (! $count) { return ''; diff --git a/tests/ConnectionFlowTest.php b/tests/ConnectionFlowTest.php new file mode 100644 index 0000000..4b7dd23 --- /dev/null +++ b/tests/ConnectionFlowTest.php @@ -0,0 +1,200 @@ +}> */ + private array $requests = []; + + private WP_User $editor; + + public function set_up(): void + { + parent::set_up(); + + $this->editor = self::factory()->user->create_and_get(['role' => 'editor', 'user_email' => 'editor@example.com']); + + wp_set_current_user($this->editor->ID); + } + + public function tear_down(): void + { + $_GET = $_REQUEST = []; + + parent::tear_down(); + } + + private function flow(string $siteUrl = ''): ConnectionFlow + { + return new ConnectionFlow(new ControlPanel('https://altimiser.example.com', $siteUrl ?: home_url(), 'shared-secret')); + } + + private function altimiserAnswers(int $status, string $body): void + { + add_filter('pre_http_request', function ($preempt, array $args, string $url) use ($status, $body) { + $this->requests[] = ['url' => $url, 'args' => $args]; + + return ['headers' => [], 'body' => $body, 'response' => ['code' => $status, 'message' => ''], 'cookies' => [], 'filename' => null]; + }, 10, 3); + } + + /** + * @return array + */ + private function queryOf(string $url): array + { + parse_str((string) parse_url($url, PHP_URL_QUERY), $query); + + return $query; + } + + private function startConnecting(): string + { + $_GET['_wpnonce'] = $_REQUEST['_wpnonce'] = wp_create_nonce('altimiser_connect'); + + return $this->flow()->start(); + } + + /** + * @param array $query + */ + private function comeBackWith(array $query): string + { + $_GET = $_REQUEST = $query; + + return $this->flow()->finish(); + } + + public function test_sends_the_editor_to_a_signed_connect_link_that_returns_to_wp_admin(): void + { + $url = $this->startConnecting(); + $query = $this->queryOf($url); + + $this->assertStringStartsWith('https://altimiser.example.com/connect?', $url); + $this->assertSame(admin_url('admin-post.php?action=altimiser_connected'), $query['redirect_uri']); + $this->assertSame('editor@example.com', $query['user']); + $this->assertSame(40, strlen($query['state'])); + $this->assertEqualsWithDelta(time() + 300, (int) $query['expires'], 2); + + [$signed, $signature] = explode('&signature=', $url); + + $this->assertSame(hash_hmac('sha256', $signed, 'shared-secret'), $signature); + } + + public function test_will_not_start_without_the_nonce_from_its_own_page(): void + { + $url = $this->flow()->start(); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $url); + $this->assertSame('error', ConnectionFlow::takeNotice()['level']); + } + + public function test_will_not_start_for_someone_who_cannot_review(): void + { + wp_set_current_user(self::factory()->user->create(['role' => 'author'])); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $this->startConnecting()); + } + + public function test_says_why_when_wp_admin_is_on_another_address_from_the_site(): void + { + $_GET['_wpnonce'] = $_REQUEST['_wpnonce'] = wp_create_nonce('altimiser_connect'); + + $url = $this->flow('https://www.client.example.com')->start(); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $url); + $this->assertStringContainsString('same address as the site itself', ConnectionFlow::takeNotice()['message']); + } + + public function test_keeps_the_connection_altimiser_hands_back(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + $this->altimiserAnswers(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","token":"'.str_repeat('ab', 32).'","expires_at":"'.gmdate('c', time() + HOUR_IN_SECONDS).'","account":{"email":"sam@agency.example"}}'); + + $url = $this->comeBackWith(['action' => 'altimiser_connected', 'code' => 'the-code', 'state' => $state]); + + $this->assertSame(admin_url('admin.php?page=altimiser'), $url); + $this->assertSame(['level' => 'success', 'message' => 'Your Altimiser account is connected.'], ConnectionFlow::takeNotice()); + $this->assertSame(str_repeat('ab', 32), Connections::live($this->editor->ID)['token']); + $this->assertStringContainsString('"code":"the-code"', $this->requests[0]['args']['body']); + $this->assertStringContainsString('"redirect_uri":"'.admin_url('admin-post.php?action=altimiser_connected').'"', $this->requests[0]['args']['body']); + } + + public function test_keeps_the_token_encrypted_and_against_this_site_only(): void + { + global $wpdb; + + Connections::put($this->editor->ID, ['connection' => 'c', 'token' => str_repeat('ab', 32), 'expires_at' => time() + 60, 'account_email' => '']); + + $stored = get_user_meta($this->editor->ID, $wpdb->get_blog_prefix().Connections::$option, true); + + $this->assertIsArray($stored); + $this->assertStringNotContainsString(str_repeat('ab', 32), (string) wp_json_encode($stored)); + $this->assertSame('', get_user_meta($this->editor->ID, Connections::$option, true)); + } + + public function test_refuses_a_return_whose_state_does_not_match_and_asks_altimiser_nothing(): void + { + $this->startConnecting(); + $this->altimiserAnswers(201, '{}'); + + $this->comeBackWith(['code' => 'the-code', 'state' => str_repeat('x', 40)]); + + $this->assertStringContainsString('could not be checked', ConnectionFlow::takeNotice()['message']); + $this->assertSame([], $this->requests); + $this->assertNull(Connections::live($this->editor->ID)); + } + + public function test_uses_a_state_once(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + $this->altimiserAnswers(422, '{"message":"That code has already been used."}'); + + $this->comeBackWith(['code' => 'the-code', 'state' => $state]); + $this->comeBackWith(['code' => 'the-code', 'state' => $state]); + + $this->assertCount(1, $this->requests); + } + + public function test_explains_a_declined_connection_without_blaming_the_editor(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + + $this->comeBackWith(['error' => 'access_denied', 'state' => $state]); + + $this->assertStringContainsString('Either it was declined, or your account has not been given this site.', ConnectionFlow::takeNotice()['message']); + } + + public function test_passes_on_altimisers_reason_for_refusing_a_code(): void + { + $state = $this->queryOf($this->startConnecting())['state']; + $this->altimiserAnswers(422, '{"message":"That code has expired."}'); + + $this->comeBackWith(['code' => 'the-code', 'state' => $state]); + + $this->assertSame(['level' => 'error', 'message' => 'Your Altimiser account could not be connected: That code has expired.'], ConnectionFlow::takeNotice()); + } + + public function test_forgets_the_connection_on_disconnecting(): void + { + Connections::put($this->editor->ID, ['connection' => 'c', 'token' => 't', 'expires_at' => time() + 60, 'account_email' => '']); + $_REQUEST['_wpnonce'] = wp_create_nonce('altimiser_disconnect'); + + $this->flow()->disconnect(); + + $this->assertNull(Connections::live($this->editor->ID)); + $this->assertSame('success', ConnectionFlow::takeNotice()['level']); + } + + public function test_keeps_the_connection_when_disconnecting_without_the_nonce(): void + { + Connections::put($this->editor->ID, ['connection' => 'c', 'token' => 't', 'expires_at' => time() + 60, 'account_email' => '']); + + $this->flow()->disconnect(); + + $this->assertNotNull(Connections::live($this->editor->ID)); + } +} diff --git a/tests/ControlPanelTest.php b/tests/ControlPanelTest.php index ede421a..8030088 100644 --- a/tests/ControlPanelTest.php +++ b/tests/ControlPanelTest.php @@ -32,17 +32,112 @@ private function answer(int $status, string $body): array return ['headers' => [], 'body' => $body, 'response' => ['code' => $status, 'message' => ''], 'cookies' => [], 'filename' => null]; } - public function test_signs_the_worked_example_in_the_protocol_document(): void + /** + * @return array{connection: string, token: string} + */ + private function connection(): array + { + return ['connection' => '01jcz6r4s8x2m0v3q9k7t5w1yd', 'token' => str_repeat('ab', 32)]; + } + + public function test_signs_the_worked_review_link_in_the_protocol_document(): void { $this->assertSame( - 'https://altimiser.example.com/review?embedded=1&expires=1769558400&site=https%3A%2F%2Fexample.com&user=editor%40example.com&signature=56424ced69568825952d43fb40de622e730610712898c7ecc35cd1b0d1dd2347', - $this->panel()->reviewUrl('editor@example.com', 1769558400), + 'https://altimiser.example.com/review?connection=01jcz6r4s8x2m0v3q9k7t5w1yd&embedded=1&expires=1769558400&site=https%3A%2F%2Fexample.com&user=editor%40example.com' + .'&signature=d747d7461ab0bd482ca2c63dbfdba805272879161a55b85294b1bfbc254d670f' + .'&connection_signature=05f7d157967aa7d78326438cc32082256bd12016a9f6eb3de2145b6e931d7cba', + $this->panel()->reviewUrl('editor@example.com', 1769558400, $this->connection()), + ); + } + + public function test_signs_the_worked_connect_link_in_the_protocol_document(): void + { + $this->assertSame( + 'https://altimiser.example.com/connect?expires=1769558400&redirect_uri=https%3A%2F%2Fexample.com%2Fcp%2Faltimiser%2Fconnect%2Fcallback&site=https%3A%2F%2Fexample.com&state=s7Kq2wX9pL4mN8vR3tY6uZ1aB5cD0eFg&user=editor%40example.com' + .'&signature=43e86c386c1c7fd4f94ffcd47fc0ea4ca48e14631ab991cf3f6d10bbd7cbc271', + $this->panel()->connectUrl('s7Kq2wX9pL4mN8vR3tY6uZ1aB5cD0eFg', 'https://example.com/cp/altimiser/connect/callback', 'editor@example.com', 1769558400), ); } public function test_leaves_out_a_user_with_no_email(): void { - $this->assertStringNotContainsString('user=', $this->panel()->reviewUrl('', 1769558400)); + $this->assertStringNotContainsString('user=', $this->panel()->reviewUrl('', 1769558400, $this->connection())); + } + + public function test_exchanges_the_code_with_a_request_signed_over_its_body(): void + { + $this->altimiserAnswers($this->answer(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","token":"'.str_repeat('ab', 32).'","expires_at":"2026-11-12T10:00:00+00:00","account":{"name":"Sam Example","email":"sam@agency.example"}}')); + + $connection = $this->panel()->exchange('the-code', 'https://example.com/wp-admin/admin-post.php?action=altimiser_connected'); + + $this->assertSame([ + 'connection' => '01jcz6r4s8x2m0v3q9k7t5w1yd', + 'token' => str_repeat('ab', 32), + 'expires_at' => 1794477600, + 'account_email' => 'sam@agency.example', + ], $connection); + + ['url' => $url, 'args' => $args] = $this->requests[0]; + $timestamp = $args['headers']['X-Altimiser-Timestamp']; + + $this->assertSame('https://altimiser.example.com/api/connections', $url); + $this->assertSame('POST', $args['method']); + $this->assertSame('{"site":"https://example.com","code":"the-code","redirect_uri":"https://example.com/wp-admin/admin-post.php?action=altimiser_connected"}', $args['body']); + $this->assertSame('sha256='.hash_hmac('sha256', "{$timestamp}\n{$args['body']}", 'shared-secret'), $args['headers']['X-Altimiser-Signature']); + $this->assertSame(0, $args['redirection']); + } + + /** + * @dataProvider failedExchanges + * + * @param array|WP_Error $response + */ + public function test_says_why_a_code_could_not_be_exchanged(array|WP_Error $response, string $reason): void + { + $this->altimiserAnswers($response); + + $connection = $this->panel()->exchange('the-code', 'https://example.com/wp-admin/admin-post.php'); + + $this->assertInstanceOf(WP_Error::class, $connection); + $this->assertSame($reason, $connection->get_error_message()); + } + + /** + * @return array|WP_Error, string}> + */ + public static function failedExchanges(): array + { + $answer = static fn (int $status, string $body): array => ['headers' => [], 'body' => $body, 'response' => ['code' => $status, 'message' => ''], 'cookies' => [], 'filename' => null]; + + return [ + 'unreachable' => [new WP_Error('http_request_failed', 'Connection timed out'), 'Altimiser could not be reached.'], + 'a used code' => [$answer(422, '{"message":"That code has already been used."}'), 'That code has already been used.'], + 'a server error' => [$answer(500, 'Server error'), 'Altimiser refused the connection.'], + 'no token' => [$answer(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","expires_at":"2026-11-12T10:00:00+00:00"}'), 'Altimiser sent an answer that could not be read.'], + 'no expiry' => [$answer(201, '{"connection":"01jcz6r4s8x2m0v3q9k7t5w1yd","token":"abc"}'), 'Altimiser sent an answer that could not be read.'], + ]; + } + + /** + * @dataProvider origins + */ + public function test_knows_whether_an_address_is_on_the_sites_own_origin(string $address, bool $same): void + { + $this->assertSame($same, $this->panel()->isOnSiteOrigin($address)); + } + + /** + * @return array + */ + public static function origins(): array + { + return [ + 'wp-admin on the same host' => ['https://example.com/wp-admin/admin-post.php?action=altimiser_connected', true], + 'the default port written out' => ['https://EXAMPLE.com:443/wp-admin/', true], + 'another host' => ['https://admin.example.com/wp-admin/', false], + 'plain http' => ['http://example.com/wp-admin/', false], + 'another port' => ['https://example.com:8443/wp-admin/', false], + ]; } public function test_expires_a_link_after_the_configured_minutes(): void @@ -152,7 +247,7 @@ public function test_names_the_site_by_its_own_address_with_no_trailing_slash(): define('ALTIMISER_SECRET', 'a-shared-secret-of-at-least-32-characters'); add_filter('home_url', static fn (): string => 'https://client.example.com/'); - $url = ControlPanel::configured()->reviewUrl('', 1769558400); + $url = ControlPanel::configured()->reviewUrl('', 1769558400, ['connection' => 'c', 'token' => 't']); $this->assertStringStartsWith('https://altimiser.example.com/review?', $url); $this->assertStringContainsString('site=https%3A%2F%2Fclient.example.com&', $url); @@ -172,7 +267,7 @@ public function test_takes_the_sites_address_from_a_constant_where_the_two_disag $panel = ControlPanel::configured(); - $this->assertStringContainsString('site=https%3A%2F%2Fwww.client.example.com&', $panel->reviewUrl('', 1769558400)); + $this->assertStringContainsString('site=https%3A%2F%2Fwww.client.example.com&', $panel->reviewUrl('', 1769558400, ['connection' => 'c', 'token' => 't'])); $this->assertEqualsWithDelta(time() + 600, $panel->linkExpiry(), 2); } } diff --git a/tests/ReviewQueuePageTest.php b/tests/ReviewQueuePageTest.php index 1816bf2..fa74b90 100644 --- a/tests/ReviewQueuePageTest.php +++ b/tests/ReviewQueuePageTest.php @@ -1,5 +1,7 @@ user->create_and_get(['role' => $role, 'user_email' => "{$role}@example.com"]); wp_set_current_user($user->ID); + if ($connected) { + $this->connect($user, time() + HOUR_IN_SECONDS); + } + return $user; } + private function connect(WP_User $user, int $expiresAt): void + { + Connections::put($user->ID, [ + 'connection' => '01jcz6r4s8x2m0v3q9k7t5w1yd', + 'token' => str_repeat('ab', 32), + 'expires_at' => $expiresAt, + 'account_email' => 'sam@agency.example', + ]); + } + private function altimiserCounts(int|WP_Error $count): void { add_filter('pre_http_request', function () use ($count) { @@ -190,10 +206,11 @@ public function test_frames_a_link_signed_for_whoever_is_signed_in(): void $this->assertStringContainsString('user=editor%40example.com', $frame[1]); $this->assertStringContainsString('embedded=1', $frame[1]); - $this->assertSignedWithTheSharedSecret($frame[1]); + $this->assertStringContainsString('connection=01jcz6r4s8x2m0v3q9k7t5w1yd', $frame[1]); + $this->assertSignedWithTheSecretAndTheToken($frame[1]); } - public function test_shows_only_the_frame(): void + public function test_shows_no_heading_or_link_around_the_frame(): void { $this->signInAs('editor'); @@ -203,18 +220,75 @@ public function test_shows_only_the_frame(): void $this->assertStringNotContainsString('assertSame(hash_hmac('sha256', $signed, 'shared-secret'), $signature); + $this->assertSame(hash_hmac('sha256', $parts[1], 'shared-secret'), $parts[2]); + $this->assertSame(hash_hmac('sha256', $parts[1], str_repeat('ab', 32)), $parts[3]); } public function test_sends_the_browser_nothing_that_could_sign_another_link(): void { $this->signInAs('editor'); - $this->assertStringNotContainsString('shared-secret', $this->renderedPage()); + $html = $this->renderedPage(); + + $this->assertStringNotContainsString('shared-secret', $html); + $this->assertStringNotContainsString(str_repeat('ab', 32), $html); + } + + public function test_says_who_is_connected_and_offers_to_disconnect(): void + { + $this->signInAs('editor'); + + $html = $this->renderedPage(); + + $this->assertStringContainsString('Connected as sam@agency.example until', $html); + $this->assertStringContainsString('name="action" value="altimiser_disconnect"', $html); + $this->assertStringContainsString('name="_wpnonce"', $html); + } + + public function test_offers_to_connect_an_editor_who_has_not_and_frames_nothing(): void + { + $this->signInAs('editor', connected: false); + + $html = html_entity_decode($this->renderedPage(), ENT_QUOTES); + + $this->assertStringContainsString('Connect your Altimiser account', $html); + $this->assertMatchesRegularExpression('#href="[^"]+/wp-admin/admin-post\.php\?action=altimiser_connect&_wpnonce=\w+"#', $html); + $this->assertStringNotContainsString('signInAs('editor', connected: false); + $this->connect($user, time() - 1); + + $this->assertStringContainsString('Connect your Altimiser account', $this->renderedPage()); + } + + public function test_shows_what_the_last_connection_step_said_once(): void + { + $this->signInAs('editor'); + set_transient('altimiser_notice_'.get_current_user_id(), ['level' => 'success', 'message' => 'Your Altimiser account is connected.'], MINUTE_IN_SECONDS); + + $this->assertStringContainsString('

    Your Altimiser account is connected.

    ', $this->renderedPage()); + $this->assertNull(ConnectionFlow::takeNotice()); + } + + public function test_shows_no_count_and_asks_nothing_until_the_editor_connects(): void + { + $this->altimiserCounts(12); + $this->signInAs('editor', connected: false); + + $this->page->addMenuItem(); + $widget = $this->renderedWidget(); + + $this->assertSame('Altimiser', $this->menuLabel()); + $this->assertStringContainsString('Connect your Altimiser account to see what is waiting for review.', $widget); + $this->assertStringContainsString('admin.php?page=altimiser', $widget); + $this->assertSame(0, $this->requests); } public function test_adds_a_dashboard_widget_for_someone_who_reviews(): void diff --git a/tests/SettingsPageTest.php b/tests/SettingsPageTest.php index 59f84eb..6ccb10c 100644 --- a/tests/SettingsPageTest.php +++ b/tests/SettingsPageTest.php @@ -1,5 +1,6 @@ assertStringContainsString(esc_html(rest_url('altimiser/v1')), $this->rendered()); } - public function test_uninstalling_removes_the_settings_and_the_kept_count(): void + public function test_uninstalling_removes_the_settings_the_kept_count_and_every_connection(): void { + $editor = self::factory()->user->create(['role' => 'editor']); update_option(Settings::$option, ['secret' => $this->longSecret]); set_transient('altimiser_summary', ['summary' => ['awaiting_review' => 1]], 300); + Connections::put($editor, ['connection' => 'c', 'token' => 't', 'expires_at' => time() + 60, 'account_email' => '']); define('WP_UNINSTALL_PLUGIN', 'altimiser/altimiser.php'); require dirname(__DIR__).'/uninstall.php'; $this->assertFalse(get_option(Settings::$option)); $this->assertFalse(get_transient('altimiser_summary')); + $this->assertFalse(get_user_option(Connections::$option, $editor)); } public function test_shows_nothing_to_someone_who_cannot_manage_options(): void diff --git a/uninstall.php b/uninstall.php index 635aa54..7008f0c 100644 --- a/uninstall.php +++ b/uninstall.php @@ -11,6 +11,7 @@ delete_option('altimiser_settings'); delete_transient('altimiser_summary'); delete_transient('altimiser_summary_lock'); + delete_metadata('user', 0, $GLOBALS['wpdb']->get_blog_prefix().'altimiser_connection', '', true); }; if (! is_multisite()) { From 8a32928e798eb1efb8046e1c56c40cebcf3a9458 Mon Sep 17 00:00:00 2001 From: Alt-Charlie Date: Fri, 13 Nov 2026 16:30:29 +0000 Subject: [PATCH 6/6] Note the tag ruleset and immutable releases in the release steps --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 98d4045..65f2677 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ WordPress's own updater offers new versions, from the latest release on GitHub. A site that keeps its plugins in git should commit the update instead, or the next deploy puts the old version back. -To publish a release, change `Version` in `altimiser.php` on `main`, then push a tag naming that version, such as `v0.2.0`. The release workflow runs the tests, checks that the tag is on `main` and matches the version, and only then builds `altimiser.zip` and publishes it. The updater trusts the latest release, so keep the ability to push tags to people who need it. +To publish a release, change `Version` in `altimiser.php` on `main`, then push a tag naming that version, such as `v0.2.0`. The release workflow runs the tests, checks that the tag is on `main` and matches the version, and only then builds `altimiser.zip` and publishes it. A ruleset lets only repository admins create a `v` tag and stops anyone moving or deleting one, and published releases are immutable, so the zip of a release cannot be swapped once it is out. The updater trusts the latest release, so keep admin access to the repository to people who need it. ## Uninstalling