diff --git a/CHANGELOG.md b/CHANGELOG.md index fcb2f51..d47f7fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,4 +31,10 @@ All notable changes are listed here. The format follows [Keep a Changelog](https - `GET /wp-json/headless/v1/search`: the site search in one shape, with front-end addresses (`headless/search/args` filter). - `GET /wp-json/headless/v1/forms` and `/forms/{provider}/{id}`: forms and how to send them, from Contact Form 7 (`headless/forms/providers` filter for other plugins). - `X-GraphQL-Preview` among the request headers CORS allows. +- `wp headless doctor`: checks on the running site, with the fix for each finding. +- `rest_plugins`: load only the listed plugins on REST requests (advanced, off by default). +- `tests/E2E/run.sh`: the contract checked over real HTTP. +- Fixed: a wrong `hl.` token was served as an anonymous request instead of answering 401 (WordPress works the user out lazily). +- Fixed: `wp headless theme install` was refused by WP-CLI (the action was not in the command's synopsis). +- Security review of the package, with these fixes: a redirect rule can no longer send a visitor to another site through `$1` (`/go/(.*)` to `/$1`), rules that repeat a repetition (`(a+)+`) are refused, the resolve route takes paths of 512 characters at most, the front gate sees `/wp-admin/../` as the home page, a rotated token never outlives the expiry it had, a preview token only opens posts of the site that made it (multisite), `preview.secret` must have 32 characters at least (the site refuses to start with a shorter one), search pages stop at 100. - mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer. diff --git a/README.md b/README.md index 09ed990..9cc6a67 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo | --- | --- | | Front gate | A request for a public page is redirected to the same path on your front end (302 by default), answered with a holding page, or with JSON. The administration, the login, `/wp-json`, `/graphql`, the cron, the uploads, `xmlrpc.php`, the sitemap and `robots.txt` are never touched; you add more with `allow`. | | Head clean-up | Removes the generator, RSD, shortlink, feeds, emoji, oEmbed and REST discovery from the page head and the headers, and turns XML-RPC and the pingback header off. | -| Public surface | Feeds answer 404, the core sitemap is off (its URLs are WordPress's), and the WordPress host tells search engines not to index it (`X-Robots-Tag`, `robots.txt`, robots meta). | +| Public surface | Feeds answer 404 (a visitor of the WordPress host is first sent to the front end like for any page), the core sitemap is off (its URLs are WordPress's), and the WordPress host tells search engines not to index it (`X-Robots-Tag`, `robots.txt`, robots meta). | | Empty theme | `wp headless theme install --activate` installs the one empty theme WordPress needs: without a valid theme it falls into recovery mode for administrators. | | Status | `wp headless status` shows the setup and what looks wrong (no front URL, a front on the same host, no theme, WP-Cron). | | CORS | WordPress answers any origin and allows credentials. The package answers the listed origins only (the front-end URL is always one), never `*`, with `Vary: Origin`, `https://*.example.com` patterns and preflight. | @@ -267,7 +267,19 @@ Contact Form 7 is supported and verified against the real plugin in CI. A checkb ## Quality -The repository follows the [Pollora harness](https://github.com/Pollora/harness) (profile `core`): `composer qa` runs every gate. +The repository follows the [Pollora harness](https://github.com/Pollora/harness) (profile `core`): `composer qa` runs every gate. `tests/E2E/run.sh` (Docker) starts a throwaway WordPress with the package as a mu-plugin and checks the contract over real HTTP with `curl`: the gate, CORS, caching, tokens, preview, search, the doctor. + +## What it costs + +Measured on a throwaway WordPress with Yoast SEO, Polylang and WPGraphQL active (median of 60 requests, `rest_do_request` inside PHP, so without the network): the list of ten posts in full goes from 64 ms to 72 ms (the links in each content are rewritten), the same list with `_fields=id,title,link` from 4.4 ms to 4.7 ms, and a single post is unchanged (6.0 ms to 5.6 ms). Indicative: measure your own site. + +## Doctor + +`wp headless doctor` looks at the running site and says what exposes it or breaks the front end, with the fix for each finding (`--format=json` for a script; it exits with an error when a check fails): the front-end URL and HTTPS, CORS, the users route as a visitor sees it, a locked REST API, plain permalinks, preview, revalidation and its cron, WPGraphQL introspection, redirect loops and chains, the theme, displayed PHP errors. + +## Loading fewer plugins on REST requests + +Advanced and off by default: `rest_plugins => ['enabled' => true, 'keep' => ['advanced-custom-fields', 'wordpress-seo/wp-seo.php']]` loads only the listed plugins (a folder or a file) when the request is for `/wp-json/`. The API gets faster, but a plugin left out loses every route, post type, field and login it adds on those requests: list each one that adds any. Classic WordPress and Bedrock only (the mu-plugin reads it before the plugins load); plugins activated for a whole network are not touched. ## License diff --git a/config/headless.php b/config/headless.php index abc1d79..03a7be2 100644 --- a/config/headless.php +++ b/config/headless.php @@ -181,4 +181,12 @@ 'forms' => [ 'enabled' => true, ], + + // Advanced, off by default. On REST requests, load only these plugins (a file `acf/acf.php` or a folder `acf`): the API gets faster, but + // a plugin left out loses every route, type, field and login it adds on those requests. List each plugin that adds one. Classic WordPress + // and Bedrock only (read from the mu-plugin before the plugins load); plugins activated for a whole network are not touched. + 'rest_plugins' => [ + 'enabled' => false, + 'keep' => [], + ], ]; diff --git a/phpstan.neon b/phpstan.neon index 2b42fe2..638a6b6 100644 --- a/phpstan.neon +++ b/phpstan.neon @@ -15,7 +15,7 @@ parameters: - vendor/wpsyntex/polylang-stubs/polylang-stubs.php ignoreErrors: # Action Scheduler is a plugin, not part of the WordPress stubs: the package uses its functions only after checking they exist - - '#Function as_[a-z_]+ not found#' + - '#Function (as_[a-z_]+|get_graphql_setting) not found#' # WPGraphQL is a plugin too: its error class exists only while it is active, and the guard runs from its own filter - '#GraphQL\\Error\\UserError#' # Contact Form 7 too: the adapter runs only once it checked the plugin is active diff --git a/src/Application/Preview/PreviewService.php b/src/Application/Preview/PreviewService.php index 542e6a2..7b9c2b6 100644 --- a/src/Application/Preview/PreviewService.php +++ b/src/Application/Preview/PreviewService.php @@ -69,10 +69,11 @@ public function linkToken(int $userId, int $postId, int $siteId): string * @throws PreviewForbiddenException when the user can no longer edit the post * @throws PreviewNotFoundException when the post is gone */ - public function exchange(string $linkToken): PreviewSession + public function exchange(string $linkToken, ?int $siteId = null): PreviewSession { $claims = TokenSigner::verify($linkToken, $this->key, ($this->clock)(), PreviewTokenType::Link); $this->checkAudience($claims); + $this->checkSite($claims, $siteId); // Burn before anything else: a token that fails the checks below is spent too if (! $this->store->burn($claims->id)) { @@ -94,7 +95,7 @@ public function exchange(string $linkToken): PreviewSession * @throws PreviewForbiddenException * @throws PreviewNotFoundException */ - public function authorize(string $sessionToken, int $postId): PreviewClaims + public function authorize(string $sessionToken, int $postId, ?int $siteId = null): PreviewClaims { if (! str_starts_with($sessionToken, 'hlp.')) { throw PreviewTokenInvalidException::raise(); @@ -102,6 +103,7 @@ public function authorize(string $sessionToken, int $postId): PreviewClaims $claims = TokenSigner::verify(substr($sessionToken, 4), $this->key, ($this->clock)(), PreviewTokenType::Session); $this->checkAudience($claims); + $this->checkSite($claims, $siteId); if ($claims->postId !== $postId) { throw PreviewForbiddenException::raise(); @@ -117,6 +119,14 @@ private function claims(PreviewTokenType $type, int $userId, int $postId, int $s return new PreviewClaims($type, $userId, $postId, $siteId, $this->audience, ($this->clock)() + $ttl, bin2hex(($this->random)(16))); } + /** The keys come from the salts of the whole network: a token made on one site must not open a post of another. */ + private function checkSite(PreviewClaims $claims, ?int $siteId): void + { + if ($siteId !== null && $claims->siteId !== $siteId) { + throw PreviewTokenInvalidException::raise(); + } + } + private function checkAudience(PreviewClaims $claims): void { if (! hash_equals($this->audience, $claims->audience)) { diff --git a/src/Application/Token/TokenService.php b/src/Application/Token/TokenService.php index 02548e2..b9b9287 100644 --- a/src/Application/Token/TokenService.php +++ b/src/Application/Token/TokenService.php @@ -104,7 +104,8 @@ public function rotate(int $userId, string $id, int $grace): IssuedToken $old = $this->owned($userId, $id); $issued = $this->create($userId, $old->name, $old->scopes, $old->routes, $old->expiresAt === null ? null : max(0, $old->expiresAt - ($this->clock)())); - $this->store->save($old->expiringAt(($this->clock)() + $grace)); + // The grace period never makes a token outlive the expiry it already had + $this->store->save($old->expiringAt(min($old->expiresAt ?? PHP_INT_MAX, ($this->clock)() + $grace))); return $issued; } diff --git a/src/Domain/Front/RequestTarget.php b/src/Domain/Front/RequestTarget.php index e2c3782..ff5fa0a 100644 --- a/src/Domain/Front/RequestTarget.php +++ b/src/Domain/Front/RequestTarget.php @@ -27,7 +27,7 @@ public function __construct( public static function fromUri(string $uri, string $method = 'GET', string $basePath = ''): self { $parts = explode('?', $uri, 2); - $path = '/'.ltrim($parts[0], '/'); + $path = self::resolveDots('/'.ltrim($parts[0], '/')); $basePath = '/'.trim($basePath, '/'); if ($basePath !== '/' && ($path === $basePath || str_starts_with($path, $basePath.'/'))) { @@ -37,6 +37,27 @@ public static function fromUri(string $uri, string $method = 'GET', string $base return new self($path, $parts[1] ?? '', strtoupper($method)); } + /** + * `/wp-admin/../` is the home page, whatever the allow-list sees in the raw address: web servers collapse the dots before WordPress runs. + */ + private static function resolveDots(string $path): string + { + $segments = []; + + foreach (explode('/', str_ireplace('%2e', '.', $path)) as $segment) { + if ($segment === '..') { + array_pop($segments); + } elseif ($segment !== '.') { + $segments[] = $segment; + } + } + + $resolved = implode('/', $segments); + $resolved = '/'.ltrim($resolved, '/'); + + return str_ends_with($path, '/..') || str_ends_with($path, '/.') ? rtrim($resolved, '/').'/' : $resolved; + } + /** The path, with the query string when there is one. */ public function pathAndQuery(bool $withQuery = true): string { diff --git a/src/Domain/Plugin/PluginFilter.php b/src/Domain/Plugin/PluginFilter.php new file mode 100644 index 0000000..1d8a206 --- /dev/null +++ b/src/Domain/Plugin/PluginFilter.php @@ -0,0 +1,57 @@ + $keep plugins to load on REST requests: a file (`acf/acf.php`) or a folder (`acf`) + */ + public function __construct(private array $keep) {} + + /** + * @param array $active the plugin files WordPress would load (`folder/file.php`) + * @return list + */ + public function filter(array $active): array + { + $kept = []; + + foreach ($active as $plugin) { + if (is_string($plugin) && $this->keeps($plugin)) { + $kept[] = $plugin; + } + } + + return $kept; + } + + public function keeps(string $plugin): bool + { + $folder = str_contains($plugin, '/') ? explode('/', $plugin, 2)[0] : $plugin; + + return in_array($plugin, $this->keep, true) || in_array($folder, $this->keep, true); + } + + /** + * Whether a request is one for the REST API, from its address alone, because it must be known before the plugins load. + * + * @param string $requestUri `$_SERVER['REQUEST_URI']` + * @param bool $hasRestRoute whether the query string has `rest_route` (plain permalinks) + */ + public static function isRestRequest(string $requestUri, bool $hasRestRoute = false): bool + { + $path = (string) parse_url($requestUri, PHP_URL_PATH); + + return $hasRestRoute || preg_match('#(?:^|/)wp-json(?:/|$)#', $path) === 1; + } +} diff --git a/src/Domain/Redirect/Redirect.php b/src/Domain/Redirect/Redirect.php index 8baea22..4afa672 100644 --- a/src/Domain/Redirect/Redirect.php +++ b/src/Domain/Redirect/Redirect.php @@ -37,7 +37,7 @@ public function __construct( throw InvalidRedirectException::badTarget($to); } - if ($regex && ! self::compiles(self::pattern($from))) { + if ($regex && (! self::compiles(self::pattern($from)) || self::backtracksTooMuch($from))) { throw InvalidRedirectException::badPattern($from); } @@ -59,7 +59,10 @@ public function resolve(string $path): ?string return null; } - return (string) preg_replace_callback('/\$(\d{1,2})/', static fn (array $reference): string => $matches[(int) $reference[1]] ?? '', $this->to); + $to = (string) preg_replace_callback('/\$(\d{1,2})/', static fn (array $reference): string => $matches[(int) $reference[1]] ?? '', $this->to); + + // What a visitor's path put into the destination must still be a destination: `/$1` with `/go//evil.com` would leave the site + return self::isDestination($to) && ! str_starts_with($to, '/\\') ? $to : null; } /** @@ -104,6 +107,15 @@ private static function compiles(string $pattern): bool } } + /** + * Whether a pattern repeats a repetition (`(a+)+`, `(.*)*`): such a pattern can take exponential time on a path that almost matches, + * and the resolve route runs every pattern on what a visitor sends. + */ + private static function backtracksTooMuch(string $from): bool + { + return preg_match('/[+*}]\)?[+*{]|\([^()]*[+*}]\)[+*{]/', $from) === 1; + } + /** A path without its trailing slash: `/about` and `/about/` are the same page. */ private static function normalise(string $path): string { diff --git a/src/Domain/Search/SearchQuery.php b/src/Domain/Search/SearchQuery.php index 710fb1b..02ce63e 100644 --- a/src/Domain/Search/SearchQuery.php +++ b/src/Domain/Search/SearchQuery.php @@ -16,6 +16,9 @@ public const int DEFAULT_PER_PAGE = 10; + /** Deep pages cost a scan of every result before them, and nobody reads page 5000 of a search */ + public const int MAX_PAGE = 100; + /** * @param list $types the content types to look in: the ones asked for that the site exposes, or all of those it exposes */ @@ -47,7 +50,7 @@ public static function fromRequest(string $term, string $types, ?string $languag mb_substr($term, 0, self::MAX_LENGTH), $kept, $language, - max(1, $page), + min(max(1, $page), self::MAX_PAGE), min(max(1, $perPage > 0 ? $perPage : self::DEFAULT_PER_PAGE), max(1, $maxPerPage)), ); } diff --git a/src/Infrastructure/Config/Settings.php b/src/Infrastructure/Config/Settings.php index 69310c9..2fe11f8 100644 --- a/src/Infrastructure/Config/Settings.php +++ b/src/Infrastructure/Config/Settings.php @@ -70,6 +70,7 @@ private function __construct( public ?GraphQlPolicy $graphql, public bool $search, public bool $forms, + public bool $restPluginFilter, ) {} /** @@ -121,7 +122,7 @@ public static function fromArray(array $config, string $backendUrl): self languageFronts: self::languageFronts($config['frontend_urls'] ?? []), apiTokens: self::bool(is_array($config['tokens'] ?? null) ? $config['tokens'] : [], 'enabled', true), previewUrl: self::previewUrl($preview, $front), - previewSecret: self::string($preview, 'secret') !== '' ? self::string($preview, 'secret') : null, + previewSecret: self::secret($preview), previewLinkTtl: max(30, self::int($preview, 'link_ttl', 300)), previewSessionTtl: max(60, self::int($preview, 'session_ttl', 1800)), revalidationTargets: self::targets($revalidation), @@ -138,9 +139,32 @@ public static function fromArray(array $config, string $backendUrl): self graphql: self::graphql($config['graphql'] ?? null), search: $front instanceof Origin && self::bool(is_array($config['search'] ?? null) ? $config['search'] : [], 'enabled', true), forms: self::bool(is_array($config['forms'] ?? null) ? $config['forms'] : [], 'enabled', true), + restPluginFilter: self::bool(is_array($config['rest_plugins'] ?? null) ? $config['rest_plugins'] : [], 'enabled', false), ); } + /** + * The signing secret of the preview, null when it is left to the salts of the site. + * + * @param array $preview + * + * @throws InvalidSettingsException when it is too short to resist guessing + */ + private static function secret(array $preview): ?string + { + $secret = self::string($preview, 'secret'); + + if ($secret === '') { + return null; + } + + if (strlen($secret) < 32) { + throw InvalidSettingsException::tooShort('preview.secret', 32); + } + + return $secret; + } + /** * The WPGraphQL settings to impose, or null when the module is off. A key set to null leaves that setting to WPGraphQL. */ diff --git a/src/Infrastructure/Config/SettingsLoader.php b/src/Infrastructure/Config/SettingsLoader.php index cb517f2..0590c29 100644 --- a/src/Infrastructure/Config/SettingsLoader.php +++ b/src/Infrastructure/Config/SettingsLoader.php @@ -22,6 +22,16 @@ final class SettingsLoader * @param int $siteId the current site of a multisite network (1 on a single site): `sites` overrides the settings of one site */ public static function load(string $backendUrl, int $siteId = 1): Settings + { + return Settings::fromArray(self::config($siteId), $backendUrl); + } + + /** + * The settings as an array, before they are checked: usable before WordPress can tell its own address. + * + * @return array + */ + public static function config(int $siteId = 1): array { $config = defined('HEADLESS_CONFIG') && is_array(HEADLESS_CONFIG) ? HEADLESS_CONFIG : []; // The short form of a single revalidation target @@ -38,7 +48,7 @@ public static function load(string $backendUrl, int $siteId = 1): Settings $config['preview'] = [...(is_array($config['preview'] ?? null) ? $config['preview'] : []), 'secret' => HEADLESS_SECRET]; } - return Settings::fromArray(self::merge($config, $frontendUrl, $siteId), $backendUrl); + return self::merge($config, $frontendUrl, $siteId); } /** diff --git a/src/Infrastructure/Exceptions/InvalidSettingsException.php b/src/Infrastructure/Exceptions/InvalidSettingsException.php index c7e3f92..1dc53d1 100644 --- a/src/Infrastructure/Exceptions/InvalidSettingsException.php +++ b/src/Infrastructure/Exceptions/InvalidSettingsException.php @@ -19,6 +19,11 @@ public static function forValue(string $key, string $value, array $allowed): sel return new self(sprintf('"%s" is not a valid value for "%s" (expected one of: %s).', $value, $key, implode(', ', $allowed))); } + public static function tooShort(string $key, int $length): self + { + return new self(sprintf('"%s" must be at least %d characters long.', $key, $length)); + } + public static function missing(string $key): self { return new self(sprintf('"%s" is required and is empty.', $key)); diff --git a/src/Infrastructure/Status/Check.php b/src/Infrastructure/Status/Check.php new file mode 100644 index 0000000..00d110b --- /dev/null +++ b/src/Infrastructure/Status/Check.php @@ -0,0 +1,26 @@ + + */ + public function toArray(): array + { + return ['id' => $this->id, 'level' => $this->level->value, 'message' => $this->message, 'fix' => $this->fix]; + } +} diff --git a/src/Infrastructure/Status/CheckLevel.php b/src/Infrastructure/Status/CheckLevel.php new file mode 100644 index 0000000..56f0678 --- /dev/null +++ b/src/Infrastructure/Status/CheckLevel.php @@ -0,0 +1,15 @@ + + */ + public static function run(Settings $settings, DoctorFacts $facts): array + { + return [ + ...self::front($settings), + ...self::rest($settings, $facts), + self::permalinks($facts), + ...self::delivery($settings, $facts), + ...self::graphql($facts), + ...self::redirects($facts), + ...($settings->restPluginFilter ? [new Check('rest-plugins', CheckLevel::Warning, 'REST requests load only the plugins you listed: any plugin left out loses its routes, types, fields and login there.', 'Check `rest_plugins.keep` after each plugin you add.')] : []), + self::theme($facts), + self::seo($facts), + new Check('debug-display', $facts->debugDisplay ? CheckLevel::Warning : CheckLevel::Ok, $facts->debugDisplay ? 'PHP errors are printed in the answers.' : 'PHP errors are not printed in the answers.', $facts->debugDisplay ? 'Set WP_DEBUG_DISPLAY to false: a notice inside a JSON answer breaks the client and leaks paths.' : ''), + ]; + } + + /** + * @param list $checks + */ + public static function failed(array $checks): bool + { + return array_filter($checks, static fn (Check $check): bool => $check->level === CheckLevel::Fail) !== []; + } + + /** + * @return list + */ + private static function front(Settings $settings): array + { + if (! $settings->front instanceof Origin) { + return [new Check('front-url', CheckLevel::Warning, 'No front-end URL: the public front of WordPress is left as it is.', 'Set HEADLESS_FRONTEND_URL.')]; + } + + $checks = [new Check('front-url', CheckLevel::Ok, 'Front end: '.$settings->front->toString())]; + + if ($settings->front->sameHostAs($settings->backend)) { + $checks[] = new Check('front-host', CheckLevel::Fail, 'The front end has the same host as WordPress: the gate cannot redirect without looping, so it lets everything through.', 'Serve the front end from another host or port.'); + } + + foreach ([['front', $settings->front], ['WordPress', $settings->backend]] as [$name, $origin]) { + if ($origin->scheme !== 'https' && ! self::isLocal($origin->host)) { + $checks[] = new Check('https', CheckLevel::Warning, sprintf('The %s address is not HTTPS: tokens and sessions travel in clear.', $name), 'Use HTTPS.'); + } + } + + return $checks; + } + + /** + * @return list + */ + private static function rest(Settings $settings, DoctorFacts $facts): array + { + $checks = []; + + $checks[] = $settings->cors instanceof CorsPolicy + ? new Check('cors', CheckLevel::Ok, 'CORS answers for the listed origins only.') + : new Check('cors', CheckLevel::Warning, 'No CORS policy: WordPress reflects any origin and allows credentials.', 'Set the front-end URL, or list `cors.origins`.'); + + if ($facts->usersStatus === null) { + $checks[] = new Check('users-route', CheckLevel::Warning, 'The users route could not be tried.'); + } elseif ($facts->usersStatus === 200) { + $checks[] = new Check('users-route', CheckLevel::Fail, 'An anonymous visitor can list the users (`/wp/v2/users`): their logins can be guessed and attacked.', 'Keep `restrict_users` on.'); + } else { + $checks[] = new Check('users-route', CheckLevel::Ok, sprintf('The users route answers %d to a visitor.', $facts->usersStatus)); + } + + $checks[] = match (true) { + $facts->postsStatus === null => new Check('rest-open', CheckLevel::Warning, 'The posts route could not be tried.'), + $facts->postsStatus === 200 => new Check('rest-open', CheckLevel::Ok, 'The REST API answers visitors.'), + default => new Check('rest-open', CheckLevel::Fail, sprintf('The posts route answers %d to a visitor: a plugin locks the REST API, and a front end cannot read the content.', $facts->postsStatus), 'Allow anonymous reads, or give the front end an API token.'), + }; + + if (! $settings->apiTokens) { + $checks[] = new Check('tokens', CheckLevel::Warning, 'API tokens are off.', 'A front end that reads private content needs one.'); + } + + return $checks; + } + + private static function permalinks(DoctorFacts $facts): Check + { + return $facts->permalinkStructure === '' + ? new Check('permalinks', CheckLevel::Fail, 'Plain permalinks: `/wp-json/` and the redirects of the front end need pretty ones.', 'Settings, Permalinks: pick any structure but "Plain".') + : new Check('permalinks', CheckLevel::Ok, 'Pretty permalinks: '.$facts->permalinkStructure); + } + + /** + * @return list + */ + private static function delivery(Settings $settings, DoctorFacts $facts): array + { + $checks = []; + + $checks[] = $settings->previewUrl === null + ? new Check('preview', CheckLevel::Warning, 'Preview is off: editors cannot see a draft on the front end.', 'Set `preview.url` to the preview route of the front end.') + : new Check('preview', CheckLevel::Ok, 'Preview goes to '.$settings->previewUrl); + + if ($settings->revalidationTargets === []) { + $checks[] = new Check('revalidation', CheckLevel::Warning, 'No revalidation target: the front end is not told when content changes.', 'Add one under `revalidation.targets`.'); + + return $checks; + } + + foreach ($settings->revalidationTargets as $target) { + if (! str_starts_with($target->url, 'https://') && ! self::isLocal((string) parse_url($target->url, PHP_URL_HOST))) { + $checks[] = new Check('revalidation-https', CheckLevel::Warning, sprintf('The target "%s" is not HTTPS.', $target->name), 'Signed requests still travel in clear: use HTTPS.'); + } + } + + $checks[] = match (true) { + $facts->actionSchedulerIsReady => new Check('revalidation', CheckLevel::Ok, 'Revalidation runs on Action Scheduler.'), + $facts->cronIsDisabled => new Check('revalidation', CheckLevel::Warning, 'Revalidation goes through WP-Cron, which is disabled: a system cron must call wp-cron.php.', 'Install Action Scheduler, or schedule `wp cron event run --due-now`.'), + default => new Check('revalidation', CheckLevel::Warning, 'Revalidation goes through WP-Cron, which runs only when a page is visited.', 'Install Action Scheduler and run a system cron.'), + }; + + return $checks; + } + + /** + * @return list + */ + private static function graphql(DoctorFacts $facts): array + { + if (! $facts->graphqlActive) { + return []; + } + + return [$facts->graphqlIntrospection === true + ? new Check('graphql', CheckLevel::Fail, 'Anyone can introspect the GraphQL schema.', 'Keep `graphql.introspection` false.') + : new Check('graphql', CheckLevel::Ok, 'WPGraphQL is active and its schema is closed to visitors.')]; + } + + /** + * Rules that send a path to itself, or round in a circle, or through several hops. + * + * @return list + */ + private static function redirects(DoctorFacts $facts): array + { + $checks = []; + $exact = array_filter($facts->redirects->all(), static fn (Redirect $rule): bool => ! $rule->regex && $rule->status !== 410); + + foreach ($exact as $rule) { + $seen = [$rule->from]; + $path = $rule->from; + + for ($hop = 0; $hop < 10; $hop++) { + $next = $facts->redirects->match($path); + + if ($next === null) { + break; + } + + $path = '/'.trim((string) parse_url($next['to'], PHP_URL_PATH), '/'); + + if (in_array($path, $seen, true) || $path === '/'.trim($rule->from, '/')) { + $checks[] = new Check('redirect-loop', CheckLevel::Fail, sprintf('The redirect of %s ends up back where it started.', $rule->from), 'Remove or change one rule of the circle.'); + + continue 2; + } + + $seen[] = $path; + } + + if (count($seen) > 2) { + $checks[] = new Check('redirect-chain', CheckLevel::Warning, sprintf('The redirect of %s takes %d hops.', $rule->from, count($seen) - 1), 'Point it straight to the last address.'); + } + } + + return $checks === [] ? [new Check('redirects', CheckLevel::Ok, sprintf('%d redirect rule(s), no loop.', count($facts->redirects->all())))] : $checks; + } + + private static function theme(DoctorFacts $facts): Check + { + return $facts->themeIsValid + ? new Check('theme', CheckLevel::Ok, 'A valid theme is active.') + : new Check('theme', CheckLevel::Fail, 'No valid theme: WordPress falls back to recovery mode.', 'Run `wp headless theme install --activate`.'); + } + + private static function seo(DoctorFacts $facts): Check + { + return $facts->seoPlugin === null + ? new Check('seo', CheckLevel::Ok, 'No SEO plugin: `headless_seo` is empty.') + : new Check('seo', CheckLevel::Ok, 'SEO plugin: '.$facts->seoPlugin); + } + + private static function isLocal(string $host): bool + { + return $host === 'localhost' || $host === '127.0.0.1' || str_ends_with($host, '.test') || str_ends_with($host, '.local') || str_ends_with($host, '.ddev.site'); + } +} diff --git a/src/Infrastructure/Status/DoctorFacts.php b/src/Infrastructure/Status/DoctorFacts.php new file mode 100644 index 0000000..ba6e392 --- /dev/null +++ b/src/Infrastructure/Status/DoctorFacts.php @@ -0,0 +1,31 @@ +register(new WordPressHooks); + // Not static: Brain Monkey binds the callbacks it records, and refuses a static closure $start = function (): void { self::boot(SettingsLoader::load(home_url(), get_current_blog_id()), new WordPressHooks); diff --git a/src/Infrastructure/WordPress/DoctorProbe.php b/src/Infrastructure/WordPress/DoctorProbe.php new file mode 100644 index 0000000..84543d8 --- /dev/null +++ b/src/Infrastructure/WordPress/DoctorProbe.php @@ -0,0 +1,65 @@ +exists(), + defined('DISABLE_WP_CRON') && DISABLE_WP_CRON, + ActionSchedulerScheduler::actionSchedulerIsReady(), + $graphql, + $graphql ? self::introspectionIsOpen() : null, + self::rules(), + ($name = SeoProviders::detect()->name()) === 'none' ? null : $name, + ); + } + + /** + * The status WordPress gives a visitor who is not logged in. + */ + private static function anonymousStatus(string $route): ?int + { + $user = get_current_user_id(); + wp_set_current_user(0); + + try { + return rest_do_request(new \WP_REST_Request('GET', $route))->get_status(); + } catch (\Throwable) { + return null; + } finally { + wp_set_current_user($user); + } + } + + private static function introspectionIsOpen(): bool + { + return get_graphql_setting('public_introspection_enabled', 'off') !== 'off'; + } + + private function rules(): RedirectRules + { + return $this->redirects->rules(); + } +} diff --git a/src/Infrastructure/WordPress/PreviewRoutes.php b/src/Infrastructure/WordPress/PreviewRoutes.php index ed86fe1..5aa1801 100644 --- a/src/Infrastructure/WordPress/PreviewRoutes.php +++ b/src/Infrastructure/WordPress/PreviewRoutes.php @@ -67,7 +67,7 @@ public function exchange(\WP_REST_Request $request): \WP_REST_Response|\WP_Error $token = $request->get_param('token'); try { - $session = $this->service->exchange(is_string($token) ? $token : ''); + $session = $this->service->exchange(is_string($token) ? $token : '', get_current_blog_id()); } catch (Throwable $throwable) { return self::error($throwable); } @@ -103,7 +103,7 @@ public function authorize(\WP_REST_Request $request): bool|\WP_Error if (is_string($header) && preg_match('/\ABearer\s+(hlp\.\S+)\z/i', trim($header), $match) === 1) { try { - $this->userId = $this->service->authorize($match[1], $postId)->userId; + $this->userId = $this->service->authorize($match[1], $postId, get_current_blog_id())->userId; } catch (Throwable $exception) { return self::error($exception); } diff --git a/src/Infrastructure/WordPress/RedirectRoutes.php b/src/Infrastructure/WordPress/RedirectRoutes.php index 34acc57..73b7e64 100644 --- a/src/Infrastructure/WordPress/RedirectRoutes.php +++ b/src/Infrastructure/WordPress/RedirectRoutes.php @@ -42,7 +42,7 @@ public function routes(): void 'methods' => 'GET', 'callback' => [$this, 'resolve'], 'permission_callback' => '__return_true', - 'args' => ['path' => ['type' => 'string', 'required' => true, 'pattern' => '\A/\S{0,1999}\z']], + 'args' => ['path' => ['type' => 'string', 'required' => true, 'pattern' => '\A/\S{0,511}\z']], ]); } diff --git a/src/Infrastructure/WordPress/RestPlugins.php b/src/Infrastructure/WordPress/RestPlugins.php new file mode 100644 index 0000000..1ca48fc --- /dev/null +++ b/src/Infrastructure/WordPress/RestPlugins.php @@ -0,0 +1,59 @@ + $query `$_GET` + */ + public static function fromSettings(string $requestUri, array $query): ?self + { + $config = SettingsLoader::config(function_exists('get_current_blog_id') ? get_current_blog_id() : 1)['rest_plugins'] ?? null; + + if (! is_array($config) || ($config['enabled'] ?? false) !== true) { + return null; + } + + $keep = array_values(array_filter(is_array($config['keep'] ?? null) ? $config['keep'] : [], is_string(...))); + + return new self(new PluginFilter($keep), PluginFilter::isRestRequest($requestUri, isset($query['rest_route']))); + } + + public function register(HookRegistrar $hooks): void + { + if (! $this->isRestRequest) { + return; + } + + $hooks->addFilter('option_active_plugins', [$this, 'plugins'], 1); + } + + /** + * @return list|mixed + */ + public function plugins(mixed $active): mixed + { + return is_array($active) ? $this->filter->filter($active) : $active; + } +} diff --git a/src/Infrastructure/WordPress/TokenAuthentication.php b/src/Infrastructure/WordPress/TokenAuthentication.php index 90bfc3a..15e157d 100644 --- a/src/Infrastructure/WordPress/TokenAuthentication.php +++ b/src/Infrastructure/WordPress/TokenAuthentication.php @@ -77,6 +77,11 @@ public function reject(mixed $errors): mixed return $errors; } + // WordPress works the current user out lazily: until something asks for it, the token has not been looked at + if (! $this->rejected && ! $this->token instanceof Token && ($this->isRestRequest)()) { + wp_get_current_user(); + } + return $this->rejected ? new \WP_Error('headless_token_invalid', 'The API token is invalid, revoked or expired.', ['status' => 401]) : $errors; } diff --git a/src/Infrastructure/WpCli/HeadlessCommand.php b/src/Infrastructure/WpCli/HeadlessCommand.php index fa3bc08..0753abe 100644 --- a/src/Infrastructure/WpCli/HeadlessCommand.php +++ b/src/Infrastructure/WpCli/HeadlessCommand.php @@ -6,6 +6,9 @@ use Closure; use Pollora\Headless\Infrastructure\Exceptions\ThemeInstallException; +use Pollora\Headless\Infrastructure\Status\Check; +use Pollora\Headless\Infrastructure\Status\CheckLevel; +use Pollora\Headless\Infrastructure\Status\Doctor; use Pollora\Headless\Infrastructure\Status\StatusReport; use Pollora\Headless\Infrastructure\WordPress\StubTheme; @@ -18,12 +21,14 @@ * @param Closure(): StatusReport $report built when a command runs: wp-config.php has been read by then * @param Closure(): StubTheme $theme * @param Closure(string): void $activate switches the active theme to the given slug + * @param (Closure(): list)|null $doctor runs the checks of `wp headless doctor` */ public function __construct( private Closure $report, private Closure $theme, private Closure $activate, private Output $output, + private ?Closure $doctor = null, ) {} /** @@ -53,11 +58,58 @@ public function status(array $args = [], array $assoc = []): void } } + /** + * Check the site for what exposes it or breaks the front end, and say how to fix each finding. + * + * Exits with an error when a check fails, so that a deployment can stop on it. + * + * ## OPTIONS + * + * [--format=] + * : `table` (default) or `json`. + * + * ## EXAMPLES + * + * wp headless doctor + * wp headless doctor --format=json + * + * @param list $args + * @param array $assoc + */ + public function doctor(array $args = [], array $assoc = []): void + { + $checks = $this->doctor instanceof Closure ? ($this->doctor)() : []; + + if (($assoc['format'] ?? 'table') === 'json') { + $this->output->line(json_encode(array_map(static fn (Check $check): array => $check->toArray(), $checks), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)); + } else { + foreach ($checks as $check) { + $line = sprintf('[%s] %s', $check->level->value, $check->message).($check->fix !== '' && $check->level !== CheckLevel::Ok ? ' → '.$check->fix : ''); + + match ($check->level) { + CheckLevel::Ok => $this->output->line($line), + default => $this->output->warning($line), + }; + } + } + + if (Doctor::failed($checks)) { + $this->output->error('The doctor found something that exposes the site or breaks the front end.'); + + return; + } + + $this->output->success('No failing check.'); + } + /** * Install the empty theme WordPress needs when the front end lives elsewhere. * * ## OPTIONS * + * + * : `install`. + * * [--activate] * : Make it the active theme once installed. * diff --git a/src/Infrastructure/WpCli/register.php b/src/Infrastructure/WpCli/register.php index bceca82..2faf826 100644 --- a/src/Infrastructure/WpCli/register.php +++ b/src/Infrastructure/WpCli/register.php @@ -14,7 +14,9 @@ use Pollora\Headless\Infrastructure\Redirect\RedirectCatalog; use Pollora\Headless\Infrastructure\Revalidation\ActionSchedulerScheduler; use Pollora\Headless\Infrastructure\Revalidation\RevalidatorFactory; +use Pollora\Headless\Infrastructure\Status\Doctor; use Pollora\Headless\Infrastructure\Status\StatusReport; +use Pollora\Headless\Infrastructure\WordPress\DoctorProbe; use Pollora\Headless\Infrastructure\WordPress\SiteContext; use Pollora\Headless\Infrastructure\WordPress\StubTheme; use Pollora\Headless\Infrastructure\WordPress\UserMetaTokenStore; @@ -48,6 +50,12 @@ static function (string $slug): void { switch_theme($slug); }, new WpCliOutput, + static function () use ($settings): array { + $config = $settings(); + $urls = $config->urls ?? new UrlMapper($config->backend, $config->backend); + + return Doctor::run($config, (new DoctorProbe(new RedirectCatalog([new OptionRedirectStore, new OldSlugRedirects($urls)])))->facts()); + }, )); WP_CLI::add_command('headless revalidate ping', new RevalidateCommand( static fn (): Revalidator => RevalidatorFactory::fromSettings($settings()), diff --git a/tests/E2E/checks.sh b/tests/E2E/checks.sh new file mode 100755 index 0000000..f24b445 --- /dev/null +++ b/tests/E2E/checks.sh @@ -0,0 +1,61 @@ +#!/bin/sh +# The assertions of tests/E2E/run.sh, run inside the container: $1 is the WordPress directory. +WP=${1:-/var/www/html} +B=http://localhost:8080 +FRONT=https://www.example.com +FAILED=0 +ok() { printf ' ok %s\n' "$1"; } +ko() { printf ' FAIL %s\n' "$1"; FAILED=1; } +check() { if [ "$2" = "$3" ]; then ok "$1"; else ko "$1 (got \"$2\", wanted \"$3\")"; fi; } +header() { curl -s -o /dev/null -D - "$@" | tr -d '\r'; } +code() { curl -s -o /dev/null -w '%{http_code}' "$@"; } + +echo "Front gate" +H=$(header "$B/hello-headless/") +check "a public page redirects" "$(echo "$H" | head -1 | cut -d' ' -f2)" "302" +check "to the same path on the front end" "$(echo "$H" | grep -i '^location:' | cut -d' ' -f2)" "$FRONT/hello-headless/" +check "wp-login stays on WordPress" "$(code "$B/wp-login.php")" "200" +check "a feed goes to the front end like any page" "$(code "$B/feed/")" "302" +check "the core sitemap is gone" "$(code "$B/wp-sitemap.xml")" "404" + +echo "REST API" +H=$(header "$B/wp-json/wp/v2/posts") +check "posts answer" "$(echo "$H" | head -1 | cut -d' ' -f2)" "200" +ETAG=$(echo "$H" | grep -i '^etag:' | cut -d' ' -f2-) +check "they carry an ETag" "$([ -n "$ETAG" ] && echo yes)" "yes" +check "they say how long to cache" "$(echo "$H" | grep -ic '^cache-control:.*max-age')" "1" +check "a matching ETag gives 304" "$(code -H "If-None-Match: $ETAG" "$B/wp-json/wp/v2/posts")" "304" +check "users are closed to visitors" "$(code "$B/wp-json/wp/v2/users")" "401" + +echo "CORS" +H=$(header -H "Origin: $FRONT" "$B/wp-json/wp/v2/posts") +check "the front end is allowed" "$(echo "$H" | grep -i '^access-control-allow-origin:' | cut -d' ' -f2)" "$FRONT" +H=$(header -H "Origin: https://evil.example.net" "$B/wp-json/wp/v2/posts") +check "another origin gets nothing" "$(echo "$H" | grep -ic '^access-control-allow-origin:')" "0" +check "and every answer varies on Origin" "$(echo "$H" | grep -ic '^vary:.*origin')" "1" +H=$(header -X OPTIONS -H "Origin: $FRONT" -H "Access-Control-Request-Method: GET" "$B/wp-json/wp/v2/posts") +check "a preflight lists methods" "$(echo "$H" | grep -ic '^access-control-allow-methods:')" "1" + +echo "Manifest, search, redirects" +check "the manifest answers" "$(code "$B/wp-json/headless/v1/site")" "200" +check "the manifest names the front end" "$(curl -s "$B/wp-json/headless/v1/site" | grep -c 'www.example.com')" "1" +check "search finds the post" "$(curl -s "$B/wp-json/headless/v1/search?q=headless" | sed "s#\\\\/#/#g" | grep -c "$FRONT/hello-headless/")" "1" +check "search refuses a short term" "$(code "$B/wp-json/headless/v1/search?q=a")" "400" +check "a post link points to the front end" "$(curl -s "$B/wp-json/wp/v2/posts" | sed "s#\\\\/#/#g" | grep -c "$FRONT/hello-headless/")" "1" + +echo "Preview and tokens" +DRAFT=$(cat /tmp/draft) +check "a draft is not public" "$(code "$B/wp-json/wp/v2/posts/$DRAFT")" "401" +check "preview needs a session" "$(code "$B/wp-json/headless/v1/preview/posts/$DRAFT")" "401" +TOKEN=$(grep -o 'hl\.[A-Za-z0-9._-]*' /tmp/token.txt | head -1) +check "a token was issued" "$([ -n "$TOKEN" ] && echo yes)" "yes" +check "the token reads the draft" "$(code -H "Authorization: Bearer $TOKEN" "$B/wp-json/headless/v1/preview/posts/$DRAFT")" "200" +check "a wrong token is refused" "$(code -H "Authorization: Bearer hl.1.aaaaaaaaaaaa.bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" "$B/wp-json/wp/v2/posts")" "401" +check "a read token cannot write" "$(code -X POST -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d '{"title":"x"}' "$B/wp-json/wp/v2/posts")" "403" + +echo "Doctor" +cd "$WP" && php -d memory_limit=1G /usr/local/bin/wp headless doctor --allow-root >/tmp/doctor.txt 2>&1 +check "the doctor finds nothing failing" "$(grep -c '^\[fail\]\|Error' /tmp/doctor.txt)" "0" + +echo +if [ "$FAILED" = 0 ]; then echo "E2E: all checks passed"; else echo "E2E: some checks failed"; cat /tmp/doctor.txt; tail -5 /tmp/server.log; exit 1; fi diff --git a/tests/E2E/run.sh b/tests/E2E/run.sh new file mode 100755 index 0000000..2538d08 --- /dev/null +++ b/tests/E2E/run.sh @@ -0,0 +1,46 @@ +#!/bin/sh +# End-to-end check over real HTTP: a throwaway WordPress in Docker (PHP's built-in server) with the package loaded as a mu-plugin, +# then curl against it. Usage: tests/E2E/run.sh [package dir]. Needs Docker and `composer install` done in the package. +# Not part of the CI harness (Pest suites cover the code); run it before a release. +set -e +PKG=$(cd "${1:-$PWD}" && pwd) +S=${WP_SCRATCH:-/tmp/wp-e2e-$$} +mkdir -p "$S/wp" +docker rm -f hl-e2e-mysql >/dev/null 2>&1 || true +docker network create hl-net >/dev/null 2>&1 || true +docker run -d --name hl-e2e-mysql --network hl-net -e MYSQL_ALLOW_EMPTY_PASSWORD=yes -e MYSQL_DATABASE=wordpress mysql:8.0 >/dev/null +# The container writes as root: remove its files from a container too +trap 'docker rm -f hl-e2e-mysql >/dev/null 2>&1 || true; docker run --rm -v "$S":/s alpine rm -rf /s/wp >/dev/null 2>&1; rmdir "$S" 2>/dev/null || true' EXIT +for i in $(seq 1 60); do docker exec hl-e2e-mysql mysqladmin ping -h 127.0.0.1 --silent >/dev/null 2>&1 && break; sleep 2; done + +# WordPress comes from the host: a container often cannot reach api.wordpress.org +[ -s /tmp/wp-latest.tar.gz ] || curl -fsSL -o /tmp/wp-latest.tar.gz https://wordpress.org/latest.tar.gz + +docker run --rm --network hl-net -u 0 -v /tmp/wp-latest.tar.gz:/wp.tar.gz:ro -v "$S/wp":/var/www/html -v "$PKG":/pkg wordpress:cli-php8.4 sh -c ' +wp() { php -d memory_limit=1G /usr/local/bin/wp "$@"; } +cd /var/www/html +tar xzf /wp.tar.gz --strip-components=1 +wp config create --allow-root --dbhost=hl-e2e-mysql --dbname=wordpress --dbuser=root --skip-check --quiet --extra-php < "https://www.example.com", "preview" => ["url" => "https://www.example.com/api/preview", "secret" => "e2e-secret-e2e-secret-e2e-secret-0123"]]); +define("DISABLE_WP_CRON", true); +PHP +wp core install --allow-root --url=http://localhost:8080 --title=e2e --admin_user=admin --admin_password=pass --admin_email=a@a.test --skip-email --quiet +wp rewrite structure "/%postname%/" --allow-root --quiet +mkdir -p wp-content/mu-plugins +echo " wp-content/mu-plugins/headless.php +cat > router.php </dev/null +wp post create --post_title="Hello headless" --post_status=publish --porcelain --allow-root > /tmp/published +wp post create --post_title="A secret draft" --post_status=draft --porcelain --allow-root > /tmp/draft +wp headless token create admin --name=e2e --scopes=read --allow-root > /tmp/token.txt 2>&1 || true +(php -S 0.0.0.0:8080 -t /var/www/html router.php >/tmp/server.log 2>&1 &) +sleep 2 +cd /pkg && sh tests/E2E/checks.sh /var/www/html +' diff --git a/tests/Integration/DoctorTest.php b/tests/Integration/DoctorTest.php new file mode 100644 index 0000000..4c03581 --- /dev/null +++ b/tests/Integration/DoctorTest.php @@ -0,0 +1,81 @@ +callbacks as $priority => $callbacks) { + foreach ($callbacks as $callback) { + $function = $callback['function']; + + if (is_array($function) && is_object($function[0]) && str_starts_with($function[0]::class, 'Pollora\\Headless\\')) { + remove_filter($hook, $function, $priority); + } + } + } + } + + delete_option('permalink_structure'); + wp_set_current_user(0); +}); + +/** + * @return array + */ +function doctorRun(): array +{ + $settings = Settings::fromArray(['frontend_url' => 'https://www.example.com'], home_url()); + Bootstrap::boot($settings, new WordPressHooks, new NoLanguages); + $GLOBALS['wp_rest_server'] = null; + rest_get_server(); + + $facts = (new DoctorProbe(new RedirectCatalog([new OptionRedirectStore])))->facts(); + $checks = []; + + foreach (Doctor::run($settings, $facts) as $check) { + $checks[$check->id] = $check; + } + + return $checks; +} + +it('sees that the package closes the users route and leaves the content open', function (): void { + update_option('permalink_structure', '/%postname%/'); + wp_set_current_user(1); + + $checks = doctorRun(); + + expect($checks['users-route']->level)->toBe(CheckLevel::Ok) + ->and($checks['rest-open']->level)->toBe(CheckLevel::Ok) + ->and($checks['permalinks']->level)->toBe(CheckLevel::Ok) + ->and($checks['cors']->level)->toBe(CheckLevel::Ok) + ->and(get_current_user_id())->toBe(1); +}); + +it('fails on plain permalinks', function (): void { + update_option('permalink_structure', ''); + + expect(doctorRun()['permalinks']->level)->toBe(CheckLevel::Fail); +}); + +it('sees WPGraphQL and its closed schema', function (): void { + update_option('permalink_structure', '/%postname%/'); + + $checks = doctorRun(); + + expect($checks['graphql']->level)->toBe(CheckLevel::Ok); +}); diff --git a/tests/Integration/RestPluginsTest.php b/tests/Integration/RestPluginsTest.php new file mode 100644 index 0000000..10d3599 --- /dev/null +++ b/tests/Integration/RestPluginsTest.php @@ -0,0 +1,33 @@ +register(new WordPressHooks); + + $kept = get_option('active_plugins'); + + expect($all)->toContain('polylang/polylang.php') + ->and($kept)->toContain('wordpress-seo/wp-seo.php') + ->and($kept)->not->toContain('polylang/polylang.php') + ->and(count($kept))->toBeLessThan(count($all)); +}); + +it('leaves the list alone on any other request', function (): void { + $all = get_option('active_plugins'); + (new RestPlugins(new PluginFilter(['wordpress-seo']), false))->register(new WordPressHooks); + + expect(get_option('active_plugins'))->toBe($all); +}); diff --git a/tests/Unit/DoctorTest.php b/tests/Unit/DoctorTest.php new file mode 100644 index 0000000..52a9216 --- /dev/null +++ b/tests/Unit/DoctorTest.php @@ -0,0 +1,189 @@ + $redirects + */ +function doctorFacts(array $redirects = [], int $users = 401, int $posts = 200, string $permalinks = '/%postname%/', bool $graphql = false, ?bool $introspection = null, bool $scheduler = true, bool $cronOff = false, bool $debug = false, bool $theme = true, ?string $seo = 'yoast'): DoctorFacts +{ + return new DoctorFacts($users, $posts, $permalinks, $debug, $theme, $cronOff, $scheduler, $graphql, $introspection, new RedirectRules($redirects), $seo); +} + +/** + * @param array $config + * @return array + */ +function doctorLevels(array $config, DoctorFacts $facts): array +{ + $levels = []; + + foreach (Doctor::run(Settings::fromArray($config, 'https://cms.example.com'), $facts) as $check) { + $levels[$check->id] = $levels[$check->id] ?? $check->level; + + if ($check->level === CheckLevel::Fail) { + $levels[$check->id] = CheckLevel::Fail; + } + } + + return $levels; +} + +const DOCTOR_GOOD = [ + 'frontend_url' => 'https://www.example.com', + 'preview' => ['url' => 'https://www.example.com/api/preview'], + 'revalidation' => ['targets' => [['name' => 'next', 'url' => 'https://www.example.com/api/revalidate', 'secret' => 's3cret']]], +]; + +it('finds nothing wrong with a well set up site', function (): void { + $checks = Doctor::run(Settings::fromArray(DOCTOR_GOOD, 'https://cms.example.com'), doctorFacts()); + + expect(array_filter($checks, static fn (Check $check): bool => $check->level !== CheckLevel::Ok))->toBe([]) + ->and(Doctor::failed($checks))->toBeFalse(); +}); + +it('warns when there is no front end, preview or revalidation', function (): void { + $levels = doctorLevels([], doctorFacts()); + + expect($levels['front-url'])->toBe(CheckLevel::Warning) + ->and($levels['preview'])->toBe(CheckLevel::Warning) + ->and($levels['revalidation'])->toBe(CheckLevel::Warning) + ->and($levels['cors'])->toBe(CheckLevel::Warning); +}); + +it('fails when the front end has the host of WordPress', function (): void { + expect(doctorLevels(['frontend_url' => 'https://cms.example.com:8080'] + DOCTOR_GOOD, doctorFacts())['front-host'] ?? null)->toBeNull() + ->and(doctorLevels(['frontend_url' => 'https://cms.example.com'] + DOCTOR_GOOD, doctorFacts())['front-host'])->toBe(CheckLevel::Fail); +}); + +it('warns about a front end that is not HTTPS, except a local one', function (): void { + expect(doctorLevels(['frontend_url' => 'http://front.example.net'] + DOCTOR_GOOD, doctorFacts())['https'])->toBe(CheckLevel::Warning) + ->and(doctorLevels(['frontend_url' => 'http://front.test'] + DOCTOR_GOOD, doctorFacts()))->not->toHaveKey('https'); +}); + +it('fails when a visitor can list users or the REST API is locked', function (): void { + $open = doctorLevels(DOCTOR_GOOD, doctorFacts(users: 200)); + $locked = doctorLevels(DOCTOR_GOOD, doctorFacts(posts: 401)); + $untried = doctorLevels(DOCTOR_GOOD, new DoctorFacts(null, null, '/%postname%/', false, true, false, true, false, null, new RedirectRules([]), null)); + + expect($open['users-route'])->toBe(CheckLevel::Fail) + ->and($locked['rest-open'])->toBe(CheckLevel::Fail) + ->and($untried['users-route'])->toBe(CheckLevel::Warning) + ->and($untried['rest-open'])->toBe(CheckLevel::Warning); +}); + +it('fails on plain permalinks and on a missing theme, warns on displayed errors', function (): void { + $levels = doctorLevels(DOCTOR_GOOD, doctorFacts(permalinks: '', theme: false, debug: true)); + + expect($levels['permalinks'])->toBe(CheckLevel::Fail) + ->and($levels['theme'])->toBe(CheckLevel::Fail) + ->and($levels['debug-display'])->toBe(CheckLevel::Warning); +}); + +it('warns about the cron that revalidation relies on without Action Scheduler', function (): void { + expect(doctorLevels(DOCTOR_GOOD, doctorFacts(scheduler: false))['revalidation'])->toBe(CheckLevel::Warning) + ->and(doctorLevels(DOCTOR_GOOD, doctorFacts(scheduler: false, cronOff: true))['revalidation'])->toBe(CheckLevel::Warning) + ->and(doctorLevels(['revalidation' => ['targets' => [['name' => 'n', 'url' => 'http://front.example.net/r', 'secret' => 's']]]] + DOCTOR_GOOD, doctorFacts())['revalidation-https'])->toBe(CheckLevel::Warning); +}); + +it('fails when WPGraphQL lets visitors introspect', function (): void { + expect(doctorLevels(DOCTOR_GOOD, doctorFacts(graphql: true, introspection: true))['graphql'])->toBe(CheckLevel::Fail) + ->and(doctorLevels(DOCTOR_GOOD, doctorFacts(graphql: true, introspection: false))['graphql'])->toBe(CheckLevel::Ok) + ->and(doctorLevels(DOCTOR_GOOD, doctorFacts()))->not->toHaveKey('graphql'); +}); + +it('warns when API tokens are off', function (): void { + expect(doctorLevels(['tokens' => ['enabled' => false]] + DOCTOR_GOOD, doctorFacts())['tokens'])->toBe(CheckLevel::Warning); +}); + +it('finds redirect loops and chains', function (): void { + $loop = doctorLevels(DOCTOR_GOOD, doctorFacts([new Redirect('/a/', '/b/'), new Redirect('/b/', '/a/')])); + $chain = doctorLevels(DOCTOR_GOOD, doctorFacts([new Redirect('/a/', '/b/'), new Redirect('/b/', '/c/')])); + $fine = doctorLevels(DOCTOR_GOOD, doctorFacts([new Redirect('/a/', '/b/'), new Redirect('/gone/', '', 410)])); + + expect($loop['redirect-loop'])->toBe(CheckLevel::Fail) + ->and($chain['redirect-chain'])->toBe(CheckLevel::Warning) + ->and($fine['redirects'])->toBe(CheckLevel::Ok); +}); + +it('reports the SEO plugin', function (): void { + $message = static fn (?string $seo): string => array_values(array_filter(Doctor::run(Settings::fromArray(DOCTOR_GOOD, 'https://cms.example.com'), doctorFacts(seo: $seo)), static fn (Check $check): bool => $check->id === 'seo'))[0]->message; + + expect($message('yoast'))->toBe('SEO plugin: yoast')->and($message(null))->toContain('No SEO plugin'); +}); + +function doctorOutput(): Output +{ + return new class implements Output + { + /** @var list */ + public array $messages = []; + + public function line(string $message): void + { + $this->messages[] = 'line: '.$message; + } + + public function success(string $message): void + { + $this->messages[] = 'success: '.$message; + } + + public function warning(string $message): void + { + $this->messages[] = 'warning: '.$message; + } + + public function error(string $message): void + { + $this->messages[] = 'error: '.$message; + } + }; +} + +/** + * @param list $checks + */ +function doctorCommand(Output $output, array $checks): HeadlessCommand +{ + return new HeadlessCommand(static fn () => throw new LogicException, static fn () => throw new LogicException, static function (): void {}, $output, static fn (): array => $checks); +} + +it('prints each check, and stops with an error when one fails', function (): void { + $output = doctorOutput(); + + doctorCommand($output, [new Check('a', CheckLevel::Ok, 'All good'), new Check('b', CheckLevel::Warning, 'Careful', 'Do this'), new Check('c', CheckLevel::Fail, 'Broken', 'Fix that')])->doctor(); + + expect($output->messages)->toBe(['line: [ok] All good', 'warning: [warning] Careful → Do this', 'warning: [fail] Broken → Fix that', 'error: The doctor found something that exposes the site or breaks the front end.']); +}); + +it('says so when nothing fails, and prints JSON on request', function (): void { + $text = doctorOutput(); + $json = doctorOutput(); + $checks = [new Check('a', CheckLevel::Warning, 'Careful', 'Do this')]; + + doctorCommand($text, $checks)->doctor(); + doctorCommand($json, $checks)->doctor([], ['format' => 'json']); + + expect($text->messages)->toBe(['warning: [warning] Careful → Do this', 'success: No failing check.']) + ->and(json_decode(substr($json->messages[0], 6), true))->toBe([['id' => 'a', 'level' => 'warning', 'message' => 'Careful', 'fix' => 'Do this']]) + ->and(end($json->messages))->toBe('success: No failing check.'); +}); + +it('has nothing to check without the closure', function (): void { + $output = doctorOutput(); + + (new HeadlessCommand(static fn () => throw new LogicException, static fn () => throw new LogicException, static function (): void {}, $output))->doctor(); + + expect($output->messages)->toBe(['success: No failing check.']); +}); diff --git a/tests/Unit/Infrastructure/ModulesTest.php b/tests/Unit/Infrastructure/ModulesTest.php index ddc642f..7c00ebc 100644 --- a/tests/Unit/Infrastructure/ModulesTest.php +++ b/tests/Unit/Infrastructure/ModulesTest.php @@ -165,6 +165,7 @@ function gateFor(FrontMode $mode, array &$ended): TemplateRedirectGate it('waits for plugins_loaded otherwise', function (): void { Functions\when('did_action')->justReturn(0); + Functions\when('get_current_blog_id')->justReturn(1); Actions\expectAdded('plugins_loaded')->once()->with(Mockery::type(Closure::class), 1); Bootstrap::fromWordPress(); diff --git a/tests/Unit/Infrastructure/PreviewInfrastructureTest.php b/tests/Unit/Infrastructure/PreviewInfrastructureTest.php index e6432dd..2e518dc 100644 --- a/tests/Unit/Infrastructure/PreviewInfrastructureTest.php +++ b/tests/Unit/Infrastructure/PreviewInfrastructureTest.php @@ -5,6 +5,10 @@ use Brain\Monkey\Actions; use Brain\Monkey\Filters; use Brain\Monkey\Functions; + +beforeEach(function (): void { + Functions\when('get_current_blog_id')->justReturn(1); +}); use Pollora\Headless\Application\Preview\PreviewService; use Pollora\Headless\Domain\Preview\PreviewClaims; use Pollora\Headless\Domain\Preview\PreviewTokenType; @@ -254,13 +258,13 @@ function paramsRequest(array $params, ?string $authorization = null): WP_REST_Re }); it('reads the preview settings', function (): void { - $settings = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'preview' => ['url' => '/draft', 'link_ttl' => 5, 'session_ttl' => 10, 'secret' => ' s3cret ']], 'https://cms.example.com'); + $settings = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'preview' => ['url' => '/draft', 'link_ttl' => 5, 'session_ttl' => 10, 'secret' => ' '.str_repeat('s', 40).' ']], 'https://cms.example.com'); $absolute = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'preview' => ['url' => 'https://preview.example.org/enter?x=1']], 'https://cms.example.com'); $off = Settings::fromArray(['frontend_url' => 'https://www.example.com', 'preview' => ['enabled' => false]], 'https://cms.example.com'); $noFront = Settings::fromArray([], 'https://cms.example.com'); expect($settings->previewUrl)->toBe('https://www.example.com/draft') - ->and($settings->previewSecret)->toBe('s3cret') + ->and($settings->previewSecret)->toBe(str_repeat('s', 40)) ->and($settings->previewLinkTtl)->toBe(30) ->and($settings->previewSessionTtl)->toBe(60) ->and($absolute->previewUrl)->toBe('https://preview.example.org/enter') diff --git a/tests/Unit/Infrastructure/TokenInfrastructureTest.php b/tests/Unit/Infrastructure/TokenInfrastructureTest.php index 038214a..5e6424d 100644 --- a/tests/Unit/Infrastructure/TokenInfrastructureTest.php +++ b/tests/Unit/Infrastructure/TokenInfrastructureTest.php @@ -71,6 +71,8 @@ function authModule(?InMemoryTokenStore $store = null, bool $rest = true): array $store ??= new InMemoryTokenStore; $service = new TokenService($store); + Functions\when('wp_get_current_user')->justReturn(null); + return [new TokenAuthentication($service, fn (): bool => $rest), $service, $store]; } @@ -325,3 +327,14 @@ function tokenCommand(Output $output, ?InMemoryTokenStore $store = null): TokenC ->and($missing->messages[0])->toContain('No token') ->and($nobody->messages[0])->toContain('No user'); }); + +it('looks at the token itself when WordPress has not asked for the user yet', function (): void { + [$module] = authModule(); + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer hl.1.aaaaaaaaaaaa.'.str_repeat('b', 43); + // WordPress works the user out when something first asks for it: the module's filter then runs + Functions\when('wp_get_current_user')->alias(static function () use ($module): void { + $module->authenticate(false); + }); + + expect($module->reject(null))->toBeInstanceOf(WP_Error::class); +}); diff --git a/tests/Unit/RestPluginsTest.php b/tests/Unit/RestPluginsTest.php new file mode 100644 index 0000000..fec5fa9 --- /dev/null +++ b/tests/Unit/RestPluginsTest.php @@ -0,0 +1,47 @@ +filter(['advanced-custom-fields/acf.php', 'seo/seo.php', 'seo/other.php', 'hello.php', 'cache/cache.php', 42]))->toBe(['advanced-custom-fields/acf.php', 'seo/seo.php']) + ->and($filter->keeps('hello.php'))->toBeFalse() + ->and((new PluginFilter(['hello.php']))->keeps('hello.php'))->toBeTrue() + ->and((new PluginFilter([]))->filter(['a/a.php']))->toBe([]); +}); + +it('tells a REST request from its address', function (): void { + expect(PluginFilter::isRestRequest('/wp-json/wp/v2/posts?per_page=2'))->toBeTrue() + ->and(PluginFilter::isRestRequest('/blog/wp-json/'))->toBeTrue() + ->and(PluginFilter::isRestRequest('/wp-json'))->toBeTrue() + ->and(PluginFilter::isRestRequest('/index.php?rest_route=/wp/v2/posts', true))->toBeTrue() + ->and(PluginFilter::isRestRequest('/wp-admin/admin-ajax.php'))->toBeFalse() + ->and(PluginFilter::isRestRequest('/my-wp-json-page/'))->toBeFalse() + ->and(PluginFilter::isRestRequest('/'))->toBeFalse(); +}); + +it('is off unless the settings turn it on', function (): void { + Brain\Monkey\Functions\when('get_current_blog_id')->justReturn(1); + + expect(RestPlugins::fromSettings('/wp-json/', []))->toBeNull() + ->and(Settings::fromArray(['rest_plugins' => ['enabled' => true]], 'https://cms.example.com')->restPluginFilter)->toBeTrue() + ->and(Settings::fromArray([], 'https://cms.example.com')->restPluginFilter)->toBeFalse(); +}); + +it('filters the active plugins of a REST request only', function (): void { + Filters\expectAdded('option_active_plugins')->once()->with(Mockery::type('array'), 1); + + $rest = new RestPlugins(new PluginFilter(['acf']), true); + $rest->register(new WordPressHooks); + (new RestPlugins(new PluginFilter(['acf']), false))->register(new WordPressHooks); + + expect($rest->plugins(['acf/acf.php', 'x/x.php']))->toBe(['acf/acf.php']) + ->and($rest->plugins('not an array'))->toBe('not an array'); +}); diff --git a/tests/Unit/SearchQueryTest.php b/tests/Unit/SearchQueryTest.php index e207682..9f364f2 100644 --- a/tests/Unit/SearchQueryTest.php +++ b/tests/Unit/SearchQueryTest.php @@ -34,7 +34,8 @@ function searchQuery(string $term = 'hello', string $types = '', ?string $lang = }); it('bounds the page and its size', function (): void { - expect(searchQuery(page: -4)?->page)->toBe(1) + expect(searchQuery(page: 99999)?->page)->toBe(SearchQuery::MAX_PAGE) + ->and(searchQuery(page: -4)?->page)->toBe(1) ->and(searchQuery(page: 3)?->page)->toBe(3) ->and(searchQuery(perPage: 0)?->perPage)->toBe(SearchQuery::DEFAULT_PER_PAGE) ->and(searchQuery(perPage: 500)?->perPage)->toBe(50) diff --git a/tests/Unit/SecurityFixesTest.php b/tests/Unit/SecurityFixesTest.php new file mode 100644 index 0000000..d0fc1af --- /dev/null +++ b/tests/Unit/SecurityFixesTest.php @@ -0,0 +1,78 @@ +resolve('/go//evil.com'))->toBeNull() + ->and($rule->resolve('/go/\\evil.com'))->toBeNull() + ->and($rule->resolve('/go/about'))->toBe('/about') + ->and((new Redirect('/x/(.*)', 'https://example.org/$1', 301, true))->resolve('/x/a'))->toBe('https://example.org/a'); +}); + +it('refuses a pattern that repeats a repetition', function (string $pattern): void { + new Redirect($pattern, '/to', 301, true); +})->throws(InvalidRedirectException::class)->with(['/(a+)+', '/(.*)*x', '/(a*)*', '/(?:a+){2,}', '/(\d+)+/end']); + +it('keeps the ordinary patterns', function (string $pattern): void { + expect((new Redirect($pattern, '/to', 301, true))->regex)->toBeTrue(); +})->with(['/blog/(.*)', '/news/(\d{4})/(.+)', '/a+b', '/(foo|bar)/baz', '/page/(\d+)/?']); + +it('resolves the dots of an address before the gate sees it', function (string $uri, string $path): void { + expect(RequestTarget::fromUri($uri)->path)->toBe($path); +})->with([ + ['/wp-admin/../?p=1', '/'], + ['/wp-admin/%2e%2e/secret', '/secret'], + ['/a/./b/../c', '/a/c'], + ['/../../x', '/x'], + ['/blog/', '/blog/'], + ['/a/..', '/'], +]); + +it('lets a rotated token live no longer than it already could', function (): void { + $now = 1000; + $store = new InMemoryTokenStore; + $counter = 0; + $service = new TokenService($store, static fn (): int => $now, static function (int $length) use (&$counter): string { + $counter++; + + return str_repeat(chr($counter), $length); + }); + $issued = $service->create(7, 'next', [TokenScope::Read], [], 60); + + $service->rotate(7, $issued->token->id, 7 * 86400); + + expect($store->find(7, $issued->token->id)?->expiresAt)->toBe(1060); +}); + +it('refuses a preview token made on another site', function (): void { + $service = new PreviewService( + new FakePreviewStore, + new FakePostAccess, + str_repeat('k', 40), + 'https://www.example.com', + 300, + 1800, + ); + $link = $service->linkToken(7, 42, 2); + + $service->exchange($link, 1); +})->throws(PreviewTokenInvalidException::class); + +it('wants a preview secret of 32 characters at least', function (): void { + Settings::fromArray(['frontend_url' => 'https://www.example.com', 'preview' => ['url' => '/p', 'secret' => 'short']], 'https://cms.example.com'); +})->throws(InvalidSettingsException::class, 'at least 32');