diff --git a/CHANGELOG.md b/CHANGELOG.md index a134fbd8..2c97a866 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,9 @@ 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 @@ -22,6 +24,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **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 ### Added 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/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/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/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/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'); + }); +});