diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bb8c3ca --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,26 @@ +name: Release + +on: + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + release: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Check the tag matches the plugin's version + 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 + + - name: Publish the release + run: gh release create "$GITHUB_REF_NAME" altimiser.zip --generate-notes + env: + GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..c105f47 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,56 @@ +name: Tests + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +concurrency: + group: tests-${{ github.ref }} + cancel-in-progress: true + +jobs: + tests: + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + php: ['8.1', '8.2', '8.3', '8.4'] + wordpress: ['6.8.*', '*'] + + services: + mysql: + image: mysql:8.4 + env: + MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' + MYSQL_DATABASE: altimiser_wordpress_tests + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping --silent" + --health-interval=10s + --health-timeout=5s + --health-retries=5 + + steps: + - uses: actions/checkout@v4 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mysqli + coverage: none + + - name: Install dependencies + run: >- + composer require --dev --no-interaction --no-progress --prefer-dist --with-all-dependencies + "roots/wordpress:${{ matrix.wordpress }}" + "wp-phpunit/wp-phpunit:${{ matrix.wordpress }}" + + - name: Run tests + run: vendor/bin/phpunit diff --git a/README.md b/README.md new file mode 100644 index 0000000..3d7c328 --- /dev/null +++ b/README.md @@ -0,0 +1,145 @@ +# 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. + +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. + +## 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. + +## Installing + +Put this repository in `wp-content/plugins/altimiser` and activate the plugin. + +Then add a shared secret to `wp-config.php`, above the line that says to stop editing: + +```php +define('ALTIMISER_SECRET', 'a long random string'); +``` + +With WP-CLI, this generates one and writes it there: + +```bash +wp config set ALTIMISER_SECRET "$(openssl rand -hex 32)" +``` + +Every request is refused until the secret is set, so an install without one is inert rather than open. + +## Connecting + +From Altimiser, using the same secret: + +```bash +php artisan altimiser:connect https://example.com https://example.com/wp-json/altimiser/v1 +``` + +Use the address the site actually answers at, including `https` and any `www`. Altimiser follows redirects, which works for this `GET`, but a `POST` that gets redirected arrives as a `GET` and fails later on. + +A successful connection shows the receiver as `wordpress` with the plugin's version and the WordPress version. Without Yoast SEO active a warning appears: "advertises no checks". + +Connect again after activating Yoast SEO, so Altimiser reads what the site can now apply. + +## What gets changed + +| Checks | Yoast SEO field | +| --- | --- | +| `title.missing`, `too_short`, `too_long`, `irrelevant`, `duplicate` | SEO title | +| `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`. + +`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. + +A change is refused rather than guessed at, and the finding goes to a person: + +| Reason | What it means | +| --- | --- | +| `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 | +| `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. + +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. + +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. + +| 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 | + +Any other page cache is not purged, so a change appears there once the cache expires. + +`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: + +```php +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. + +Two more constants are available: + +| Constant | What it is for | +| --- | --- | +| `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 | + +## 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. + +## When the connection fails + +`altimiser:connect` prints the status and the start of the response. + +| 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` 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 | +| `401` or `403` with another code, such as `rest_not_logged_in` | Something is refusing anonymous REST requests before the signature is looked at. Altimiser's requests are anonymous, because the signature is what identifies them | Security plugins and any `rest_authentication_errors` filter. Allow `/wp-json/altimiser/v1/` | +| `403` from something other than WordPress, or a timeout | A firewall or CDN in front of the site | Let Altimiser's server through | + +Each row was reproduced on a local install except the firewall row and the missing headers, which are inferred. + +Two common security plugins need nothing doing. From reading their source, and not from testing on a running site: the REST API restriction in Kadence Security 9.0.3 (formerly iThemes Security) covers only `wp` routes, and the REST hooks in Wordfence 8.2.2 cover only user routes. + +## 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. + +```bash +composer install +mysql -h127.0.0.1 -uroot -e "CREATE DATABASE IF NOT EXISTS altimiser_wordpress_tests" +vendor/bin/phpunit +``` + +GitHub Actions runs them on PHP 8.1 to 8.4, against WordPress 6.8 and the latest release. + +`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`. diff --git a/altimiser.php b/altimiser.php new file mode 100644 index 0000000..5b7e0ba --- /dev/null +++ b/altimiser.php @@ -0,0 +1,47 @@ +registerRoutes(); +}); + +add_action('plugins_loaded', static function (): void { + $controlPanel = ControlPanel::configured(); + + if ($controlPanel !== null) { + (new ReviewQueuePage($controlPanel))->register(); + } +}); + +(new Updater(__FILE__))->register(); diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..f9cae2c --- /dev/null +++ b/composer.json @@ -0,0 +1,34 @@ +{ + "name": "alt-design/altimiser-wordpress", + "description": "Applies Altimiser's approved changes to a WordPress site.", + "type": "wordpress-plugin", + "license": "proprietary", + "require": { + "php": ">=8.1" + }, + "require-dev": { + "phpunit/phpunit": "^9.6", + "roots/wordpress": ">=6.8", + "wp-phpunit/wp-phpunit": ">=6.8", + "yoast/phpunit-polyfills": "^2.0", + "composer/installers": "^2.3", + "wpackagist-plugin/wordpress-seo": "*" + }, + "extra": { + "wordpress-install-dir": "wordpress", + "installer-paths": { + "vendor/wp-plugins/{$name}/": ["type:wordpress-plugin"] + } + }, + "config": { + "allow-plugins": { + "roots/wordpress-core-installer": true, + "composer/installers": true + } + }, + "repositories": [{ + "name": "wpackagist", + "type": "composer", + "url": "https://wpackagist.org" + }] +} diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..46ddaf3 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,8 @@ + + + + + tests + + + diff --git a/src/ChangeDispatcher.php b/src/ChangeDispatcher.php new file mode 100644 index 0000000..3495a87 --- /dev/null +++ b/src/ChangeDispatcher.php @@ -0,0 +1,102 @@ + $appliers + */ + public function __construct(private array $appliers, private PageCache $pageCache) {} + + /** + * Does a bounded amount of work and hands the rest back as deferred, because no + * web server holds a request open for hundreds of changes. Altimiser sends the + * rest again, and a change already in place comes back as already applied. + * + * 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. + * + * @param array $changes + * @return array> + */ + public function dispatch(array $changes, bool $dryRun): array + { + $startedAt = microtime(true); + $batchSize = (int) apply_filters('altimiser_batch_size', 10); + $budget = $this->timeBudget(); + $results = []; + + foreach ($changes as $change) { + if ($results !== [] && $this->outOfRoom(count($results), $batchSize, $startedAt, $budget)) { + $results[] = ChangeResult::deferred($change->id); + + continue; + } + + $results[] = $this->applyOne($change, $dryRun); + } + + if (! $dryRun && array_intersect(['applied', 'already_applied'], array_column($results, 'status')) !== []) { + $this->pageCache->purge(); + } + + return $results; + } + + /** + * Half the limit, because a request killed mid-change leaves it unrecorded, and + * one change can take a while once it has been started. + */ + public function timeBudget(): float + { + $budget = (float) apply_filters('altimiser_time_budget', 45); + $limit = (int) ini_get('max_execution_time'); + + return $limit > 0 ? min($budget, $limit / 2) : $budget; + } + + private function outOfRoom(int $attempted, int $batchSize, float $startedAt, float $budget): bool + { + return $attempted >= $batchSize || microtime(true) - $startedAt > $budget; + } + + /** + * 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; + } + + try { + return $applier->apply($change, $dryRun); + } catch (Throwable $exception) { + return ChangeResult::failed($change->id, 'write_failed', $exception->getMessage()); + } + } + + return ChangeResult::skipped( + $change->id, + 'unsupported_check', + "This receiver has no transform for {$change->check}.", + ); + } +} diff --git a/src/ChangeRequest.php b/src/ChangeRequest.php new file mode 100644 index 0000000..79c4f1b --- /dev/null +++ b/src/ChangeRequest.php @@ -0,0 +1,53 @@ + $target + */ + private function __construct( + public readonly string $id, + public readonly string $check, + public readonly string $url, + public readonly array $target, + public readonly ?string $currentValue, + public readonly ?string $suggestedValue, + ) {} + + /** + * Null when the change is malformed, which is reported for that change alone. + */ + public static function fromPayload(mixed $change): ?self + { + if (! is_array($change)) { + return null; + } + + foreach (['id', 'check', 'url'] as $required) { + if (! is_string($change[$required] ?? null) || $change[$required] === '') { + return null; + } + } + + foreach (['current_value', 'suggested_value'] as $optional) { + if (! is_string($change[$optional] ?? '')) { + return null; + } + } + + if (! is_array($change['target'] ?? [])) { + return null; + } + + return new self( + $change['id'], + $change['check'], + $change['url'], + $change['target'] ?? [], + $change['current_value'] ?? null, + $change['suggested_value'] ?? null, + ); + } +} diff --git a/src/ChangeResult.php b/src/ChangeResult.php new file mode 100644 index 0000000..9be7d37 --- /dev/null +++ b/src/ChangeResult.php @@ -0,0 +1,51 @@ + $location + * @return array + */ + public static function applied(string $id, array $location, ?string $from, ?string $to): array + { + return array_filter( + ['id' => $id, 'status' => 'applied', 'location' => $location, 'from' => $from, 'to' => $to], + static fn (mixed $value): bool => $value !== null, + ); + } + + /** + * @param array $location + * @return array + */ + public static function alreadyApplied(string $id, array $location, string $message): array + { + return ['id' => $id, 'status' => 'already_applied', 'location' => $location, 'message' => $message]; + } + + /** + * @return array + */ + public static function deferred(string $id): array + { + return ['id' => $id, 'status' => 'deferred', 'message' => 'Not attempted in this request. Send it again.']; + } + + /** + * @return array + */ + public static function skipped(string $id, string $reason, string $message): array + { + return ['id' => $id, 'status' => 'skipped', 'reason' => $reason, 'message' => $message]; + } + + /** + * @return array + */ + public static function failed(string $id, string $reason, string $message): array + { + return ['id' => $id, 'status' => 'failed', 'reason' => $reason, 'message' => $message]; + } +} diff --git a/src/ContentResolver.php b/src/ContentResolver.php new file mode 100644 index 0000000..ef9e988 --- /dev/null +++ b/src/ContentResolver.php @@ -0,0 +1,66 @@ +findTerm($url); + } + + return $this->isPublishedAt($url, $postId) ? get_post($postId) : 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. + */ + private function isPublishedAt(string $url, int $postId): bool + { + if (get_post_status($postId) !== 'publish') { + return false; + } + + return $this->address(get_permalink($postId)) === $this->address($url); + } + + private function findTerm(string $url): ?WP_Term + { + foreach (get_taxonomies(['public' => true]) as $taxonomy) { + $term = get_term_by('slug', wp_basename($this->path($url)), $taxonomy); + + if (! $term instanceof WP_Term) { + continue; + } + + if ($this->address(get_term_link($term)) === $this->address($url)) { + return $term; + } + } + + return null; + } + + private function address(string $url): string + { + return $this->path($url).'?'.parse_url($url, PHP_URL_QUERY); + } + + /** + * Decoded, because WordPress keeps a slug in another alphabet percent encoded in + * lower case, and a scan may have seen it in upper case or as the letters themselves. + */ + private function path(string $url): string + { + return trim(rawurldecode((string) parse_url($url, PHP_URL_PATH)), '/'); + } +} diff --git a/src/ControlPanel.php b/src/ControlPanel.php new file mode 100644 index 0000000..02ac0be --- /dev/null +++ b/src/ControlPanel.php @@ -0,0 +1,97 @@ +linkMinutes * MINUTE_IN_SECONDS; + } + + public function reviewUrl(string $user, int $expires): string + { + $url = "{$this->altimiserUrl}/review?".http_build_query(array_filter([ + 'embedded' => '1', + 'expires' => $expires, + 'site' => $this->siteUrl, + 'user' => $user, + ])); + + return "{$url}&signature=".hash_hmac('sha256', $url, $this->secret); + } + + /** + * 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. + */ + public function awaitingReview(): ?int + { + $cached = get_transient('altimiser_awaiting_review'); + + if (is_array($cached)) { + return $cached['count']; + } + + $count = $this->fetchAwaitingReview(); + + set_transient('altimiser_awaiting_review', ['count' => $count], 5 * MINUTE_IN_SECONDS); + + return $count; + } + + /** + * Redirects are not followed, because the signature would be sent on to wherever + * they lead. + */ + private function fetchAwaitingReview(): ?int + { + $timestamp = time(); + + $response = wp_remote_get("{$this->altimiserUrl}/api/summary?".http_build_query(['site' => $this->siteUrl]), [ + 'timeout' => 5, + 'redirection' => 0, + 'headers' => [ + 'X-Altimiser-Timestamp' => (string) $timestamp, + 'X-Altimiser-Signature' => 'sha256='.hash_hmac('sha256', "{$timestamp}\n", $this->secret), + 'Accept' => 'application/json', + ], + ]); + + if (wp_remote_retrieve_response_code($response) !== 200) { + return null; + } + + $count = json_decode(wp_remote_retrieve_body($response), true)['awaiting_review'] ?? null; + + return is_int($count) ? $count : null; + } +} diff --git a/src/PageCache.php b/src/PageCache.php new file mode 100644 index 0000000..bdea2c8 --- /dev/null +++ b/src/PageCache.php @@ -0,0 +1,35 @@ +getMessage()}"); + } + } +} diff --git a/src/Receiver.php b/src/Receiver.php new file mode 100644 index 0000000..751db70 --- /dev/null +++ b/src/Receiver.php @@ -0,0 +1,154 @@ + WP_REST_Server::READABLE, + 'callback' => [$this, 'health'], + 'permission_callback' => [$this, 'verifySignature'], + ]); + + register_rest_route('altimiser/v1', '/changes', [ + 'methods' => WP_REST_Server::CREATABLE, + 'callback' => [$this, 'changes'], + 'permission_callback' => [$this, 'verifySignature'], + ]); + } + + public function verifySignature(WP_REST_Request $request): bool|WP_Error + { + $secret = defined('ALTIMISER_SECRET') ? constant('ALTIMISER_SECRET') : null; + + if (! is_string($secret) || trim($secret) === '') { + return $this->refuse('Altimiser is not configured on this site.'); + } + + $timestamp = (int) $request->get_header('X-Altimiser-Timestamp'); + + if (abs(time() - $timestamp) > $this->toleranceInSeconds) { + return $this->refuse('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 true; + } + + public function health(): WP_REST_Response + { + $checks = array_merge([], ...array_map( + static fn (YoastApplier $applier): array => $applier->checks(), + $this->appliers(), + )); + + return $this->uncached([ + 'receiver' => 'wordpress', + 'receiver_version' => get_file_data($this->pluginFile, ['version' => 'Version'])['version'], + 'cms_version' => get_bloginfo('version'), + 'capabilities' => $checks === [] ? [] : ['content.update'], + 'checks' => $checks, + 'integrations' => ['yoast' => $this->yoastState()], + 'site_url' => home_url(), + ]); + } + + public function changes(WP_REST_Request $request): WP_REST_Response|WP_Error + { + $payload = json_decode($request->get_body(), true); + + if (! is_array($payload) || ! is_array($payload['changes'] ?? null) || ! is_bool($payload['dry_run'] ?? false)) { + return new WP_Error( + 'altimiser_unreadable', + 'The body needs a changes array, and dry_run has to be true or false where it is sent.', + ['status' => 422], + ); + } + + $changes = []; + $rejected = []; + + foreach ($payload['changes'] as $index => $change) { + $parsed = ChangeRequest::fromPayload($change); + + if ($parsed === null) { + $id = is_array($change) && is_string($change['id'] ?? null) ? $change['id'] : "index-{$index}"; + $rejected[] = ChangeResult::failed($id, 'invalid_change', 'This change is malformed and could not be read.'); + + continue; + } + + $changes[] = $parsed; + } + + $dispatcher = new ChangeDispatcher($this->appliers(), new PageCache()); + + return new WP_REST_Response([ + 'results' => [...$rejected, ...$dispatcher->dispatch($changes, $payload['dry_run'] ?? false)], + ]); + } + + /** + * @return array + */ + private function appliers(): array + { + return $this->yoast === null ? [] : [new YoastApplier($this->yoast, new ContentResolver())]; + } + + /** + * @return array + */ + private function yoastState(): array + { + return $this->yoast === null + ? ['installed' => false] + : ['installed' => true, 'version' => $this->yoast->version()]; + } + + /** + * WordPress only sends no-cache headers to logged in users, and this caller + * never is one. A page cache that kept this response would serve it to later + * requests without running the signature check. + * + * Core marks Last-Modified for removal with false, which a REST response would + * send as an empty header, so falsy values are filtered out. + * + * Breeze 2.1.11 keeps REST responses of 255 bytes or more, ignoring both the + * constant and the headers. Its one exception that a request can reach is + * post_password_required() being true when its buffer callback runs at shutdown. + * + * @param array $body + */ + private function uncached(array $body): WP_REST_Response + { + if (! defined('DONOTCACHEPAGE')) { + define('DONOTCACHEPAGE', true); + } + + add_action('shutdown', static fn () => add_filter('post_password_required', '__return_true'), 0); + + 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 new file mode 100644 index 0000000..e120214 --- /dev/null +++ b/src/ReviewQueuePage.php @@ -0,0 +1,92 @@ +capability)) { + return; + } + + add_menu_page('Altimiser', 'Altimiser'.$this->badge(), $this->capability, 'altimiser', [$this, 'render'], $this->icon()); + } + + /** + * The Statamic addon's rocket. It is a line drawing and WordPress only recolours fills + * to match the admin colour scheme, so the lines mask a filled square. + */ + private function icon(): string + { + $rocket = 'M11.4 4.9c2.6-2.6 5.4-2.8 6.6-2.7.1 1.2-.1 4-2.7 6.6l-5 5-3.9-3.9 5-5Z M6.6 12.2 3.1 9.9l2.8-1.7 2.3.6m3.1 6.6 2.3 3.5 1.7-2.8-.6-2.3 M7.9 12.1 4.6 15.4 M13.8 6.2a1 1 0 1 1-1.4 1.4 1 1 0 0 1 1.4-1.4Z'; + + return 'data:image/svg+xml;base64,'.base64_encode( + '' + ."" + .'' + ); + } + + public function addDashboardWidget(): void + { + if (! current_user_can($this->capability)) { + return; + } + + wp_add_dashboard_widget('altimiser', 'Altimiser', [$this, 'renderWidget']); + } + + public function render(): void + { + printf( + '' + .'', + esc_url($this->panel->reviewUrl(wp_get_current_user()->user_email, $this->panel->linkExpiry())), + ); + } + + public function renderWidget(): void + { + printf( + '

%s

Open the review queue

', + esc_html($this->describe($this->panel->awaitingReview())), + esc_url(admin_url('admin.php?page=altimiser')), + ); + } + + private function badge(): string + { + $count = $this->panel->awaitingReview(); + + if (! $count) { + return ''; + } + + return sprintf( + ' %1$d waiting for review', + $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.", + }; + } +} diff --git a/src/Updater.php b/src/Updater.php new file mode 100644 index 0000000..aa8f881 --- /dev/null +++ b/src/Updater.php @@ -0,0 +1,76 @@ + $pluginData + * @return mixed + */ + public function offerLatestRelease(mixed $update, array $pluginData, string $pluginFile): mixed + { + if ($pluginFile !== plugin_basename($this->pluginFile)) { + return $update; + } + + $response = wp_remote_get('https://api.github.com/repos/alt-design/altimiser-wordpress/releases/latest', [ + 'timeout' => 5, + 'headers' => ['Accept' => 'application/vnd.github+json'], + ]); + + if (wp_remote_retrieve_response_code($response) !== 200) { + return $update; + } + + $release = json_decode(wp_remote_retrieve_body($response), true); + $assets = $release['assets'] ?? []; + $package = is_array($assets) ? $this->package($assets) : null; + + if ($package === null || ! is_string($release['tag_name'] ?? null)) { + return $update; + } + + return [ + 'slug' => 'altimiser', + 'version' => ltrim($release['tag_name'], 'v'), + 'url' => 'https://github.com/alt-design/altimiser-wordpress', + 'package' => $package, + ]; + } + + /** + * Only the built zip will do. The archive GitHub makes of a tag unpacks into a + * folder named after the commit, and WordPress would install that as a new plugin. + * WordPress runs what it downloads, so it has to come from this repository's releases. + * + * @param array $assets + */ + private function package(array $assets): ?string + { + foreach ($assets as $asset) { + if (($asset['name'] ?? null) !== 'altimiser.zip') { + continue; + } + + $address = $asset['browser_download_url'] ?? null; + + return is_string($address) && str_starts_with($address, 'https://github.com/alt-design/altimiser-wordpress/releases/download/') + ? $address + : null; + } + + return null; + } +} diff --git a/src/Yoast.php b/src/Yoast.php new file mode 100644 index 0000000..3669fe6 --- /dev/null +++ b/src/Yoast.php @@ -0,0 +1,132 @@ +ID, WPSEO_Meta::$meta_prefix.$field, true) + : WPSEO_Taxonomy_Meta::get_term_meta($record, $record->taxonomy, $this->termField($field)); + + return is_string($value) ? $value : ''; + } + + /** + * What Yoast falls back to when the record has no value of its own, in the order + * its presentations use: a title always has a default, a description may not. + */ + public function template(WP_Post|WP_Term $record, string $field): string + { + $subject = $record instanceof WP_Post ? $record->post_type : "tax-{$record->taxonomy}"; + + return match ($field) { + 'title' => WPSEO_Options::get("title-{$subject}") + ?: (WPSEO_Option_Titles::get_instance()->get_defaults()["title-{$subject}"] ?? ''), + 'metadesc' => (string) WPSEO_Options::get("metadesc-{$subject}", ''), + default => '', + }; + } + + public function render(string $value, WP_Post|WP_Term $record): string + { + return wpseo_replace_vars($value, $record); + } + + public function storageKey(WP_Post|WP_Term $record, string $field): string + { + return $record instanceof WP_Post + ? WPSEO_Meta::$meta_prefix.$field + : "wpseo_{$this->termField($field)}"; + } + + public function write(WP_Post|WP_Term $record, string $field, string $value): void + { + if ($record instanceof WP_Post) { + WPSEO_Meta::set_value($field, $value, $record->ID); + $this->rebuildPost($record); + + return; + } + + $this->writeTerm($record, $field, $value); + } + + public function clear(WP_Post|WP_Term $record, string $field): void + { + if ($record instanceof WP_Post) { + delete_post_meta($record->ID, WPSEO_Meta::$meta_prefix.$field); + $this->rebuildPost($record); + + return; + } + + $this->writeTerm($record, $field, ''); + } + + private function termField(string $field): string + { + return $field === 'metadesc' ? 'desc' : $field; + } + + /** + * Yoast would do this itself in a shutdown function, which is after the page cache + * has been purged, and a visitor arriving in between would put the old value straight + * back into the cache. Left to Yoast's own timing if a later version moves the class. + */ + private function rebuildPost(WP_Post $post): void + { + if (class_exists(Indexable_Post_Watcher::class)) { + YoastSEO()->classes->get(Indexable_Post_Watcher::class)->build_indexable($post->ID); + } + } + + /** + * Passes every field back, because WPSEO_Taxonomy_Meta::set_value() keeps only the + * text fields it is given and empties the term's other title, description and + * social values. + */ + private function writeTerm(WP_Term $term, string $field, string $value): void + { + WPSEO_Taxonomy_Meta::set_values($term->term_id, $term->taxonomy, [ + ...WPSEO_Taxonomy_Meta::get_term_meta($term, $term->taxonomy), + "wpseo_{$this->termField($field)}" => $value, + ]); + + $this->rebuildTerm($term); + } + + /** + * Term values live in an option, which Yoast's watchers do not listen to, and the + * term's page is rendered from an indexable they maintain, so without this it goes + * on printing the old value. Firing edited_term would tell every other plugin the + * term had been edited. wp_update_term() would fire it too, and it also runs the + * term's own description through wp_filter_kses, whoever is signed in. + */ + private function rebuildTerm(WP_Term $term): void + { + if (class_exists(Indexable_Term_Watcher::class)) { + YoastSEO()->classes->get(Indexable_Term_Watcher::class)->build_indexable($term->term_id); + } + } +} diff --git a/src/YoastApplier.php b/src/YoastApplier.php new file mode 100644 index 0000000..6be249c --- /dev/null +++ b/src/YoastApplier.php @@ -0,0 +1,185 @@ + + */ + public function checks(): array + { + $checks = [ + 'title.missing', + 'title.too_short', + 'title.too_long', + 'title.irrelevant', + 'title.duplicate', + 'meta_description.missing', + 'meta_description.too_short', + 'meta_description.too_long', + 'meta_description.irrelevant', + 'meta_description.duplicate', + ]; + + return $this->yoast->printsSocialTags() ? [...$checks, 'open_graph.missing'] : $checks; + } + + 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 ?? '') === '') { + return ChangeResult::skipped( + $change->id, + 'no_suggestion', + 'There is no replacement value for this check, and this receiver cannot work one out for itself.', + ); + } + + $field = $this->field($change); + + if ($field === null) { + return ChangeResult::skipped($change->id, 'no_field', "Yoast has no text field for {$change->check} on this tag."); + } + + $record = $this->content->find($change->url); + + if ($record === null) { + return ChangeResult::skipped($change->id, 'not_found', "Nothing editable answers to {$change->url}."); + } + + return $this->applyToRecord($change, $record, $field, $dryRun); + } + + /** + * @return array + */ + private function applyToRecord(ChangeRequest $change, WP_Post|WP_Term $record, string $field, bool $dryRun): array + { + $stored = $this->yoast->stored($record, $field); + $inherited = $this->yoast->render($this->yoast->template($record, $field), $record); + $rendered = $stored === '' ? $inherited : $this->yoast->render($stored, $record); + $suggested = $this->yoast->render($change->suggestedValue, $record); + $location = $this->describe($record, $field); + + if ($this->comparable($suggested) === '') { + return ChangeResult::skipped($change->id, 'no_suggestion', 'The replacement value has no text in it once markup is removed.'); + } + + if ($this->same($rendered, $suggested)) { + return ChangeResult::alreadyApplied($change->id, $location, 'This page already has this value.'); + } + + $refusal = $this->refusal($change, $stored, $rendered); + + if ($refusal !== null) { + return $refusal; + } + + $scanned = trim($change->currentValue ?? ''); + $location['inherited'] = $stored === '' && $scanned !== ''; + $location['flattened_template'] = str_contains($stored, '%%'); + $from = $stored === '' ? null : $stored; + + if ($dryRun) { + return ChangeResult::applied($change->id, $location, $from, $change->suggestedValue); + } + + if ($this->same($inherited, $suggested)) { + $this->yoast->clear($record, $field); + + return ChangeResult::applied($change->id, $location, $from, $change->suggestedValue); + } + + $this->yoast->write($record, $field, $change->suggestedValue); + + $written = $this->yoast->stored($record, $field); + + if ($written === '' || $written === $stored) { + return ChangeResult::failed($change->id, 'write_failed', "Nothing new was stored in {$location['field']}."); + } + + return ChangeResult::applied($change->id, $location, $from, $written); + } + + /** + * A value of the page's own that differs is somebody's work. An empty field whose + * template does not produce what the scan saw could be a renamed page or something + * else printing the tag, and telling those apart is not possible from here. + * + * @return ?array + */ + private function refusal(ChangeRequest $change, string $stored, string $rendered): ?array + { + if ($this->unchanged(trim($change->currentValue ?? ''), $stored, $rendered)) { + return null; + } + + return $stored === '' + ? ChangeResult::skipped($change->id, 'ambiguous', 'This page has no value of its own and its template does not produce what the scan saw, so applying would be a guess.') + : ChangeResult::skipped($change->id, 'value_changed', 'This value has changed since the scan, so it was left alone.'); + } + + /** + * A scan sees template variables filled in. A revert sends back what was written, + * which still has them, so either form of the value counts as the one on the page. + */ + private function unchanged(string $scanned, string $stored, string $rendered): bool + { + if ($scanned === '') { + return $stored === ''; + } + + return $this->same($rendered, $scanned) || $this->same($stored, $scanned); + } + + private function field(ChangeRequest $change): ?string + { + return match (strstr($change->check, '.', true)) { + 'title' => 'title', + 'meta_description' => 'metadesc', + default => $this->socialField((string) ($change->target['selector'] ?? '')), + }; + } + + private function socialField(string $selector): ?string + { + return preg_match('/og:(title|description)/', $selector, $tag) === 1 ? "opengraph-{$tag[1]}" : null; + } + + /** + * @return array + */ + private function describe(WP_Post|WP_Term $record, string $field): array + { + $identity = $record instanceof WP_Post + ? ['type' => 'post', 'id' => $record->ID, 'collection' => $record->post_type] + : ['type' => 'term', 'id' => $record->term_id, 'taxonomy' => $record->taxonomy]; + + return [...$identity, 'field' => $this->yoast->storageKey($record, $field)]; + } + + private function same(string $first, string $second): bool + { + return $this->comparable($first) === $this->comparable($second); + } + + private function comparable(string $value): string + { + $decoded = html_entity_decode($value, ENT_QUOTES | ENT_HTML5, 'UTF-8'); + + return trim((string) preg_replace('/\s+/u', ' ', $decoded)); + } +} diff --git a/tests/ChangeRequestHandlingTest.php b/tests/ChangeRequestHandlingTest.php new file mode 100644 index 0000000..3132ae5 --- /dev/null +++ b/tests/ChangeRequestHandlingTest.php @@ -0,0 +1,200 @@ +set_permalink_structure('/%postname%/'); + + $pageId = self::factory()->post->create(['post_type' => 'page', 'post_name' => 'about', 'post_title' => 'About']); + + update_post_meta($pageId, '_yoast_wpseo_metadesc', 'About us.'); + } + + public function test_refuses_an_unsigned_request(): void + { + $request = new WP_REST_Request('POST', '/altimiser/v1/changes'); + + $request->set_body('{"changes":[]}'); + + $this->assertSame(401, $this->dispatch($request)->get_status()); + } + + public function test_refuses_a_body_altered_after_signing(): void + { + $request = $this->signedPost('{"dry_run":false,"changes":[]}'); + + $request->set_body('{"dry_run":false,"changes":[{}]}'); + + $this->assertRefused($this->dispatch($request), 'Signature does not match.'); + } + + public function test_takes_the_worked_example_in_the_protocol_document(): void + { + $response = $this->dispatch($this->signedPost('{"dry_run":false,"changes":[]}')); + + $this->assertSame(200, $response->get_status()); + $this->assertSame([], $response->get_data()['results']); + } + + /** + * @dataProvider unreadableBodies + */ + public function test_answers_a_body_it_cannot_read_with_a_422(string $body): void + { + $response = $this->dispatch($this->signedPost($body)); + + $this->assertSame(422, $response->get_status()); + $this->assertArrayHasKey('message', $response->get_data()); + } + + /** + * @return array + */ + public static function unreadableBodies(): array + { + return [ + 'empty' => [''], + 'no changes' => ['{"dry_run":true}'], + 'changes that are not a list' => ['{"changes":"all of them"}'], + 'a dry run that is not a boolean' => ['{"dry_run":"no","changes":[]}'], + ]; + } + + public function test_leaves_wordpress_to_refuse_a_body_that_is_not_json(): void + { + $this->assertSame(400, $this->dispatch($this->signedPost('changes'))->get_status()); + } + + public function test_answers_every_change_by_the_id_it_was_given(): void + { + $results = $this->send([$this->change(['id' => 'first']), $this->change(['id' => 'second'])]); + + $this->assertSame(['first', 'second'], array_column($results, 'id')); + } + + /** + * @dataProvider malformedChanges + */ + public function test_fails_a_malformed_change_and_processes_the_rest(mixed $malformed, string $expectedId): void + { + $results = $this->send([$malformed, $this->change(['id' => 'good'])]); + + $this->assertSame($expectedId, $results[0]['id']); + $this->assertSame('failed', $results[0]['status']); + $this->assertSame('invalid_change', $results[0]['reason']); + $this->assertSame('good', $results[1]['id']); + $this->assertSame('applied', $results[1]['status']); + } + + /** + * @return array + */ + public static function malformedChanges(): array + { + return [ + 'not an object' => ['nonsense', 'index-0'], + 'no id' => [['check' => 'title.too_long', 'url' => 'https://example.org/'], 'index-0'], + 'no check' => [['id' => 'bad', 'url' => 'https://example.org/'], 'bad'], + 'no url' => [['id' => 'bad', 'check' => 'title.too_long'], 'bad'], + 'a target that is not an object' => [['id' => 'bad', 'check' => 'title.too_long', 'url' => 'https://example.org/', 'target' => 'head'], 'bad'], + 'a value that is not text' => [['id' => 'bad', 'check' => 'title.too_long', 'url' => 'https://example.org/', 'current_value' => 12], 'bad'], + ]; + } + + public function test_skips_a_check_it_has_no_transform_for(): void + { + $result = $this->sendOne(['check' => 'something.we.do.not.do']); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('unsupported_check', $result['reason']); + } + + public function test_skips_a_url_that_maps_to_nothing_editable(): void + { + $result = $this->sendOne(['url' => home_url('/no-such-page/')]); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('not_found', $result['reason']); + } + + public function test_reports_a_write_that_threw_as_failed_and_carries_on(): void + { + $failOnce = static function (): void { + throw new RuntimeException('The database went away.'); + }; + + add_action('update_post_metadata', $failOnce); + + [$first] = $this->send([$this->change()]); + + remove_action('update_post_metadata', $failOnce); + + $this->assertSame('failed', $first['status']); + $this->assertSame('write_failed', $first['reason']); + } + + public function test_attempts_ten_changes_and_defers_the_rest(): void + { + $changes = array_map( + fn (int $index): array => $this->change(['id' => "change-{$index}"]), + range(1, 15), + ); + + $results = $this->send($changes); + + $this->assertCount(15, $results); + $this->assertSame(range(1, 15), array_map(static fn (array $result): int => (int) substr($result['id'], 7), $results)); + $this->assertCount(5, array_filter($results, static fn (array $result): bool => $result['status'] === 'deferred')); + } + + public function test_takes_its_batch_size_from_a_filter(): void + { + add_filter('altimiser_batch_size', static fn (): int => 2); + + $results = $this->send([$this->change(), $this->change(), $this->change()]); + + $this->assertSame('deferred', $results[2]['status']); + $this->assertNotSame('deferred', $results[1]['status']); + } + + public function test_stops_starting_changes_once_the_time_budget_is_spent(): void + { + add_filter('altimiser_time_budget', static fn (): int => -1); + + $results = $this->send([$this->change(), $this->change(), $this->change()]); + + $this->assertNotSame('deferred', $results[0]['status']); + $this->assertSame('deferred', $results[1]['status']); + $this->assertSame('deferred', $results[2]['status']); + } + + public function test_always_attempts_one_change_so_a_batch_cannot_stall(): void + { + add_filter('altimiser_batch_size', static fn (): int => 0); + + $this->assertNotSame('deferred', $this->sendOne()['status']); + } + + public function test_keeps_its_time_budget_below_the_execution_limit(): void + { + $original = ini_get('max_execution_time'); + + ini_set('max_execution_time', '30'); + + $budget = (new AltDesign\Altimiser\ChangeDispatcher([], new AltDesign\Altimiser\PageCache()))->timeBudget(); + + ini_set('max_execution_time', $original); + + $this->assertSame(15.0, $budget); + } +} diff --git a/tests/ControlPanelTest.php b/tests/ControlPanelTest.php new file mode 100644 index 0000000..89cb259 --- /dev/null +++ b/tests/ControlPanelTest.php @@ -0,0 +1,178 @@ +}> */ + private array $requests = []; + + private function panel(): ControlPanel + { + return new ControlPanel('https://altimiser.example.com', 'https://example.com', 'shared-secret'); + } + + /** + * @param array|WP_Error $response + */ + private function altimiserAnswers(array|WP_Error $response): void + { + add_filter('pre_http_request', function ($preempt, array $args, string $url) use ($response) { + $this->requests[] = ['url' => $url, 'args' => $args]; + + return $response; + }, 10, 3); + } + + /** + * @return array + */ + 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 + { + $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), + ); + } + + public function test_leaves_out_a_user_with_no_email(): void + { + $this->assertStringNotContainsString('user=', $this->panel()->reviewUrl('', 1769558400)); + } + + public function test_expires_a_link_after_the_configured_minutes(): void + { + $panel = new ControlPanel('https://altimiser.example.com', 'https://example.com', 'shared-secret', 10); + + $this->assertEqualsWithDelta(time() + 600, $panel->linkExpiry(), 2); + } + + public function test_reads_the_count_with_a_request_signed_over_the_empty_body(): void + { + $this->altimiserAnswers($this->answer(200, '{"awaiting_review":12,"pending":3}')); + + $this->assertSame(12, $this->panel()->awaitingReview()); + + ['url' => $url, 'args' => $args] = $this->requests[0]; + $timestamp = $args['headers']['X-Altimiser-Timestamp']; + + $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(0, $args['redirection']); + } + + public function test_keeps_the_count_rather_than_asking_on_every_page(): void + { + $this->altimiserAnswers($this->answer(200, '{"awaiting_review":0}')); + + $this->assertSame(0, $this->panel()->awaitingReview()); + $this->assertSame(0, $this->panel()->awaitingReview()); + $this->assertCount(1, $this->requests); + } + + /** + * @dataProvider unusableAnswers + * + * @param array|WP_Error $response + */ + public function test_has_no_number_when_altimiser_gives_no_usable_answer(array|WP_Error $response): void + { + $this->altimiserAnswers($response); + + $this->assertNull($this->panel()->awaitingReview()); + } + + /** + * @return array|WP_Error}> + */ + public static function unusableAnswers(): 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')], + 'refused' => [$answer(401, '{"message":"Signature does not match."}')], + 'a server error' => [$answer(500, 'Server error')], + 'not json' => [$answer(200, 'A login page')], + 'json that is not an object' => [$answer(200, '12')], + 'no count in it' => [$answer(200, '{"pending":3}')], + 'a count that is not a number' => [$answer(200, '{"awaiting_review":"twelve"}')], + ]; + } + + public function test_remembers_altimiser_being_unreachable_so_only_one_page_waits(): void + { + $this->altimiserAnswers(new WP_Error('http_request_failed', 'Connection timed out')); + + $this->panel()->awaitingReview(); + $this->panel()->awaitingReview(); + + $this->assertCount(1, $this->requests); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_needs_altimisers_address_before_it_can_link_to_it(): void + { + define('ALTIMISER_SECRET', 'shared-secret'); + + $this->assertNull(ControlPanel::configured()); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_needs_the_secret_before_it_can_sign_anything(): void + { + define('ALTIMISER_URL', 'https://altimiser.example.com'); + + $this->assertNull(ControlPanel::configured()); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + 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'); + add_filter('home_url', static fn (): string => 'https://client.example.com/'); + + $url = ControlPanel::configured()->reviewUrl('', 1769558400); + + $this->assertStringStartsWith('https://altimiser.example.com/review?', $url); + $this->assertStringContainsString('site=https%3A%2F%2Fclient.example.com&', $url); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + 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_SITE_URL', 'https://www.client.example.com/'); + define('ALTIMISER_LINK_MINUTES', 10); + + $panel = ControlPanel::configured(); + + $this->assertStringContainsString('site=https%3A%2F%2Fwww.client.example.com&', $panel->reviewUrl('', 1769558400)); + $this->assertEqualsWithDelta(time() + 600, $panel->linkExpiry(), 2); + } +} diff --git a/tests/HealthTest.php b/tests/HealthTest.php new file mode 100644 index 0000000..e5d2213 --- /dev/null +++ b/tests/HealthTest.php @@ -0,0 +1,159 @@ +dispatch($this->signedRequest())->get_data(); + + $this->assertSame('wordpress', $health['receiver']); + $this->assertSame(get_bloginfo('version'), $health['cms_version']); + $this->assertSame(home_url(), $health['site_url']); + } + + public function test_reads_its_version_from_the_plugin_header(): void + { + preg_match('/^ \* Version: (.+)$/m', file_get_contents(dirname(__DIR__).'/altimiser.php'), $header); + + $health = $this->dispatch($this->signedRequest())->get_data(); + + $this->assertSame($header[1], $health['receiver_version']); + } + + public function test_advertises_what_it_can_write_through_yoast(): void + { + $health = $this->dispatch($this->signedRequest())->get_data(); + + $this->assertEqualsCanonicalizing([ + 'title.missing', + 'title.too_short', + 'title.too_long', + 'title.irrelevant', + 'title.duplicate', + 'meta_description.missing', + 'meta_description.too_short', + 'meta_description.too_long', + 'meta_description.irrelevant', + 'meta_description.duplicate', + 'open_graph.missing', + ], $health['checks']); + $this->assertSame(['content.update'], $health['capabilities']); + $this->assertSame(['installed' => true, 'version' => WPSEO_VERSION], $health['integrations']['yoast']); + } + + public function test_withholds_social_tags_when_yoast_is_set_not_to_print_them(): void + { + WPSEO_Options::set('opengraph', false); + + $checks = $this->dispatch($this->signedRequest())->get_data()['checks']; + + WPSEO_Options::set('opengraph', true); + + $this->assertNotContains('open_graph.missing', $checks); + $this->assertContains('title.too_long', $checks); + } + + public function test_advertises_nothing_without_a_supported_seo_plugin(): void + { + $receiver = new AltDesign\Altimiser\Receiver(dirname(__DIR__).'/altimiser.php', null); + + $health = $receiver->health()->get_data(); + + $this->assertSame([], $health['checks']); + $this->assertSame([], $health['capabilities']); + $this->assertSame(['installed' => false], $health['integrations']['yoast']); + } + + public function test_fails_a_change_without_a_supported_seo_plugin_so_its_approval_is_kept(): void + { + $receiver = new AltDesign\Altimiser\Receiver(dirname(__DIR__).'/altimiser.php', null); + + $response = $receiver->changes($this->signedPost((string) json_encode(['changes' => [$this->change()]]))); + + $this->assertSame('failed', $response->get_data()['results'][0]['status']); + $this->assertSame('seo_plugin_inactive', $response->get_data()['results'][0]['reason']); + } + + /** + * Breeze 2.1.11 keeps REST responses and has no other way to opt out. + * + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_marks_the_response_so_older_breeze_will_not_keep_it(): void + { + $pageId = self::factory()->post->create(); + + $this->assertFalse(post_password_required($pageId)); + + $this->dispatch($this->signedRequest()); + $this->shutDown(); + + $this->assertTrue(post_password_required($pageId)); + } + + private function shutDown(): void + { + remove_action('shutdown', 'wp_ob_end_flush_all', 1); + + do_action('shutdown'); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_leaves_page_caches_alone_for_a_refused_request(): void + { + $pageId = self::factory()->post->create(); + + $this->dispatch($this->request()); + $this->shutDown(); + + $this->assertFalse(defined('DONOTCACHEPAGE')); + $this->assertFalse(post_password_required($pageId)); + } + + public function test_cannot_be_kept_by_a_cache_and_served_to_an_unsigned_request(): void + { + $headers = $this->dispatch($this->signedRequest())->get_headers(); + + $this->assertStringContainsString('no-store', $headers['Cache-Control']); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_tells_page_cache_plugins_not_to_keep_it(): void + { + $this->assertFalse(defined('DONOTCACHEPAGE')); + + $this->dispatch($this->signedRequest()); + + $this->assertTrue(defined('DONOTCACHEPAGE')); + } + + public function test_sends_no_header_without_a_value(): void + { + $this->assertNotContains(false, $this->dispatch($this->signedRequest())->get_headers()); + } + + public function test_says_nothing_about_the_site_to_an_unsigned_request(): void + { + $response = $this->dispatch($this->request()); + + $this->assertSame(401, $response->get_status()); + $this->assertArrayNotHasKey('receiver', $response->get_data()); + } +} diff --git a/tests/NoSecretTest.php b/tests/NoSecretTest.php new file mode 100644 index 0000000..cc22f87 --- /dev/null +++ b/tests/NoSecretTest.php @@ -0,0 +1,45 @@ +assertRefused( + $this->dispatch($this->signedRequest()), + 'Altimiser is not configured on this site.', + ); + } + + /** + * @dataProvider guessableSecrets + */ + public function test_refuses_a_request_signed_with_a_secret_anyone_could_guess(mixed $configured, string $signedWith): void + { + define('ALTIMISER_SECRET', $configured); + + $this->assertRefused( + $this->dispatch($this->signedRequest(secret: $signedWith)), + 'Altimiser is not configured on this site.', + ); + } + + /** + * @return array + */ + public static function guessableSecrets(): array + { + return [ + 'empty' => ['', ''], + 'whitespace' => [' ', ' '], + 'true' => [true, '1'], + 'a number' => [12345, '12345'], + ]; + } +} diff --git a/tests/PageCacheTest.php b/tests/PageCacheTest.php new file mode 100644 index 0000000..1a8fd6f --- /dev/null +++ b/tests/PageCacheTest.php @@ -0,0 +1,135 @@ +set_permalink_structure('/%postname%/'); + + $this->pageId = self::factory()->post->create(['post_type' => 'page', 'post_name' => 'about', 'post_title' => 'About']); + + update_post_meta($this->pageId, '_yoast_wpseo_metadesc', 'About us.'); + } + + private function purges(callable $request): int + { + $before = did_action('litespeed_purge_all'); + + $request(); + + return did_action('litespeed_purge_all') - $before; + } + + private function descriptionYoastPrints(): ?string + { + global $wpdb; + + return $wpdb->get_var($wpdb->prepare( + "SELECT description FROM {$wpdb->prefix}yoast_indexable WHERE object_type = 'post' AND object_id = %d", + $this->pageId, + )); + } + + public function test_purges_once_yoast_has_rebuilt_what_the_page_prints(): void + { + $printedAtPurge = null; + + $recordWhatIsPrinted = function () use (&$printedAtPurge): void { + $printedAtPurge = $this->descriptionYoastPrints(); + }; + + add_action('litespeed_purge_all', $recordWhatIsPrinted); + + $this->sendOne(); + + remove_action('litespeed_purge_all', $recordWhatIsPrinted); + + $this->assertSame('How our studio works, and who we build for.', $printedAtPurge); + } + + public function test_rebuilds_what_the_page_prints_when_a_value_is_cleared_too(): void + { + $this->sendOne(); + + (new AltDesign\Altimiser\Yoast())->clear(get_post($this->pageId), 'metadesc'); + + $this->assertNull($this->descriptionYoastPrints()); + } + + public function test_purges_during_the_request_because_w3_total_cache_flushes_on_a_shutdown_hook_of_its_own(): void + { + $this->assertSame(1, $this->purges(fn () => $this->sendOne())); + } + + public function test_purges_once_for_a_request_that_applied_several_changes(): void + { + $purges = $this->purges(fn () => $this->send([ + $this->change(), + $this->change(['check' => 'title.missing', 'current_value' => null, 'suggested_value' => 'About our studio']), + ])); + + $this->assertSame(1, $purges); + } + + public function test_leaves_the_cache_alone_on_a_dry_run(): void + { + $this->assertSame(0, $this->purges(fn () => $this->sendOne(dryRun: true))); + } + + public function test_leaves_the_cache_alone_when_nothing_landed(): void + { + $this->assertSame(0, $this->purges(fn () => $this->sendOne(['current_value' => 'Not what is there']))); + } + + public function test_purges_when_the_fix_was_already_in_place_because_the_request_that_wrote_it_may_have_died_before_its_purge(): void + { + $this->sendOne(); + + $this->assertSame(1, $this->purges(fn () => $this->sendOne())); + } + + /** + * @runInSeparateProcess + * + * @preserveGlobalState disabled + */ + public function test_reaches_each_plugin_that_is_active(): void + { + require __DIR__.'/fixtures/page-cache-plugins.php'; + + $beforeBreeze = did_action('breeze_clear_all_cache'); + + (new AltDesign\Altimiser\PageCache())->purge(); + + $this->assertSame(['rocket', 'w3tc', 'super-cache'], $GLOBALS['altimiser_purged']); + $this->assertSame($beforeBreeze + 1, did_action('breeze_clear_all_cache')); + } + + 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); + + $logged = ini_set('error_log', '/dev/null'); + $result = $this->sendOne(); + + ini_set('error_log', (string) $logged); + remove_action('litespeed_purge_all', $failing); + + $this->assertSame('applied', $result['status']); + } +} diff --git a/tests/ReceiverTestCase.php b/tests/ReceiverTestCase.php new file mode 100644 index 0000000..b04644a --- /dev/null +++ b/tests/ReceiverTestCase.php @@ -0,0 +1,114 @@ +set_body($body); + + if ($timestamp !== null) { + $request->set_header('X-Altimiser-Timestamp', $timestamp); + } + + if ($signature !== null) { + $request->set_header('X-Altimiser-Signature', $signature); + } + + return $request; + } + + protected function signedRequest(string $body = '', ?int $timestamp = null, ?string $secret = null): WP_REST_Request + { + $timestamp ??= time(); + + return $this->request( + $body, + (string) $timestamp, + $this->protocolSignature($body, $timestamp, $secret ?? self::$secret), + ); + } + + protected function signedPost(string $body): WP_REST_Request + { + $timestamp = time(); + $request = new WP_REST_Request('POST', '/altimiser/v1/changes'); + + $request->set_body($body); + $request->set_header('Content-Type', 'application/json'); + $request->set_header('X-Altimiser-Timestamp', (string) $timestamp); + $request->set_header('X-Altimiser-Signature', $this->protocolSignature($body, $timestamp, self::$secret)); + + return $request; + } + + /** + * @param array $overrides + * @return array + */ + protected function change(array $overrides = []): array + { + return [ + 'id' => 'fingerprint-abc', + 'check' => 'meta_description.too_short', + 'url' => home_url('/about/'), + 'target' => ['selector' => 'meta[name="description"]', 'attribute' => 'content'], + 'current_value' => 'About us.', + 'suggested_value' => 'How our studio works, and who we build for.', + ...$overrides, + ]; + } + + /** + * @param array $changes + * @return array> + */ + protected function send(array $changes, bool $dryRun = false): array + { + $body = json_encode(['dry_run' => $dryRun, 'changes' => $changes]); + + return $this->dispatch($this->signedPost($body))->get_data()['results']; + } + + /** + * @param array $overrides + * @return array + */ + protected function sendOne(array $overrides = [], bool $dryRun = false): array + { + return $this->send([$this->change($overrides)], $dryRun)[0]; + } + + protected function dispatch(WP_REST_Request $request): WP_REST_Response + { + return rest_get_server()->dispatch($request); + } + + protected function assertRefused(WP_REST_Response $response, string $message): void + { + $this->assertSame(401, $response->get_status()); + $this->assertSame($message, $response->get_data()['message']); + } +} diff --git a/tests/ReviewQueuePageTest.php b/tests/ReviewQueuePageTest.php new file mode 100644 index 0000000..19c0b07 --- /dev/null +++ b/tests/ReviewQueuePageTest.php @@ -0,0 +1,258 @@ +page = new ReviewQueuePage(new ControlPanel('https://altimiser.example.com', 'https://example.com', 'shared-secret')); + } + + public function tear_down(): void + { + set_current_screen('front'); + + parent::tear_down(); + } + + private function signInAs(string $role): WP_User + { + $user = self::factory()->user->create_and_get(['role' => $role, 'user_email' => "{$role}@example.com"]); + + wp_set_current_user($user->ID); + + return $user; + } + + private function altimiserCounts(int|WP_Error $count): void + { + add_filter('pre_http_request', function () use ($count) { + $this->requests++; + + return $count instanceof WP_Error + ? $count + : ['headers' => [], 'body' => wp_json_encode(['awaiting_review' => $count]), 'response' => ['code' => 200, 'message' => ''], 'cookies' => [], 'filename' => null]; + }); + } + + /** + * @return array|null + */ + private function menuItem(): ?array + { + global $menu; + + foreach ($menu as $item) { + if ($item[2] === 'altimiser') { + return $item; + } + } + + return null; + } + + private function menuLabel(): ?string + { + return $this->menuItem()[0] ?? null; + } + + private function renderedPage(): string + { + ob_start(); + $this->page->render(); + + return (string) ob_get_clean(); + } + + private function renderedWidget(): string + { + ob_start(); + $this->page->renderWidget(); + + return (string) ob_get_clean(); + } + + /** + * @return array + */ + public static function rolesWithAccess(): array + { + return ['editor' => ['editor'], 'administrator' => ['administrator']]; + } + + /** + * @return array + */ + public static function rolesWithoutAccess(): array + { + return ['author' => ['author'], 'contributor' => ['contributor'], 'subscriber' => ['subscriber']]; + } + + /** + * @dataProvider rolesWithAccess + */ + public function test_lists_the_page_at_the_top_level_for_someone_who_reviews(string $role): void + { + global $submenu; + + $this->altimiserCounts(0); + $this->signInAs($role); + + $this->page->addMenuItem(); + + $this->assertSame('Altimiser', $this->menuLabel()); + $this->assertEmpty($submenu); + } + + public function test_gives_the_menu_item_an_icon_wordpress_can_recolour(): void + { + $this->altimiserCounts(0); + $this->signInAs('editor'); + + $this->page->addMenuItem(); + + $prefix = 'data:image/svg+xml;base64,'; + $icon = $this->menuItem()[6]; + + $this->assertStringStartsWith($prefix, $icon); + + $svg = base64_decode(substr($icon, strlen($prefix))); + + $this->assertNotFalse(simplexml_load_string($svg)); + $this->assertStringContainsString('', $svg); + $this->assertSame(1, substr_count($svg, 'fill='), 'WordPress overwrites every fill, and one on the lines would fill the rocket in.'); + } + + /** + * @dataProvider rolesWithoutAccess + */ + public function test_shows_nothing_to_someone_who_does_not_and_spends_no_request_on_them(string $role): void + { + $this->altimiserCounts(3); + $this->signInAs($role); + + $this->page->addMenuItem(); + $this->page->addDashboardWidget(); + + global $wp_meta_boxes; + + $this->assertNull($this->menuLabel()); + $this->assertEmpty($wp_meta_boxes); + $this->assertSame(0, $this->requests); + } + + public function test_shows_the_count_on_the_menu_item(): void + { + $this->altimiserCounts(12); + $this->signInAs('editor'); + + $this->page->addMenuItem(); + + $this->assertStringContainsString('', $this->menuLabel()); + $this->assertStringContainsString('12 waiting for review', $this->menuLabel()); + } + + public function test_keeps_the_page_and_loses_the_number_when_altimiser_is_unreachable(): void + { + $this->altimiserCounts(new WP_Error('http_request_failed', 'Connection timed out')); + $this->signInAs('editor'); + + $this->page->addMenuItem(); + + $this->assertSame('Altimiser', $this->menuLabel()); + } + + public function test_frames_a_link_signed_for_whoever_is_signed_in(): void + { + $this->signInAs('editor'); + + $html = html_entity_decode($this->renderedPage(), ENT_QUOTES); + + preg_match('/

Where we work.

'; + + $wpdb->update($wpdb->term_taxonomy, ['description' => $description], ['term_id' => $term->term_id]); + clean_term_cache($term->term_id, 'category'); + WPSEO_Taxonomy_Meta::set_values($term->term_id, 'category', ['wpseo_desc' => 'About us.']); + + $this->assertSame('applied', $this->sendOne(['url' => get_term_link($term)])['status']); + $this->assertSame($description, get_term($term->term_id)->description); + } + + public function test_reports_a_write_something_else_blocked_as_failed(): void + { + $this->storeDescription('About us.'); + + add_filter('update_post_metadata', '__return_true'); + + $result = $this->sendOne(); + + $this->assertSame('failed', $result['status']); + $this->assertSame('write_failed', $result['reason']); + } + + /** + * @dataProvider statusesAScanCannotSee + */ + public function test_finds_nothing_for_a_page_a_scan_could_not_have_seen(string $status): void + { + $hiddenId = self::factory()->post->create([ + 'post_type' => 'page', + 'post_status' => $status, + 'post_name' => 'hidden', + 'post_title' => 'Hidden', + 'post_date' => gmdate('Y-m-d H:i:s', time() + DAY_IN_SECONDS), + ]); + + update_post_meta($hiddenId, '_yoast_wpseo_metadesc', 'About us.'); + + $this->assertSame('not_found', $this->sendOne(['url' => home_url("/?page_id={$hiddenId}")])['reason']); + $this->assertSame('not_found', $this->sendOne(['url' => home_url('/hidden/')])['reason']); + $this->assertSame('About us.', get_post_meta($hiddenId, '_yoast_wpseo_metadesc', true)); + } + + /** + * @return array + */ + public static function statusesAScanCannotSee(): array + { + return ['draft' => ['draft'], 'pending' => ['pending'], 'private' => ['private'], 'future' => ['future'], 'trash' => ['trash']]; + } + + public function test_finds_nothing_for_a_revision(): void + { + wp_update_post(['ID' => $this->pageId, 'post_content' => 'First version.']); + wp_update_post(['ID' => $this->pageId, 'post_content' => 'Second version.']); + + $revisions = wp_get_post_revisions($this->pageId); + + $this->assertNotEmpty($revisions); + $this->assertSame('not_found', $this->sendOne(['url' => home_url('/?p='.array_key_first($revisions))])['reason']); + } + + /** + * @dataProvider addressesThatAreNotThePageItself + */ + public function test_does_not_write_to_a_page_for_an_address_beneath_it(string $suffix): void + { + $this->storeDescription('About us.'); + + $this->assertSame('not_found', $this->sendOne(['url' => home_url("/about/{$suffix}")])['reason']); + $this->assertSame('About us.', $this->storedDescription()); + } + + /** + * @return array + */ + public static function addressesThatAreNotThePageItself(): array + { + return ['a later page' => ['2/'], 'its feed' => ['feed/'], 'its embed' => ['embed/']]; + } + + public function test_resolves_a_page_whichever_way_its_address_is_written(): void + { + $pageId = self::factory()->post->create(['post_type' => 'page', 'post_name' => 'новости', 'post_title' => 'Новости']); + $encoded = rawurlencode('новости'); + + update_post_meta($pageId, '_yoast_wpseo_metadesc', 'About us.'); + + foreach (['/новости/', "/{$encoded}/", '/'.strtolower($encoded).'/', '/'.strtolower($encoded)] as $address) { + $result = $this->sendOne(['url' => home_url($address)], dryRun: true); + + $this->assertSame($pageId, $result['location']['id'] ?? null, $address); + } + } + + public function test_resolves_a_term_whichever_way_its_address_is_written(): void + { + $term = self::factory()->category->create_and_get(['name' => 'Новости', 'slug' => 'новости']); + $encoded = rawurlencode('новости'); + + WPSEO_Taxonomy_Meta::set_values($term->term_id, 'category', ['wpseo_desc' => 'About us.']); + + foreach (['/category/новости/', "/category/{$encoded}/", '/category/'.strtolower($encoded).'/'] as $address) { + $result = $this->sendOne(['url' => home_url($address)], dryRun: true); + + $this->assertSame($term->term_id, $result['location']['id'] ?? null, $address); + } + } + + public function test_resolves_a_child_term_by_its_full_path(): void + { + $parentId = self::factory()->category->create(['name' => 'News', 'slug' => 'news']); + $child = self::factory()->category->create_and_get(['name' => 'Local', 'slug' => 'local', 'parent' => $parentId]); + + WPSEO_Taxonomy_Meta::set_values($child->term_id, 'category', ['wpseo_desc' => 'About us.']); + + $this->assertSame($child->term_id, $this->sendOne(['url' => home_url('/category/news/local/')], dryRun: true)['location']['id'] ?? null); + $this->assertSame('not_found', $this->sendOne(['url' => home_url('/category/local/')], dryRun: true)['reason']); + } + + public function test_resolves_a_post_on_plain_permalinks(): void + { + $this->set_permalink_structure(''); + $this->storeDescription('About us.'); + + $result = $this->sendOne(['url' => get_permalink($this->pageId)], dryRun: true); + + $this->assertSame($this->pageId, $result['location']['id'] ?? null); + } + + public function test_does_not_write_to_a_page_for_its_address_with_a_query_on_the_end(): void + { + $this->storeDescription('About us.'); + + $this->assertSame('not_found', $this->sendOne(['url' => home_url('/about/?ref=newsletter')])['reason']); + $this->assertSame('About us.', $this->storedDescription()); + } + + /** + * @dataProvider queriesThatAnswerAsAStaticHomePage + */ + public function test_does_not_write_to_a_static_home_page_for_an_address_that_only_answers_as_it(string $query): void + { + update_option('show_on_front', 'page'); + update_option('page_on_front', $this->pageId); + + $result = $this->sendOne(['check' => 'meta_description.missing', 'current_value' => null, 'url' => home_url("/{$query}")]); + + $this->assertSame('not_found', $result['reason']); + $this->assertSame('', $this->storedDescription()); + } + + /** + * @return array + */ + public static function queriesThatAnswerAsAStaticHomePage(): array + { + return ['a search' => ['?s=anything'], 'a later page' => ['?paged=2']]; + } + + public function test_does_not_write_to_a_term_for_its_address_with_a_query_on_the_end(): void + { + $term = self::factory()->category->create_and_get(['name' => 'News', 'slug' => 'news']); + + WPSEO_Taxonomy_Meta::set_values($term->term_id, 'category', ['wpseo_desc' => 'About us.']); + + $this->assertSame('not_found', $this->sendOne(['url' => get_term_link($term).'?paged=2'])['reason']); + $this->assertSame('About us.', WPSEO_Taxonomy_Meta::get_term_meta($term, 'category', 'desc')); + } +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php new file mode 100644 index 0000000..3a399e3 --- /dev/null +++ b/tests/bootstrap.php @@ -0,0 +1,20 @@ +