Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions config/wordpress.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,

Expand Down
28 changes: 27 additions & 1 deletion src/Route/Infrastructure/Middleware/WordPressHeaders.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.<condition>` — per WordPress condition (e.g. `is_front_page`, `is_single`)
Expand Down Expand Up @@ -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;
Expand All @@ -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.
*
Expand Down
64 changes: 60 additions & 4 deletions src/VersionCheck/Infrastructure/Sources/HttpGet.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,83 @@

/**
* 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<string, string> $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<string, string> $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;
}

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<string, string> $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<string, mixed> $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;
}
}
164 changes: 164 additions & 0 deletions tests/Feature/VersionCheck/HttpGetRedirectTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
<?php

declare(strict_types=1);

use Brain\Monkey\Functions;
use Pollora\VersionCheck\Infrastructure\Sources\GitHubSource;
use Pollora\VersionCheck\Infrastructure\Sources\HttpGet;

const GET_URL = 'https://api.github.com/repos/acme/crm/tags';
const GET_TOKEN = ['Authorization' => 'Bearer fake-token'];

/**
* Answer WordPress HTTP requests from a map of URL => [status, Location, body], recording each request.
*
* @param array<string, array{0: int, 1?: mixed, 2?: string}> $answers
* @param array<int, array{url: string, arguments: array<string, mixed>}> $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']],
]);
});
Loading
Loading