diff --git a/CHANGELOG.md b/CHANGELOG.md index e2d8c16..525d47c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes are listed here. The format follows [Keep a Changelog](https ## [Unreleased] +### Changed + +- Development: `antecedent/patchwork` is pinned to the commit of antecedent/patchwork#235, so that the mutation score is measured right. +- Tests only: the true mutation score of the suite went from 78 % to over 94 %. + ## [1.0.1] - 2026-11-27 Security fixes: upgrade. diff --git a/composer.json b/composer.json index dbdcc31..46c7872 100644 --- a/composer.json +++ b/composer.json @@ -23,7 +23,7 @@ "php": "^8.3" }, "require-dev": { - "antecedent/patchwork": "^2.2", + "antecedent/patchwork": "dev-master#d588654e5c1304810b038db2b5c98d39b6f76c61 as 2.2.6", "brain/monkey": "^2.7", "illuminate/support": "^13.0", "laravel/pint": "^1.22.1", diff --git a/tests/Unit/Behaviour/ChangeReportingTest.php b/tests/Unit/Behaviour/ChangeReportingTest.php new file mode 100644 index 0000000..dc08c53 --- /dev/null +++ b/tests/Unit/Behaviour/ChangeReportingTest.php @@ -0,0 +1,235 @@ +justReturn(4); + Functions\when('get_locale')->justReturn('en_US'); + Functions\when('get_object_taxonomies')->justReturn([]); + Functions\when('get_post_type_object')->alias(static function (string $name): ?WP_Post_Type { + if ($name === 'unknown') { + return null; + } + + $type = Mockery::mock('WP_Post_Type'); + $type->show_in_rest = $name !== 'hidden'; + + return $type; + }); + Functions\when('get_permalink')->alias(static fn (WP_Post $post): string => 'https://www.example.com/'.$post->post_name.'/'); + + return [new ChangeWatcher($revalidator, $languages ?? new NoLanguages, $options), $pending]; +} + +function reportingPost(array $fields = []): WP_Post +{ + return new WP_Post(array_merge(['ID' => 12, 'post_name' => 'hello', 'post_type' => 'post', 'post_status' => 'publish'], $fields)); +} + +/** A multilingual site whose post 12 is French and whose other posts have no language. */ +function reportingLanguages(bool $active = true): Languages +{ + $languages = Mockery::mock(Languages::class); + $languages->shouldReceive('isActive')->andReturn($active); + $languages->shouldReceive('ofPost')->andReturnUsing(static fn (int $id): ?string => $id === 12 ? 'fr' : null); + + return $languages; +} + +it('watches the options a front end depends on', function (): void { + expect(ChangeWatcher::defaultOptions())->toBe([ + 'blogname', 'blogdescription', 'home', 'siteurl', 'page_on_front', 'page_for_posts', 'show_on_front', 'permalink_structure', + 'category_base', 'tag_base', 'posts_per_page', 'date_format', 'time_format', 'timezone_string', 'gmt_offset', 'WPLANG', + 'site_icon', 'sidebars_widgets', 'headless_redirects', + ]); +}); + +it('takes from each hook the arguments it reads, and commits late at shutdown', function (): void { + Actions\expectAdded('transition_post_status')->once()->with(Mockery::type('array'), 10, 3); + Actions\expectAdded('post_updated')->once()->with(Mockery::type('array'), 10, 3); + Actions\expectAdded('before_delete_post')->once()->with(Mockery::type('array'), 10, 2); + + foreach (['created_term', 'edited_term', 'delete_term'] as $hook) { + Actions\expectAdded($hook)->once()->with(Mockery::type('array'), 10, 3); + } + + Actions\expectAdded('shutdown')->once()->with(Mockery::type('array'), 20); + + [$watcher] = reportingWatcher(); + $watcher->register(new WordPressHooks); +}); + +it('reports one event from the first state to the last, keeping the slug before the first change', function (): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->postTransition('publish', 'draft', reportingPost()); + $watcher->postUpdated(12, reportingPost(), reportingPost(['post_name' => 'earlier'])); + $watcher->postTransition('publish', 'publish', reportingPost()); + $watcher->commit(); + + expect($pending->events)->toHaveCount(1) + ->and($pending->events[0]->name)->toBe(ChangeEvent::POST_PUBLISHED) + ->and($pending->events[0]->post['old_slug'])->toBe('earlier') + ->and($pending->events[0]->post['status_from'])->toBe('draft'); +}); + +it('ignores a former state that is not a post', function (): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->postTransition('publish', 'publish', reportingPost()); + $watcher->postUpdated(12, reportingPost(), 'not a post'); + $watcher->commit(); + + expect($pending->events[0]->post['old_slug'])->toBeNull(); +}); + +it('gives no old slug when the slug did not change', function (): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->postTransition('publish', 'publish', reportingPost()); + $watcher->postUpdated(12, reportingPost(), reportingPost()); + $watcher->commit(); + + expect($pending->events[0]->post['old_slug'])->toBeNull() + ->and($pending->events[0]->urls)->toBe(['https://www.example.com/hello/']); +}); + +it('says nothing of the deletion of what was not public', function (mixed $id, mixed $post): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->postDeleting($id, $post); + $watcher->commit(); + + expect($pending->events)->toBe([]); +})->with([ + 'a number given as text' => ['12', reportingPost()], + 'not a post' => [12, (object) ['post_status' => 'publish', 'post_type' => 'post']], + 'a draft' => [12, reportingPost(['post_status' => 'draft'])], + 'a type the REST API does not serve' => [12, reportingPost(['post_type' => 'hidden'])], +]); + +it('reports a deleted post with where it was', function (): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->postDeleting(12, reportingPost()); + $watcher->commit(); + + expect($pending->events[0]->name)->toBe(ChangeEvent::POST_DELETED) + ->and($pending->events[0]->urls)->toBe(['https://www.example.com/hello/']) + ->and($pending->events[0]->post)->toBe(['id' => 12, 'type' => 'post', 'slug' => 'hello', 'old_slug' => null, 'status_from' => 'publish', 'status_to' => 'deleted']); +}); + +it('never reports the technical post types', function (string $type): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->postTransition('publish', 'draft', reportingPost(['post_type' => $type])); + $watcher->commit(); + + expect($pending->events)->toBe([]); +})->with(['revision', 'nav_menu_item', 'auto-draft', 'customize_changeset', 'attachment', 'hidden', 'unknown']); + +it('tags a post with its terms of the taxonomies the REST API serves, past the ones it does not', function (): void { + [$watcher, $pending] = reportingWatcher(); + Functions\when('get_object_taxonomies')->justReturn([ + (object) ['name' => 'private', 'show_in_rest' => false], + (object) ['name' => 'category', 'show_in_rest' => true], + ]); + Functions\when('get_the_terms')->alias(static fn (WP_Post $post, string $taxonomy): array => [(object) ['term_id' => $taxonomy === 'category' ? 3 : 99]]); + + $watcher->postTransition('publish', 'draft', reportingPost()); + $watcher->commit(); + + expect($pending->events[0]->tags)->toBe(['post:12', 'type:post', 'site:4', 'term:3']); +}); + +it('lists no address for a post that has none', function (): void { + [$watcher, $pending] = reportingWatcher(); + Functions\when('get_permalink')->justReturn(false); + + $watcher->postTransition('publish', 'publish', reportingPost()); + $watcher->commit(); + + expect($pending->events[0]->urls)->toBe([]); +}); + +it('keeps the addresses a list when the new one is missing', function (): void { + [$watcher, $pending] = reportingWatcher(); + Functions\when('get_permalink')->alias(static fn (WP_Post $post): string|false => $post->post_name === 'hello' ? false : 'https://www.example.com/earlier/'); + + $watcher->postTransition('publish', 'publish', reportingPost()); + $watcher->postUpdated(12, reportingPost(), reportingPost(['post_name' => 'earlier'])); + $watcher->commit(); + + expect($pending->events[0]->urls)->toBe(['https://www.example.com/earlier/']); +}); + +it('says nothing of a term of a taxonomy the REST API does not serve', function (bool $exists): void { + [$watcher, $pending] = reportingWatcher(); + $taxonomy = false; + + if ($exists) { + $taxonomy = Mockery::mock('WP_Taxonomy'); + $taxonomy->show_in_rest = false; + } + + Functions\when('get_taxonomy')->justReturn($taxonomy); + Functions\when('get_term_link')->justReturn('https://www.example.com/t/'); + + $watcher->termChanged(3, 3, 'secret'); + $watcher->commit(); + + expect($pending->events)->toBe([]); +})->with([true, false]); + +it('gives a post its own language on a multilingual site, and the site\'s locale otherwise', function (bool $active, int $id, string $locale): void { + [$watcher, $pending] = reportingWatcher(reportingLanguages($active)); + + $watcher->postTransition('publish', 'draft', reportingPost(['ID' => $id])); + $watcher->commit(); + + expect($pending->events[0]->locale)->toBe($locale); +})->with([[true, 12, 'fr'], [true, 13, 'en_US'], [false, 12, 'en_US']]); + +it('asks no language for what is not a post', function (): void { + [$watcher, $pending] = reportingWatcher(reportingLanguages()); + + $watcher->optionChanged('blogname'); + $watcher->commit(); + + expect($pending->events[0]->locale)->toBe('en_US')->and($pending->events[0]->tags)->toBe(['options', 'option:blogname', 'site:4']); +}); + +it('reports each gathered change once', function (): void { + [$watcher, $pending] = reportingWatcher(); + + $watcher->mediaChanged(5); + $watcher->commit(); + $watcher->commit(); + + expect($pending->events)->toHaveCount(1) + ->and($pending->events[0]->tags)->toBe(['media', 'media:5', 'site:4']) + ->and($pending->events[0]->siteId)->toBe(4); +}); diff --git a/tests/Unit/Behaviour/CommandMessagesTest.php b/tests/Unit/Behaviour/CommandMessagesTest.php new file mode 100644 index 0000000..cdb32eb --- /dev/null +++ b/tests/Unit/Behaviour/CommandMessagesTest.php @@ -0,0 +1,220 @@ + */ + 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; + } + }; +} + +function saidTokens(Output $output, InMemoryTokenStore $store): TokenCommand +{ + return new TokenCommand(new TokenService($store, static fn (): int => 1_000_000), static fn (string $who): ?int => $who === 'editor' ? 7 : null, static fn (): int => 1_000_000, $output); +} + +it('announces a new token, then its secret', function (): void { + $output = saidOutput(); + $store = new InMemoryTokenStore; + + saidTokens($output, $store)->create(['editor']); + + $token = array_values($store->tokens)[0]; + + expect($output->messages[0])->toBe('success: Token '.$token->id.' created. Copy the secret now: it cannot be shown again.') + ->and($output->messages[1])->toStartWith('line: hl.7.') + ->and($token->scopes)->toBe([TokenScope::Read]) + ->and($token->expiresAt)->toBeNull() + ->and($token->routes)->toBe([]); +}); + +it('says which token a rotation replaces', function (): void { + $output = saidOutput(); + $store = new InMemoryTokenStore; + saidTokens(saidOutput(), $store)->create(['editor']); + $old = array_values($store->tokens)[0]->id; + + saidTokens($output, $store)->rotate(['editor', $old]); + + $new = array_values($store->tokens)[1]->id; + + expect($output->messages[0])->toBe('success: Token '.$new.' replaces '.$old.', which works for the grace period. Copy the secret now: it cannot be shown again.'); +}); + +it('reads a list of routes with blanks and empty entries as a list of routes', function (): void { + $store = new InMemoryTokenStore; + + saidTokens(saidOutput(), $store)->create(['editor'], ['routes' => ' ,/wp/v2/posts , /acme ', 'scopes' => ',read,']); + + $token = array_values($store->tokens)[0]; + + expect($token->routes)->toBe(['/wp/v2/posts', '/acme'])->and($token->scopes)->toBe([TokenScope::Read]); +}); + +it('takes a name given as a number', function (): void { + $store = new InMemoryTokenStore; + + saidTokens(saidOutput(), $store)->create(['editor'], ['name' => 2026]); + + expect(array_values($store->tokens)[0]->name)->toBe('2026'); +}); + +it('says when a listed token expires', function (): void { + $output = saidOutput(); + $store = new InMemoryTokenStore; + saidTokens(saidOutput(), $store)->create(['editor'], ['expires' => '1d', 'name' => 'n']); + $id = array_values($store->tokens)[0]->id; + + saidTokens($output, $store)->list_(['editor']); + + expect($output->messages)->toBe(['line: '.$id.' n [read] all routes expires '.gmdate('Y-m-d H:i', 1_086_400).' UTC']); +}); + +it('says it has no user to a command given none', function (string $command): void { + $output = saidOutput(); + + saidTokens($output, new InMemoryTokenStore)->{$command}(); + + expect($output->messages)->toBe(['error: No user "".']); +})->with(['create', 'list_', 'revoke', 'rotate']); + +it('says which token it did not find when given none', function (string $command): void { + $output = saidOutput(); + + saidTokens($output, new InMemoryTokenStore)->{$command}(['editor']); + + expect($output->messages)->toBe(['error: No token "" for this user.']); +})->with(['revoke', 'rotate']); + +function saidDoctor(Output $output, array $checks): HeadlessCommand +{ + return new HeadlessCommand(static fn () => null, static fn () => null, static fn () => null, $output, static fn (): array => $checks); +} + +it('prints what to do after a check that is not ok, and only then', function (): void { + $output = saidOutput(); + + saidDoctor($output, [new Check('a', CheckLevel::Ok, 'fine', 'nothing'), new Check('b', CheckLevel::Warning, 'hm', 'do it'), new Check('c', CheckLevel::Warning, 'bare')])->doctor(); + + expect($output->messages)->toBe(['line: [ok] fine', 'warning: [warning] hm → do it', 'warning: [warning] bare', 'success: No failing check.']); +}); + +it('prints the checks as readable JSON when asked', function (): void { + $output = saidOutput(); + + saidDoctor($output, [new Check('a', CheckLevel::Ok, 'see /wp-json/')])->doctor([], ['format' => 'json']); + + expect($output->messages[0])->toBe("line: [\n {\n \"id\": \"a\",\n \"level\": \"ok\",\n \"message\": \"see /wp-json/\",\n \"fix\": \"\"\n }\n]"); +}); + +it('explains the theme command to who gives no action', function (): void { + $output = saidOutput(); + + saidDoctor($output, [])->theme(); + + expect($output->messages)->toBe(['error: Usage: wp headless theme install [--activate]']); +}); + +it('writes an OpenAPI document of the namespaces asked for, readable as it is', function (): void { + $output = saidOutput(); + $written = []; + $command = new SchemaCommand( + static fn (): array => ['/a/v1' => [['methods' => 'GET']], '/b/v1' => [['methods' => 'GET']], '/c/v1' => [['methods' => 'GET']]], + static fn (): array => ['title' => 'Été', 'version' => '1', 'server' => 'https://x.test/wp-json'], + static fn () => null, + $output, + static function (string $file, string $content) use (&$written): bool { + $written = [$file, $content]; + + return true; + }, + ); + + $command->openapi([], ['namespace' => ' , a/v1 , b/v1', 'file' => 'api.json']); + + expect($written[1])->toContain("\n \"openapi\": \"3.0.3\"", '"title": "Été"', '"url": "https://x.test/wp-json"') + ->and($written[1])->toEndWith("}\n") + ->and(array_keys(json_decode($written[1], true)['paths']))->toBe(['/a/v1', '/b/v1']) + ->and($output->messages)->toBe(['success: 2 paths written to api.json.']); +}); + +it('prints the document when the file name is empty', function (): void { + $output = saidOutput(); + $command = new SchemaCommand(static fn (): array => [], static fn (): array => ['title' => 't', 'version' => '1', 'server' => 's'], static fn () => 'type Query', $output, static fn (): bool => false); + + $command->graphql([], ['file' => '']); + + expect($output->messages)->toBe(['line: type Query']); +}); + +it('names the folder or the file of the theme it could not write', function (string $case): void { + $root = sys_get_temp_dir().'/headless-said-'.bin2hex(random_bytes(6)); + $source = $root.'-source'; + mkdir($root); + mkdir($source); + file_put_contents($source.'/style.css', 'css'); + $expected = '"'.$root.'/headless/index.php"'; + + if ($case === 'folder') { + file_put_contents($root.'/headless', 'a file in the way'); + $expected = '"'.$root.'/headless"'; + } + + // mkdir() and copy() warn about what they cannot do: the exception is what is read here + set_error_handler(static fn (): bool => true); + + try { + (new StubTheme($root.'/', $source))->install(); + } catch (ThemeInstallException $exception) { + expect($exception->getMessage())->toContain($expected); + + return; + } finally { + restore_error_handler(); + } + + throw new RuntimeException('Expected an exception'); +})->with(['folder', 'file']); + +it('refuses a themes directory that does not exist', function (): void { + (new StubTheme(sys_get_temp_dir().'/headless-missing-'.bin2hex(random_bytes(6)), '/nowhere'))->install(); +})->throws(ThemeInstallException::class, 'Cannot write'); diff --git a/tests/Unit/Behaviour/DoctorAndStatusReportTest.php b/tests/Unit/Behaviour/DoctorAndStatusReportTest.php new file mode 100644 index 0000000..3bb97b8 --- /dev/null +++ b/tests/Unit/Behaviour/DoctorAndStatusReportTest.php @@ -0,0 +1,215 @@ + 'https://www.example.com', + 'revalidation' => ['targets' => [['name' => 'next', 'url' => 'https://www.example.com/api/revalidate', 'secret' => 'k'], ['name' => 'cdn', 'url' => 'https://cdn.example.com/hook', 'secret' => 'j']]], +]; + +function reportFacts(array $over = []): DoctorFacts +{ + $facts = array_replace(['users' => 401, 'posts' => 200, 'permalinks' => '/%postname%/', 'debug' => false, 'theme' => true, 'cronOff' => false, 'scheduler' => true, 'graphql' => false, 'introspection' => null, 'redirects' => [], 'seo' => null], $over); + + return new DoctorFacts($facts['users'], $facts['posts'], $facts['permalinks'], $facts['debug'], $facts['theme'], $facts['cronOff'], $facts['scheduler'], $facts['graphql'], $facts['introspection'], new RedirectRules($facts['redirects']), $facts['seo']); +} + +/** @return list */ +function reportChecks(array $config, DoctorFacts $facts, string $backend = 'https://cms.example.com'): array +{ + return array_map(static fn (Check $check): array => array_values($check->toArray()), Doctor::run(Settings::fromArray($config, $backend), $facts)); +} + +/** @return list the messages of the checks with one of these ids */ +function reportMessages(array $ids, array $config, DoctorFacts $facts, string $backend = 'https://cms.example.com'): array +{ + return array_values(array_map( + static fn (array $check): string => $check[1].': '.$check[2], + array_filter(reportChecks($config, $facts, $backend), static fn (array $check): bool => in_array($check[0], $ids, true)), + )); +} + +it('prints every check of a well set up site', function (): void { + expect(reportChecks(REPORT_SITE, reportFacts()))->toBe([ + ['front-url', 'ok', 'Front end: https://www.example.com', ''], + ['cors', 'ok', 'CORS answers for the listed origins only.', ''], + ['users-route', 'ok', 'The users route answers 401 to a visitor.', ''], + ['rest-open', 'ok', 'The REST API answers visitors.', ''], + ['permalinks', 'ok', 'Pretty permalinks: /%postname%/', ''], + ['preview', 'ok', 'Preview goes to https://www.example.com/api/preview', ''], + ['revalidation', 'ok', 'Revalidation runs on Action Scheduler.', ''], + ['redirects', 'ok', '0 redirect rule(s), no loop.', ''], + ['theme', 'ok', 'A valid theme is active.', ''], + ['seo', 'ok', 'No SEO plugin: `headless_seo` is empty.', ''], + ['debug-display', 'ok', 'PHP errors are not printed in the answers.', ''], + ]); +}); + +it('prints what to do about each thing that is wrong', function (): void { + $facts = reportFacts(['users' => 200, 'posts' => 403, 'permalinks' => '', 'debug' => true, 'theme' => false, 'scheduler' => false, 'graphql' => true, 'introspection' => true, 'seo' => 'yoast']); + + expect(reportChecks(['tokens' => ['enabled' => false], 'rest_plugins' => ['enabled' => true]], $facts))->toBe([ + ['front-url', 'warning', 'No front-end URL: the public front of WordPress is left as it is.', 'Set HEADLESS_FRONTEND_URL.'], + ['cors', 'warning', 'No CORS policy: WordPress reflects any origin and allows credentials.', 'Set the front-end URL, or list `cors.origins`.'], + ['users-route', 'fail', 'An anonymous visitor can list the users (`/wp/v2/users`): their logins can be guessed and attacked.', 'Keep `restrict_users` on.'], + ['rest-open', 'fail', 'The posts route answers 403 to a visitor: a plugin locks the REST API, and a front end cannot read the content.', 'Allow anonymous reads, or give the front end an API token.'], + ['tokens', 'warning', 'API tokens are off.', 'A front end that reads private content needs one.'], + ['permalinks', 'fail', 'Plain permalinks: `/wp-json/` and the redirects of the front end need pretty ones.', 'Settings, Permalinks: pick any structure but "Plain".'], + ['preview', 'warning', 'Preview is off: editors cannot see a draft on the front end.', 'Set `preview.url` to the preview route of the front end.'], + ['revalidation', 'warning', 'No revalidation target: the front end is not told when content changes.', 'Add one under `revalidation.targets`.'], + ['graphql', 'fail', 'Anyone can introspect the GraphQL schema.', 'Keep `graphql.introspection` false.'], + ['redirects', 'ok', '0 redirect rule(s), no loop.', ''], + ['rest-plugins', '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.'], + ['theme', 'fail', 'No valid theme: WordPress falls back to recovery mode.', 'Run `wp headless theme install --activate`.'], + ['seo', 'ok', 'SEO plugin: yoast', ''], + ['debug-display', 'warning', 'PHP errors are printed in the answers.', 'Set WP_DEBUG_DISPLAY to false: a notice inside a JSON answer breaks the client and leaks paths.'], + ]); +}); + +it('says when the routes could not be tried', function (): void { + expect(reportMessages(['users-route', 'rest-open'], REPORT_SITE, reportFacts(['users' => null, 'posts' => null])))->toBe([ + 'warning: The users route could not be tried.', + 'warning: The posts route could not be tried.', + ]); +}); + +it('warns of each address that is not HTTPS, unless it is a local one', function (string $host, bool $local): void { + $warnings = reportMessages(['https'], ['frontend_url' => 'http://'.$host.':3000'], reportFacts(), 'http://'.$host); + + expect($warnings)->toBe($local ? [] : [ + 'warning: The front address is not HTTPS: tokens and sessions travel in clear.', + 'warning: The WordPress address is not HTTPS: tokens and sessions travel in clear.', + ]); +})->with([ + ['localhost', true], ['127.0.0.1', true], ['site.test', true], ['site.local', true], ['site.ddev.site', true], + ['example.com', false], ['test.example.com', false], ['local.example.com', false], ['ddev.site.example.com', false], ['localhost.example.com', false], +]); + +it('warns of a revalidation target that is not HTTPS, unless it is a local one', function (string $url, bool $warned): void { + $config = ['revalidation' => ['targets' => [['name' => 'next', 'url' => $url, 'secret' => 'k']]]]; + + expect(reportMessages(['revalidation-https'], $config, reportFacts()))->toBe($warned ? ['warning: The target "next" is not HTTPS.'] : []); +})->with([['http://hooks.example.com/r', true], ['https://hooks.example.com/r', false], ['http://localhost:3000/r', false]]); + +it('says how revalidation is delivered without Action Scheduler', function (bool $cronOff, string $message): void { + expect(reportMessages(['revalidation'], REPORT_SITE, reportFacts(['scheduler' => false, 'cronOff' => $cronOff])))->toBe(['warning: '.$message]); +})->with([ + [true, 'Revalidation goes through WP-Cron, which is disabled: a system cron must call wp-cron.php.'], + [false, 'Revalidation goes through WP-Cron, which runs only when a page is visited.'], +]); + +it('says a closed GraphQL schema is closed', function (): void { + expect(reportMessages(['graphql'], REPORT_SITE, reportFacts(['graphql' => true, 'introspection' => false])))->toBe(['ok: WPGraphQL is active and its schema is closed to visitors.']); +}); + +/** @param list $pairs */ +function reportRedirects(array $pairs, array $more = []): array +{ + $rules = array_map(static fn (array $pair): Redirect => new Redirect($pair[0], $pair[1]), $pairs); + + return reportMessages(['redirects', 'redirect-loop', 'redirect-chain'], REPORT_SITE, reportFacts(['redirects' => [...$rules, ...$more]])); +} + +it('counts the rules when none loops or chains, the gone ones and the patterns included', function (): void { + expect(reportRedirects([['/a', '/b']], [new Redirect('/gone', '', 410), new Redirect('/p/(.*)', '/p/x/$1', 301, true)]))->toBe(['ok: 3 redirect rule(s), no loop.']); +}); + +it('does not follow a gone rule or a pattern as the start of a chain', function (): void { + $rules = [new Redirect('/b', '/c'), new Redirect('/c', '/d')]; + $starts = [new Redirect('/gone', '/b', 410), new Redirect('/x(.*)', '/b', 301, true)]; + + expect(reportRedirects([], [...$starts, ...$rules]))->toBe(['warning: The redirect of /b takes 2 hops.']); +}); + +it('fails every rule of a circle', function (): void { + expect(reportRedirects([['/a/', 'https://www.example.com/b/'], ['/b', '/a']]))->toBe([ + 'fail: The redirect of /a/ ends up back where it started.', + 'fail: The redirect of /b ends up back where it started.', + ]); +}); + +it('fails a rule that only comes back to its own address written another way', function (): void { + expect(reportRedirects([['/a/', '/a?x=1']]))->toBe(['fail: The redirect of /a/ ends up back where it started.']); +}); + +it('fails a rule that leads into a circle it is not part of', function (): void { + expect(reportRedirects([['/in', '/a'], ['/a', '/b'], ['/b', '/a']]))->toContain('fail: The redirect of /in ends up back where it started.'); +}); + +it('warns of the rules that take several hops, with their number, and stops following after ten', function (): void { + $pairs = array_map(static fn (int $i): array => ['/p'.$i, '/p'.($i + 1)], range(0, 11)); + $messages = reportRedirects($pairs); + + expect($messages)->toHaveCount(11) + ->and($messages[0])->toBe('warning: The redirect of /p0 takes 10 hops.') + ->and($messages[2])->toBe('warning: The redirect of /p2 takes 10 hops.') + ->and($messages[3])->toBe('warning: The redirect of /p3 takes 9 hops.') + ->and($messages[10])->toBe('warning: The redirect of /p10 takes 2 hops.'); +}); + +function reportLanguages(bool $active): Languages +{ + $languages = Mockery::mock(Languages::class); + $languages->shouldReceive('isActive')->andReturn($active); + $languages->shouldReceive('plugin')->andReturn('polylang'); + $languages->shouldReceive('all')->andReturn(['en', 'fr']); + + return $languages; +} + +it('prints every row of the status of a working site', function (): void { + $report = StatusReport::build(Settings::fromArray(REPORT_SITE, 'https://cms.example.com/wp'), new SiteContext(1, 'en_US', false, 'https://cms.example.com/wp'), true, false, reportLanguages(true), true); + + expect($report->rows)->toBe([ + ['Site', '#1, en_US'], + ['WordPress URL', 'https://cms.example.com/wp'], + ['Front-end URL', 'https://www.example.com'], + ['Front gate', 'redirect (302)'], + ['Languages', 'polylang (en, fr)'], + ['Preview', 'https://www.example.com/api/preview'], + ['Revalidation', 'next, cdn (Action Scheduler)'], + ['Head clean-up', 'on'], + ['XML-RPC', 'off'], + ['Feeds', 'off'], + ['Core sitemap', 'off'], + ['Origin noindex', 'on'], + ['Empty theme', 'valid theme active'], + ['WP-Cron', 'runs on page loads'], + ])->and($report->warnings)->toBe([]); +}); + +it('prints every row of the status of a site with everything left on', function (): void { + $config = ['clean_head' => false, 'disable_xmlrpc' => false, 'disable_feeds' => false, 'disable_sitemaps' => false, 'noindex_origin' => false]; + $report = StatusReport::build(Settings::fromArray($config, 'https://cms.example.com'), new SiteContext(3, 'de_DE', true, 'https://cms.example.com'), false, true, reportLanguages(false)); + + expect($report->rows)->toBe([ + ['Site', '#3, de_DE (multisite)'], + ['WordPress URL', 'https://cms.example.com'], + ['Front-end URL', 'not set'], + ['Front gate', 'off'], + ['Languages', 'single language'], + ['Preview', 'off'], + ['Revalidation', 'off'], + ['Head clean-up', 'off'], + ['XML-RPC', 'on'], + ['Feeds', 'on'], + ['Core sitemap', 'on'], + ['Origin noindex', 'off'], + ['Empty theme', 'missing'], + ['WP-Cron', 'disabled (a system cron must run it)'], + ]); +}); diff --git a/tests/Unit/Behaviour/HooksAndAddressesTest.php b/tests/Unit/Behaviour/HooksAndAddressesTest.php new file mode 100644 index 0000000..8fa1877 --- /dev/null +++ b/tests/Unit/Behaviour/HooksAndAddressesTest.php @@ -0,0 +1,168 @@ +once()->with(Mockery::type('array'), 1); + $removed = []; + Functions\when('remove_action')->alias(static function (string $hook, string $callback, int $priority = 10) use (&$removed): void { + $removed[] = [$hook, $callback, $priority]; + }); + + $module = new CleanUp(true, false); + $module->register(new WordPressHooks); + $module->cleanHead(); + + expect($removed)->toBe([ + ['wp_head', 'wp_generator', 10], + ['wp_head', 'rsd_link', 10], + ['wp_head', 'wlwmanifest_link', 10], + ['wp_head', 'wp_shortlink_wp_head', 10], + ['wp_head', 'rest_output_link_wp_head', 10], + ['wp_head', 'feed_links', 2], + ['wp_head', 'feed_links_extra', 3], + ['wp_head', 'wp_oembed_add_discovery_links', 4], + ['wp_head', 'wp_oembed_add_discovery_links', 10], + ['wp_head', 'print_emoji_detection_script', 7], + ['wp_print_styles', 'print_emoji_styles', 10], + ['template_redirect', 'rest_output_link_header', 11], + ['template_redirect', 'wp_shortlink_header', 11], + ]); +}); + +it('takes from each link filter the arguments it reads, and rewrites content after WordPress rendered it', function (): void { + foreach (['post_link', 'page_link', 'post_type_link'] as $filter) { + Filters\expectAdded($filter)->once()->with(Mockery::type('array'), 10, 2); + } + + foreach (['term_link', 'post_type_archive_link', 'author_link'] as $filter) { + Filters\expectAdded($filter)->once()->with(Mockery::type('array'), 10, 1); + } + + Filters\expectAdded('the_content')->once()->with(Mockery::type('array'), 20, 1); + + $urls = Mockery::mock(FrontUrls::class); + (new FrontLinks($urls, new ContentLinks($urls)))->register(new WordPressHooks); +}); + +it('asks the language of the post a link is for, by object or by number', function (mixed $post, ?string $language): void { + $urls = Mockery::mock(FrontUrls::class); + $urls->shouldReceive('toFront')->once()->with('url', $language)->andReturn('front'); + $languages = Mockery::mock(Languages::class); + $languages->shouldReceive('ofPost')->andReturnUsing(static fn (int $id): string => 'language of '.$id); + + expect((new FrontLinks($urls, null, $languages))->postLink('url', $post))->toBe('front'); +})->with([ + [new WP_Post(['ID' => 4]), 'language of 4'], + ['12', 'language of 12'], + [1, 'language of 1'], + [0, null], + [null, null], + ['slug', null], +]); + +it('asks no language without a multilingual plugin', function (): void { + $urls = Mockery::mock(FrontUrls::class); + $urls->shouldReceive('toFront')->once()->with('url', null)->andReturn('front'); + + expect((new FrontLinks($urls, null))->postLink('url', 4))->toBe('front'); +}); + +it('keeps the links of WordPress\'s own directories, below its folder', function (): void { + $urls = Mockery::mock(FrontUrls::class); + $urls->shouldReceive('toFront')->andReturnUsing(static fn (string $url): string => 'front:'.$url); + $links = new ContentLinks($urls, basePath: '/wp/'); + $kept = 'ag'; + + expect($links->rewrite($kept))->toBe($kept) + ->and($links->rewrite('b'))->toBe('b'); +}); + +it('compares the ETags a client holds whatever the blanks around them', function (string $header, bool $held): void { + expect(Etag::matches($header, '"a"'))->toBe($held); +})->with([[' "a" ', true], ['"b", W/"a"', true], [' * ', true], [' ', false], ['"b"', false]]); + +it('keeps a plugin by its folder however deep its file is', function (): void { + expect((new PluginFilter(['acf']))->keeps('acf/pro/acf.php'))->toBeTrue() + ->and(PluginFilter::isRestRequest('http://:80'))->toBeFalse(); +}); + +it('searches from two characters, in a list of the types asked for, on a page from 1', function (): void { + $query = static fn (string $term, string $types = '', int $page = 1, int $perPage = 0): ?SearchQuery => SearchQuery::fromRequest($term, $types, null, $page, $perPage, 50, ['post', 'page', 'event'], []); + + expect($query('ab'))->not->toBeNull() + ->and($query('a'))->toBeNull() + ->and($query('ab', 'x, event,,page')->types)->toBe(['event', 'page']) + ->and($query('ab', ',,page')->types)->toBe(['page']) + ->and($query('ab', page: 0)->page)->toBe(1) + ->and($query('ab', page: -4)->page)->toBe(1) + ->and($query('ab', perPage: -1)->perPage)->toBe(10) + ->and($query('ab', perPage: 1)->perPage)->toBe(1); +}); + +it('asks WPML for its languages, past the "all" of the administration', function (): void { + $asked = new ArrayObject; + Functions\when('get_post_type')->justReturn('page'); + Functions\when('home_url')->justReturn('https://cms.example.com/'); + Functions\when('apply_filters')->alias(static function (string $hook, mixed ...$args) use ($asked): mixed { + $asked[$hook] = $args; + + return match ($hook) { + 'wpml_active_languages' => ['en' => [], 'fr' => []], + 'wpml_element_trid' => 33, + 'wpml_get_element_translations' => ['en' => (object) ['element_id' => '4'], 'fr' => (object) ['element_id' => 'x'], 'de' => (object) [], 'es' => 'junk'], + default => null, + }; + }); + $wpml = new WpmlLanguages; + + expect($wpml->all())->toBe(['en', 'fr']) + ->and($asked['wpml_active_languages'])->toBe([null, ['skip_missing' => 0]]) + ->and($wpml->translations(4))->toBe(['en' => 4]) + ->and($asked['wpml_element_trid'])->toBe([null, 4, 'post_page']) + ->and($asked['wpml_get_element_translations'])->toBe([null, 33, 'post_page']); +}); + +it('takes no empty or "all" answer of WPML for a language or an address', function (mixed $answer): void { + Functions\when('home_url')->justReturn('https://cms.example.com/'); + Functions\when('apply_filters')->alias(static fn (string $hook): mixed => $hook === 'wpml_post_language_details' ? ['language_code' => $answer] : $answer); + $wpml = new WpmlLanguages; + + expect([$wpml->current(), $wpml->ofPost(1), $wpml->homeUrl('fr')])->toBe([null, null, null]); +})->with(['', 5, false]); + +it('has no current language when WPML shows all of them', function (): void { + Functions\when('apply_filters')->justReturn('all'); + + expect((new WpmlLanguages)->current())->toBeNull(); +}); + +it('asks Polylang for the slugs of its languages', function (): void { + Functions\expect('pll_languages_list')->once()->with(['fields' => 'slug'])->andReturn([2 => 7, 3 => 'fr']); + + expect((new PolylangLanguages)->all())->toBe(['fr']); +}); + +it('takes no empty answer of Polylang for a language', function (): void { + Functions\when('pll_current_language')->justReturn(''); + Functions\when('pll_get_post_language')->justReturn(''); + Functions\when('pll_home_url')->justReturn(''); + $polylang = new PolylangLanguages; + + expect([$polylang->current(), $polylang->ofPost(1), $polylang->homeUrl('fr')])->toBe([null, null, null]); +}); diff --git a/tests/Unit/Behaviour/MediaAndManifestShapeTest.php b/tests/Unit/Behaviour/MediaAndManifestShapeTest.php new file mode 100644 index 0000000..ce20a15 --- /dev/null +++ b/tests/Unit/Behaviour/MediaAndManifestShapeTest.php @@ -0,0 +1,196 @@ +justReturn(new WP_Post($over + ['ID' => 9, 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_title' => 'Title', 'post_excerpt' => 'Caption', 'post_content' => 'Description', 'post_modified_gmt' => '2026-03-01 10:00:00'])); + Functions\when('get_post_mime_type')->justReturn($mime); + Functions\when('wp_get_attachment_url')->justReturn('https://cms.example.com/u/2026/a.jpg'); + Functions\when('wp_get_attachment_metadata')->justReturn($metadata); + Functions\when('get_post_meta')->alias(static fn (int $id, string $key, bool $single = false): mixed => $single + ? ($key === '_wp_attachment_image_alt' ? 'Alt' : ['x' => '0.25', 'y' => 0.75]) + : ['not the single value']); + Functions\when('wp_get_attachment_image_srcset')->justReturn('set 1x'); + Functions\when('apply_filters')->alias(static fn (string $hook, mixed $value): mixed => $value); +} + +it('describes an image with its sizes, in the order of their names', function (): void { + shapeFile('image/jpeg', ['width' => '1200', 'height' => 800, 'filesize' => '5000', 'length' => 3, 'sizes' => [ + 'thumbnail' => ['file' => 't.jpg', 'width' => '150', 'height' => 100], + 'large' => ['file' => 'l.jpg'], + 'broken' => ['width' => 1], + 'junk' => 'x', + ]]); + + expect((new NormalizedMedia)->for(9))->toBe([ + 'id' => 9, + 'kind' => 'image', + 'mime' => 'image/jpeg', + 'url' => 'https://cms.example.com/u/2026/a.jpg', + 'title' => 'Title', + 'alt' => 'Alt', + 'caption' => 'Caption', + 'description' => 'Description', + 'width' => 1200, + 'height' => 800, + 'filesize' => 5000, + 'duration' => null, + 'focal_point' => ['x' => 0.25, 'y' => 0.75], + 'sizes' => [ + 'large' => ['url' => 'https://cms.example.com/u/2026/l.jpg', 'width' => 0, 'height' => 0], + 'thumbnail' => ['url' => 'https://cms.example.com/u/2026/t.jpg', 'width' => 150, 'height' => 100], + 'full' => ['url' => 'https://cms.example.com/u/2026/a.jpg', 'width' => 1200, 'height' => 800], + ], + 'srcset' => 'set 1x', + 'modified_gmt' => '2026-03-01T10:00:00', + ]); +}); + +it('describes a video with its length, and none of what only an image has', function (): void { + shapeFile('video/mp4', ['width' => 1920, 'height' => 1080, 'length' => '62']); + + $media = (new NormalizedMedia)->for(9); + + expect([$media['kind'], $media['width'], $media['height'], $media['filesize'], $media['duration'], $media['focal_point'], $media['sizes'], $media['srcset']]) + ->toBe(['video', null, null, null, 62, null, [], null]); +}); + +it('gives no full size to an image missing a measure', function (array $metadata): void { + shapeFile('image/png', $metadata); + + expect((new NormalizedMedia)->for(9)['sizes'])->toBe([]); +})->with([[['width' => 10]], [['height' => 10]]]); + +it('takes the focal point a filter gives, and keeps the stored one when the filter gives nonsense', function (mixed $filtered, array $expected): void { + shapeFile('image/png', []); + Functions\when('apply_filters')->justReturn($filtered); + + expect((new NormalizedMedia)->for(9)['focal_point'])->toBe($expected); +})->with([ + [['x' => 1, 'y' => 0], ['x' => 1.0, 'y' => 0.0]], + ['nonsense', ['x' => 0.25, 'y' => 0.75]], +]); + +it('reads a focal point from 0 to 1 on both axes, and nothing outside', function (mixed $x, mixed $y, bool $valid): void { + $point = FocalPoint::tryFrom(['x' => $x, 'y' => $y]); + + expect($point?->toArray())->toBe($valid ? ['x' => (float) $x, 'y' => (float) $y] : null); +})->with([ + [0, 0, true], [1, 1, true], ['0.5', '1', true], [-0.1, 0, false], [0, -0.1, false], [1.1, 0, false], [0, 1.1, false], ['a', 0, false], [0, 'a', false], [null, 0, false], +]); + +it('tells the kind of a file from its type, whatever its case', function (string $mime, MediaKind $kind): void { + expect(MediaKind::fromMime($mime))->toBe($kind); +})->with([['IMAGE/PNG', MediaKind::Image], ['Video/mp4', MediaKind::Video], ['audio/ogg', MediaKind::Audio], ['image', MediaKind::File], ['', MediaKind::File]]); + +it('moves uploads to a CDN written with a trailing slash, and nothing else', function (): void { + $urls = new MediaUrls('https://cms.example.com/u/', 'https://cdn.example.com/'); + + expect($urls->toCdn('http://cms.example.com/u/a.jpg'))->toBe('https://cdn.example.com/a.jpg') + ->and($urls->toCdn('https://cms.example.com/u'))->toBe('https://cdn.example.com') + ->and($urls->toCdn('https://cms.example.com/uploads/a.jpg'))->toBe('https://cms.example.com/uploads/a.jpg') + ->and($urls->rewriteHtml(''))->toBe(''); +}); + +it('builds a tree that loses no item, whatever points at what', function (): void { + $item = static fn (int $id, int $parent, int $order): array => ['id' => $id, 'parent' => $parent, 'order' => $order]; + $names = static function (array $tree) use (&$names): array { + return array_map(static fn (array $node): array => [$node['id'], $names($node['children'])], $tree); + }; + + expect($names(MenuTree::build([$item(1, 1, 1), $item(2, 99, 2), $item(3, 1, 3)])))->toBe([[1, [[3, []]]], [2, []]]) + ->and($names(MenuTree::build([$item(5, 6, 1), $item(6, 5, 2), $item(7, 6, 3), $item(8, 0, 4)])))->toBe([[8, []], [5, [[6, [[7, []]]]]]]) + ->and($names(MenuTree::build([$item(1, 2, 1), $item(2, 1, 2), $item(3, 4, 3), $item(4, 3, 4)])))->toBe([[1, [[2, []]]], [3, [[4, []]]]]); +}); + +it('keeps the children of a parent that stays, when one of them leaves a circle', function (): void { + $item = static fn (int $id, int $parent, int $order): array => ['id' => $id, 'parent' => $parent, 'order' => $order]; + + $tree = MenuTree::build([$item(2, 3, 1), $item(3, 2, 2), $item(4, 3, 3)]); + + expect(array_column($tree, 'id'))->toBe([2]) + ->and(array_column($tree[0]['children'], 'id'))->toBe([3]) + ->and(array_column($tree[0]['children'][0]['children'], 'id'))->toBe([4]); +}); + +it('lists a menu item that has nothing but itself', function (): void { + foreach (['get_current_blog_id' => 1, 'home_url' => 'https://cms.example.com', 'get_locale' => 'pt_BR', 'wp_timezone_string' => 'UTC', 'is_multisite' => false, 'get_nav_menu_locations' => [], 'get_post_types' => [], 'get_taxonomies' => []] as $function => $value) { + Functions\when($function)->justReturn($value); + } + Functions\when('get_bloginfo')->returnArg(); + Functions\when('get_option')->alias(static fn (string $name, mixed $default = false): mixed => $default); + Functions\when('wp_get_nav_menus')->justReturn([(object) ['term_id' => 1, 'slug' => 'm', 'name' => 'M']]); + Functions\when('wp_get_nav_menu_items')->justReturn(['junk', new stdClass]); + Functions\when('get_registered_nav_menus')->justReturn([]); + $urls = Mockery::mock(FrontUrls::class); + $urls->shouldReceive('toFront')->andReturnArg(0); + $languages = Mockery::mock(Languages::class); + $languages->shouldReceive('isActive')->andReturn(false); + $languages->shouldReceive('current')->andReturn(null); + + $manifest = (new SiteManifest($urls, Origin::fromUrl('https://www.example.com'), $languages))->build(); + + expect($manifest['menus'][0]['items'])->toBe([['id' => 0, 'title' => '', 'url' => '', 'path' => null, 'target' => '', 'classes' => [], 'type' => '', 'object' => '', 'object_id' => 0, 'children' => []]]) + ->and($manifest['site']['language'])->toBe('pt') + ->and($manifest['languages'])->toBe([]) + ->and($manifest['permalink_structure'])->toBe(''); +}); + +it('lists only the types and taxonomies that are public and served by the REST API', function (): void { + foreach (['get_current_blog_id' => 1, 'home_url' => 'https://cms.example.com', 'get_locale' => 'en_US', 'wp_timezone_string' => 'UTC', 'is_multisite' => false, 'get_nav_menu_locations' => [], 'wp_get_nav_menus' => [], 'get_registered_nav_menus' => []] as $function => $value) { + Functions\when($function)->justReturn($value); + } + Functions\when('get_bloginfo')->returnArg(); + Functions\when('get_option')->alias(static fn (string $name, mixed $default = false): mixed => $default); + $all = []; + + foreach (['open' => [true, true], 'private' => [false, true], 'classic' => [true, false]] as $name => [$public, $rest]) { + $all[$name] = (object) ['name' => $name, 'label' => $name, 'public' => $public, 'show_in_rest' => $rest, 'rest_base' => '', 'rest_namespace' => '', 'hierarchical' => 1, 'has_archive' => false, 'rewrite' => false, 'object_type' => []]; + } + + $matching = static fn (array $criteria, string $output): array => array_filter($all, static fn (object $type): bool => array_intersect_assoc($criteria, (array) $type) === $criteria); + Functions\when('get_post_types')->alias($matching); + Functions\when('get_taxonomies')->alias($matching); + $languages = Mockery::mock(Languages::class); + $languages->shouldReceive('isActive')->andReturn(false); + $languages->shouldReceive('current')->andReturn('en'); + + $manifest = (new SiteManifest(Mockery::mock(FrontUrls::class), Origin::fromUrl('https://www.example.com'), $languages))->build(); + + expect(array_column($manifest['post_types'], 'name'))->toBe(['open']) + ->and(array_column($manifest['taxonomies'], 'name'))->toBe(['open']) + ->and($manifest['post_types'][0]['hierarchical'])->toBeTrue() + ->and($manifest['taxonomies'][0]['hierarchical'])->toBeTrue(); +}); + +it('moves the address of each social image and breadcrumb, keeping the rest', function (): void { + $seo = new Seo('x', + openGraph: ['type' => null, 'title' => null, 'description' => null, 'url' => null, 'site_name' => null, 'locale' => null, 'images' => [['url' => 'a', 'width' => 1, 'height' => 2, 'alt' => 'A']]], + jsonLd: [['n' => 3, 'url' => 'https://a.test/', 'text' => 'see https://a.test/']], + breadcrumbs: [['label' => 'Home', 'url' => 'a']], + ); + + $moved = $seo->withUrls(static fn (string $url): string => 'moved '.$url); + + expect($moved->openGraph['images'])->toBe([['url' => 'moved a', 'width' => 1, 'height' => 2, 'alt' => 'A']]) + ->and($moved->breadcrumbs)->toBe([['label' => 'Home', 'url' => 'moved a']]) + ->and($moved->jsonLd)->toBe([['n' => 3, 'url' => 'moved https://a.test/', 'text' => 'see https://a.test/']]); +}); diff --git a/tests/Unit/Behaviour/OpenApiDocumentTest.php b/tests/Unit/Behaviour/OpenApiDocumentTest.php new file mode 100644 index 0000000..f75b6f2 --- /dev/null +++ b/tests/Unit/Behaviour/OpenApiDocumentTest.php @@ -0,0 +1,105 @@ +> */ +function documentPaths(array $routes, array $namespaces = []): array +{ + return (new OpenApiBuilder('t', '1', 'https://x.test', $namespaces))->build($routes)['paths']; +} + +it('writes the whole document of a small API', function (): void { + $document = (new OpenApiBuilder('The site', '2.0', 'https://x.test/wp-json/'))->build([ + '/a/v1/thing-list' => [['methods' => ['GET' => true], 'args' => []]], + ]); + + expect($document)->toBe([ + 'openapi' => '3.0.3', + 'info' => ['title' => 'The site', 'version' => '2.0'], + 'servers' => [['url' => 'https://x.test/wp-json']], + 'paths' => ['/a/v1/thing-list' => ['get' => ['operationId' => 'getAV1ThingList', 'tags' => ['a/v1'], 'responses' => ['200' => ['description' => 'OK']]]]], + 'components' => ['securitySchemes' => ['bearer' => ['type' => 'http', 'scheme' => 'bearer', 'description' => 'An API token of the site (hl.…), or an application password with Basic authentication.']]], + ]); +}); + +it('puts the arguments of a read and of a delete in the address, and those of a write in the body', function (string $method, bool $inAddress): void { + $operation = documentPaths(['/a' => [['methods' => $method, 'args' => ['q' => ['type' => 'string']]]]])['/a'][strtolower($method)]; + + expect(array_key_exists('parameters', $operation))->toBe($inAddress) + ->and(array_key_exists('requestBody', $operation))->toBe(! $inAddress); +})->with([['GET', true], ['DELETE', true], ['POST', false], ['PUT', false], ['PATCH', false]]); + +it('marks as required only what is required, in the address and in the body', function (): void { + $args = ['a' => ['required' => true], 'b' => ['required' => false], 'c' => [], 'd' => ['required' => 1]]; + $paths = documentPaths(['/x' => [['methods' => 'GET, POST', 'args' => $args]], '/y' => [['methods' => 'POST', 'args' => ['b' => ['required' => false]]]]]); + + expect($paths['/x']['get']['parameters'])->toBe([ + ['name' => 'a', 'in' => 'query', 'required' => true, 'schema' => ['type' => 'string']], + ['name' => 'b', 'in' => 'query', 'schema' => ['type' => 'string']], + ['name' => 'c', 'in' => 'query', 'schema' => ['type' => 'string']], + ['name' => 'd', 'in' => 'query', 'schema' => ['type' => 'string']], + ])->and($paths['/x']['post']['requestBody']['content']['application/json']['schema']['required'])->toBe(['a']) + ->and($paths['/y']['post']['requestBody'])->toBe(['content' => ['application/json' => ['schema' => ['type' => 'object', 'properties' => ['b' => ['type' => 'string']]]]]]); +}); + +it('keeps each type OpenAPI knows, and calls the rest text', function (mixed $type, string $expected): void { + $parameter = documentPaths(['/a' => [['methods' => 'GET', 'args' => ['q' => ['type' => $type]]]]])['/a']['get']['parameters'][0]; + + expect($parameter['schema']['type'])->toBe($expected); +})->with([ + ['string', 'string'], ['integer', 'integer'], ['number', 'number'], ['boolean', 'boolean'], ['array', 'array'], ['object', 'object'], + ['mixed', 'string'], ['null', 'string'], [5, 'string'], [['null', 'integer'], 'integer'], [['boolean', 'null'], 'boolean'], [['null'], 'string'], [[], 'string'], +]); + +it('keeps the limits WordPress states, and no empty one', function (): void { + $limits = ['enum' => ['a'], 'default' => 'a', 'minimum' => 1, 'maximum' => 2, 'format' => 'uri', 'minLength' => 3, 'maxLength' => 4]; + $args = ['q' => ['type' => 'string', 'sanitize_callback' => 'x', ...$limits], 'r' => ['default' => null], 'l' => ['type' => 'array'], 'm' => ['type' => 'array', 'items' => 'broken']]; + $parameters = documentPaths(['/a' => [['methods' => 'GET', 'args' => $args]]])['/a']['get']['parameters']; + + expect(array_column($parameters, 'schema'))->toBe([ + ['type' => 'string', ...$limits], + ['type' => 'string'], + ['type' => 'array', 'items' => ['type' => 'string']], + ['type' => 'array', 'items' => ['type' => 'string']], + ]); +}); + +it('reads every endpoint after one it cannot read, and a pattern that is a number', function (): void { + $paths = documentPaths([ + '/broken' => 'not endpoints', + '/a' => ['junk', ['methods' => 'get']], + 123 => [['methods' => 'GET']], + ]); + + expect(array_keys($paths))->toBe(['/123', '/a']); +}); + +it('takes the methods a list switches on, written in any case', function (): void { + $paths = documentPaths(['/a' => [['methods' => ['GET' => true, 'POST' => false]]], '/b' => [['methods' => ' post ,delete, OPTIONS']]]); + + expect(array_keys($paths['/a']))->toBe(['get'])->and(array_keys($paths['/b']))->toBe(['post', 'delete']); +}); + +it('names a group used twice in a pattern once', function (): void { + $operation = documentPaths(['/a/(?P\d+)|/b/(?P\d+)' => [['methods' => 'GET']]]); + + expect(array_values($operation)[0]['get']['parameters'])->toHaveCount(1); +}); + +it('keeps a namespace itself, and nothing that only starts like it', function (): void { + $routes = ['/wp/v2' => [['methods' => 'GET']], '/wp/v2x' => [['methods' => 'GET']], '/wp/v2/posts' => [['methods' => 'GET']]]; + + expect(array_keys(documentPaths($routes, ['wp/v2'])))->toBe(['/wp/v2', '/wp/v2/posts']); +}); + +it('leaves out an argument that has no name or no description of itself', function (): void { + $operation = documentPaths(['/a' => [['methods' => 'GET', 'args' => [5 => ['type' => 'string'], 'broken' => 'text', 'kept' => []]]]])['/a']['get']; + + expect(array_column($operation['parameters'], 'name'))->toBe(['kept']); +}); diff --git a/tests/Unit/Behaviour/SeoSourcesShapeTest.php b/tests/Unit/Behaviour/SeoSourcesShapeTest.php new file mode 100644 index 0000000..8682107 --- /dev/null +++ b/tests/Unit/Behaviour/SeoSourcesShapeTest.php @@ -0,0 +1,209 @@ + the social keys of Yoast and All in One SEO, one value each */ +function shapeSocialJson(): array +{ + $json = []; + + foreach (['og_type', 'og_title', 'og_description', 'og_url', 'og_site_name', 'og_locale', 'twitter_card', 'twitter_title', 'twitter_description', 'twitter_image', 'twitter_site', 'twitter_creator'] as $key) { + $json[$key] = 'value of '.$key; + } + + return $json; +} + +function shapeExpected(string $source, array $over = []): array +{ + return array_replace([ + 'source' => $source, + 'title' => null, + 'description' => null, + 'robots' => ['index' => true, 'follow' => true, 'directives' => []], + 'canonical' => null, + 'open_graph' => ['type' => null, 'title' => null, 'description' => null, 'url' => null, 'site_name' => null, 'locale' => null, 'images' => []], + 'twitter' => ['card' => null, 'title' => null, 'description' => null, 'image' => null, 'site' => null, 'creator' => null], + 'json_ld' => [], + 'breadcrumbs' => [], + ], $over); +} + +function shapeSocialExpected(): array +{ + return [ + 'open_graph' => ['type' => 'value of og_type', 'title' => 'value of og_title', 'description' => 'value of og_description', 'url' => 'value of og_url', 'site_name' => 'value of og_site_name', 'locale' => 'value of og_locale', 'images' => []], + 'twitter' => ['card' => 'value of twitter_card', 'title' => 'value of twitter_title', 'description' => 'value of twitter_description', 'image' => 'value of twitter_image', 'site' => 'value of twitter_site', 'creator' => 'value of twitter_creator'], + ]; +} + +it('puts every value of Yoast SEO in its place', function (): void { + $seo = SeoMapper::yoast([...shapeSocialJson(), 'title' => 'T', 'description' => 'D', 'canonical' => 'C']); + + expect($seo->toArray())->toBe(shapeExpected('yoast', ['title' => 'T', 'description' => 'D', 'canonical' => 'C', ...shapeSocialExpected()])); +}); + +it('puts every value of All in One SEO in its place', function (): void { + $json = shapeSocialJson(); + unset($json['twitter_image']); + $seo = SeoMapper::aioseo([...$json, 'title' => 'T', 'description' => 'D', 'canonical_url' => 'C', 'twitter_image_url' => 'value of twitter_image', 'og_image_url' => 'I', 'og_image_width' => '800', 'og_image_height' => 600]); + $social = shapeSocialExpected(); + $social['open_graph']['images'] = [['url' => 'I', 'width' => 800, 'height' => 600, 'alt' => null]]; + + expect($seo->toArray())->toBe(shapeExpected('aioseo', ['title' => 'T', 'description' => 'D', 'canonical' => 'C', ...$social])); +}); + +it('puts every value of SEOPress in its place', function (): void { + $seo = SeoMapper::seopress([ + 'title' => 'T', 'description' => 'D', 'canonical' => 'C', + 'og' => ['type' => 'a', 'title' => 'b', 'description' => 'c', 'url' => 'd', 'site_name' => 'e', 'image' => 'f'], + 'twitter' => ['card' => 'g', 'title' => 'h', 'description' => 'i', 'image' => 'j'], + ]); + + expect($seo->toArray())->toBe(shapeExpected('seopress', [ + 'title' => 'T', 'description' => 'D', 'canonical' => 'C', + 'open_graph' => ['type' => 'a', 'title' => 'b', 'description' => 'c', 'url' => 'd', 'site_name' => 'e', 'locale' => null, 'images' => [['url' => 'f', 'width' => null, 'height' => null, 'alt' => null]]], + 'twitter' => ['card' => 'g', 'title' => 'h', 'description' => 'i', 'image' => 'j', 'site' => null, 'creator' => null], + ])); +}); + +it('puts every value of a printed head in its place', function (): void { + $meta = ''; + + foreach (['og:type', 'og:title', 'og:description', 'og:url', 'og:site_name', 'og:locale', 'twitter:card', 'twitter:title', 'twitter:description', 'twitter:image', 'twitter:site', 'twitter:creator'] as $name) { + // The first of two tags with one name counts + $meta .= ''; + } + + $meta .= '' + .''; + $seo = SeoMapper::headHtml($meta.'', 'other'); + + expect($seo->toArray())->toBe(shapeExpected('other', [ + 'description' => 'D', + 'open_graph' => ['type' => 'og:type first', 'title' => 'og:title first', 'description' => 'og:description first', 'url' => 'og:url first', 'site_name' => 'og:site_name first', 'locale' => 'og:locale first', 'images' => [ + ['url' => 'one', 'width' => 10, 'height' => 20, 'alt' => 'first picture'], + ['url' => 'two', 'width' => null, 'height' => null, 'alt' => null], + ]], + 'twitter' => ['card' => 'twitter:card first', 'title' => 'twitter:title first', 'description' => 'twitter:description first', 'image' => 'twitter:image first', 'site' => 'twitter:site first', 'creator' => 'twitter:creator first'], + ])); +}); + +it('reads an empty answer of any plugin as nothing at all', function (string $source): void { + $seo = match ($source) { + 'yoast' => SeoMapper::yoast([]), + 'aioseo' => SeoMapper::aioseo([]), + 'seopress' => SeoMapper::seopress([]), + 'rankmath' => SeoMapper::headHtml(''), + }; + + expect($seo->toArray())->toBe(shapeExpected($source)); +})->with(['yoast', 'aioseo', 'seopress', 'rankmath']); + +it('takes a text of blanks, or something that is not text, as nothing', function (mixed $value): void { + expect(SeoMapper::yoast(['description' => $value])->description)->toBeNull(); +})->with(['', " \n ", 5, [[]]]); + +it('keeps the robots directives that say something', function (): void { + expect(SeoMapper::yoast(['robots' => ['index' => 'index', 'follow' => 'follow', 'a' => '', 'b' => 5, 'c' => 'noarchive']])->directives)->toBe(['noarchive']) + ->and(SeoMapper::aioseo(['robots' => 'index, follow,, noindex ,nofollow, noarchive'])->directives)->toBe(['noarchive']) + ->and(SeoMapper::aioseo(['robots' => ['noarchive', ['nested'], 'nosnippet']])->directives)->toBe(['noarchive', 'nosnippet']) + ->and(SeoMapper::headHtml('')->directives)->toBe(['noarchive']); +}); + +it('takes the robots of a head whatever their case', function (): void { + $seo = SeoMapper::headHtml(''); + + expect($seo->index)->toBeFalse()->and($seo->follow)->toBeFalse(); +}); + +it('reads what SEOPress calls yes, and nothing else', function (mixed $value, bool $set): void { + $seo = SeoMapper::seopress(['robots' => ['noindex' => $value, 'nofollow' => $value]]); + + expect($seo->index)->toBe(! $set)->and($seo->follow)->toBe(! $set); +})->with([[true, true], [1, true], ['1', true], ['yes', true], ['true', true], [false, false], [0, false], [2, false], ['0', false], ['no', false], [null, false]]); + +it('leaves out of SEOPress breadcrumbs what has no name', function (): void { + $seo = SeoMapper::seopress(['breadcrumbs' => ['junk', ['url' => 'x'], ['name' => 5], ['name' => 'Home']]]); + + expect($seo->breadcrumbs)->toBe([['label' => 'Home', 'url' => null]]); +}); + +it('lists the nodes of a graph that are nodes', function (string $source): void { + $json = ['schema' => ['@graph' => ['junk', 3 => ['@type' => 'WebPage']]]]; + $seo = $source === 'yoast' ? SeoMapper::yoast($json) : SeoMapper::aioseo($json); + + expect($seo->jsonLd)->toBe([['@type' => 'WebPage']]); +})->with(['yoast', 'aioseo']); + +it('collects the structured data of every script, alone or in a graph', function (): void { + $script = static fn (string $json): string => ""; + $seo = SeoMapper::headHtml($script('{"@type":"Organization"}').$script('{"@graph":["junk",{"@type":"WebPage"}]}').$script('"text"')); + + expect($seo->jsonLd)->toBe([['@type' => 'Organization'], ['@type' => 'WebPage']]); +}); + +it('decodes the entities of a title, a canonical address and a meta, and trims the title', function (): void { + $seo = SeoMapper::headHtml(' Tom's "page" '); + + expect($seo->title)->toBe('Tom\'s "page"') + ->and($seo->canonical)->toBe('https://a.test/?a=1&b=2') + ->and($seo->description)->toBe("Tom's"); +}); + +it('has no title when the head has an empty one', function (): void { + expect(SeoMapper::headHtml(' ')->title)->toBeNull(); +}); + +it('ignores a meta without a name or without a content', function (): void { + $seo = SeoMapper::headHtml(''); + + expect($seo->description)->toBeNull()->and($seo->twitter['card'])->toBe('summary'); +}); + +it('keeps the images of a social card that have an address, with the measures that are numbers', function (): void { + $seo = SeoMapper::yoast(['og_image' => [ + 'junk', + ['width' => 1], + ['url' => ''], + ['url' => 5], + ['url' => 'a', 'width' => 'wide', 'height' => '30', 'alt' => 'A'], + ['url' => 'b', 'width' => '40', 'height' => 'tall', 'alt' => ' '], + ]]); + + expect($seo->openGraph['images'])->toBe([ + ['url' => 'a', 'width' => null, 'height' => 30, 'alt' => 'A'], + ['url' => 'b', 'width' => 40, 'height' => null, 'alt' => null], + ]); +}); + +it('takes the address of a Twitter image given as an object', function (): void { + expect(SeoMapper::yoast(['twitter_image' => ['url' => 'u']])->twitter['image'])->toBe('u') + ->and(SeoMapper::yoast(['twitter_image' => ['width' => 1]])->twitter['image'])->toBeNull(); +}); + +it('reads breadcrumbs from the item of a list, whichever way it names its page', function (): void { + $seo = SeoMapper::yoast(['schema' => ['@graph' => [ + ['@type' => 'WebPage', 'itemListElement' => [['name' => 'not a breadcrumb']]], + ['@type' => 'BreadcrumbList', 'itemListElement' => 'broken'], + ['@type' => ['BreadcrumbList'], 'itemListElement' => [ + 'junk', + ['item' => ['name' => 'Home', '@id' => 'https://a.test/']], + ['name' => 'Blog', 'item' => 'https://a.test/blog/'], + ['item' => 'https://a.test/nameless/'], + ['name' => 'Here'], + ]], + ]]]); + + expect($seo->breadcrumbs)->toBe([ + ['label' => 'Home', 'url' => 'https://a.test/'], + ['label' => 'Blog', 'url' => 'https://a.test/blog/'], + ['label' => 'Here', 'url' => null], + ]); +}); diff --git a/tests/Unit/Behaviour/SettingsDefaultsTest.php b/tests/Unit/Behaviour/SettingsDefaultsTest.php new file mode 100644 index 0000000..c9d7542 --- /dev/null +++ b/tests/Unit/Behaviour/SettingsDefaultsTest.php @@ -0,0 +1,126 @@ + 'https://www.example.com'], $backend); +} + +it('closes and trims everything by default', function (): void { + $settings = chosenSettings(); + + expect([ + $settings->cleanHead, $settings->disableXmlRpc, $settings->disableFeeds, $settings->disableSitemaps, $settings->noindexOrigin, + $settings->restrictUsers, $settings->disallowFileEdit, $settings->rewriteLinks, $settings->rewriteContentLinks, $settings->apiTokens, + $settings->manifest, $settings->redirects, $settings->oldSlugRedirects, $settings->mediaRoutes, $settings->blocks, $settings->seo, + $settings->search, $settings->forms, + ])->toBe(array_fill(0, 18, true)) + ->and($settings->restPluginFilter)->toBeFalse() + ->and($settings->previewLinkTtl)->toBe(300) + ->and($settings->previewSessionTtl)->toBe(1800) + ->and($settings->previewSecret)->toBeNull() + ->and($settings->revalidationDebounce)->toBe(3) + ->and($settings->revalidationAttempts)->toBe(5) + ->and($settings->perPageMax)->toBeNull() + ->and($settings->mediaCdn)->toBeNull(); +}); + +it('keeps the query of a redirect by default', function (): void { + expect(chosenSettings()->gate->decide(RequestTarget::fromUri('/a?b=c'))->location)->toBe('https://www.example.com/a?b=c'); +}); + +it('switches off each part that is told to be off', function (string $key): void { + $settings = chosenSettings([$key => ['enabled' => false]]); + $property = ['search' => 'search', 'forms' => 'forms', 'seo' => 'seo', 'blocks' => 'blocks', 'media' => 'mediaRoutes', 'manifest' => 'manifest', 'redirects' => 'redirects', 'tokens' => 'apiTokens'][$key]; + + expect($settings->{$property})->toBeFalse(); +})->with(['search', 'forms', 'seo', 'blocks', 'media', 'manifest', 'redirects', 'tokens']); + +it('opens none of the routes of a front end that is not there', function (): void { + $settings = Settings::fromArray([], 'https://cms.example.com'); + + expect([$settings->manifest, $settings->redirects, $settings->mediaRoutes, $settings->blocks, $settings->seo, $settings->search])->toBe(array_fill(0, 6, false)) + ->and($settings->previewUrl)->toBeNull(); +}); + +it('takes the directory of WordPress from its address, without a trailing slash', function (): void { + expect(chosenSettings(backend: 'https://cms.example.com/wp/')->basePath)->toBe('/wp'); +}); + +it('accepts a preview secret from 32 characters', function (): void { + expect(chosenSettings(['preview' => ['secret' => str_repeat('x', 32)]])->previewSecret)->toBe(str_repeat('x', 32)); +}); + +it('refuses a preview secret of 31 characters', function (): void { + chosenSettings(['preview' => ['secret' => str_repeat('x', 31)]]); +})->throws(InvalidSettingsException::class); + +it('keeps the ceiling of per_page only where it lowers WordPress\'s', function (mixed $asked, ?int $kept): void { + expect(chosenSettings(['per_page_max' => $asked])->perPageMax)->toBe($kept); +})->with([[0, null], [1, 1], [99, 99], [100, null], [101, null]]); + +it('caches for a minute, five on a CDN, and allows a minute of stale answer by default', function (): void { + expect(chosenSettings()->restCache?->cacheControl('GET', 200, false, false, '/wp/v2/posts'))->toBe('public, max-age=60, s-maxage=300, stale-while-revalidate=60'); +}); + +it('sends no credentials and lets a preflight be kept ten minutes by default, one origin each once', function (): void { + $cors = chosenSettings(['cors' => ['origins' => ['https://www.example.com', 'https://other.test']]])->cors; + $decision = $cors?->decide(new CorsRequest('https://www.example.com', 'OPTIONS', 'GET')); + + expect($decision?->headers['Access-Control-Max-Age'])->toBe('600') + ->and($decision?->headers)->not->toHaveKey('Access-Control-Allow-Credentials'); +}); + +it('imposes the cautious GraphQL settings by default, and the numbers a project writes', function (): void { + expect(chosenSettings()->graphql)->toEqual(new GraphQlPolicy) + ->and(chosenSettings(['graphql' => ['batch_limit' => '7', 'max_depth' => -3, 'graphiql' => true]])->graphql)->toEqual(new GraphQlPolicy(batchLimit: 7, maxDepth: 0, graphiql: true)) + ->and(chosenSettings(['graphql' => ['batch_limit' => -1, 'max_depth' => '4']])->graphql)->toEqual(new GraphQlPolicy(batchLimit: 0, maxDepth: 4)) + ->and(chosenSettings(['graphql' => ['batch_limit' => 'many', 'max_depth' => null, 'introspection' => null]])->graphql)->toEqual(new GraphQlPolicy(introspection: null, maxDepth: null)); +}); + +it('allows one batch query and one level of depth when asked to', function (): void { + expect((new GraphQlPolicy(batchLimit: 1, maxDepth: 1))->forced())->toMatchArray(['batch_queries_enabled' => 'on', 'batch_limit' => 1, 'query_depth_enabled' => 'on', 'query_depth_max' => 1]); +}); + +it('ignores the blanks around the address of a language, and a blank one', function (): void { + expect(array_keys(chosenSettings(['frontend_urls' => ['fr' => ' https://www.example.fr ', 'de' => ' ']])->languageFronts))->toBe(['fr']); +}); + +it('reads every target after one without an address, and names those without a name', function (): void { + $targets = chosenSettings(['revalidation' => ['targets' => [ + ['url' => ''], + ['url' => 'https://a.test', 'secret' => 'k', 'name' => ''], + ['url' => 'https://b.test', 'secret' => 'k', 'name' => 7], + ]]])->revalidationTargets; + + expect(array_map(static fn ($target): string => $target->name, $targets))->toBe(['target-1', '7']); +}); + +it('keeps the strings of a list that say something, and each watched option once', function (): void { + $settings = chosenSettings(['revalidation' => ['options' => ['', ['nested'], 'blogname', 'mine', 5]]]); + + expect(array_slice($settings->revalidationOptions, -2))->toBe(['mine', '5']) + ->and(array_is_list($settings->revalidationOptions))->toBeTrue() + ->and($settings->revalidationOptions)->not->toContain(''); +}); + +it('lays the settings of one site over the shared ones, and only those', function (): void { + $config = ['a' => 1, 'b' => 2, 'sites' => [2 => ['b' => 3]]]; + + expect(SettingsLoader::merge($config, null, 2))->toBe(['a' => 1, 'b' => 3]) + ->and(SettingsLoader::merge($config, null, 3))->toBe(['a' => 1, 'b' => 2]) + ->and(SettingsLoader::merge(['a' => 1, 'sites' => 'broken'], null, 2))->toBe(['a' => 1]) + ->and(SettingsLoader::merge(['a' => 1, 'sites' => [2 => 'broken']], null, 2))->toBe(['a' => 1]); +}); diff --git a/tests/Unit/Behaviour/StartingTest.php b/tests/Unit/Behaviour/StartingTest.php new file mode 100644 index 0000000..c48fdeb --- /dev/null +++ b/tests/Unit/Behaviour/StartingTest.php @@ -0,0 +1,157 @@ + */ +function startedModules(array $config, ?Languages $languages = null): array +{ + Functions\when('wp_salt')->alias(static fn (string $scheme): string => 'salt of '.$scheme); + Functions\when('wp_upload_dir')->justReturn(['baseurl' => 'https://cms.example.com/wp-content/uploads']); + + return Bootstrap::modules(Settings::fromArray($config + ['frontend_url' => 'https://www.example.com'], 'https://cms.example.com'), $languages); +} + +function startedModule(array $modules, string $class): ?Module +{ + return array_values(array_filter($modules, static fn (Module $module): bool => $module instanceof $class))[0] ?? null; +} + +it('leaves out exactly the part that is switched off', function (array $config, array $gone): void { + $all = array_map(get_class(...), startedModules([])); + $left = array_map(get_class(...), startedModules($config)); + + expect(array_values(array_diff($all, $left)))->toBe($gone)->and(array_diff($left, $all))->toBe([]); +})->with([ + 'GraphQL' => [['graphql' => ['enabled' => false]], [GraphQl::class]], + 'preview' => [['preview' => ['enabled' => false]], [PreviewLinks::class, PreviewRoutes::class]], + 'manifest' => [['manifest' => ['enabled' => false]], [ManifestRoutes::class]], + 'redirects' => [['redirects' => ['enabled' => false]], [RedirectRoutes::class]], + 'SEO' => [['seo' => ['enabled' => false]], [SeoField::class]], + 'search' => [['search' => ['enabled' => false]], [SearchRoutes::class]], + 'forms' => [['forms' => ['enabled' => false]], [FormRoutes::class]], + 'blocks' => [['blocks' => ['enabled' => false]], [BlocksField::class]], + 'media' => [['media' => ['enabled' => false]], [MediaRoutes::class]], + 'tokens' => [['tokens' => ['enabled' => false]], [TokenAuthentication::class]], +]); + +it('attaches none of the front-end parts without a front end', function (): void { + $classes = array_map(get_class(...), startedModules(['frontend_url' => ''])); + + expect(array_intersect($classes, [PreviewLinks::class, PreviewRoutes::class, ManifestRoutes::class, RedirectRoutes::class, SeoField::class, SearchRoutes::class, MediaRoutes::class, BlocksField::class, MediaCdn::class]))->toBe([]); +}); + +/** The token a preview link carries. */ +function startedLinkToken(array $modules): string +{ + return (string) startedModule($modules, PreviewLinks::class)?->link('', new WP_Post(['ID' => 42])); +} + +/** What the exchange route says to a token. */ +function startedExchange(array $modules, string $token): string +{ + $request = new WP_REST_Request('POST', '/headless/v1/preview/exchange'); + $request->set_param('token', $token); + $answer = startedModule($modules, PreviewRoutes::class)?->exchange($request); + + return $answer instanceof WP_Error ? $answer->get_error_code() : 'accepted'; +} + +function startedPreviewSite(): void +{ + $transients = new ArrayObject; + Functions\when('set_transient')->alias(static function (string $key) use ($transients): bool { + $transients[$key] = true; + + return true; + }); + Functions\when('get_transient')->alias(static fn (string $key): bool => isset($transients[$key])); + Functions\when('delete_transient')->justReturn(true); + Functions\when('get_current_user_id')->justReturn(7); + Functions\when('get_current_blog_id')->justReturn(1); + Functions\when('user_can')->justReturn(true); + Functions\when('get_permalink')->justReturn('https://www.example.com/a/'); + Functions\when('get_locale')->justReturn('en_US'); + Functions\when('add_query_arg')->alias(static fn (array $args): string => $args['token']); + Functions\when('get_post')->justReturn(new WP_Post(['ID' => 42])); + Functions\when('get_post_type_object')->alias(static function (): WP_Post_Type { + $type = Mockery::mock('WP_Post_Type'); + $type->show_in_rest = true; + + return $type; + }); +} + +it('signs previews with both salts of the site: another site cannot forge them', function (string $changed): void { + startedPreviewSite(); + $salts = ['auth' => 'salt of auth', 'secure_auth' => 'salt of secure_auth']; + $modules = startedModules([]); + + expect(startedExchange($modules, startedLinkToken($modules)))->toBe('accepted'); + + Functions\when('wp_salt')->alias(static fn (string $scheme): string => $scheme === $changed ? 'another' : $salts[$scheme]); + $other = Bootstrap::modules(Settings::fromArray(['frontend_url' => 'https://www.example.com'], 'https://cms.example.com')); + + expect(startedExchange($modules, startedLinkToken($other)))->toBe('preview_token_invalid'); +})->with(['auth', 'secure_auth']); + +it('signs previews with the secret of the settings when there is one, whatever the salts', function (): void { + startedPreviewSite(); + $config = ['preview' => ['secret' => str_repeat('s', 40)]]; + $modules = startedModules($config); + Functions\when('wp_salt')->justReturn('another'); + $other = Bootstrap::modules(Settings::fromArray($config + ['frontend_url' => 'https://www.example.com'], 'https://cms.example.com')); + + expect(startedExchange($modules, startedLinkToken($other)))->toBe('accepted') + ->and(startedExchange(startedModules([]), startedLinkToken($other)))->toBe('preview_token_invalid'); +}); + +it('caps a search at fifty results unless a lower ceiling is set', function (?int $ceiling, string $description): void { + $routes = []; + Functions\when('register_rest_route')->alias(static function (string $namespace, string $route, array $args) use (&$routes): void { + $routes = $args; + }); + + startedModule(startedModules($ceiling === null ? [] : ['per_page_max' => $ceiling]), SearchRoutes::class)?->routes(); + + expect($routes['args']['per_page']['description'])->toBe($description); +})->with([[null, 'Capped at 50.'], [10, 'Capped at 10.']]); + +it('starts at once when the plugins are loaded, and waits for them otherwise', function (int $loaded): void { + Functions\when('did_action')->justReturn($loaded); + Functions\when('get_current_blog_id')->justReturn(1); + Functions\expect('home_url')->times($loaded > 0 ? 1 : 0)->andReturn('https://cms.example.com'); + Actions\expectAdded('plugins_loaded')->times($loaded > 0 ? 0 : 1); + Functions\when('wp_salt')->justReturn('salt'); + + Bootstrap::fromWordPress(); +})->with([0, 1]); + +it('starts the modules it builds', function (): void { + Actions\expectAdded('rest_api_init')->atLeast()->once(); + + Bootstrap::boot(Settings::fromArray([], 'https://cms.example.com'), new WordPressHooks); +}); diff --git a/tests/Unit/Security/ApiTokenGuardTest.php b/tests/Unit/Security/ApiTokenGuardTest.php new file mode 100644 index 0000000..75b0f72 --- /dev/null +++ b/tests/Unit/Security/ApiTokenGuardTest.php @@ -0,0 +1,137 @@ + 10_000); + + return [new TokenAuthentication($service, static fn (): bool => true), $service]; +} + +it('gives a read token every safe method and no other', function (string $method, bool $allowed): void { + $token = new Token('0123456789ab', 7, 'a', 'hash', [TokenScope::Read], [], 1); + + expect(ScopePolicy::allows($token, $method, '/wp/v2/posts'))->toBe($allowed); +})->with([['GET', true], ['HEAD', true], ['OPTIONS', true], ['options', true], ['POST', false], ['PUT', false], ['PATCH', false], ['DELETE', false]]); + +it('reads a scope whatever its case and the blanks around it', function (): void { + expect(TokenScope::fromName(" WRITE\n"))->toBe(TokenScope::Write); +}); + +it('refuses a scope that does not exist', function (): void { + TokenScope::fromName('admin'); +})->throws(InvalidTokenException::class); + +it('does not bring an expired token back to life by rotating it', function (): void { + $now = 10_000; + $service = new TokenService(new InMemoryTokenStore, function () use (&$now): int { + return $now; + }); + $old = $service->create(7, 'a', [TokenScope::Write], [], 60); + + $now += 120; + $new = $service->rotate(7, $old->token->id, 600); + + expect($service->authenticate($new->secret))->toBeNull() + ->and($service->authenticate($old->secret))->toBeNull(); +}); + +it('keeps the routes of a stored token as a list', function (): void { + $token = Token::fromArray(['id' => 'a', 'hash' => 'h', 'user' => 1, 'scopes' => ['read'], 'routes' => [3, '/wp/v2']]); + + expect($token?->routes)->toBe(['/wp/v2']); +}); + +it('reads a user meta as the single value WordPress keeps', function (): void { + $token = new Token('0123456789ab', 7, 'a', 'hash', [TokenScope::Read], [], 1); + Functions\when('get_user_meta')->alias(static function (int $user, string $key, bool $single = false) use ($token): mixed { + $value = [$token->id => $token->toArray()]; + + return $single ? $value : [$value]; + }); + + expect((new UserMetaTokenStore)->find(7, $token->id)?->id)->toBe($token->id); +}); + +it('reads a bearer header with blanks around it', function (): void { + [$module, $service] = guardTokenModule(); + $_SERVER['HTTP_AUTHORIZATION'] = ' Bearer '.$service->create(7, 'a', [TokenScope::Read])->secret." \n"; + + expect($module->authenticate(false))->toBe(7); +}); + +it('does not work the current user out again once the token has been looked at', function (string $secret): void { + [$module, $service] = guardTokenModule(); + $valid = $service->create(7, 'a', [TokenScope::Read])->secret; + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer '.($secret === 'valid' ? $valid : $secret); + Functions\expect('wp_get_current_user')->never(); + + $module->authenticate(false); + $answer = $module->reject(null); + + expect($answer instanceof WP_Error)->toBe($secret !== 'valid'); +})->with(['valid', 'hl.7.0123456789ab.'.str_repeat('A', 43)]); + +it('takes a request for REST or GraphQL from what WordPress and WPGraphQL say', function (string $setup, string $expected): void { + $code = <<<'PHP' + use Pollora\Headless\Application\Token\TokenService; + use Pollora\Headless\Domain\Token\TokenScope; + use Pollora\Headless\Infrastructure\WordPress\TokenAuthentication; + use Pollora\Headless\Tests\Fixtures\InMemoryTokenStore; + $service = new TokenService(new InMemoryTokenStore); + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer '.$service->create(7, 'a', [TokenScope::Read])->secret; + echo var_export((new TokenAuthentication($service))->authenticate(false), true); + PHP; + + expect(isolated($setup.$code))->toBe($expected); +})->with([ + 'neither' => ['', 'false'], + 'a REST request' => ["define('REST_REQUEST', true); ", '7'], + 'REST switched off' => ["define('REST_REQUEST', false); ", 'false'], + 'a GraphQL request' => ['function is_graphql_http_request() { return true; } ', '7'], + 'another request with WPGraphQL' => ['function is_graphql_http_request() { return false; } ', 'false'], +]); + +it('passes the users guard and the sitemap filter every argument they read', function (): void { + Filters\expectAdded('rest_pre_dispatch')->once()->with(Mockery::type('array'), 10, 3); + Filters\expectAdded('wp_sitemaps_add_provider')->once()->with(Mockery::type('array'), 10, 2); + + (new RestSecurity(true, false))->register(new WordPressHooks); +}); + +it('turns the file editors off only when asked to', function (bool $disallow, string $expected): void { + $code = 'use Pollora\Headless\Infrastructure\WordPress\RestSecurity; use Pollora\Headless\Infrastructure\WordPress\WordPressHooks; ' + .'(new RestSecurity(false, '.var_export($disallow, true).'))->register(new WordPressHooks); ' + ."echo defined('DISALLOW_FILE_EDIT') ? var_export(DISALLOW_FILE_EDIT, true) : 'undefined';"; + + expect(isolated($code))->toBe($expected); +})->with([[true, 'true'], [false, 'undefined']]); + +it('leaves a file editor setting the site already made', function (): void { + $code = "define('DISALLOW_FILE_EDIT', false); " + .'(new Pollora\Headless\Infrastructure\WordPress\RestSecurity(false, true))->register(new Pollora\Headless\Infrastructure\WordPress\WordPressHooks); ' + .'echo var_export(DISALLOW_FILE_EDIT, true);'; + + expect(isolated($code))->toBe('false'); +}); diff --git a/tests/Unit/Security/BrowserAndFrontGateTest.php b/tests/Unit/Security/BrowserAndFrontGateTest.php new file mode 100644 index 0000000..4d61e33 --- /dev/null +++ b/tests/Unit/Security/BrowserAndFrontGateTest.php @@ -0,0 +1,173 @@ +allows(RequestTarget::fromUri($path)))->toBeTrue(); +})->with([ + '/wp-admin', '/wp-admin/', '/wp-admin/options.php', '/wp-login.php', '/wp-json', '/wp-json/wp/v2/posts', '/graphql', '/wp-cron.php', + '/wp-content/uploads/2026/a.jpg', '/xmlrpc.php', '/wp-sitemap.xml', '/robots.txt', +]); + +it('keeps what only starts like an allowed path behind the gate', function (string $path): void { + expect(AllowList::defaults()->allows(RequestTarget::fromUri($path)))->toBeFalse(); +})->with([ + '/wp-adminx', '/wp-jsonx/a', '/graphql-docs', '/robots.txtx', '/wp-content/uploads-old/a', '/wp-content/plugins/a.php', '/', '/blog/wp-admin', +]); + +it('does not let dot segments walk out of an allowed path', function (string $uri): void { + expect(AllowList::defaults()->allows(RequestTarget::fromUri($uri)))->toBeFalse(); +})->with(['/wp-admin/..', '/wp-admin/../secret', '/wp-json/%2e%2e/secret', '/wp-admin/%2E./secret', '/wp-json/wp/../../secret']); + +it('resolves dot segments to the path a server would serve', function (string $uri, string $path): void { + expect(RequestTarget::fromUri($uri)->path)->toBe($path); +})->with([ + ['/blog/a/..', '/blog/'], + ['/blog/a/.', '/blog/a/'], + ['/blog/./a', '/blog/a'], + ['/..', '/'], + ['blog', '/blog'], + ['//blog', '/blog'], +]); + +it('keeps a second question mark in the query', function (): void { + $target = RequestTarget::fromUri('/a?next=/b?c=1'); + + expect($target->path)->toBe('/a')->and($target->query)->toBe('next=/b?c=1'); +}); + +it('allows an extra prefix next to the defaults, written with or without slashes', function (): void { + $list = AllowList::defaults()->with('health/', '/hooks'); + + expect($list->prefixes)->toBe([...AllowList::defaults()->prefixes, '/health', '/hooks']) + ->and($list->allows(RequestTarget::fromUri('/health')))->toBeTrue() + ->and($list->allows(RequestTarget::fromUri('/hooks/x')))->toBeTrue(); +}); + +it('keeps the prefixes a list, each once', function (): void { + expect((new AllowList(['a', '/a/', 'b']))->prefixes)->toBe(['/a', '/b']); +}); + +it('reads a URL written with blanks around it', function (): void { + expect(Origin::fromUrl(" https://www.example.com \n")->toString())->toBe('https://www.example.com'); +}); + +it('moves a URL to the front whatever the case of its scheme and port', function (): void { + $mapper = new UrlMapper(Origin::fromUrl('https://cms.example.com:8443'), Origin::fromUrl('https://www.example.com')); + + expect($mapper->toFront('HTTPS://cms.example.com:8443/a'))->toBe('https://www.example.com/a') + ->and($mapper->toFront('https://cms.example.com/a'))->toBe('https://cms.example.com/a'); +}); + +it('gives the path and query of an address', function (string $url, string $path): void { + expect(UrlPath::of($url))->toBe($path); +})->with([ + ['https://www.example.com/a/?b=1', '/a/?b=1'], + ['https://www.example.com/a/', '/a/'], + ['https://www.example.com', '/'], + ['https://www.example.com?b=1', '/?b=1'], +]); + +it('keeps matching the origins listed after a sub-domain pattern', function (): void { + $cors = new CorsPolicy(['https://*.a.test', 'https://b.test']); + + expect($cors->allows('https://b.test'))->toBeTrue()->and($cors->allows('https://x.a.test'))->toBeTrue(); +}); + +it('reads an origin or a pattern whatever its case and the blanks around it', function (): void { + $cors = new CorsPolicy([' HTTPS://*.Example.COM ', ' https://other.test ']); + + expect($cors->allows('https://app.example.com'))->toBeTrue() + ->and($cors->allows('https://other.test'))->toBeTrue() + ->and($cors->allows('https://other.test/'))->toBeTrue(); +}); + +it('matches a pattern with a port on that port only', function (): void { + $cors = new CorsPolicy(['https://*.example.com:8443']); + + expect($cors->allows('https://app.example.com:8443'))->toBeTrue() + ->and($cors->allows('https://app.example.com'))->toBeFalse() + ->and($cors->allows('https://app.example.com:9000'))->toBeFalse(); +}); + +it('says which response headers a script may read', function (): void { + $decision = (new CorsPolicy(['https://a.test']))->decide(new CorsRequest('https://a.test')); + + expect($decision->headers)->toBe([ + 'Vary' => 'Origin', + 'Access-Control-Allow-Origin' => 'https://a.test', + 'Access-Control-Expose-Headers' => 'X-WP-Total, X-WP-TotalPages, Link', + ]); +}); + +it('answers a preflight with the headers asked for only when each one is allowed', function (?string $asked, string $expected): void { + $cors = new CorsPolicy(['https://a.test'], headers: ['Authorization', 'Content-Type']); + + expect($cors->decide(new CorsRequest('https://a.test', 'options', 'GET', $asked))->headers['Access-Control-Allow-Headers'])->toBe($expected); +})->with([ + 'mixed case' => ['AUTHORIZATION , content-type', 'AUTHORIZATION, content-type'], + 'an empty entry' => [',authorization,', 'authorization'], + 'one too many' => ['authorization, x-evil', 'Authorization, Content-Type'], + 'nothing' => ['', 'Authorization, Content-Type'], + 'no header' => [null, 'Authorization, Content-Type'], +]); + +it('does not take an empty requested method for a preflight', function (): void { + expect((new CorsRequest('https://a.test', 'OPTIONS', ''))->isPreflight())->toBeFalse() + ->and((new CorsRequest('https://a.test', 'options', 'GET'))->isPreflight())->toBeTrue(); +}); + +it('never redirects when the gate answers with a page or JSON', function (FrontMode $mode, string $body): void { + $_SERVER['REQUEST_URI'] = '/blog'; + Functions\expect('wp_redirect')->never(); + Functions\expect('status_header')->once()->with(404); + Functions\expect('nocache_headers')->once(); + Functions\when('wp_json_encode')->alias('json_encode'); + Functions\when('get_bloginfo')->alias(static fn (string $key): string => $key === 'name' ? 'My ' : ''); + Functions\when('esc_html')->alias(static fn (string $text): string => htmlspecialchars($text)); + $count = 0; + + ob_start(); + edgeGate($mode, $count)->handle(); + + expect(ob_get_clean())->toBe($body)->and($count)->toBe(1); +})->with([ + [FrontMode::Page, 'My <Site>

This site has no public front end.

'], + [FrontMode::Json, '{"status":404,"message":"This site has no public front end."}'], +]); + +it('takes an unreadable address for the home page', function (): void { + $_SERVER['REQUEST_URI'] = ['/wp-admin']; + $_SERVER['REQUEST_METHOD'] = ['POST']; + Functions\expect('wp_redirect')->once()->with('https://www.example.com/', 302, 'Pollora Headless'); + $count = 0; + + edgeGate(FrontMode::Redirect, $count)->handle(); + + expect($count)->toBe(1); +}); diff --git a/tests/Unit/Security/ContentExposureTest.php b/tests/Unit/Security/ContentExposureTest.php new file mode 100644 index 0000000..24228e0 --- /dev/null +++ b/tests/Unit/Security/ContentExposureTest.php @@ -0,0 +1,386 @@ +set_param('_fields', $fields); + + return $request; +} + +/** @param list $rows */ +function leakDatabase(array $rows): void +{ + $wpdb = Mockery::mock('wpdb'); + $wpdb->prefix = 'wp_'; + $wpdb->postmeta = 'wp_postmeta'; + $wpdb->posts = 'wp_posts'; + $wpdb->shouldReceive('esc_like')->andReturnArg(0); + $wpdb->shouldReceive('prepare')->andReturnUsing(static fn (string $sql): string => $sql); + $wpdb->shouldReceive('get_var')->andReturn('wp_rank_math_redirections'); + $wpdb->shouldReceive('get_results')->andReturn($rows); + $GLOBALS['wpdb'] = $wpdb; +} + +function leakRank(array $sources, string $to = '/new/', mixed $code = '301'): object +{ + return (object) ['sources' => serialize($sources), 'url_to' => $to, 'header_code' => $code]; +} + +// Media, blocks and SEO + +it('describes the featured image of the post asked about, and nothing when it has none', function (): void { + $media = Mockery::mock(MediaCatalog::class); + $media->shouldReceive('for')->with(9)->andReturn(['id' => 9]); + $media->shouldReceive('for')->with(1)->andReturn(['id' => 1]); + Functions\when('get_post_thumbnail_id')->alias(static fn (mixed $post): int|false => match ($post) { + 5 => 9, + 6 => 1, + 0 => false, + default => 9999, + }); + $routes = new MediaRoutes($media); + + expect($routes->featured(['id' => 5], 'headless_featured_media', leakRequest('headless_featured_media')))->toBe(['id' => 9]) + ->and($routes->featured(['id' => 6], 'headless_featured_media', leakRequest('headless_featured_media')))->toBe(['id' => 1]) + ->and($routes->featured([], 'headless_featured_media', leakRequest('headless_featured_media')))->toBeNull(); +}); + +it('asks for the blocks of no post when the answer names none', function (): void { + $asked = new ArrayObject; + Functions\when('get_post')->alias(static function (mixed $id) use ($asked): ?WP_Post { + $asked[] = $id; + + return null; + }); + + (new BlocksField)->blocks([], 'headless_blocks', leakRequest('headless_blocks')); + + expect($asked->getArrayCopy())->toBe([0]); +}); + +it('renders a damaged block from the parts a block has, and marks dynamic inner blocks only', function (): void { + $rendered = new ArrayObject; + WP_Block_Type_Registry::$types = ['a/dynamic' => new WP_Block_Type(null, true), 'a/static' => new WP_Block_Type(null, false)]; + Functions\when('setup_postdata')->justReturn(true); + Functions\when('parse_blocks')->justReturn([[ + 'blockName' => 'a/static', + 'innerBlocks' => [ + ['blockName' => 'a/dynamic', 'innerBlocks' => 'broken', 'extra' => 1], + ['blockName' => 'a/static'], + ['blockName' => 'a/unknown'], + ], + ]]); + Functions\when('render_block')->alias(static function (array $block) use ($rendered): string { + $rendered[] = $block; + + return 'html'; + }); + + $blocks = BlocksField::forContent('content', new WP_Post); + + expect(array_map(static fn (array $block): bool => array_key_exists('rendered', $block), $blocks[0]['inner_blocks']))->toBe([true, false, false]) + ->and($rendered[0]['innerBlocks'])->toHaveCount(3) + ->and($rendered[0]['attrs'])->toBe([]) + ->and($rendered[0]['innerContent'])->toBe([]) + ->and($rendered[0]['innerHTML'])->toBe('') + ->and($rendered[1])->toBe(['blockName' => 'a/dynamic', 'innerBlocks' => [], 'extra' => 1, 'attrs' => [], 'innerHTML' => '', 'innerContent' => []]); +}); + +it('puts the earlier post back after rendering blocks', function (bool $had): void { + $setUp = new ArrayObject; + $before = $had ? new WP_Post(['ID' => 1]) : null; + $GLOBALS['post'] = $before; + Functions\when('setup_postdata')->alias(static function (WP_Post $post) use ($setUp): void { + $setUp[] = $post->ID; + }); + Functions\when('parse_blocks')->justReturn([]); + + BlocksField::forContent('', new WP_Post(['ID' => 2])); + + expect($setUp->getArrayCopy())->toBe($had ? [2, 1] : [2])->and($GLOBALS['post'])->toBe($before); +})->with([true, false]); + +it('numbers inner blocks by their order, whatever the keys of the parser', function (): void { + $tree = BlockTree::from( + [['blockName' => 'a/b', 'innerBlocks' => [7 => ['blockName' => 'a/c'], 3 => ['blockName' => 'a/d']]]], + static fn (string $name, array $attributes): array => $attributes, + static fn (array $block): string => '', + static fn (string $name): bool => false, + ); + + expect(array_column($tree[0]['inner_blocks'], 'id'))->toBe(['0.0', '0.1']); +}); + +it('asks the SEO source about the post or term of the answer, and about nothing when it names none', function (): void { + $asked = new ArrayObject; + $provider = Mockery::mock(SeoProvider::class); + $provider->shouldReceive('forPost')->andReturnUsing(static function (int $id) use ($asked) { + $asked[] = ['post', $id]; + + return null; + }); + $provider->shouldReceive('forTerm')->andReturnUsing(static function (int $id, string $taxonomy) use ($asked) { + $asked[] = ['term', $id, $taxonomy]; + + return null; + }); + $seo = new SeoField($provider, Mockery::mock(FrontUrls::class)); + + expect($seo->forPost([], 'headless_seo', leakRequest('headless_seo')))->toBeNull() + ->and($seo->forTerm([], 'headless_seo', leakRequest('headless_seo')))->toBeNull() + ->and($asked->getArrayCopy())->toBe([['post', 0], ['term', 0, '']]); +}); + +// Redirects + +it('lists no more rules than the limit, and says when it cut them', function (int $count, bool $truncated): void { + $rules = array_map(static fn (int $i): Redirect => new Redirect('/old-'.$i, '/new'), range(1, $count)); + $source = Mockery::mock(RedirectSource::class); + $source->shouldReceive('redirects')->andReturn($rules); + Functions\when('rest_ensure_response')->alias(static fn (array $data): WP_REST_Response => new WP_REST_Response($data)); + + $data = (new RedirectRoutes(new RedirectCatalog([$source])))->all()->get_data(); + + expect($data['count'])->toBe($count) + ->and($data['redirects'])->toHaveCount(min($count, 5000)) + ->and($data['truncated'])->toBe($truncated); +})->with([[5000, false], [5001, true]]); + +it('reads from Rank Math every rule after one it cannot use', function (): void { + leakDatabase([ + leakRank([['pattern' => 'contains', 'comparison' => 'contains'], ['pattern' => 'one', 'comparison' => 'exact']]), + leakRank([['pattern' => 'bad', 'comparison' => 'exact'], ['pattern' => 'two', 'comparison' => 'exact']], code: '999'), + leakRank([['pattern' => '/three', 'comparison' => 'exact'], 'not a source', ['comparison' => 'exact'], ['pattern' => 'x']]), + ]); + + expect(array_map(static fn (Redirect $rule): string => $rule->from, (new RankMathRedirects)->redirects()))->toBe(['/one', '/three']); +}); + +it('instantiates no object held in the sources of Rank Math', function (): void { + $payload = 'a:1:{i:0;a:2:{s:7:"pattern";s:3:"one";s:10:"comparison";O:8:"stdClass":0:{}}}'; + leakDatabase([(object) ['sources' => $payload, 'url_to' => '/new/', 'header_code' => '301']]); + + expect((new RankMathRedirects)->redirects())->toBe([]); +}); + +it('skips a Rank Math rule with no destination or status', function (): void { + leakDatabase([(object) ['sources' => serialize([['pattern' => 'one', 'comparison' => 'exact']])]]); + + expect((new RankMathRedirects)->redirects())->toBe([]); +}); + +it('reads no redirection without a database', function (): void { + expect((new RankMathRedirects)->redirects())->toBe([]); +}); + +it('lists the old slugs after the ones it has to leave out', function (): void { + Functions\when('get_transient')->justReturn(false); + Functions\when('set_transient')->justReturn(true); + $row = static fn (mixed $id, mixed $slug): object => (object) ['post_id' => $id, 'old_slug' => $slug]; + leakDatabase([$row(null, 'x'), $row('1', 'now'), $row('2', 'same'), $row('3', 'before')]); + $asked = new ArrayObject; + Functions\when('get_post')->alias(static function (mixed $id) use ($asked): WP_Post { + $asked[] = $id; + + // Post 2 has plain permalinks: both of its addresses are the same + return new WP_Post(['ID' => $id, 'post_name' => 'now', 'post_type' => $id === 2 ? 'plain' : 'post']); + }); + Functions\when('is_post_type_viewable')->justReturn(true); + Functions\when('get_permalink')->alias(static fn (WP_Post $post): string => 'https://cms.example.com/'.($post->post_type === 'plain' ? '?p=2' : $post->post_name.'/')); + $urls = Mockery::mock(FrontUrls::class); + $urls->shouldReceive('toFront')->andReturnArg(0); + + $rules = (new OldSlugRedirects($urls))->redirects(); + + expect(array_map(static fn (Redirect $rule): array => $rule->toArray(), $rules))->toBe([['from' => '/before/', 'to' => '/now/', 'status' => 301, 'regex' => false, 'source' => 'old-slug']]) + ->and($asked->getArrayCopy())->toBe([1, 2, 3]); +}); + +it('gives the cached old slugs as a list, without the ones it cannot read', function (): void { + Functions\when('get_transient')->justReturn(['junk', ['from' => '/a'], ['from' => '/b', 'to' => '/c']]); + + $rules = (new OldSlugRedirects(Mockery::mock(FrontUrls::class)))->redirects(); + + expect(array_keys($rules))->toBe([0])->and($rules[0]->from)->toBe('/b'); +}); + +// Forms + +it('looks past a provider that is not the one asked for', function (): void { + $other = Mockery::mock(FormProvider::class); + $other->shouldReceive('name')->andReturn('other'); + $other->shouldReceive('find')->never(); + $wanted = Mockery::mock(FormProvider::class); + $wanted->shouldReceive('name')->andReturn('cf7'); + $wanted->shouldReceive('find')->once()->with('12')->andReturn(null); + Functions\when('apply_filters')->justReturn([1 => 'junk', 4 => $other, 6 => $wanted]); + $request = new WP_REST_Request('GET', '/headless/v1/forms/cf7/12'); + $request->set_param('provider', 'cf7'); + $request->set_param('id', '12'); + + $error = (new FormRoutes([]))->show($request); + + expect([$error->get_error_code(), $error->get_error_data()])->toBe(['headless_form_not_found', ['status' => 404]]); +}); + +it('reads every Contact Form 7 form, and the choices of the fields that have some', function (): void { + require_once dirname(__DIR__, 2).'/Stubs/contact-form-7.php'; + Functions\when('rest_url')->returnArg(1); + $tags = [ + 'not a tag', + new WPCF7_FormTag('radio', 'size', [5 => 's', 9 => 'l'], ['Small']), + new WPCF7_FormTag('text', 'who', ['default']), + new WPCF7_FormTag('select', 'one', ['a'], ['A']), + new WPCF7_FormTag('select', 'many', ['a'], ['A'], ['multiple']), + new WPCF7_FormTag('radio', 'flagged', [], [], ['multiple']), + new WPCF7_FormTag('checkbox', 'boxes', 'x', 'X'), + new WPCF7_FormTag('checkbox', 'alone', ['y'], ['Y'], ['exclusive']), + ]; + WPCF7_ContactForm::$forms = [12 => new WPCF7_ContactForm(12, 'Contact', 'fr_FR', $tags)]; + + $fields = array_map(static fn ($field): array => [$field->name, $field->multiple, $field->options], (new ContactForm7Provider)->forms()[0]->fields); + WPCF7_ContactForm::$forms = []; + + expect($fields)->toBe([ + ['size', false, [['value' => 's', 'label' => 'Small'], ['value' => 'l', 'label' => 'l']]], + ['who', false, []], + ['one', false, [['value' => 'a', 'label' => 'A']]], + ['many', true, [['value' => 'a', 'label' => 'A']]], + ['flagged', false, []], + ['boxes', true, [['value' => 'x', 'label' => 'X']]], + ['alone', false, [['value' => 'y', 'label' => 'Y']]], + ]); +}); + +// REST performance + +it('gives each of its filters the priority and arguments it reads', function (): void { + Filters\expectAdded('rest_post_dispatch')->once()->with(Mockery::type('array'), 20, 3); + Filters\expectAdded('rest_pre_serve_request')->once()->with(Mockery::type('array'), 5, 3); + Filters\expectAdded('rest_pre_dispatch')->once()->with(Mockery::type('array'), 5, 3); + + (new RestPerformance(new RestCachePolicy, 20))->register(new WordPressHooks); +}); + +it('lowers per_page only above the ceiling', function (mixed $asked, ?int $ceiling, bool $lowered): void { + $request = new WP_REST_Request; + $request->set_param('per_page', $asked); + + (new RestPerformance(null, $ceiling))->capPerPage(null, null, $request); + + expect($request->get_param('per_page'))->toBe($lowered ? $ceiling : $asked); +})->with([ + 'under' => [19, 20, false], + 'at' => ['20', 20, false], + 'over' => ['21', 20, true], + 'not a number' => ['many', 20, false], + 'a decimal just over' => ['20.5', 20, false], + 'no ceiling' => [500, null, false], +]); + +it('does not mark answers cacheable without a policy', function (): void { + $response = new WP_REST_Response(['id' => 1]); + + (new RestPerformance(null, 20))->markCacheable($response, null, new WP_REST_Request('GET', '/wp/v2/posts')); + + expect($response->get_headers())->toBe([]); +}); + +// Plugins loaded on a REST request + +it('registers the plugin filter on a REST request only', function (bool $rest): void { + Filters\expectAdded('option_active_plugins')->times($rest ? 1 : 0); + + (new RestPlugins(new PluginFilter([]), $rest))->register(new WordPressHooks); +})->with([true, false]); + +it('takes the plugins to keep from the settings of the current site, only when switched on', function (string $setup, string $config, string $expected): void { + $code = $setup."define('HEADLESS_CONFIG', ".$config.'); ' + .'$module = Pollora\Headless\Infrastructure\WordPress\RestPlugins::fromSettings("/wp-json/", []); ' + .'echo json_encode($module?->plugins(["a/a.php", "b/b.php"]));'; + + expect(isolated($code))->toBe($expected); +})->with([ + 'switched on' => ['', "['rest_plugins' => ['enabled' => true, 'keep' => ['a']]]", '["a\/a.php"]'], + 'no switch' => ['', "['rest_plugins' => ['keep' => ['a']]]", 'null'], + 'a truthy switch is not on' => ['', "['rest_plugins' => ['enabled' => 1, 'keep' => ['a']]]", 'null'], + 'switched off' => ['', "['rest_plugins' => ['enabled' => false]]", 'null'], + 'not a list of settings' => ['', "['rest_plugins' => true]", 'null'], + 'the first site without multisite' => ['', "['sites' => [0 => [], 1 => ['rest_plugins' => ['enabled' => true, 'keep' => ['b']]], 2 => []]]", '["b\/b.php"]'], + 'the current site' => ['function get_current_blog_id() { return 3; } ', "['sites' => [1 => [], 3 => ['rest_plugins' => ['enabled' => true, 'keep' => ['b']]]]]", '["b\/b.php"]'], +]); + +// GraphQL + +it('keeps one Vary list from WPGraphQL and the policy', function (): void { + $_SERVER['HTTP_ORIGIN'] = 'https://a.test'; + $graphql = new GraphQl(new GraphQlPolicy, new CorsPolicy(['https://a.test'])); + + $headers = $graphql->headers(['Vary' => ' Accept-Encoding ,, Origin ,Cookie']); + + expect($headers['Vary'])->toBe('Accept-Encoding, Origin, Cookie') + ->and($headers['Access-Control-Allow-Origin'])->toBe('https://a.test'); +}); + +it('does nothing at a root field without the token module', function (): void { + expect((new GraphQl(new GraphQlPolicy))->guard('kept', null, [], null, null, 'RootMutation'))->toBe('kept'); +}); + +it('refuses a mutation to a token limited to reading, after letting its query through', function (): void { + $service = new TokenService(new InMemoryTokenStore); + $auth = new TokenAuthentication($service, static fn (): bool => true); + $_SERVER['HTTP_AUTHORIZATION'] = 'Bearer '.$service->create(7, 'a', [TokenScope::Read], ['/graphql'])->secret; + $auth->authenticate(false); + unset($_SERVER['HTTP_AUTHORIZATION']); + $guard = new GraphQl(new GraphQlPolicy, null, $auth); + + expect($guard->guard(null, null, [], null, null, 'RootQuery'))->toBeNull() + ->and(static fn () => $guard->guard(null, null, [], null, null, 'RootMutation'))->toThrow(UserError::class); +}); diff --git a/tests/Unit/Security/PreviewAndNotificationsTest.php b/tests/Unit/Security/PreviewAndNotificationsTest.php new file mode 100644 index 0000000..134c1c7 --- /dev/null +++ b/tests/Unit/Security/PreviewAndNotificationsTest.php @@ -0,0 +1,288 @@ + rtrim(strtr(base64_encode($bytes), '+/', '-_'), '='); + $payload = $encode($json); + + return $payload.'.'.$encode(hash_hmac('sha256', $payload, 'key', true)); +} + +/** @return array{Revalidator, FakeTransport, FakeDeliveries} */ +function notifier(): array +{ + $transport = new FakeTransport; + $deliveries = new FakeDeliveries; + $revalidator = new Revalidator([new Target('next', 'https://a.test/hook', 'k')], new FakePending, $deliveries, new FakeScheduler, $transport, new RecordingLogger, clock: static fn (): int => 5000); + + return [$revalidator, $transport, $deliveries]; +} + +it('refuses a rightly signed payload that lacks what a preview token holds', function (string $json): void { + TokenSigner::verify(signedPayload($json), 'key', 1000, PreviewTokenType::Link); +})->throws(PreviewTokenInvalidException::class)->with([ + 'no type' => ['{"u":7,"p":42,"s":1,"a":"x","e":2000,"j":"id"}'], + 'an empty id' => ['{"t":"link","u":7,"p":42,"s":1,"a":"x","e":2000,"j":""}'], + 'a text' => ['"link"'], +]); + +it('makes tokens that fit in an address, each with 128 random bits of its own', function (): void { + $store = new FakePreviewStore; + $token = (new PreviewService($store, new FakePostAccess, 'key', 'https://www.example.com'))->linkToken(7, 42, 1); + $claims = TokenSigner::verify($token, 'key', time(), PreviewTokenType::Link); + + expect($token)->toMatch('/\A[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\z/') + ->and($claims->id)->toMatch('/\A[0-9a-f]{32}\z/'); +}); + +it('keeps WordPress\'s preview link when there is no post to point at', function (): void { + Functions\when('get_current_user_id')->justReturn(7); + Functions\when('user_can')->justReturn(true); + $module = new PreviewLinks(new PreviewService(new FakePreviewStore, new FakePostAccess, 'key', 'https://www.example.com'), 'https://www.example.com/api/preview'); + + expect($module->link('wp-link', null))->toBe('wp-link') + ->and($module->link('wp-link', (object) ['ID' => 42]))->toBe('wp-link'); +}); + +it('gives the front end the path of the permalink, with its query only when there is one', function (string|false $permalink, string $path): void { + Functions\when('get_current_user_id')->justReturn(7); + Functions\when('user_can')->justReturn(true); + Functions\when('get_permalink')->justReturn($permalink); + Functions\when('get_current_blog_id')->justReturn(1); + Functions\when('get_locale')->justReturn('en_US'); + Functions\when('add_query_arg')->alias(static fn (array $args): string => $args['path']); + $module = new PreviewLinks(new PreviewService(new FakePreviewStore, new FakePostAccess, 'key', 'https://www.example.com'), 'https://www.example.com/api/preview'); + + expect($module->link('wp-link', new WP_Post(['ID' => 42, 'post_type' => 'post'])))->toBe($path); +})->with([ + ['https://www.example.com/blog/hello/', '/blog/hello/'], + ['https://www.example.com/blog/?p=42', '/blog/?p=42'], + [false, ''], +]); + +/** WordPress answering the preview of post 42, recording which post was set up. */ +function overlaySite(ArrayObject $setUp, mixed &$asked = null): void +{ + Functions\when('get_post')->justReturn(new WP_Post(['ID' => 42, 'post_title' => 'Saved'])); + Functions\when('wp_get_post_revision')->alias(static function (mixed $id) use (&$asked): WP_Post { + $asked = $id; + + return new WP_Post(['ID' => 50, 'post_parent' => 42, 'post_title' => 'Revision']); + }); + Functions\when('get_current_user_id')->justReturn(3); + Functions\when('wp_set_current_user')->justReturn(null); + Functions\when('rest_get_route_for_post')->justReturn('/wp/v2/posts/42'); + Functions\when('rest_do_request')->justReturn(new WP_REST_Response(['title' => ['raw' => 'T'], 'content' => ['raw' => 'C'], 'excerpt' => ['raw' => 'E']])); + Functions\when('setup_postdata')->alias(static function (WP_Post $post) use ($setUp): void { + $setUp[] = $post->post_title; + }); + Functions\when('get_the_excerpt')->justReturn('Excerpt'); + Functions\when('apply_filters')->returnArg(2); +} + +it('shows a revision with what else the fields hold, then sets the earlier post up again', function (): void { + $setUp = new ArrayObject; + $asked = null; + overlaySite($setUp, $asked); + $GLOBALS['post'] = new WP_Post(['ID' => 1, 'post_title' => 'Before']); + + $data = (new PreviewPostResponse)->build(42, 7, '50')->get_data(); + + expect($asked)->toBe(50) + ->and($data['title'])->toBe(['raw' => 'T', 'rendered' => 'Revision']) + ->and($data['excerpt'])->toBe(['raw' => 'E', 'rendered' => 'Excerpt']) + ->and($data['preview']['source'])->toBe('revision') + ->and($setUp->getArrayCopy())->toBe(['Revision', 'Before']); +}); + +it('sets no post up again when there was none', function (): void { + $setUp = new ArrayObject; + overlaySite($setUp); + + (new PreviewPostResponse)->build(42, 7, '50'); + + expect($setUp->getArrayCopy())->toBe(['Revision'])->and($GLOBALS['post'])->toBeNull(); +}); + +it('sends nothing for a retry of a target that is no longer configured', function (): void { + [$revalidator, $transport, $deliveries] = notifier(); + $deliveries->bodies['gone-abc'] = '{"id":"abc"}'; + + $revalidator->retry('gone', 'abc', 2); + + expect($transport->sent)->toBe([]); +}); + +it('pings with a signed ping event, a first attempt of a delivery of its own', function (): void { + [$revalidator, $transport] = notifier(); + + $revalidator->ping(); + + [, $body, $headers] = $transport->sent[0]; + $payload = json_decode($body, true); + + expect($payload['id'])->toMatch('/\A[0-9a-f]{24}\z/') + ->and($payload['events'][0]['event'])->toBe('ping') + ->and($payload['tags'])->toBe(['ping']) + ->and($headers['X-Headless-Attempt'])->toBe('1') + ->and($headers['X-Headless-Delivery'])->toBe($payload['id']) + ->and(WebhookSigner::verify($body, 'k', 5000, $headers['X-Headless-Signature'], 5000))->toBeTrue(); +}); + +it('retries only a call that names a target, a delivery and an attempt', function (mixed $target, mixed $id, mixed $attempt, int $sent): void { + [$revalidator, $transport, $deliveries] = notifier(); + $deliveries->bodies['next-abc'] = '{}'; + $deliveries->bodies['next-5'] = '{}'; + + (new RevalidationRunner($revalidator))->retry($target, $id, $attempt); + + expect($transport->sent)->toHaveCount($sent); +})->with([ + 'complete' => ['next', 'abc', 2, 1], + 'no target' => [null, 'abc', 2, 0], + 'a number for the delivery' => ['next', 5, 2, 0], + 'a text for the attempt' => ['next', 'abc', '2', 0], +]); + +it('posts a notification once, without following redirects, and gives up after ten seconds', function (): void { + Functions\expect('wp_remote_post')->once()->with('https://a.test/hook', [ + 'body' => '{}', + 'headers' => ['X-A' => '1'], + 'timeout' => 10, + 'redirection' => 0, + 'user-agent' => 'Pollora-Headless/1', + ])->andReturn([]); + Functions\when('wp_remote_retrieve_response_code')->justReturn(200); + + expect((new WpHttpTransport)->send(new Target('next', 'https://a.test/hook', 'k'), '{}', ['X-A' => '1'])->delivered)->toBeTrue(); +}); + +it('counts a notification as delivered from 200 to 299 only', function (int|string $code, bool $delivered): void { + Functions\when('wp_remote_post')->justReturn([]); + Functions\when('wp_remote_retrieve_response_code')->justReturn($code); + + $result = (new WpHttpTransport)->send(new Target('next', 'https://a.test/hook', 'k'), '{}', []); + + expect($result->delivered)->toBe($delivered)->and($result->status)->toBe((int) $code); +})->with([[199, false], [200, true], ['204', true], [299, true], [300, false]]); + +it('says a batch is incomplete only past a limit, and cuts it there', function (string $what, int $limit): void { + $of = static function (int $count) use ($what): Batch { + $items = array_map(static fn (int $i): string => 'https://a.test/'.$i, range(1, $count)); + + return Batch::of(match ($what) { + 'tags' => [new ChangeEvent('x', $items)], + 'urls' => [new ChangeEvent('x', [], $items)], + 'events' => array_map(static fn (): ChangeEvent => new ChangeEvent('x', ['t']), $items), + }); + }; + + expect($of($limit)->truncated)->toBeFalse() + ->and($of($limit)->{$what})->toHaveCount($limit) + ->and($of($limit + 1)->truncated)->toBeTrue() + ->and($of($limit + 1)->{$what})->toHaveCount($limit); +})->with([['tags', 200], ['urls', 200], ['events', 100]]); + +it('writes a notification a front end reads as it is: addresses unescaped, paths with their queries', function (): void { + $json = Batch::of([new ChangeEvent('x', ['café'], ['https://a.test/été/?p=1', 'https://a.test/b', 'https://other.test/b', 'https://a.test'])])->toJson('id', 1); + + expect($json)->toContain('"café"', 'https://a.test/été/?p=1') + ->and(json_decode($json, true)['paths'])->toBe(['/été/?p=1', '/b', '']); +}); + +it('keeps the tags of a stored change as a list', function (): void { + expect(ChangeEvent::fromArray(['event' => 'x', 'tags' => [1, 'a']])?->tags)->toBe(['a']); +}); + +it('stores each pending change apart, under a random name, and never autoloaded', function (): void { + Functions\when('wp_json_encode')->alias('json_encode'); + Functions\expect('add_option')->once()->with( + Mockery::on(static fn (string $name): bool => preg_match('/\Aheadless_ev_[0-9a-f]{16}\z/', $name) === 1), + '{"event":"x","tags":["a"],"urls":[],"post":null,"site":1,"locale":""}', + '', + false, + ); + + (new OptionPendingEvents)->push(new ChangeEvent('x', ['a'])); +}); + +it('takes at most 500 pending changes, oldest first, from its own rows', function (): void { + $wpdb = Mockery::mock('wpdb'); + $wpdb->options = 'wp_options'; + $wpdb->shouldReceive('esc_like')->with('headless_ev_')->andReturn('headless\_ev\_'); + $wpdb->shouldReceive('prepare')->once()->with( + 'SELECT option_name, option_value FROM %i WHERE option_name LIKE %s ORDER BY option_id ASC LIMIT %d', + 'wp_options', + 'headless\_ev\_%', + 500, + )->andReturn('sql'); + $wpdb->shouldReceive('get_results')->with('sql')->andReturn([(object) ['option_name' => 'headless_ev_a']]); + $GLOBALS['wpdb'] = $wpdb; + Functions\expect('delete_option')->once()->with('headless_ev_a')->andReturn(true); + + expect((new OptionPendingEvents)->drain())->toBe([]); +}); + +it('delays a flush and a retry from now, with Action Scheduler or WP-Cron', function (string $backend): void { + $times = new ArrayObject; + Functions\when('did_action')->justReturn($backend === 'action scheduler' ? 1 : 0); + Functions\when('as_has_scheduled_action')->justReturn(false); + Functions\when('wp_next_scheduled')->justReturn(false); + $record = static function (int $time) use ($times): void { + $times[] = $time - time(); + }; + Functions\when('as_schedule_single_action')->alias($record); + Functions\when('wp_schedule_single_event')->alias($record); + + $scheduler = new ActionSchedulerScheduler; + $scheduler->scheduleFlush(100); + $scheduler->scheduleRetry('next', 'abc', 2, 300); + + expect($times[0])->toBeGreaterThanOrEqual(99)->toBeLessThanOrEqual(100) + ->and($times[1])->toBeGreaterThanOrEqual(299)->toBeLessThanOrEqual(300); +})->with(['action scheduler', 'wp-cron']); + +it('asks Action Scheduler itself whether it is ready, when it can', function (string $setup, string $expected): void { + $code = 'function did_action($hook) { return 1; } '.$setup + .'echo var_export(Pollora\Headless\Infrastructure\Revalidation\ActionSchedulerScheduler::actionSchedulerIsReady(), true);'; + + expect(isolated($code))->toBe($expected); +})->with([ + 'no functions' => ['', 'false'], + 'ready' => ['function as_schedule_single_action() {} class ActionScheduler { public static function is_initialized() { return true; } } ', 'true'], + 'not ready' => ['function as_schedule_single_action() {} class ActionScheduler { public static function is_initialized() { return false; } } ', 'false'], + 'an older copy, after its init' => ['function as_schedule_single_action() {} ', 'true'], +]); diff --git a/tests/Unit/Security/PublicRoutesContractTest.php b/tests/Unit/Security/PublicRoutesContractTest.php new file mode 100644 index 0000000..0f894e1 --- /dev/null +++ b/tests/Unit/Security/PublicRoutesContractTest.php @@ -0,0 +1,159 @@ +> every route registered, by address */ +function exposureRoutes(object $module): ArrayObject +{ + $routes = new ArrayObject; + Functions\when('register_rest_route')->alias(static function (string $namespace, string $route, array $args) use ($routes): bool { + $routes[$namespace.$route] = $args; + + return true; + }); + $module->routes(); + + return $routes; +} + +function exposureAnything(string $interface): object +{ + return Mockery::mock($interface); +} + +function exposurePreview(): PreviewRoutes +{ + return new PreviewRoutes(new PreviewService(new FakePreviewStore, new FakePostAccess, 'key', 'https://www.example.com'), new PreviewPostResponse); +} + +it('opens the preview exchange to a POST carrying a token', function (): void { + $module = exposurePreview(); + $route = exposureRoutes($module)['headless/v1/preview/exchange']; + + expect($route)->toBe([ + 'methods' => 'POST', + 'callback' => [$module, 'exchange'], + 'permission_callback' => '__return_true', + 'args' => ['token' => ['type' => 'string', 'required' => true]], + ]); +}); + +it('keeps a previewed post behind the permission check, with a strict revision argument', function (): void { + $module = exposurePreview(); + $route = exposureRoutes($module)['headless/v1/preview/posts/(?P\d+)']; + + expect($route['methods'])->toBe('GET') + ->and($route['callback'])->toBe([$module, 'read']) + ->and($route['permission_callback'])->toBe([$module, 'authorize']) + ->and($route['args']['id'])->toBe(['type' => 'integer', 'required' => true]) + ->and($route['args']['rev'])->toBe(['type' => 'string', 'default' => 'autosave', 'pattern' => '\A(autosave|live|\d+)\z']); +}); + +it('opens the redirects to GET only, and takes one bounded path to resolve', function (): void { + $module = new RedirectRoutes(new RedirectCatalog([])); + $routes = exposureRoutes($module); + + expect($routes['headless/v1/redirects'])->toBe(['methods' => 'GET', 'callback' => [$module, 'all'], 'permission_callback' => '__return_true']) + ->and($routes['headless/v1/redirects/resolve'])->toBe([ + 'methods' => 'GET', + 'callback' => [$module, 'resolve'], + 'permission_callback' => '__return_true', + 'args' => ['path' => ['type' => 'string', 'required' => true, 'pattern' => '\A/\S{0,511}\z']], + ]); +}); + +it('opens the forms and the manifest to GET only', function (): void { + $forms = new FormRoutes([]); + $manifest = new ManifestRoutes((new ReflectionClass(SiteManifest::class))->newInstanceWithoutConstructor()); + $routes = exposureRoutes($forms); + + expect($routes['headless/v1/forms'])->toBe(['methods' => 'GET', 'callback' => [$forms, 'index'], 'permission_callback' => '__return_true']) + ->and($routes['headless/v1/forms/(?P[a-z0-9_-]+)/(?P[A-Za-z0-9_-]+)'])->toBe(['methods' => 'GET', 'callback' => [$forms, 'show'], 'permission_callback' => '__return_true']) + ->and(exposureRoutes($manifest)['headless/v1/site'])->toBe(['methods' => 'GET', 'callback' => [$manifest, 'show'], 'permission_callback' => '__return_true']); +}); + +it('opens a media file to GET by its number', function (): void { + Functions\when('get_post_types')->justReturn([]); + $module = new MediaRoutes(exposureAnything(MediaCatalog::class)); + + expect(exposureRoutes($module)['headless/v1/media/(?P\d+)'])->toBe([ + 'methods' => 'GET', + 'callback' => [$module, 'show'], + 'permission_callback' => '__return_true', + 'args' => ['id' => ['type' => 'integer', 'required' => true]], + ]); +}); + +it('opens the search to GET, with its arguments', function (): void { + $module = new SearchRoutes(exposureAnything(FrontUrls::class), exposureAnything(Languages::class), 25); + $route = exposureRoutes($module)['headless/v1/search']; + + expect($route['methods'])->toBe('GET') + ->and($route['callback'])->toBe([$module, 'search']) + ->and($route['permission_callback'])->toBe('__return_true') + ->and($route['args'])->toBe([ + 'q' => ['type' => 'string', 'required' => true, 'description' => 'The words to search for (two characters at least).'], + 'type' => ['type' => 'string', 'description' => 'Comma-separated content types to look in; every public type by default.'], + 'lang' => ['type' => 'string', 'description' => 'A language code, when the site has languages.'], + 'page' => ['type' => 'integer', 'default' => 1, 'minimum' => 1], + 'per_page' => ['type' => 'integer', 'default' => 10, 'minimum' => 1, 'description' => 'Capped at 25.'], + ]); +}); + +it('adds the featured image, the blocks and the SEO to public types the REST API serves, and to no other', function (string $module, array $expected): void { + $instance = match ($module) { + 'media' => new MediaRoutes(exposureAnything(MediaCatalog::class)), + 'blocks' => new BlocksField, + 'seo' => new SeoField(exposureAnything(SeoProvider::class), exposureAnything(FrontUrls::class)), + }; + $fields = new ArrayObject; + $all = [ + 'post' => ['public' => true, 'show_in_rest' => true], + 'secret' => ['public' => false, 'show_in_rest' => true], + 'classic' => ['public' => true, 'show_in_rest' => false], + ]; + $matching = static fn (array $criteria): array => array_keys(array_filter($all, static fn (array $type): bool => array_intersect_assoc($criteria, $type) === $criteria)); + Functions\when('get_post_types')->alias($matching); + Functions\when('get_taxonomies')->alias($matching); + Functions\when('post_type_supports')->justReturn(true); + Functions\when('register_rest_route')->justReturn(true); + Functions\when('register_rest_field')->alias(static function (string $type, string $name, array $args) use ($fields): void { + $fields[] = [$type, $name, $args['get_callback'][1], $args['schema']]; + }); + + $module === 'media' ? $instance->routes() : $instance->fields(); + + expect($fields->getArrayCopy())->toBe($expected); +})->with([ + 'media' => ['media', [['post', 'headless_featured_media', 'featured', ['description' => 'The featured image in full (ask for it in _fields).', 'type' => ['object', 'null'], 'context' => ['view', 'edit']]]]], + 'blocks' => ['blocks', [['post', 'headless_blocks', 'blocks', ['description' => 'The blocks of the content as stable JSON (ask for it in _fields).', 'type' => ['array', 'null'], 'context' => ['view', 'edit']]]]], + 'seo' => ['seo', [ + ['post', 'headless_seo', 'forPost', ['description' => 'Search and social metadata in one shape (ask for it in _fields).', 'type' => ['object', 'null'], 'context' => ['view', 'edit']]], + ['post', 'headless_seo', 'forTerm', ['description' => 'Search and social metadata in one shape (ask for it in _fields).', 'type' => ['object', 'null'], 'context' => ['view', 'edit']]], + ]], +]); diff --git a/tests/Unit/Security/StoredDataExposureTest.php b/tests/Unit/Security/StoredDataExposureTest.php new file mode 100644 index 0000000..84f8420 --- /dev/null +++ b/tests/Unit/Security/StoredDataExposureTest.php @@ -0,0 +1,91 @@ +prefix = 'wp_'; + $wpdb->shouldReceive('esc_like')->andReturnArg(0); + $wpdb->shouldReceive('prepare')->andReturn('sql'); + $wpdb->shouldReceive('get_var')->andReturn('wp_rank_math_redirections'); + $wpdb->shouldReceive('get_results')->andReturn([(object) ['sources' => serialize([new ExposureWokenObject]), 'url_to' => '/new', 'header_code' => '301']]); + $GLOBALS['wpdb'] = $wpdb; + + expect((new RankMathRedirects)->redirects())->toBe([]) + ->and(ExposureWokenObject::$woken)->toBe(0); +}); + +it('hides a file attached to a post the visitor may not read, the first post of the site included', function (): void { + $file = new WP_Post(['ID' => 9, 'post_type' => 'attachment', 'post_status' => 'inherit', 'post_parent' => 1]); + $parent = new WP_Post(['ID' => 1, 'post_status' => 'private']); + Functions\when('get_post')->alias(static fn (int $id): WP_Post => $id === 9 ? $file : $parent); + Functions\when('is_post_publicly_viewable')->justReturn(false); + Functions\expect('current_user_can')->once()->with('read_post', 1)->andReturn(false); + + expect((new NormalizedMedia)->for(9))->toBeNull(); +}); + +it('does not read a stored rule without a pattern flag as a pattern', function (): void { + $rule = Redirect::tryFromArray(['from' => '/a.b', 'to' => '/c']); + + expect($rule?->regex)->toBeFalse()->and($rule?->resolve('/aXb'))->toBeNull(); +}); + +it('matches a pattern that holds the character the package delimits patterns with', function (): void { + expect((new Redirect('/a#(\d+)', '/b/$1', 301, true))->resolve('/a#7'))->toBe('/b/7'); +}); + +it('does not autoload the rules after one is removed', function (): void { + Functions\when('get_option')->justReturn(['/a' => ['from' => '/a', 'to' => '/b']]); + Functions\expect('update_option')->once()->with('headless_redirects', Mockery::type('array'), false); + + expect((new OptionRedirectStore)->remove('/a'))->toBeTrue(); +}); + +it('keeps the newest rules of an editor up to the limit, each under its own path', function (): void { + $stored = []; + + foreach (range(1, OptionRedirectStore::LIMIT) as $i) { + $stored['/old-'.$i] = ['from' => '/old-'.$i, 'to' => '/new']; + } + + Functions\when('get_option')->justReturn($stored); + Functions\expect('update_option')->once()->with('headless_redirects', Mockery::on(static fn (array $all): bool => count($all) === OptionRedirectStore::LIMIT + && array_key_first($all) === '/old-2' + && array_key_last($all) === '/last'), false); + + (new OptionRedirectStore)->save(new Redirect('/last', '/new')); +}); + +it('refuses a feed before WordPress prints it', function (): void { + foreach (['do_feed', 'do_feed_rdf', 'do_feed_rss', 'do_feed_rss2', 'do_feed_atom'] as $feed) { + Actions\expectAdded($feed)->once()->with(Mockery::type('array'), 1); + } + + (new PublicSurface(true, false, false))->register(new WordPressHooks); +});