diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bf2b97cd..bb38ac40 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -306,9 +306,11 @@ jobs: - name: Generate application key run: ddev exec php artisan key:generate --no-interaction + # Through the script, which still gives the site its theme when GitHub's API + # refuses pollora:install the list of tags - name: Install WordPress run: | - ddev exec php artisan pollora:install --install \ + ddev exec bash packages/framework/tests/e2e/bin/install-wordpress.sh --install \ --title="Pollora" \ --description="Pollora CI" \ --admin-user=admin \ diff --git a/.github/workflows/harness.yml b/.github/workflows/harness.yml index 48501da5..24d96433 100644 --- a/.github/workflows/harness.yml +++ b/.github/workflows/harness.yml @@ -17,3 +17,6 @@ jobs: uses: Pollora/harness/.github/workflows/php-package.yml@v0.1.41 permissions: contents: read + with: + # The pull request into main scores every file new since the previous release, which can outlast the default of 30 + quality-timeout-minutes: 90 diff --git a/CHANGELOG.md b/CHANGELOG.md index aff84507..2c97a866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,29 @@ All notable changes to the Pollora framework will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased](https://github.com/Pollora/framework/compare/v13.45.1...develop) +## [Unreleased](https://github.com/Pollora/framework/compare/v13.45.2...develop) + +## [v13.45.2](https://github.com/Pollora/framework/compare/v13.45.1...v13.45.2) - 2026-12-04 + +### Added + +- **`Pollora\Testing\IsolatesWordPressHooks`: the hooks of one test no longer reach the next one** ([#741](https://github.com/Pollora/framework/issues/741)). A test process loads WordPress once and creates one application per test, so the callbacks of a flushed application stayed in `$wp_filter` and failed, or ran twice, when a later test fired them. Add the trait to the base test case of the project (`use IsolatesWordPressHooks;`); nothing changes without it. After each test, `$wp_filter`, `$wp_actions` and `$wp_filters` go back to what loading WordPress left: what the application or the test hooked is removed, what the core, plugins, must-use plugins and `functions.php` hooked is kept, as are the static methods hooked while the application booted and what `pollora/roles` and `pollora/schedule` hook once per process. It restores hooks only: other statics and WordPress globals still outlive a test. A callback hooked by a file first included during a test is removed with the rest and does not come back. Requires `APP_ENV=testing` for the load to be recorded; without it, each test only gets back the hooks it started with. + +### Changed + +- **The module template bundled with the framework is level with `pollora/module-default` v1.0.0**: its `package.json` asks for the current `@wordpress/*` packages (`block-editor` ^20, `blocks` ^17.1, `components` ^44, `element` ^10.1, `i18n` ^7.1), so that `npm install` in a module written from this copy, when the download fails, prints no peer or deprecation warning. Existing modules are not changed. +- **`pollora:make:block` adds the same `@wordpress/*` versions** to a theme, plugin or module that does not declare these packages. Versions already declared are left as they are. + +### Fixed + +- **In a test process, every application has the theme and plugins that register with Pollora, not only the first** ([#749](https://github.com/Pollora/framework/issues/749)). WordPress includes `functions.php` and plugin files once per process, so from the second test on `pollora_register()` was never called again: no theme views, configuration or providers, and no plugin ones. The calls made while WordPress loads are now remembered and repeated for each later application, and what they hook into `plugins_loaded`, `setup_theme`, `after_setup_theme`, `widgets_init`, `init` and `wp_loaded` runs again, without counting those actions twice; the callbacks of the earlier application they replace are unhooked, with or without `IsolatesWordPressHooks`. Only under unit tests (`APP_ENV=testing`): nothing is repeated elsewhere. Only `pollora_register()` is repeated: other code of `functions.php`, of a plugin file or of `app/inc` still runs once per process, as does a direct call to a registrar. +- **The files of a module's `app/inc` are included once per process.** A module registered a second time, as when a child theme and its parent both call `pollora_register(ModuleType::Theme)`, included them again, which is fatal when one declares a function. +- **`pollora:make:theme`, `pollora:make:plugin` and `pollora:make:module` can authenticate their requests to the GitHub API** ([#747](https://github.com/Pollora/framework/issues/747)). Since 13.45.1 nothing is downloaded when the list of tags cannot be read, and the anonymous limit of 60 requests an hour for each IP address is easily reached from a shared address such as a CI runner. Set `MODULES_GITHUB_TOKEN` (`modules.versions.github_token`, so far only used by the update checks of private modules) and those requests are authenticated. The token goes to `https://api.github.com` only: not to the archive or checksum downloads of github.com, and not along a redirect that leaves the API. It therefore does not make the archive of a private repository downloadable. `GITHUB_TOKEN` is not read: map it to `MODULES_GITHUB_TOKEN` where that is wanted. A refusal for a `403` or `429` now says how to configure the token. **If you already set `MODULES_GITHUB_TOKEN`**, these commands now send it too: a token that is expired or revoked makes them fail with a `401` where the anonymous request would have worked. Without a token nothing changes. + +### Security + +- **WordPress pages bound to one visitor are no longer sent as publicly cacheable. This changes what a shared cache may store.** The framework answered `Cache-Control: public` to every visitor not logged in to WordPress, so a shared cache could store such a page and serve it, its cookies or session included, to someone else. Where it would have answered `public`, it now answers `private, no-cache, must-revalidate` (`no-store` is kept) when `wordpress.sessions` is enabled and the page is served by a `Route::wp()` route that has the session of the `web` group, as one declared in `routes/web.php` does (**enabled is the framework default when the project's `config/wordpress.php` lacks the key**); when a cookie is set or queued, `setcookie()` and `session_start()` included; when the request otherwise has a Laravel session; or when a `Cache-Control` already sent forbids shared storage. **If your front end needs no session, set `'sessions' => false` in `config/wordpress.php`**: the session no longer keeps those pages out of shared caches (`csrf_token()`, `old()` and flash data then have nothing to read from). A plugin that sets a cookie for every visitor now keeps the pages it does so on out of shared caches. Cache directives your application sets on its response are left as they are. If a shared cache stands in front of the site, purge it after upgrading. +- **Redirects of the module update check are handled by the framework when the request carries a token.** They are followed only within the same scheme, host and port, up to five, which covers a renamed repository; any other redirect counts as no answer. Requests without credentials are unchanged. ## [v13.45.1](https://github.com/Pollora/framework/compare/v13.45.0...v13.45.1) - 2026-12-03 diff --git a/config/modules-defaults.php b/config/modules-defaults.php index 1ee5040e..ae1194b7 100644 --- a/config/modules-defaults.php +++ b/config/modules-defaults.php @@ -15,7 +15,9 @@ 'capability' => 'activate_plugins', ], - // Update checks of the modules installed by Composer from a private GitHub repository + // Token of the requests to api.github.com: update checks of the modules installed by Composer + // from a private GitHub repository, and the tag lists read by pollora:make:theme, make:plugin + // and make:module, which GitHub otherwise limits to 60 an hour for each IP address 'versions' => [ 'github_token' => env('MODULES_GITHUB_TOKEN'), ], diff --git a/config/wordpress.php b/config/wordpress.php index 9ea4d5a0..a2ad1f37 100644 --- a/config/wordpress.php +++ b/config/wordpress.php @@ -66,6 +66,7 @@ * Set to false to leave the session, error-sharing and CSRF middleware off * Route::wp() routes; Laravel-native routes are not affected. * csrf_token(), old() and flash data then have nothing to read from. + * While a route has a session, shared caches are told not to store its pages. */ 'sessions' => true, diff --git a/rector.php b/rector.php index 561beb55..b4fd2cd0 100644 --- a/rector.php +++ b/rector.php @@ -3,8 +3,7 @@ declare(strict_types=1); use Rector\Config\RectorConfig; -use Rector\Php83\Rector\ClassMethod\AddOverrideAttributeToOverriddenMethodsRector; -use Rector\TypeDeclaration\Rector\ClassMethod\ScalarParamTypeByMethodCallTypeRector; +use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector; use RectorLaravel\Rector\ArrayDimFetch\ServerVariableToRequestFacadeRector; use RectorLaravel\Rector\FuncCall\UnlinkFuncCallToFileFacadeDeleteRector; use RectorLaravel\Rector\MethodCall\ContainerBindConcreteWithClosureOnlyRector; @@ -17,11 +16,10 @@ __DIR__.'/tests', ]) ->withSkip([ - AddOverrideAttributeToOverriddenMethodsRector::class, - // getAttribute($key) and setAttribute($key) override Eloquent's untyped - // signatures: typing $key would be a fatal incompatible declaration. - ScalarParamTypeByMethodCallTypeRector::class => [ - __DIR__.'/src/Models/Concerns/HasTypedMeta.php', + // An empty method of a test double is there to be called or reflected: + // Rector 2.9.2 removes them. + RemoveEmptyClassMethodRector::class => [ + __DIR__.'/tests', ], // rector-laravel 2.7 turns every unlink() into File::delete(). The // cleanup of temp files, caches and test fixtures runs where the diff --git a/src/Block/UI/Console/MakeBlockCommand.php b/src/Block/UI/Console/MakeBlockCommand.php index 901e9740..2bb9f4c3 100644 --- a/src/Block/UI/Console/MakeBlockCommand.php +++ b/src/Block/UI/Console/MakeBlockCommand.php @@ -42,11 +42,11 @@ class MakeBlockCommand extends Command private const array NPM_DEPENDENCIES = [ '@roots/vite-plugin' => '^2.0.0', 'glob' => '^11.0.0', - '@wordpress/blocks' => '^14.0.0', - '@wordpress/block-editor' => '^14.0.0', - '@wordpress/components' => '^29.0.0', - '@wordpress/element' => '^6.0.0', - '@wordpress/i18n' => '^5.0.0', + '@wordpress/blocks' => '^17.1.0', + '@wordpress/block-editor' => '^20.0.0', + '@wordpress/components' => '^44.0.0', + '@wordpress/element' => '^10.1.0', + '@wordpress/i18n' => '^7.1.0', ]; /** diff --git a/src/Modules/Domain/Exceptions/ModuleException.php b/src/Modules/Domain/Exceptions/ModuleException.php index 5a49f99f..86214b86 100644 --- a/src/Modules/Domain/Exceptions/ModuleException.php +++ b/src/Modules/Domain/Exceptions/ModuleException.php @@ -70,6 +70,31 @@ public static function tagListUnavailable(string $repository, string $reason): s return new self(sprintf('Unable to read the list of tags of %s (%s), so the version to install is unknown. Nothing was downloaded: the default branch has no checksum and is not installed instead. Retry later, or ask for an explicit version (--repo-version), whose checksum is checked as usual.', $repository, $reason)); } + /** + * The list of tags was answered with another status than 200 and 404. + * + * @param string $repository The GitHub repository whose tags could not be listed + * @param int $status HTTP status of the answer + * @param bool $authenticated Whether a token was sent + */ + public static function tagListRefused(string $repository, int $status, bool $authenticated): self + { + $message = self::tagListUnavailable($repository, 'HTTP '.$status)->getMessage(); + + if ($authenticated && in_array($status, [401, 403, 429], true)) { + $message .= ' The request was sent with the token of MODULES_GITHUB_TOKEN (modules.versions.github_token): check that it is still valid, has not reached its rate limit and may read this repository.'; + } elseif (! $authenticated && in_array($status, [403, 429], true)) { + $message .= ' GitHub allows 60 anonymous requests an hour for each IP address: to authenticate them, set MODULES_GITHUB_TOKEN in the environment (modules.versions.github_token) to a GitHub token, and run php artisan config:clear if the configuration is cached.'; + } + + return new self($message); + } + + public static function gitHubTokenMalformed(): self + { + return new self('The GitHub token of MODULES_GITHUB_TOKEN (modules.versions.github_token) holds a space, a line break or a character outside ASCII, which no token has. Nothing was sent: fix or remove the value.'); + } + public static function checksumMismatch(string $url, string $expected, string $actual): self { return new self(sprintf('Checksum mismatch for %s: the release publishes SHA-256 %s, the downloaded archive has %s. Nothing was extracted. Do not install it unless the module author explains the difference.', $url, $expected, $actual)); diff --git a/src/Modules/Infrastructure/Services/ModuleAssetManager.php b/src/Modules/Infrastructure/Services/ModuleAssetManager.php index d98ded73..e33f9fc0 100644 --- a/src/Modules/Infrastructure/Services/ModuleAssetManager.php +++ b/src/Modules/Infrastructure/Services/ModuleAssetManager.php @@ -12,6 +12,7 @@ use Pollora\Asset\Application\Services\AssetManager; use Pollora\Foundation\Support\IncludesFiles; use Psr\Log\LoggerInterface; +use Symfony\Component\Finder\Finder; /** * Generic module asset manager. @@ -144,8 +145,14 @@ public function loadModuleIncludes(string $modulePath): void { $includeDirectory = $modulePath.'/app/inc'; - if (is_dir($includeDirectory)) { - $this->includes($includeDirectory); + if (! is_dir($includeDirectory)) { + return; + } + + // Once per process: a module registered again (a later application of a test process, a parent and a child + // theme) must not declare its functions twice + foreach (Finder::create()->files()->name('*.php')->in($includeDirectory)->sortByName() as $file) { + @include_once $file->getRealPath(); } } diff --git a/src/Modules/Infrastructure/Services/ModuleDownloader.php b/src/Modules/Infrastructure/Services/ModuleDownloader.php index 463d278b..5e4af0ae 100644 --- a/src/Modules/Infrastructure/Services/ModuleDownloader.php +++ b/src/Modules/Infrastructure/Services/ModuleDownloader.php @@ -4,6 +4,9 @@ namespace Pollora\Modules\Infrastructure\Services; +use Illuminate\Http\Client\ConnectionException; +use Illuminate\Http\Client\Response; +use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Http; use Illuminate\Support\Facades\Log; use InvalidArgumentException; @@ -26,6 +29,8 @@ * - Verifies the archive of a tag against the SHA-256 published with its release * (asset `module.sha256`, see {@see ReleaseChecksum}), and warns when there is none * - Refuses to pick a version when the list of tags cannot be read + * - Authenticates its requests to api.github.com, and those only, with the token of + * `modules.versions.github_token` when one is configured * - Generic implementation for both themes and plugins * * Example usage: @@ -36,6 +41,16 @@ */ class ModuleDownloader { + /** + * Root of the GitHub API, the only address the token is sent to. + */ + private const string API_ROOT = 'https://api.github.com/'; + + /** + * Redirects of the API followed with the token: a renamed repository answers one. + */ + private const int MAX_API_REDIRECTS = 5; + /** * GitHub repository full name (e.g. 'owner/repo'). */ @@ -199,7 +214,7 @@ public function downloadForModule(ModuleInterface $module, string $destination): */ public function getAvailableVersions(): array { - $response = Http::get(sprintf('https://api.github.com/repos/%s/tags', $this->repository)); + $response = $this->requestApi(sprintf('repos/%s/tags', $this->repository), $this->gitHubToken()); if (! $response->successful()) { return []; @@ -215,7 +230,7 @@ public function getAvailableVersions(): array */ public function getRepositoryInfo(): array { - $response = Http::get('https://api.github.com/repos/'.$this->repository); + $response = $this->requestApi('repos/'.$this->repository, $this->gitHubToken()); if (! $response->successful()) { throw ModuleException::repositoryUnreachable($this->repository); @@ -290,10 +305,13 @@ protected function getLatestTag(): ?string */ private function listTagNames(): array { + // Read outside the try: a token that cannot be used is not a failed request + $token = $this->gitHubToken(); + try { // 100 rather than the default 30: a repository with more tags than that // could have its highest version on the second page, unreachable here. - $response = Http::get(sprintf('https://api.github.com/repos/%s/tags?per_page=100', $this->repository)); + $response = $this->requestApi(sprintf('repos/%s/tags?per_page=100', $this->repository), $token); } catch (Throwable) { throw ModuleException::tagListUnavailable($this->repository, 'the request failed'); } @@ -303,7 +321,7 @@ private function listTagNames(): array } if ($response->status() !== 200) { - throw ModuleException::tagListUnavailable($this->repository, 'HTTP '.$response->status()); + throw ModuleException::tagListRefused($this->repository, $response->status(), $token !== null); } // Objects are kept as objects: `{}` must not pass for the empty list @@ -321,6 +339,67 @@ private function listTagNames(): array ); } + /** + * The token that authenticates the requests to the API, from `modules.versions.github_token`. + * + * @return string|null Null when none is configured: the requests are then anonymous + * + * @throws ModuleException When the value holds characters no token has. The HTTP + * client would quote it in its own error message. + */ + private function gitHubToken(): ?string + { + $configured = Config::get('modules.versions.github_token'); + $token = is_string($configured) ? trim($configured) : ''; + + if ($token === '') { + return null; + } + + if (preg_match('/^[\x21-\x7E]+$/D', $token) !== 1) { + throw ModuleException::gitHubTokenMalformed(); + } + + return $token; + } + + /** + * GET on the GitHub API. + * + * With a token, redirects are followed here rather than by the HTTP client, and + * only to the API itself: any other one is returned as the answer, so the token + * never leaves api.github.com whatever the client does with its headers. + * + * @param string $path Path below the root of the API + * + * @throws ConnectionException When GitHub cannot be reached + */ + private function requestApi(string $path, #[\SensitiveParameter] ?string $token): Response + { + $url = self::API_ROOT.$path; + + if ($token === null) { + return Http::get($url); + } + + $redirects = 0; + + do { + try { + $response = Http::withToken($token)->withoutRedirecting()->get($url); + } catch (Throwable) { + // Whatever failed, not chained: the original may hold the request, and with it the token + throw new ConnectionException(sprintf('Unable to reach %s.', $url)); + } + + $url = $response->header('Location'); + } while (in_array($response->status(), [301, 302, 303, 307, 308], true) + && str_starts_with($url, self::API_ROOT) + && $redirects++ < self::MAX_API_REDIRECTS); + + return $response; + } + /** * Pick the highest version among tag names. * @@ -386,7 +465,7 @@ private function normaliseVersion(string $name): string */ protected function getDefaultBranch(): string { - $response = Http::get('https://api.github.com/repos/'.$this->repository); + $response = $this->requestApi('repos/'.$this->repository, $this->gitHubToken()); if (! $response->successful()) { return 'main'; diff --git a/src/Modules/stubs/module-default/package.json b/src/Modules/stubs/module-default/package.json index 6f39b08c..976fc984 100644 --- a/src/Modules/stubs/module-default/package.json +++ b/src/Modules/stubs/module-default/package.json @@ -10,11 +10,11 @@ "@pollora/vite-config": "^1.0.0", "@roots/vite-plugin": "^2.0.0", "@tailwindcss/vite": "^4.2.3", - "@wordpress/block-editor": "^14.0.0", - "@wordpress/blocks": "^14.0.0", - "@wordpress/components": "^29.0.0", - "@wordpress/element": "^6.0.0", - "@wordpress/i18n": "^5.0.0", + "@wordpress/block-editor": "^20.0.0", + "@wordpress/blocks": "^17.1.0", + "@wordpress/components": "^44.0.0", + "@wordpress/element": "^10.1.0", + "@wordpress/i18n": "^7.1.0", "laravel-vite-plugin": "^3.0.1", "tailwindcss": "^4.2.3", "vite": "^8.0.9" diff --git a/src/Route/Infrastructure/Middleware/WordPressHeaders.php b/src/Route/Infrastructure/Middleware/WordPressHeaders.php index f562155f..ee789816 100644 --- a/src/Route/Infrastructure/Middleware/WordPressHeaders.php +++ b/src/Route/Infrastructure/Middleware/WordPressHeaders.php @@ -22,6 +22,9 @@ * 3. Sets public cache directives for cacheable HTML responses served * to non-authenticated visitors, unless the response is marked private * through the `pollora/route/private_response` filter + * 4. Marks private instead a response it would have made public that is bound + * to its visitor: it sets a cookie, its request has a session, or a + * `Cache-Control` already sent forbids shared storage * * Cache TTL is resolved from configuration in this order: * - `wordpress.cache.ttl.` — per WordPress condition (e.g. `is_front_page`, `is_single`) @@ -87,7 +90,11 @@ public function handle(Request $request, Closure $next): SymfonyResponse if ($this->isMarkedPrivate($request, $response)) { $this->applyPrivateCacheHeaders($response); } elseif (! $hasExplicitCacheConfig && $this->shouldApplyPublicCache($response)) { - $this->applyPublicCacheHeaders($response); + if ($this->isBoundToVisitor($request, $response)) { + $this->applyPrivateCacheHeaders($response); + } else { + $this->applyPublicCacheHeaders($response); + } } return $response; @@ -108,6 +115,25 @@ private function isMarkedPrivate(Request $request, SymfonyResponse $response): b && (bool) apply_filters('pollora/route/private_response', false, $request, $response); } + /** + * Whether the response belongs to this visitor, whoever is logged in. + * + * A cookie may be set by `setcookie()` or `session_start()`, which only PHP + * knows of, or sit on the response. A session of the request, and a cookie + * queued with Laravel, get theirs from middleware that runs after this one + * (the `web` group around a route of routes/web.php): the response has no + * cookie yet. A `Cache-Control` sent with `header()` that forbids shared + * storage, as WordPress sends for a password protected post, stays in the + * answer beside the one of the response, and so has the last word. + */ + private function isBoundToVisitor(Request $request, SymfonyResponse $response): bool + { + return $request->hasSession() + || $response->headers->getCookies() !== [] + || (app()->bound('cookie') && resolve('cookie')->getQueuedCookies() !== []) + || preg_grep('/^(?:Set-Cookie:|Cache-Control:.*\b(?:private|no-store|no-cache)\b)/i', $this->sentHeaders()) !== []; + } + /** * Forbid shared caches to store the response. * diff --git a/src/Testing/IsolatesWordPressHooks.php b/src/Testing/IsolatesWordPressHooks.php new file mode 100644 index 00000000..a368f4c8 --- /dev/null +++ b/src/Testing/IsolatesWordPressHooks.php @@ -0,0 +1,46 @@ +wordPressHooksAtStart = WordPressHookState::capture(); + } + + protected function tearDownIsolatesWordPressHooks(): void + { + $atStart = $this->wordPressHooksAtStart; + + if (! $atStart instanceof WordPressHookState) { + return; + } + + $kept = WordPressLoadRecorder::loaded()?->with($atStart, OncePerProcessHooks::isStaticMethod(...)) ?? $atStart; + $atEnd = WordPressHookState::capture(); + + $kept + ->with($atStart, OncePerProcessHooks::belongsToPackage(...)) + ->with($atEnd, OncePerProcessHooks::belongsToPackage(...)) + ->restore(); + + $this->wordPressHooksAtStart = null; + } +} diff --git a/src/Testing/ModuleRegistrations.php b/src/Testing/ModuleRegistrations.php new file mode 100644 index 00000000..d23eae24 --- /dev/null +++ b/src/Testing/ModuleRegistrations.php @@ -0,0 +1,111 @@ + */ + private static array $registrations = []; + + /** What the load hooked, the framework's own callbacks included */ + private static ?WordPressHookState $hookedByLoad = null; + + private static ?WordPressHookState $hookedByLastReplay = null; + + public static function startRecording(): void + { + self::$recording = true; + } + + public static function stopRecording(): void + { + self::$recording = false; + } + + public static function keepHooksOfLoad(WordPressHookState $hooks): void + { + if (self::$registrations !== []) { + self::$hookedByLoad = $hooks; + } + } + + /** + * Remembers a call of `pollora_register()`. Does nothing outside of a recorded load. + */ + public static function record(ModuleType $type, ?string $name, ?string $path): void + { + if (! self::$recording) { + return; + } + + // A parent and a child theme both register the theme: once is enough + self::$registrations[$type->value.':'.$name] ??= [$type, $name, $path]; + } + + /** + * Registers the recorded modules in the current application, then runs what they hooked into the actions the load + * already fired. + */ + public static function replay(): void + { + if (self::$registrations === []) { + return; + } + + $before = WordPressHookState::capture(); + + foreach (self::$registrations as [$type, $name, $path]) { + pollora_register($type, $name, $path); + } + + foreach (self::LOAD_ACTIONS as $action) { + if (($GLOBALS['wp_actions'][$action] ?? 0) > 0) { + $before->runCallbacksAddedTo($action); + } + } + + // The callbacks of the registrations replaced here: bound to an application that is gone, or about to run the + // same code twice + $added = WordPressHookState::capture()->addedSince($before); + + self::$hookedByLoad?->removeRegisteredAgain($before); + self::$hookedByLastReplay?->removeRegisteredAgain($before); + self::$hookedByLastReplay = $added; + } + + public static function forget(): void + { + self::$recording = false; + self::$registrations = []; + self::$hookedByLoad = null; + self::$hookedByLastReplay = null; + } +} diff --git a/src/Testing/OncePerProcessHooks.php b/src/Testing/OncePerProcessHooks.php new file mode 100644 index 00000000..c0ee6d6b --- /dev/null +++ b/src/Testing/OncePerProcessHooks.php @@ -0,0 +1,83 @@ + + */ + private static array $removedHandlers = []; + + public static function isStaticMethod(mixed $callback): bool + { + if (is_string($callback)) { + return str_contains($callback, '::'); + } + + return is_array($callback) && is_string($callback[0] ?? null); + } + + public static function belongsToPackage(mixed $callback): bool + { + if (is_array($callback)) { + $object = $callback[0] ?? null; + + return $object instanceof WordPressRoleInjector + || $object instanceof WordPressRoleLabelTranslator + || $object instanceof ScheduleEngine + || $object instanceof CronInterceptor; + } + + if (! $callback instanceof \Closure) { + return false; + } + + $function = new \ReflectionFunction($callback); + $object = $function->getClosureThis(); + + if ($object instanceof CronInterceptor) { + return true; + } + + if (! $object instanceof ScheduleEngine) { + return false; + } + + // A handler given as a closure comes with its application, and the next one attaches its own + $handler = $function->getStaticVariables()['handler'] ?? null; + + if (! $handler instanceof \Closure) { + return true; + } + + if (! in_array($handler, self::$removedHandlers, true)) { + self::$removedHandlers[] = $handler; + } + + return false; + } +} diff --git a/src/Testing/WordPressHookState.php b/src/Testing/WordPressHookState.php new file mode 100644 index 00000000..0ab0a258 --- /dev/null +++ b/src/Testing/WordPressHookState.php @@ -0,0 +1,248 @@ + $hooks + * @param array $actions + * @param array $filters + */ + private function __construct(private array $hooks, private array $actions, private array $filters) {} + + public static function capture(): self + { + return new self( + // Hooks set before plugin.php was included are still arrays: the load turns them into WP_Hook + self::copy(array_filter($GLOBALS['wp_filter'] ?? [], static fn (mixed $hook): bool => $hook instanceof \WP_Hook)), + $GLOBALS['wp_actions'] ?? [], + $GLOBALS['wp_filters'] ?? [], + ); + } + + /** + * The callbacks of this state that an earlier one did not have, with the counts of this state. + */ + public function addedSince(self $before): self + { + $hooks = self::copy($this->hooks); + + foreach ($before->hooks as $name => $hook) { + if (! isset($hooks[$name])) { + continue; + } + + foreach ($hook->callbacks as $priority => $callbacks) { + foreach ($callbacks as $callback) { + $hooks[$name]->remove_filter($name, $callback['function'], $priority); + } + } + + if ($hooks[$name]->callbacks === []) { + unset($hooks[$name]); + } + } + + return new self($hooks, $this->actions, $this->filters); + } + + /** + * This state, without the callbacks bound to an object whose code is in a directory. + */ + public function withoutObjectCallbacksFrom(string $directory): self + { + $directory = rtrim($directory, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR; + $hooks = self::copy($this->hooks); + + foreach ($this->hooks as $name => $hook) { + foreach ($hook->callbacks as $priority => $callbacks) { + foreach ($callbacks as $callback) { + if (str_starts_with((string) $this->objectCallbackFile($callback['function']), $directory)) { + $hooks[$name]->remove_filter($name, $callback['function'], $priority); + } + } + } + + if ($hooks[$name]->callbacks === []) { + unset($hooks[$name]); + } + } + + return new self($hooks, $this->actions, $this->filters); + } + + /** + * This state, plus the callbacks of another one that a filter accepts. + * + * @param \Closure(mixed): bool $accepts + */ + public function with(self $other, \Closure $accepts): self + { + $hooks = self::copy($this->hooks); + + foreach ($other->hooks as $name => $hook) { + foreach ($hook->callbacks as $priority => $callbacks) { + foreach ($callbacks as $id => $callback) { + if (isset($hooks[$name]->callbacks[$priority][$id]) || ! $accepts($callback['function'])) { + continue; + } + + $hooks[$name] ??= new \WP_Hook; + $hooks[$name]->add_filter($name, $callback['function'], $priority, $callback['accepted_args']); + } + } + } + + return new self($hooks, $this->actions, $this->filters); + } + + /** + * Runs the callbacks an action gained since this state, and those only, in the order of their priorities. + * The others stay hooked, and the action is not counted as fired once more. + */ + public function runCallbacksAddedTo(string $action): void + { + $hook = $GLOBALS['wp_filter'][$action] ?? null; + + if (! $hook instanceof \WP_Hook) { + return; + } + + $added = clone $hook; + + foreach (isset($this->hooks[$action]) ? $this->hooks[$action]->callbacks : [] as $priority => $callbacks) { + foreach ($callbacks as $callback) { + $added->remove_filter($action, $callback['function'], $priority); + } + } + + if ($added->callbacks === []) { + return; + } + + $GLOBALS['wp_filter'][$action] = $added; + $GLOBALS['wp_current_filter'][] = $action; + + try { + $added->do_action(['']); + } finally { + array_pop($GLOBALS['wp_current_filter']); + + // What the callbacks hooked into the action they were running in + foreach ($added->callbacks as $priority => $callbacks) { + foreach ($callbacks as $id => $callback) { + if (! isset($hook->callbacks[$priority][$id])) { + $hook->add_filter($action, $callback['function'], $priority, $callback['accepted_args']); + } + } + } + + $GLOBALS['wp_filter'][$action] = $hook; + } + } + + /** + * Unhooks the callbacks of this state that WordPress was given again since another one: the same code, at the same + * priority, from a new object. A theme class hooked during the load would otherwise run once for the application + * that loaded WordPress and once for the current one. + */ + public function removeRegisteredAgain(self $since): void + { + foreach ($this->hooks as $name => $hook) { + $current = $GLOBALS['wp_filter'][$name] ?? null; + + if (! $current instanceof \WP_Hook) { + continue; + } + + foreach ($hook->callbacks as $priority => $callbacks) { + $added = array_diff_key($current->callbacks[$priority] ?? [], ($since->hooks[$name] ?? null)?->callbacks[$priority] ?? []); + $code = array_filter(array_map(fn (array $callback): ?string => $this->code($callback['function']), $added)); + + foreach (array_diff_key($callbacks, $added) as $callback) { + if (\in_array($this->code($callback['function']), $code, true)) { + $current->remove_filter($name, $callback['function'], $priority); + } + } + } + } + } + + /** + * Put WordPress back in this state. Callbacks removed since are back, in their order; the others are gone. + */ + public function restore(): void + { + $GLOBALS['wp_filter'] = self::copy($this->hooks); + $GLOBALS['wp_actions'] = $this->actions; + $GLOBALS['wp_filters'] = $this->filters; + } + + /** + * The file holding the code of a callback bound to an object, null for any other callback. + */ + private function objectCallbackFile(mixed $callback): ?string + { + if ($callback instanceof \Closure) { + $function = new \ReflectionFunction($callback); + + return $function->getClosureThis() === null ? null : ($function->getFileName() ?: null); + } + + if (is_object($callback)) { + $callback = [$callback, '__invoke']; + } + + if (! is_array($callback) || ! is_object($callback[0] ?? null) || ! method_exists($callback[0], $callback[1])) { + return null; + } + + return (new \ReflectionMethod($callback[0], $callback[1]))->getFileName() ?: null; + } + + /** + * What tells that two callbacks of different objects are the same code, null for a callback without an object: + * WordPress already keys those by name. + */ + private function code(mixed $callback): ?string + { + if ($callback instanceof \Closure) { + $function = new \ReflectionFunction($callback); + $object = $function->getClosureThis(); + + return implode(':', [ + $object === null ? '' : $object::class, + (string) $function->getFileName(), + (string) $function->getStartLine(), + $function->getName(), + ]); + } + + if (\is_object($callback)) { + return $callback::class.'::__invoke'; + } + + return \is_array($callback) && \is_object($callback[0] ?? null) ? $callback[0]::class.'::'.$callback[1] : null; + } + + /** + * A `WP_Hook` is changed in place, so a state keeps and gives copies. + * + * @param array $hooks + * @return array + */ + private static function copy(array $hooks): array + { + return array_map(static fn (\WP_Hook $hook): \WP_Hook => clone $hook, $hooks); + } +} diff --git a/src/Testing/WordPressLoadRecorder.php b/src/Testing/WordPressLoadRecorder.php new file mode 100644 index 00000000..287649df --- /dev/null +++ b/src/Testing/WordPressLoadRecorder.php @@ -0,0 +1,88 @@ +addedSince($before); + ModuleRegistrations::keepHooksOfLoad($added); + + self::$loaded = $added->withoutObjectCallbacksFrom(\dirname(__DIR__)); + } + + /** + * Null while no load was recorded. + */ + public static function loaded(): ?WordPressHookState + { + return self::$loaded; + } + + public static function forget(): void + { + self::$before = null; + self::$loaded = null; + ModuleRegistrations::forget(); + } +} diff --git a/src/VersionCheck/Infrastructure/Sources/HttpGet.php b/src/VersionCheck/Infrastructure/Sources/HttpGet.php index 28f4957d..a920d20c 100644 --- a/src/VersionCheck/Infrastructure/Sources/HttpGet.php +++ b/src/VersionCheck/Infrastructure/Sources/HttpGet.php @@ -6,22 +6,36 @@ /** * A JSON GET through WordPress's HTTP API, which honours the site's proxy settings. + * + * WordPress sends the headers of a request again when it follows a redirect, + * whatever host it leads to. A request with headers of its own beyond `Accept` + * therefore has its redirects followed here, within the origin it was sent to. */ class HttpGet { /** - * @param array $headers + * Redirects followed for a request with such headers: a renamed GitHub repository answers one. */ - public function json(string $url, array $headers = []): mixed + private const int MAX_REDIRECTS = 5; + + /** + * @param array $headers Any header but `Accept` is treated as a credential + * @return mixed The decoded body of a 200 answer, null otherwise: a redirect that is not followed included + */ + public function json(string $url, #[\SensitiveParameter] array $headers = []): mixed { if (! function_exists('wp_remote_get')) { return null; } - $response = wp_remote_get($url, [ + $arguments = [ 'timeout' => 5, 'headers' => ['Accept' => 'application/json', ...$headers], - ]); + ]; + + $response = $this->carriesCredentials($headers) + ? $this->getWithinOrigin($url, $arguments) + : wp_remote_get($url, $arguments); if (is_wp_error($response) || (int) wp_remote_retrieve_response_code($response) !== 200) { return null; @@ -29,4 +43,46 @@ public function json(string $url, array $headers = []): mixed return json_decode((string) wp_remote_retrieve_body($response), true); } + + /** + * Whether a header may identify the caller. Only `Accept` is known not to, so + * that a token sent under a name of its own is covered too. + * + * @param array $headers + */ + private function carriesCredentials(#[\SensitiveParameter] array $headers): bool + { + return array_filter(array_keys($headers), static fn (string $name): bool => strtolower($name) !== 'accept') !== []; + } + + /** + * A GET whose redirects are followed only to URLs written under the same + * `scheme://host[:port]/` as the first one. Any other redirect, a relative one + * included, is returned as the answer. + * + * The comparison is textual: nothing depends on how the transport would read + * a URL written another way. + * + * @param array $arguments + * @return mixed What wp_remote_get() answered last + */ + private function getWithinOrigin(string $url, #[\SensitiveParameter] array $arguments): mixed + { + $origin = preg_match('#^https?://[^/?\#\\\\]+#i', $url, $matches) === 1 ? $matches[0].'/' : null; + $arguments['redirection'] = 0; + $redirects = 0; + + do { + $response = wp_remote_get($url, $arguments); + + if ($origin === null || is_wp_error($response) + || ! in_array((int) wp_remote_retrieve_response_code($response), [301, 302, 303, 307, 308], true)) { + break; + } + + $url = wp_remote_retrieve_header($response, 'location'); + } while (is_string($url) && str_starts_with($url, $origin) && $redirects++ < self::MAX_REDIRECTS); + + return $response; + } } diff --git a/src/WordPress/Bootstrap.php b/src/WordPress/Bootstrap.php index 9fea8a04..e55de0f4 100644 --- a/src/WordPress/Bootstrap.php +++ b/src/WordPress/Bootstrap.php @@ -14,6 +14,7 @@ use Pollora\Hook\Domain\Contract\Action; use Pollora\Support\Facades\Constant; use Pollora\Support\WordPress; +use Pollora\Testing\WordPressLoadRecorder; use Pollora\WordPress\Events\WordPressBooting; class Bootstrap @@ -184,7 +185,19 @@ private function loadWordPressSettings(): void event(new WordPressBooting($lightweight)); if (! $this->consoleDetectionService->isWpCli()) { + // Tests using IsolatesWordPressHooks need to know which hooks the load added + $record = app()->runningUnitTests(); + $alreadyLoaded = $record && in_array(realpath(ABSPATH.'wp-settings.php'), get_included_files(), true); + + if ($record) { + WordPressLoadRecorder::start(); + } + require_once ABSPATH.'wp-settings.php'; + + if ($record) { + WordPressLoadRecorder::finish($alreadyLoaded); + } } } diff --git a/src/helpers.php b/src/helpers.php index 95e49030..8b40daaf 100755 --- a/src/helpers.php +++ b/src/helpers.php @@ -7,6 +7,7 @@ use Pollora\Modules\Domain\Enums\ModuleType; use Pollora\Plugin\Application\Services\PluginRegistrar; use Pollora\Support\RecursiveMenuIterator; +use Pollora\Testing\ModuleRegistrations; use Pollora\Theme\Domain\Contracts\ThemeRegistrarInterface; if (! function_exists('pollora_register')) { @@ -45,6 +46,9 @@ function pollora_register(ModuleType $type, ?string $name = null, ?string $path return; } + // Only records while a test process loads WordPress, which includes the calling file once + ModuleRegistrations::record($type, $name, $path); + try { match ($type) { ModuleType::Theme => resolve(ThemeRegistrarInterface::class)->register(), diff --git a/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php b/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php index 6a507221..864c1bab 100644 --- a/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php +++ b/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php @@ -136,6 +136,17 @@ public function log($level, string|Stringable $message, array $context = []): vo unset($GLOBALS['pollora_inc_order']); }); + it('includes a file once, however often its module is registered', function (): void { + File::ensureDirectoryExists($this->module.'/app/inc'); + $function = 'pollora_inc_'.str_replace('.', '', uniqid('', true)); + file_put_contents($this->module.'/app/inc/helpers.php', "app))->loadModuleIncludes($this->module); + (new ModuleAssetManager($this->app))->loadModuleIncludes($this->module); + + expect($function())->toBe('declared'); + }); + it('has no include to load when app/inc does not exist', function (): void { (new ModuleAssetManager($this->app))->loadModuleIncludes($this->module); diff --git a/tests/Feature/ModuleScaffold/ModuleDownloaderTokenTest.php b/tests/Feature/ModuleScaffold/ModuleDownloaderTokenTest.php new file mode 100644 index 00000000..7fc3d288 --- /dev/null +++ b/tests/Feature/ModuleScaffold/ModuleDownloaderTokenTest.php @@ -0,0 +1,280 @@ +tmp.'/scratch/'.$filename; + } + + public function defaultBranch(): string + { + return $this->getDefaultBranch(); + } + }; +} + +function tokenArchive(string $path): string +{ + $zip = new ZipArchive; + $zip->open($path, ZipArchive::CREATE); + $zip->addFromString('theme-default-1.0.0/style.css', '/* theme */'); + $zip->close(); + + return (string) file_get_contents($path); +} + +/** + * The Authorization header of every request sent, by URL. + * + * @return array + */ +function sentAuthorizations(): array +{ + return Http::recorded() + ->mapWithKeys(fn (array $pair): array => [$pair[0]->url() => $pair[0]->header('Authorization')[0] ?? '']) + ->all(); +} + +/** + * The refusal of a download whose version has to be read from the list of tags. + */ +function tagRefusal(string $tmp): ModuleException +{ + try { + tokenDownloader($tmp)->downloadAndExtract($tmp.'/themes'); + } catch (ModuleException $moduleException) { + return $moduleException; + } + + throw new RuntimeException('The download was not refused.'); +} + +beforeEach(function (): void { + $this->tmp = sys_get_temp_dir().'/pollora-token-'.uniqid(); + File::ensureDirectoryExists($this->tmp); + config(['modules.versions.github_token' => API_TOKEN]); + Http::preventStrayRequests(); +}); + +afterEach(function (): void { + File::deleteDirectory($this->tmp); +}); + +describe('ModuleDownloader with a GitHub token', function (): void { + it('sends it to api.github.com and nowhere else', function (): void { + $archive = tokenArchive($this->tmp.'/source.zip'); + Http::fake([ + API_TAGS => Http::response([['name' => 'v1.0.0']]), + 'https://'.TAG_ARCHIVE => Http::response($archive), + 'https://'.TAG_CHECKSUM => Http::response('', 302, ['Location' => 'https://'.TAG_STORAGE]), + 'https://'.TAG_STORAGE => Http::response(hash('sha256', $archive)), + ]); + + tokenDownloader($this->tmp)->downloadAndExtract($this->tmp.'/themes'); + + expect(sentAuthorizations())->toBe([ + 'https://api.github.com/repos/Pollora/theme-default/tags?per_page=100' => 'Bearer '.API_TOKEN, + 'https://'.TAG_ARCHIVE => '', + 'https://'.TAG_CHECKSUM => '', + 'https://'.TAG_STORAGE => '', + ]); + }); + + it('authenticates every other request to the API', function (): void { + Http::fake([ + API_TAGS => Http::response([['name' => 'v1.0.0']]), + API_REPOSITORY => Http::response(['default_branch' => 'trunk']), + ]); + $downloader = tokenDownloader($this->tmp); + + expect($downloader->getAvailableVersions())->toBe(['v1.0.0']) + ->and($downloader->getRepositoryInfo())->toBe(['default_branch' => 'trunk']) + ->and($downloader->defaultBranch())->toBe('trunk') + ->and(array_unique(array_values(sentAuthorizations())))->toBe(['Bearer '.API_TOKEN]); + Http::assertSentCount(3); + }); + + it('drops the white space a secrets file leaves around it', function (): void { + config(['modules.versions.github_token' => ' '.API_TOKEN."\n"]); + Http::fake([API_TAGS => Http::response([])]); + + tokenDownloader($this->tmp)->getAvailableVersions(); + + Http::assertSent(fn (Request $request): bool => $request->header('Authorization') === ['Bearer '.API_TOKEN]); + }); + + it('sends nothing when there is no token', function (mixed $token): void { + config(['modules.versions.github_token' => $token]); + Http::fake([API_TAGS => Http::response([['name' => 'v1.0.0']])]); + + tokenDownloader($this->tmp)->getAvailableVersions(); + + Http::assertSent(fn (Request $request): bool => ! $request->hasHeader('Authorization')); + })->with([ + 'unset' => [null], + 'empty' => [''], + 'blank' => [" \n"], + 'not a string' => [false], + ]); + + it('refuses a value no header can carry, without showing it or sending anything', function (string $token): void { + config(['modules.versions.github_token' => $token]); + Http::fake(); + + $refusal = tagRefusal($this->tmp); + + expect($refusal->getMessage())->toContain('MODULES_GITHUB_TOKEN', 'Nothing was sent') + ->not->toContain('sentinel'); + Http::assertNothingSent(); + })->with([ + 'line break inside' => ["sentinel\r\nX-Injected: 1"], + 'space inside' => ['sentinel value'], + 'outside ASCII' => ["sentinel-\u{00E9}"], + ]); + + it('follows a redirect that stays on the API, still authenticated', function (int $status): void { + Http::fake([ + API_TAGS => Http::response('', $status, ['Location' => 'https://api.github.com/repositories/42/tags?per_page=100']), + 'api.github.com/repositories/42/tags*' => Http::response([['name' => 'v2.0.0']]), + ]); + + expect(tokenDownloader($this->tmp)->getAvailableVersions())->toBe(['v2.0.0']) + ->and(array_unique(array_values(sentAuthorizations())))->toBe(['Bearer '.API_TOKEN]); + Http::assertSentCount(2); + })->with([301, 302, 303, 307, 308]); + + it('does not follow a redirect that leaves the API, and installs nothing', function (string $location): void { + Http::fake([API_TAGS => Http::response('', 301, ['Location' => $location])]); + + expect(tagRefusal($this->tmp)->getMessage())->toContain('(HTTP 301)'); + Http::assertSentCount(1); + })->with([ + 'another host' => ['https://example.com/tags'], + 'a look-alike host' => ['https://api.github.com.example.com/tags'], + 'user info before another host' => ['https://api.github.com@example.com/tags'], + 'the API in a query string' => ['https://example.com/?u=https://api.github.com/'], + 'plain HTTP' => ['http://api.github.com/repositories/42/tags'], + 'github.com' => ['https://github.com/Pollora/theme-default/tags'], + 'no location' => [''], + ]); + + it('only follows a Location on a redirect status', function (): void { + Http::fake([API_TAGS => Http::response('', 403, ['Location' => 'https://api.github.com/repositories/42/tags'])]); + + expect(tagRefusal($this->tmp)->getMessage())->toContain('(HTTP 403)'); + Http::assertSentCount(1); + }); + + it('gives up after five redirects', function (): void { + Http::fake(['api.github.com/*' => Http::response('', 302, ['Location' => 'https://api.github.com/loop'])]); + + expect(tagRefusal($this->tmp)->getMessage())->toContain('(HTTP 302)'); + Http::assertSentCount(6); + }); + + it('says which setting to check when GitHub refuses the request', function (int $status): void { + Http::fake([API_TAGS => Http::response(['message' => 'Bad credentials'], $status)]); + + expect(tagRefusal($this->tmp)->getMessage()) + ->toContain('(HTTP '.$status.')', 'Nothing was downloaded', '--repo-version', 'sent with the token', 'MODULES_GITHUB_TOKEN', 'modules.versions.github_token') + ->not->toContain('anonymous', API_TOKEN); + })->with([401, 403, 429]); + + it('keeps it out of the console and the log', function (Closure $answer): void { + Log::spy(); + Http::fake([API_TAGS => $answer()]); + $output = new BufferedOutput; + + (new ModuleScaffolderService)->downloadAndScaffold('Pollora/theme-default', $this->tmp.'/themes', $this->tmp.'/themes/demo', [], null, $output); + + expect($output->fetch())->toContain('Failed to download: Unable to read the list of tags')->not->toContain(API_TOKEN); + + foreach (['emergency', 'alert', 'critical', 'error', 'warning', 'notice', 'info', 'debug', 'log'] as $level) { + Log::shouldNotHaveReceived($level); + } + })->with([ + 'refused' => [fn () => Http::response('', 403)], + 'unreachable' => [fn () => Http::failedConnection('Could not resolve host')], + ]); + + it('lets a connection failure through without the request that carried it', function (): void { + Http::fake([API_REPOSITORY => Http::failedConnection('Could not resolve host')]); + + try { + tokenDownloader($this->tmp)->getRepositoryInfo(); + } catch (ConnectionException $connectionException) { + expect($connectionException->getMessage())->toBe('Unable to reach https://api.github.com/repos/Pollora/theme-default.') + ->and($connectionException->getPrevious())->toBeNull(); + + return; + } + + $this->fail('The connection failure was swallowed.'); + }); +}); + +describe('ModuleDownloader failing in an unforeseen way with a token', function (): void { + it('lets nothing of the original failure through', function (): void { + // Stands for any failure the client does not turn into a connection error + Http::fake(fn (Request $request): never => throw new LogicException('Sent '.$request->header('Authorization')[0])); + + try { + tokenDownloader($this->tmp)->getRepositoryInfo(); + } catch (ConnectionException $connectionException) { + expect($connectionException->getMessage())->not->toContain(API_TOKEN) + ->and($connectionException->getPrevious())->toBeNull(); + + return; + } + + $this->fail('The failure was swallowed.'); + }); +}); + +describe('ModuleDownloader refused without a token', function (): void { + beforeEach(function (): void { + config(['modules.versions.github_token' => null]); + }); + + it('says how to configure one when the rate limit may be the cause', function (int $status): void { + Http::fake([API_TAGS => Http::response('', $status)]); + + expect(tagRefusal($this->tmp)->getMessage()) + ->toContain('(HTTP '.$status.')', 'Nothing was downloaded', '--repo-version', '60 anonymous requests an hour', 'MODULES_GITHUB_TOKEN', 'modules.versions.github_token'); + })->with([403, 429]); + + it('does not mention it when the status has nothing to do with it', function (int $status): void { + Http::fake([API_TAGS => Http::response('', $status)]); + + expect(tagRefusal($this->tmp)->getMessage()) + ->toContain('(HTTP '.$status.')') + ->not->toContain('MODULES_GITHUB_TOKEN'); + })->with([401, 500, 503]); +}); diff --git a/tests/Feature/Testing/IsolatesWordPressHooksTest.php b/tests/Feature/Testing/IsolatesWordPressHooksTest.php new file mode 100644 index 00000000..7ebcb905 --- /dev/null +++ b/tests/Feature/Testing/IsolatesWordPressHooksTest.php @@ -0,0 +1,59 @@ + null); + + fireHook('probe_footer'); + fireHook('probe_must_use'); + + expect(HookingServiceProvider::$handled)->toHaveCount(2) + ->and(HookingServiceProvider::$mustUseRuns)->toBe(1); + + // The next one finds nothing of that application, nor of what the test added + $this->bootNextApplication(); + + HookingServiceProvider::$handled = []; + + fireHook('probe_footer'); + + $current = resolve('probe.name'); + + expect(HookingServiceProvider::$handled)->toBe([$current, $current]) + ->and(hookedCallbacks())->toBe(['probe_must_use' => 1, 'probe_footer' => 2]) + ->and($GLOBALS['wp_actions'])->toBe(['probe_footer' => 1]); + + // The one after keeps what loading WordPress added, and as many callbacks + $this->bootNextApplication(); + + fireHook('probe_must_use'); + + expect(HookingServiceProvider::$mustUseRuns)->toBe(2) + ->and(hookedCallbacks())->toBe(['probe_must_use' => 1, 'probe_footer' => 2]) + ->and($GLOBALS['wp_actions'])->toBe(['probe_must_use' => 1]); +}); diff --git a/tests/Feature/Testing/ModuleRegistrationsTest.php b/tests/Feature/Testing/ModuleRegistrationsTest.php new file mode 100644 index 00000000..0a402bfd --- /dev/null +++ b/tests/Feature/Testing/ModuleRegistrationsTest.php @@ -0,0 +1,94 @@ +app); +}); + +afterEach(function (): void { + afterLoadingModules(); +}); + +/** + * @param Closure(): void $files what the load includes, nothing for a later one + */ +function loadWordPress(?Closure $files = null): void +{ + WordPressLoadRecorder::start(); + + if ($files instanceof Closure) { + $files(); + } + + WordPressLoadRecorder::finish(! $files instanceof Closure); +} + +it('repeats each registration of the load once, with its arguments, in their order', function (): void { + loadWordPress(function (): void { + pollora_register(ModuleType::Plugin, 'one', '/plugins/one'); + pollora_register(ModuleType::Theme); + pollora_register(ModuleType::Plugin, 'two', '/plugins/two'); + pollora_register(ModuleType::Theme); + pollora_register(ModuleType::Plugin, 'one', '/elsewhere/one'); + }); + takeModuleLog(); + + loadWordPress(); + + expect(takeModuleLog())->toBe([ + 'plugin one registered from /plugins/one', + 'theme registered', + 'plugin two registered from /plugins/two', + ]); +}); + +it('unhooks what the load, then each replay, had hooked and the next registration hooks again', function (): void { + loadWordPress(function (): void { + pollora_register(ModuleType::Theme); + }); + + foreach (['second', 'third'] as $ignored) { + loadWordPress(); + takeModuleLog(); + + fireHook('probe_content'); + + expect(takeModuleLog())->toHaveCount(1); + } +}); + +it('repeats nothing that was registered outside of a load', function (): void { + loadWordPress(static function (): void {}); + pollora_register(ModuleType::Theme); + takeModuleLog(); + + loadWordPress(); + + expect(takeModuleLog())->toBe([]) + ->and(hookedCallbacks()['probe_content'])->toBe(1); +}); + +it('forgets the registrations with the load', function (): void { + WordPressLoadRecorder::start(); + pollora_register(ModuleType::Theme); + WordPressLoadRecorder::forget(); + // No longer recording either + pollora_register(ModuleType::Theme); + takeModuleLog(); + + loadWordPress(); + + expect(takeModuleLog())->toBe([]); +}); diff --git a/tests/Feature/Testing/ReplaysModuleRegistrationsTest.php b/tests/Feature/Testing/ReplaysModuleRegistrationsTest.php new file mode 100644 index 00000000..2928ddf8 --- /dev/null +++ b/tests/Feature/Testing/ReplaysModuleRegistrationsTest.php @@ -0,0 +1,65 @@ +toContain('theme registered', 'core init', 'theme init') + ->and(config('theme.menus'))->toBe(['primary']); + + // The next one registers them again, and runs only what they hooked into the actions of the load + $this->bootNextApplication(); + + expect(takeModuleLog())->toBe(REPLAYED) + ->and(config('theme.menus'))->toBe(['primary']) + ->and(config('theme.templates'))->toBe(['wide']) + ->and($GLOBALS['wp_actions']['init'])->toBe(1) + ->and($GLOBALS['wp_filter']['init']->callbacks)->toHaveKeys([10, 20, 50]); + + $counts = hookedCallbacks(); + + // The theme class hooked by the first application is replaced, not joined + fireHook('probe_content'); + + expect(takeModuleLog())->toBe(['content of application '.spl_object_id(app())]); + + // Outside of the load: nothing to repeat + pollora_register(ModuleType::Plugin, 'from-a-test', '/plugins/from-a-test'); + takeModuleLog(); + + // Every later one gets the same theme and as many callbacks + $this->bootNextApplication(); + + expect(takeModuleLog())->toBe(REPLAYED) + ->and(config('theme.menus'))->toBe(['primary']) + ->and(hookedCallbacks())->toBe($counts); + + fireHook('probe_content'); + + expect(takeModuleLog())->toBe(['content of application '.spl_object_id(app())]); +}); diff --git a/tests/Feature/Testing/ReplaysModuleRegistrationsWithoutIsolationTest.php b/tests/Feature/Testing/ReplaysModuleRegistrationsWithoutIsolationTest.php new file mode 100644 index 00000000..96f479ef --- /dev/null +++ b/tests/Feature/Testing/ReplaysModuleRegistrationsWithoutIsolationTest.php @@ -0,0 +1,43 @@ +toContain('theme registered'); + + // The next one replaces the callbacks of the earlier registration + $this->bootNextApplication(); + + expect(takeModuleLog())->toContain('theme registered', 'theme init')->not->toContain('core init'); + + $counts = hookedCallbacks(); + + // Application after application, they do not pile up + $this->bootNextApplication(); + + takeModuleLog(); + + // Each earlier `init` callback of the theme hooked one more into `init` and `wp_loaded`, and none came back twice + expect(hookedCallbacks()['probe_content'])->toBe($counts['probe_content']) + ->and(hookedCallbacks()['after_setup_theme'])->toBe($counts['after_setup_theme']) + ->and(hookedCallbacks()['init'])->toBe($counts['init']); + + fireHook('probe_content'); + + expect(takeModuleLog())->toBe(['content of application '.spl_object_id(app())]); +}); diff --git a/tests/Feature/VersionCheck/HttpGetRedirectTest.php b/tests/Feature/VersionCheck/HttpGetRedirectTest.php new file mode 100644 index 00000000..fb9fb960 --- /dev/null +++ b/tests/Feature/VersionCheck/HttpGetRedirectTest.php @@ -0,0 +1,164 @@ + 'Bearer fake-token']; + +/** + * Answer WordPress HTTP requests from a map of URL => [status, Location, body], recording each request. + * + * @param array $answers + * @param array}> $requests + */ +function redirectingHttp(array $answers, array &$requests): void +{ + Functions\when('wp_remote_get')->alias(function (string $url, array $arguments = []) use ($answers, &$requests): array { + $requests[] = ['url' => $url, 'arguments' => $arguments]; + [$code, $location, $body] = ($answers[$url] ?? [404]) + [1 => '', 2 => '{}']; + + return ['code' => $code, 'location' => $location, 'body' => $body]; + }); + Functions\when('is_wp_error')->alias(fn (mixed $response): bool => $response === 'error'); + Functions\when('wp_remote_retrieve_response_code')->alias(fn (array $response): int => $response['code']); + Functions\when('wp_remote_retrieve_header')->alias(fn (array $response, string $header): mixed => $response[$header]); + Functions\when('wp_remote_retrieve_body')->alias(fn (array $response): string => $response['body']); +} + +describe('HttpGet with credentials', function (): void { + it('does not leave the redirects to WordPress', function (array $headers): void { + $requests = []; + redirectingHttp([GET_URL => [200, '', '{"ok":true}']], $requests); + + expect((new HttpGet)->json(GET_URL, $headers))->toBe(['ok' => true]) + ->and($requests[0]['arguments']['redirection'])->toBe(0) + ->and($requests[0]['arguments']['headers'])->toBe(['Accept' => 'application/json', ...$headers]); + })->with([ + 'a bearer token' => [GET_TOKEN], + 'any casing' => [['authorization' => 'Bearer fake-token']], + 'a cookie' => [['Cookie' => 'session=fake']], + 'a header of its own' => [['X-Api-Key' => 'fake']], + 'after an Accept header' => [['Accept' => 'application/vnd.github+json', 'Authorization' => 'Bearer fake-token']], + ]); + + it('follows a redirect that stays on the same origin, with the same arguments', function (int $status): void { + $requests = []; + $target = 'https://api.github.com/repositories/42/tags'; + redirectingHttp([GET_URL => [$status, $target], $target => [200, '', '[{"name":"v1.0.0"}]']], $requests); + + expect((new HttpGet)->json(GET_URL, GET_TOKEN))->toBe([['name' => 'v1.0.0']]) + ->and(array_column($requests, 'url'))->toBe([GET_URL, $target]) + ->and($requests[1]['arguments'])->toBe($requests[0]['arguments']); + })->with([301, 302, 303, 307, 308]); + + it('sends nothing anywhere else', function (mixed $location): void { + $requests = []; + redirectingHttp([GET_URL => [302, $location]], $requests); + + expect((new HttpGet)->json(GET_URL, GET_TOKEN))->toBeNull() + ->and(array_column($requests, 'url'))->toBe([GET_URL]) + ->and($requests[0]['arguments']['redirection'])->toBe(0); + })->with([ + 'another host' => ['https://elsewhere.example/tags'], + 'a host that starts alike' => ['https://api.github.com.elsewhere.example/tags'], + 'the origin as user information' => ['https://api.github.com@elsewhere.example/tags'], + 'plain HTTP' => ['http://api.github.com/tags'], + 'another port' => ['https://api.github.com:8443/tags'], + 'a protocol-relative URL' => ['//elsewhere.example/tags'], + 'a relative path' => ['/repositories/42/tags'], + 'the host written another way' => ['https://API.github.com/tags'], + 'no Location' => [''], + 'several Location headers' => [['https://api.github.com/a', 'https://elsewhere.example/b']], + ]); + + it('stops at a redirect that leaves the origin after one that did not', function (): void { + $requests = []; + $target = 'https://api.github.com/repositories/42/tags'; + redirectingHttp([GET_URL => [301, $target], $target => [302, 'https://elsewhere.example/tags']], $requests); + + expect((new HttpGet)->json(GET_URL, GET_TOKEN))->toBeNull() + ->and(array_column($requests, 'url'))->toBe([GET_URL, $target]); + }); + + it('keeps the port of the first URL', function (): void { + $requests = []; + redirectingHttp([ + 'http://127.0.0.1:8931' => [302, 'http://127.0.0.1:8931/next'], + 'http://127.0.0.1:8931/next' => [302, 'http://127.0.0.1:8932/next'], + ], $requests); + + expect((new HttpGet)->json('http://127.0.0.1:8931', GET_TOKEN))->toBeNull() + ->and(array_column($requests, 'url'))->toBe(['http://127.0.0.1:8931', 'http://127.0.0.1:8931/next']); + }); + + it('follows five redirects and no more', function (): void { + $requests = []; + redirectingHttp([GET_URL => [302, GET_URL]], $requests); + + expect((new HttpGet)->json(GET_URL, GET_TOKEN))->toBeNull() + ->and($requests)->toHaveCount(6); + }); + + it('follows nothing from a URL whose origin it cannot read', function (): void { + $requests = []; + redirectingHttp(['api.github.com/tags' => [302, 'https://api.github.com/tags']], $requests); + + expect((new HttpGet)->json('api.github.com/tags', GET_TOKEN))->toBeNull() + ->and($requests)->toHaveCount(1) + ->and($requests[0]['arguments']['redirection'])->toBe(0); + }); + + it('answers null when a redirect it follows ends in an error', function (): void { + $calls = 0; + $redirects = []; + redirectingHttp([], $redirects); + Functions\when('wp_remote_get')->alias(function () use (&$calls): mixed { + return ++$calls === 1 ? ['code' => 301, 'location' => 'https://api.github.com/next', 'body' => ''] : 'error'; + }); + + expect((new HttpGet)->json(GET_URL, GET_TOKEN))->toBeNull() + ->and($calls)->toBe(2); + }); + + it('follows the redirect GitHub answers for a renamed repository', function (): void { + $requests = []; + $listed = 'https://api.github.com/repos/acme/crm/tags?per_page=100'; + // The shape GitHub answers: a 301 to the numeric id of the repository, as an absolute URL + $moved = 'https://api.github.com/repositories/123456789/tags?per_page=100'; + redirectingHttp([$listed => [301, $moved], $moved => [200, '', '[{"name":"v3.1.0"}]']], $requests); + + expect((new HttpGet)->json($listed, GET_TOKEN))->toBe([['name' => 'v3.1.0']]) + ->and(array_column($requests, 'url'))->toBe([$listed, $moved]) + ->and($requests[1]['arguments']['headers']['Authorization'])->toBe('Bearer fake-token'); + }); + + it('reads the tags of a renamed private repository, and keeps the token on the API', function (): void { + $requests = []; + redirectingHttp([ + 'https://api.github.com/repos/acme/crm/releases/latest' => [302, 'https://elsewhere.example/latest'], + 'https://api.github.com/repos/acme/crm/tags?per_page=100' => [301, 'https://api.github.com/repositories/42/tags?per_page=100'], + 'https://api.github.com/repositories/42/tags?per_page=100' => [200, '', '[{"name":"v2.0.0"}]'], + ], $requests); + + expect((new GitHubSource(new HttpGet, 'acme/crm', 'fake-token'))->latest('acme/crm'))->toBe('2.0.0') + ->and(array_filter(array_column($requests, 'url'), fn (string $url): bool => ! str_starts_with($url, 'https://api.github.com/')))->toBe([]); + }); +}); + +describe('HttpGet without credentials', function (): void { + it('leaves the redirects to WordPress, as before', function (array $headers, array $sent): void { + $requests = []; + redirectingHttp([GET_URL => [302, 'https://elsewhere.example/tags']], $requests); + + expect((new HttpGet)->json(GET_URL, $headers))->toBeNull() + ->and($requests)->toBe([['url' => GET_URL, 'arguments' => ['timeout' => 5, 'headers' => $sent]]]); + })->with([ + 'no header' => [[], ['Accept' => 'application/json']], + 'an Accept header' => [['Accept' => 'application/vnd.github+json'], ['Accept' => 'application/vnd.github+json']], + 'an Accept header in lower case' => [['accept' => 'text/json'], ['Accept' => 'application/json', 'accept' => 'text/json']], + ]); +}); diff --git a/tests/Support/Testing/BootsNextApplication.php b/tests/Support/Testing/BootsNextApplication.php new file mode 100644 index 00000000..37765470 --- /dev/null +++ b/tests/Support/Testing/BootsNextApplication.php @@ -0,0 +1,21 @@ +tearDown(); + $this->setUp(); + } +} diff --git a/tests/Support/Testing/HookingServiceProvider.php b/tests/Support/Testing/HookingServiceProvider.php new file mode 100644 index 00000000..066e89d4 --- /dev/null +++ b/tests/Support/Testing/HookingServiceProvider.php @@ -0,0 +1,53 @@ + */ + public static array $handled = []; + + public function register(): void + { + $this->app->instance('probe.name', 'application '.spl_object_id($this->app)); + + hookInto('probe_footer', fn () => self::$handled[] = $this->app->make('probe.name')); + + if (self::$loaded) { + return; + } + + WordPressLoadRecorder::forget(); + WordPressLoadRecorder::start(); + // What wp-settings.php includes once: here a must-use plugin + hookInto('probe_must_use', static fn (): int => self::$mustUseRuns++); + WordPressLoadRecorder::finish(); + + self::$loaded = true; + } + + public function boot(): void + { + hookInto('probe_footer', fn () => self::$handled[] = $this->app->make('probe.name'), 20); + } + + public static function reset(): void + { + self::$loaded = false; + self::$mustUseRuns = 0; + self::$handled = []; + } +} diff --git a/tests/Support/Testing/IsolatedModuleLoadingTestCase.php b/tests/Support/Testing/IsolatedModuleLoadingTestCase.php new file mode 100644 index 00000000..2045cd1c --- /dev/null +++ b/tests/Support/Testing/IsolatedModuleLoadingTestCase.php @@ -0,0 +1,12 @@ + */ + public static array $log = []; + + public function register(): void + { + self::bindRegistrars($this->app); + } + + /** + * Binds registrars that log what they are asked to register. + */ + public static function bindRegistrars(Application $app): void + { + $app->instance(ThemeRegistrarInterface::class, new ProbeThemeRegistrar($app)); + + $plugins = Mockery::mock(PluginRegistrar::class); + $plugins->shouldReceive('register')->andReturnUsing(function (string $name, string $path): PluginModuleInterface { + self::$log[] = "plugin {$name} registered from {$path}"; + + hookInto('plugins_loaded', static function (): void { + self::$log[] = 'plugin plugins_loaded'; + }); + + return Mockery::mock(PluginModuleInterface::class); + }); + $app->instance(PluginRegistrar::class, $plugins); + } + + public function boot(): void + { + $alreadyLoaded = self::$loaded; + + WordPressLoadRecorder::start(); + + if (! $alreadyLoaded) { + hookInto('init', ModuleLoadingServiceProvider::class.'::coreInit'); + + pollora_register(ModuleType::Plugin, 'probe-plugin', '/plugins/probe-plugin'); + // A child theme and its parent both register the theme + pollora_register(ModuleType::Theme); + pollora_register(ModuleType::Theme); + + foreach (['plugins_loaded', 'after_setup_theme', 'init', 'widgets_init', 'wp_loaded'] as $action) { + fireHook($action); + } + + self::$loaded = true; + } + + WordPressLoadRecorder::finish($alreadyLoaded); + } + + public static function coreInit(): void + { + self::$log[] = 'core init'; + } + + public static function reset(): void + { + self::$loaded = false; + self::$log = []; + } +} diff --git a/tests/Support/Testing/ModuleLoadingTestCase.php b/tests/Support/Testing/ModuleLoadingTestCase.php new file mode 100644 index 00000000..8e66af97 --- /dev/null +++ b/tests/Support/Testing/ModuleLoadingTestCase.php @@ -0,0 +1,17 @@ +application; + } +} diff --git a/tests/Support/Testing/ProbeThemeRegistrar.php b/tests/Support/Testing/ProbeThemeRegistrar.php new file mode 100644 index 00000000..dcf88904 --- /dev/null +++ b/tests/Support/Testing/ProbeThemeRegistrar.php @@ -0,0 +1,64 @@ +app; + $name = 'application '.spl_object_id($app); + + ModuleLoadingServiceProvider::$log[] = 'theme registered'; + + hookInto('probe_content', [new ProbeThemeHooks($name), 'filterContent']); + + hookInto('init', static function () use ($app): void { + ModuleLoadingServiceProvider::$log[] = 'theme init'; + $app->make('config')->set('theme.templates', ['wide']); + + hookInto('init', static fn (): null => null, 50); + hookInto('wp_loaded', static function (): void { + ModuleLoadingServiceProvider::$log[] = 'theme wp_loaded'; + }); + }, 20); + + hookInto('widgets_init', static function (): void { + ModuleLoadingServiceProvider::$log[] = 'theme widgets_init'; + }); + + hookInto('after_setup_theme', static function () use ($app): void { + ModuleLoadingServiceProvider::$log[] = 'theme after_setup_theme'; + $app->make('config')->set('theme.menus', ['primary']); + }, 1); + + hookInto('rest_api_init', static function (): void { + ModuleLoadingServiceProvider::$log[] = 'theme rest_api_init'; + }); + + return \Mockery::mock(ThemeModuleInterface::class); + } + + public function getActiveTheme(): ?ThemeModuleInterface + { + return null; + } + + public function isThemeActive(string $themeName): bool + { + return false; + } + + public function resetActiveTheme(): void {} +} diff --git a/tests/Support/Testing/module-loading.php b/tests/Support/Testing/module-loading.php new file mode 100644 index 00000000..f8ccff70 --- /dev/null +++ b/tests/Support/Testing/module-loading.php @@ -0,0 +1,38 @@ + what was registered and run since the last call + */ +function takeModuleLog(): array +{ + $log = ModuleLoadingServiceProvider::$log; + ModuleLoadingServiceProvider::$log = []; + + return $log; +} diff --git a/tests/Support/Testing/wordpress-hooks.php b/tests/Support/Testing/wordpress-hooks.php new file mode 100644 index 00000000..68994dbd --- /dev/null +++ b/tests/Support/Testing/wordpress-hooks.php @@ -0,0 +1,90 @@ +> */ + public array $callbacks = []; + + public function add_filter(string $hook, mixed $callback, int $priority, int $acceptedArgs): void + { + $this->callbacks[$priority][self::id($callback)] = ['function' => $callback, 'accepted_args' => $acceptedArgs]; + ksort($this->callbacks); + } + + public function remove_filter(string $hook, mixed $callback, int $priority): bool + { + $id = self::id($callback); + + if (! isset($this->callbacks[$priority][$id])) { + return false; + } + + unset($this->callbacks[$priority][$id]); + + if ($this->callbacks[$priority] === []) { + unset($this->callbacks[$priority]); + } + + return true; + } + + /** @param array $args */ + public function do_action(array $args): void + { + foreach ($this->callbacks as $callbacks) { + foreach ($callbacks as $callback) { + ($callback['function'])(...$args); + } + } + } + + public static function id(mixed $callback): string + { + if (is_string($callback)) { + return $callback; + } + + if (is_object($callback)) { + return spl_object_hash($callback); + } + + return is_object($callback[0]) ? spl_object_hash($callback[0]).$callback[1] : $callback[0].'::'.$callback[1]; + } + } +} + +function hookInto(string $name, mixed $callback, int $priority = 10): void +{ + $GLOBALS['wp_filter'][$name] ??= new WP_Hook; + $GLOBALS['wp_filter'][$name]->add_filter($name, $callback, $priority, 1); +} + +function fireHook(string $name): void +{ + $GLOBALS['wp_actions'][$name] = ($GLOBALS['wp_actions'][$name] ?? 0) + 1; + + foreach (($GLOBALS['wp_filter'][$name] ?? null)?->callbacks ?? [] as $callbacks) { + foreach ($callbacks as $callback) { + ($callback['function'])(); + } + } +} + +/** + * @return array the number of callbacks of each hook + */ +function hookedCallbacks(): array +{ + return array_map( + static fn (WP_Hook $hook): int => array_sum(array_map(count(...), $hook->callbacks)), + $GLOBALS['wp_filter'] ?? [], + ); +} diff --git a/tests/Unit/Block/MakeBlockCommandTest.php b/tests/Unit/Block/MakeBlockCommandTest.php index 337f9c13..5cd025d4 100644 --- a/tests/Unit/Block/MakeBlockCommandTest.php +++ b/tests/Unit/Block/MakeBlockCommandTest.php @@ -2,6 +2,8 @@ declare(strict_types=1); +use Pollora\Block\UI\Console\MakeBlockCommand; + /** * Path to the framework stubs directory (relative to framework root). */ @@ -118,6 +120,22 @@ function blockStubsDir(): string describe('MakeBlockCommand npm dependencies', function (): void { + it('adds the versions the bundled module template asks for', function (): void { + $added = (new ReflectionClassConstant(MakeBlockCommand::class, 'NPM_DEPENDENCIES'))->getValue(); + $template = json_decode( + (string) file_get_contents(dirname(__DIR__, 3).'/src/Modules/stubs/module-default/package.json'), + true, + )['devDependencies']; + + $shared = array_intersect_key($added, $template); + + expect($shared)->toHaveKeys(['@wordpress/blocks', '@wordpress/block-editor', '@wordpress/components', '@wordpress/element', '@wordpress/i18n']); + + foreach ($shared as $dependency => $version) { + expect([$dependency => $version])->toBe([$dependency => $template[$dependency]]); + } + }); + it('adds missing npm dependencies to package.json', function (): void { $packageJson = json_decode(file_get_contents($this->tempDir.'/package.json'), true); $devDeps = $packageJson['devDependencies'] ?? []; @@ -125,11 +143,11 @@ function blockStubsDir(): string $npmDeps = [ '@roots/vite-plugin' => '^2.0.0', 'glob' => '^11.0.0', - '@wordpress/blocks' => '^14.0.0', - '@wordpress/block-editor' => '^14.0.0', - '@wordpress/components' => '^29.0.0', - '@wordpress/element' => '^6.0.0', - '@wordpress/i18n' => '^5.0.0', + '@wordpress/blocks' => '^17.1.0', + '@wordpress/block-editor' => '^20.0.0', + '@wordpress/components' => '^44.0.0', + '@wordpress/element' => '^10.1.0', + '@wordpress/i18n' => '^7.1.0', ]; $added = []; diff --git a/tests/Unit/Route/Infrastructure/Middleware/WordPressHeadersTest.php b/tests/Unit/Route/Infrastructure/Middleware/WordPressHeadersTest.php index 33a9799b..945dfde8 100644 --- a/tests/Unit/Route/Infrastructure/Middleware/WordPressHeadersTest.php +++ b/tests/Unit/Route/Infrastructure/Middleware/WordPressHeadersTest.php @@ -4,9 +4,13 @@ use Illuminate\Config\Repository; use Illuminate\Container\Container; +use Illuminate\Cookie\CookieJar; use Illuminate\Http\Request; +use Illuminate\Session\ArraySessionHandler; +use Illuminate\Session\Store; use Pollora\Route\Infrastructure\Middleware\WordPressHeaders; use Pollora\Route\Infrastructure\Models\Route; +use Symfony\Component\HttpFoundation\Cookie; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response as SymfonyResponse; use Symfony\Component\HttpFoundation\StreamedResponse; @@ -582,3 +586,106 @@ protected function sentHeaders(): array ->and($headers->hasCacheControlDirective('private'))->toBeTrue(); }); }); + +describe('responses bound to their visitor', function (): void { + beforeEach(function (): void { + Brain\Monkey\Functions\when('is_user_logged_in')->justReturn(false); + + $this->request = Request::create('/page'); + $this->request->setRouteResolver(fn (): null => null); + + $this->page = fn (): Response => new SymfonyResponse('content', 200, ['Content-Type' => 'text/html']); + + $this->sending = fn (string ...$headers): WordPressHeaders => new class($headers) extends WordPressHeaders + { + public function __construct(private readonly array $headers) {} + + protected function sentHeaders(): array + { + return $this->headers; + } + }; + }); + + afterEach(function (): void { + Container::getInstance()->forgetInstance('cookie'); + }); + + it('keeps out of shared caches a page for which PHP already holds a cookie', function (string $header): void { + $response = ($this->sending)($header)->handle($this->request, $this->page); + + expect($response->headers->hasCacheControlDirective('public'))->toBeFalse() + ->and($response->headers->hasCacheControlDirective('private'))->toBeTrue() + ->and($response->headers->hasCacheControlDirective('max-age'))->toBeFalse(); + })->with([ + 'setcookie()' => ['Set-Cookie: visitor=fake; path=/'], + 'any casing' => ['set-cookie: visitor=fake'], + ]); + + it('keeps out of shared caches a page that carries a cookie', function (): void { + $response = $this->middleware->handle($this->request, function (): Response { + $inner = ($this->page)(); + $inner->headers->setCookie(new Cookie('visitor', 'fake')); + + return $inner; + }); + + expect($response->headers->hasCacheControlDirective('private'))->toBeTrue() + ->and($response->headers->hasCacheControlDirective('public'))->toBeFalse() + ->and($response->headers->getCookies())->toHaveCount(1); + }); + + it('keeps out of shared caches a page whose request has a session, before its cookie is added', function (): void { + $this->request->setLaravelSession(new Store('session', new ArraySessionHandler(1))); + + $response = $this->middleware->handle($this->request, $this->page); + + expect($response->headers->hasCacheControlDirective('private'))->toBeTrue() + ->and($response->headers->hasCacheControlDirective('public'))->toBeFalse(); + }); + + it('keeps out of shared caches a page with a cookie queued for later', function (): void { + $jar = new CookieJar; + $jar->queue('visitor', 'fake'); + Container::getInstance()->instance('cookie', $jar); + + $response = $this->middleware->handle($this->request, $this->page); + + expect($response->headers->hasCacheControlDirective('private'))->toBeTrue() + ->and($response->headers->hasCacheControlDirective('public'))->toBeFalse(); + }); + + it('adds no public directive beside a sent Cache-Control that forbids shared storage', function (string $header, bool $noStore): void { + $response = ($this->sending)($header)->handle($this->request, $this->page); + + expect($response->headers->hasCacheControlDirective('public'))->toBeFalse() + ->and($response->headers->hasCacheControlDirective('private'))->toBeTrue() + ->and($response->headers->hasCacheControlDirective('no-store'))->toBe($noStore); + })->with([ + 'the no-cache headers of WordPress' => ['Cache-Control: no-cache, must-revalidate, max-age=0, no-store, private', true], + 'a PHP session' => ['Cache-Control: no-store, no-cache, must-revalidate', true], + 'private' => ['Cache-Control: private, max-age=60', false], + 'no-cache' => ['Cache-Control: no-cache', false], + ]); + + it('stays public without a cookie, a session or such a header', function (): void { + Container::getInstance()->instance('cookie', new CookieJar); + + $response = ($this->sending)('Cache-Control: max-age=600, must-revalidate', 'X-Pingback: https://example.test/xmlrpc.php') + ->handle($this->request, $this->page); + + expect($response->headers->hasCacheControlDirective('public'))->toBeTrue(); + }); + + it('leaves the directives the application set on its response', function (): void { + $response = ($this->sending)('Set-Cookie: visitor=fake')->handle($this->request, function (): Response { + $inner = ($this->page)(); + $inner->setPublic()->setMaxAge(60); + + return $inner; + }); + + expect($response->headers->hasCacheControlDirective('public'))->toBeTrue() + ->and($response->headers->getCacheControlDirective('max-age'))->toBe('60'); + }); +}); diff --git a/tests/Unit/Testing/WordPressHookStateTest.php b/tests/Unit/Testing/WordPressHookStateTest.php new file mode 100644 index 00000000..10ab181f --- /dev/null +++ b/tests/Unit/Testing/WordPressHookStateTest.php @@ -0,0 +1,220 @@ +globals = [$GLOBALS['wp_filter'] ?? null, $GLOBALS['wp_actions'] ?? null, $GLOBALS['wp_filters'] ?? null]; + $GLOBALS['wp_filter'] = $GLOBALS['wp_actions'] = $GLOBALS['wp_filters'] = []; + WordPressLoadRecorder::forget(); +}); + +afterEach(function (): void { + [$GLOBALS['wp_filter'], $GLOBALS['wp_actions'], $GLOBALS['wp_filters']] = $this->globals; + WordPressLoadRecorder::forget(); +}); + +/** + * A callback written as an array, the form the hooks under test tell apart from a closure. + * + * @return array{object|string, string} + */ +function pair(object|string $target, string $method): array +{ + return [$target, $method]; +} + +/** + * The callbacks WordPress would run on a hook. + * + * @return list + */ +function callbacksOf(string $name): array +{ + $found = []; + + foreach (($GLOBALS['wp_filter'][$name] ?? null)?->callbacks ?? [] as $callbacks) { + array_push($found, ...array_column($callbacks, 'function')); + } + + return $found; +} + +/** + * The callback the scheduling engine of pollora/schedule hooks for a handler. + */ +function attachedBy(ScheduleEngine $engine, string|Closure $handler): Closure +{ + $hooked = null; + Functions\when('add_action')->alias(function (string $hook, Closure $callback) use (&$hooked): void { + $hooked = $callback; + }); + + $engine->attach('probe_schedule', $handler); + + return $hooked; +} + +it('puts the hooks and their counts back, with what was removed since', function (): void { + hookInto('probe', 'strlen'); + $GLOBALS['wp_actions'] = ['init' => 1]; + $GLOBALS['wp_filters'] = ['the_title' => 2]; + $state = WordPressHookState::capture(); + + $GLOBALS['wp_filter']['probe']->remove_filter('probe', 'strlen', 10); + hookInto('later', 'strlen'); + $GLOBALS['wp_actions'] = ['init' => 4]; + $GLOBALS['wp_filters'] = []; + + $state->restore(); + + expect(callbacksOf('probe'))->toBe(['strlen']) + ->and(callbacksOf('later'))->toBe([]) + ->and($GLOBALS['wp_actions'])->toBe(['init' => 1]) + ->and($GLOBALS['wp_filters'])->toBe(['the_title' => 2]); +}); + +it('can be restored again after what was restored changed', function (): void { + hookInto('probe', 'strlen'); + $state = WordPressHookState::capture(); + + $state->restore(); + hookInto('probe', 'strrev'); + $state->restore(); + + expect(callbacksOf('probe'))->toBe(['strlen']); +}); + +it('keeps only what the first load added', function (): void { + hookInto('probe', 'strlen'); + // Hooked before plugin.php was included: still an array until the load + $GLOBALS['wp_filter']['early'] = [10 => []]; + + WordPressLoadRecorder::start(); + unset($GLOBALS['wp_filter']['early']); + hookInto('probe', 'strrev'); + hookInto('loaded', 'trim'); + WordPressLoadRecorder::finish(); + + WordPressLoadRecorder::start(); + hookInto('loaded', 'ltrim'); + WordPressLoadRecorder::finish(); + + WordPressLoadRecorder::loaded()->restore(); + + expect(callbacksOf('probe'))->toBe(['strrev']) + ->and(callbacksOf('loaded'))->toBe(['trim']); +}); + +it('keeps everything when WordPress was loaded before the application', function (): void { + hookInto('probe', 'strlen'); + + WordPressLoadRecorder::start(); + WordPressLoadRecorder::finish(alreadyLoaded: true); + $GLOBALS['wp_filter'] = []; + WordPressLoadRecorder::loaded()->restore(); + + expect(callbacksOf('probe'))->toBe(['strlen']); +}); + +it('records nothing without a start', function (): void { + WordPressLoadRecorder::finish(); + + expect(WordPressLoadRecorder::loaded())->toBeNull(); +}); + +it('drops the callbacks bound to an object whose code is in a directory', function (): void { + $here = new class + { + public function method(): void {} + + public function __invoke(): void {} + + public function closure(): Closure + { + return fn (): object => $this; + } + }; + $static = static fn (): null => null; + + hookInto('dropped', pair($here, 'method')); + hookInto('dropped', $here); + hookInto('dropped', $here->closure()); + hookInto('kept', $static); + hookInto('kept', 'strlen'); + // A method that only __call() answers has no file + hookInto('kept', pair(new ArrayObject, 'missing')); + + WordPressHookState::capture()->withoutObjectCallbacksFrom(__DIR__)->restore(); + + expect(callbacksOf('dropped'))->toBe([]) + ->and(callbacksOf('kept'))->toHaveCount(3); + + hookInto('elsewhere', pair($here, 'method')); + WordPressHookState::capture()->withoutObjectCallbacksFrom(__DIR__.'/elsewhere')->restore(); + + expect(callbacksOf('elsewhere'))->toHaveCount(1); +}); + +it('adds the callbacks of another state a filter accepts, once', function (): void { + hookInto('probe', 'DateTime::createFromFormat'); + hookInto('probe', pair(DateTime::class, 'getLastErrors'), 20); + hookInto('probe', 'strlen'); + hookInto('probe', pair(new ArrayObject, 'count')); + $other = WordPressHookState::capture(); + + $GLOBALS['wp_filter'] = []; + hookInto('probe', 'DateTime::createFromFormat'); + + WordPressHookState::capture()->with($other, OncePerProcessHooks::isStaticMethod(...))->restore(); + + expect(callbacksOf('probe'))->toBe(['DateTime::createFromFormat', pair(DateTime::class, 'getLastErrors')]); +}); + +it('knows what pollora/roles hooks once per process', function (): void { + $injector = (new ReflectionClass(WordPressRoleInjector::class))->newInstanceWithoutConstructor(); + $translator = (new ReflectionClass(WordPressRoleLabelTranslator::class))->newInstanceWithoutConstructor(); + + expect(OncePerProcessHooks::belongsToPackage(pair($injector, 'inject')))->toBeTrue() + ->and(OncePerProcessHooks::belongsToPackage(pair($translator, 'translate')))->toBeTrue() + // The registry of an application is hooked with closures + ->and(OncePerProcessHooks::belongsToPackage($injector->inject(...)))->toBeFalse() + ->and(OncePerProcessHooks::belongsToPackage(pair(new ArrayObject, 'count')))->toBeFalse() + ->and(OncePerProcessHooks::belongsToPackage('strlen'))->toBeFalse() + ->and(OncePerProcessHooks::belongsToPackage(static fn (): null => null))->toBeFalse(); +}); + +it('keeps the handlers the scheduling engine will not attach again', function (): void { + $engine = new ScheduleEngine; + $interceptor = (new ReflectionClass(CronInterceptor::class))->newInstanceWithoutConstructor(); + $guard = Closure::bind(fn (): null => null, $interceptor, CronInterceptor::class); + + expect(OncePerProcessHooks::belongsToPackage(attachedBy($engine, 'probe_other_hook')))->toBeTrue() + ->and(OncePerProcessHooks::belongsToPackage($engine->attach(...)))->toBeTrue() + ->and(OncePerProcessHooks::belongsToPackage(pair($engine, 'attach')))->toBeTrue() + ->and(OncePerProcessHooks::belongsToPackage($guard))->toBeTrue() + ->and(OncePerProcessHooks::belongsToPackage(pair($interceptor, 'any')))->toBeTrue(); +}); + +it('lets go of a closure given to the scheduling engine, without freeing its id', function (): void { + $handler = fn (): null => null; + $reference = WeakReference::create($handler); + $callback = attachedBy(new ScheduleEngine, $handler); + + expect(OncePerProcessHooks::belongsToPackage($callback))->toBeFalse() + ->and(OncePerProcessHooks::belongsToPackage($callback))->toBeFalse(); + + unset($handler, $callback); + + expect($reference->get())->toBeInstanceOf(Closure::class); +}); diff --git a/tests/Unit/Tooling/LatestTemplateTagTest.php b/tests/Unit/Tooling/LatestTemplateTagTest.php new file mode 100644 index 00000000..abe4a30d --- /dev/null +++ b/tests/Unit/Tooling/LatestTemplateTagTest.php @@ -0,0 +1,67 @@ + $tags + */ +function latestTemplateTag(array $tags, string $asked = 'owner/template'): Process +{ + $base = sys_get_temp_dir().'/pollora-tags-'.bin2hex(random_bytes(6)); + $repository = $base.'/owner/template.git'; + mkdir($repository, 0700, true); + + $git = static fn (string ...$arguments): string => trim((new Process( + ['git', '-c', 'user.name=Test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', '-c', 'tag.gpgsign=false', ...$arguments], + $repository, + ))->mustRun()->getOutput()); + + $git('init', '--quiet', '--bare'); + $tree = $git('hash-object', '-w', '-t', 'tree', '/dev/null'); + $commit = $git('commit-tree', $tree, '-m', 'initial'); + + foreach ($tags as $position => $tag) { + // Annotated every other time: git lists those twice unless asked not to + $position % 2 === 0 ? $git('tag', '-a', '-m', $tag, $tag, $commit) : $git('tag', $tag, $commit); + } + + $script = new Process( + [PHP_BINARY, 'tests/e2e/bin/latest-template-tag.php', $asked], + dirname(__DIR__, 3), + ['POLLORA_TEMPLATE_GIT_BASE' => $base.'/'], + ); + $script->run(); + + (new Process(['rm', '-rf', $base]))->mustRun(); + + return $script; +} + +it('prints the tag the make commands would install', function (array $tags, string $expected): void { + $script = latestTemplateTag($tags); + + expect($script->getExitCode())->toBe(0, $script->getErrorOutput()) + ->and($script->getOutput())->toBe($expected."\n"); +})->with([ + 'highest version, not highest name' => [['0.9', '0.10.1', '0.10.0'], '0.10.1'], + 'with and without a v, annotated or not' => [['1.1.2', 'v1.7.2', 'v1.4.0', 'latest'], 'v1.7.2'], + 'a stable version over a newer pre-release' => [['v1.0.0', 'v2.0.0-beta.1'], 'v1.0.0'], + 'a pre-release when there is nothing else' => [['v2.0.0-beta.1', 'v2.0.0-beta.2'], 'v2.0.0-beta.2'], +]); + +it('fails without printing a tag when it cannot tell which one', function (array $tags, string $asked, string $reason): void { + $script = latestTemplateTag($tags, $asked); + + expect($script->getExitCode())->toBe(1) + ->and($script->getOutput())->toBe('') + ->and($script->getErrorOutput())->toContain($reason); +})->with([ + 'no tag' => [[], 'owner/template', 'no tag that is a version'], + 'no version among the tags' => [['latest', 'nightly'], 'owner/template', 'no tag that is a version'], + 'unreadable repository' => [['v1.0.0'], 'owner/absent', 'git ls-remote failed'], +]); diff --git a/tests/e2e/bin/fixtures.sh b/tests/e2e/bin/fixtures.sh index 591df963..66e4edbc 100755 --- a/tests/e2e/bin/fixtures.sh +++ b/tests/e2e/bin/fixtures.sh @@ -22,7 +22,8 @@ # down remove all of it, and give modules_statuses.json back as it was set -euo pipefail -FIXTURES="$(cd "$(dirname "$0")/../fixtures" && pwd)" +BIN="$(cd "$(dirname "$0")" && pwd)" +FIXTURES="$(cd "$BIN/../fixtures" && pwd)" PLUGIN=e2e-blocks PLUGIN_DIR=public/content/plugins/$PLUGIN @@ -48,7 +49,10 @@ case "${1:-}" in up) # Plugin if [ ! -d "$PLUGIN_DIR" ]; then - php artisan pollora:make:plugin "$PLUGIN" --asset=true --no-interaction + # The tag is read over the git protocol: the command would ask api.github.com, + # whose anonymous limit CI runners share + tag=$(php "$BIN/latest-template-tag.php" pollora/plugin-default) + php artisan pollora:make:plugin "$PLUGIN" --repo-version="$tag" --asset=true --no-interaction fi php artisan pollora:make:block dynamic-card --plugin="$PLUGIN" --title="Dynamic Card" --force --no-interaction diff --git a/tests/e2e/bin/install-wordpress.sh b/tests/e2e/bin/install-wordpress.sh new file mode 100755 index 00000000..ede2c4cd --- /dev/null +++ b/tests/e2e/bin/install-wordpress.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# +# Install WordPress on the Pollora site under test. Run from its root, inside +# its container, with the options of pollora:install. +# +# pollora:install generates the theme "default" from the latest tag of +# pollora/theme-default, which it reads from api.github.com; it takes no option +# to give it a version. Anonymous calls to the API are limited per IP address, +# which CI runners share. When, and only when, the list of tags was refused, the +# theme is generated here instead, with the same command and the tag read over +# the git protocol. Any other reason for a missing theme fails. +set -euo pipefail + +BIN="$(cd "$(dirname "$0")" && pwd)" +THEME=default +REPOSITORY=pollora/theme-default + +log=$(mktemp) +trap 'rm -f "$log"' EXIT + +php artisan pollora:install "$@" 2>&1 | tee "$log" + +if [ ! -f "themes/$THEME/style.css" ]; then + if ! grep -qF "Unable to read the list of tags of $REPOSITORY " "$log"; then + echo "::error::pollora:install generated no theme, and not because the list of tags was refused" >&2 + exit 1 + fi + + tag=$(php "$BIN/latest-template-tag.php" "$REPOSITORY") + echo "::warning::pollora:install could not list the tags of $REPOSITORY: generating the theme from tag $tag" + php artisan pollora:make:theme "$THEME" --repository="$REPOSITORY" --repo-version="$tag" --activate --no-interaction +fi + +active=$(wp theme list --status=active --field=name) + +if [ "$active" != "$THEME" ]; then + echo "::error::the active theme is \"$active\" instead of \"$THEME\"" >&2 + exit 1 +fi diff --git a/tests/e2e/bin/latest-template-tag.php b/tests/e2e/bin/latest-template-tag.php new file mode 100644 index 00000000..e593f7fd --- /dev/null +++ b/tests/e2e/bin/latest-template-tag.php @@ -0,0 +1,77 @@ + + * + * Exits 1, printing nothing on standard output, when the tag the command would + * have chosen cannot be told. POLLORA_TEMPLATE_GIT_BASE replaces + * https://github.com/ (used by the tests). + */ + +declare(strict_types=1); + +use Pollora\Modules\Infrastructure\Services\ModuleDownloader; +use Symfony\Component\Process\Process; + +require getcwd().'/vendor/autoload.php'; + +$fail = static function (string $reason): never { + fwrite(STDERR, "::error::Unable to resolve the template tag: {$reason}\n"); + exit(1); +}; + +$repository = $argv[1] ?? ''; + +if ($repository === '') { + $fail('no repository given (usage: latest-template-tag.php )'); +} + +$downloader = new ModuleDownloader($repository); +$base = getenv('POLLORA_TEMPLATE_GIT_BASE') ?: 'https://github.com/'; + +// Run outside any checkout, so that no credential of a repository configuration is used +$git = new Process( + ['git', 'ls-remote', '--tags', '--refs', $base.$repository.'.git'], + sys_get_temp_dir(), + ['GIT_TERMINAL_PROMPT' => '0'], + timeout: 60, +); +$git->run(); + +if (! $git->isSuccessful()) { + $fail(sprintf('git ls-remote failed for %s: %s', $repository, trim($git->getErrorOutput()))); +} + +preg_match_all('#\trefs/tags/(.+)$#m', $git->getOutput(), $matches); +$listed = $matches[1]; + +// The command reads one page of 100 tags from the API, in an order git does not give +if (count($listed) >= 100) { + $fail(sprintf('%s has %d tags, more than the command reads', $repository, count($listed))); +} + +// The names the command keeps are those setVersion() accepts +$names = array_values(array_filter($listed, static function (string $name) use ($downloader): bool { + try { + $downloader->setVersion($name); + + return true; + } catch (InvalidArgumentException) { + return false; + } +})); + +$tag = $downloader->selectLatestVersion($names); + +// Without any version, the command takes the first tag of the API answer: unknown here +if ($tag === null || preg_match('/^v?\d+(\.\d+)*(?:[-+.].*)?$/iD', $tag) !== 1) { + $fail(sprintf('%s has no tag that is a version', $repository)); +} + +echo $tag, "\n";