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
2 changes: 1 addition & 1 deletion .github/workflows/harness.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ permissions: {}

jobs:
harness:
uses: Pollora/harness/.github/workflows/php-package.yml@v0.1.41
uses: Pollora/harness/.github/workflows/php-package.yml@v0.1.43
with:
# Runs the integration suite against a real WordPress and a real MySQL (job "WordPress integration"). The job
# starts it through the test:integration script of composer.json.
Expand Down
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.10.2] - 2026-12-04

A security release for the export of the image classes to Bunny: upgrade if a Bunny API key is configured.

### Security

- `wp pollora media thumbs export --driver=bunny` (and `pollora:media:thumbs:export` with the framework) no longer lets WordPress follow the redirects of its requests to the Bunny API: WordPress sent the `AccessKey` header, and on a write the classes, to wherever a redirect led. A redirect is followed only within `https://api.bunny.net`, up to five; any other one is reported as a refusal (since 0.6.0)

### Fixed

- A write of the classes answered by a `302` or a `303` was followed by a read and reported as applied. It is now reported as a refusal (since 0.6.0)

## [0.10.1] - 2026-12-02

A security release. Every version before it is affected: upgrade, then repair what is already on the disk. Read *Changed* first: some behaviour changes.
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"pestphp/pest": "^3.8.2",
"php-stubs/wp-cli-stubs": "dev-master",
"phpstan/phpstan": "^2.1.16",
"pollora/harness": "^0.1.41",
"pollora/harness": "^0.1.43",
"szepeviktor/phpstan-wordpress": "^2.0"
},
"autoload": {
Expand Down
62 changes: 59 additions & 3 deletions src/Infrastructure/WordPress/WordPressBunnyPullZone.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@

/**
* The pull zone API of Bunny, called with the HTTP API of WordPress. The access key is sent in the
* `AccessKey` header and nowhere else: not in a URL, not in a message.
* `AccessKey` header and nowhere else: not in a URL, not in a message, not to another origin.
*
* @see https://bunny.net/docs/reference/pullzonepublic_updatepullzone
*/
final readonly class WordPressBunnyPullZone implements BunnyPullZone
{
private const string ENDPOINT = 'https://api.bunny.net/pullzone/';
private const string ORIGIN = 'https://api.bunny.net';

private const string ENDPOINT = self::ORIGIN.'/pullzone/';

private const int MAX_REDIRECTS = 5;

public function __construct(#[SensitiveParameter] private string $accessKey) {}

Expand Down Expand Up @@ -71,7 +75,7 @@ private function request(string $method, string $pullZone, ?array $payload = nul
$args['body'] = (string) json_encode($payload, JSON_UNESCAPED_SLASHES);
}

$response = \wp_remote_request(self::ENDPOINT.$pullZone, $args);
$response = $this->send(self::ENDPOINT.$pullZone, $args);

if (\is_wp_error($response)) {
throw BunnyRequestFailedException::unreachable($response->get_error_message());
Expand All @@ -87,4 +91,56 @@ private function request(string $method, string $pullZone, ?array $payload = nul

return is_array($decoded) ? $decoded : [];
}

/**
* WordPress sends the headers of a request again to wherever a redirect leads, the access key included. Its
* redirects are therefore turned off and followed here, within the origin of the API. A write is only followed
* where the redirect keeps it a write: after a 302 or a 303 it would be read instead, and taken for done.
*
* @param array{method: string, timeout: int, headers: array<string, string>, body?: string} $args
* @return array<array-key, mixed>|\WP_Error The last answer: a redirect that is not followed is returned as is
*/
private function send(string $url, #[SensitiveParameter] array $args): array|\WP_Error
{
$args['redirection'] = 0;
$redirects = $args['method'] === 'GET' ? [301, 302, 303, 307, 308] : [301, 307, 308];
$response = \wp_remote_request($url, $args);

for ($followed = 0; $followed < self::MAX_REDIRECTS; $followed++) {
if (\is_wp_error($response)) {
break;
}

$target = in_array((int) \wp_remote_retrieve_response_code($response), $redirects, true)
? $this->withinOrigin(\wp_remote_retrieve_header($response, 'location'))
: null;

if ($target === null) {
break;
}

$response = \wp_remote_request($target, $args);
}

return $response;
}

/**
* The URL a `Location` leads to when it stays on the API: written under its origin, or a path from its root.
* The comparison is textual: nothing depends on how the transport would read a URL written another way.
*
* @param mixed $location A list when the answer has several `Location` headers
*/
private function withinOrigin(mixed $location): ?string
{
if (! is_string($location)) {
return null;
}

if (str_starts_with($location, '/') && ! str_starts_with($location, '//')) {
return self::ORIGIN.$location;
}

return str_starts_with($location, self::ORIGIN.'/') ? $location : null;
}
}
5 changes: 5 additions & 0 deletions tests/Fixtures/WpRest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,11 @@ final class WP_Error
{
/** @param array<string, mixed> $data */
public function __construct(public string $code = '', public string $message = '', public array $data = []) {}

public function get_error_message(): string
{
return $this->message;
}
}
}

Expand Down
155 changes: 155 additions & 0 deletions tests/Unit/WordPressBunnyPullZoneRedirectTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
<?php

declare(strict_types=1);

use Brain\Monkey\Functions;
use Pollora\Media\Domain\Exceptions\BunnyRequestFailedException;
use Pollora\Media\Infrastructure\WordPress\WordPressBunnyPullZone;

/*
* The stand-in for the HTTP API behaves as WordPress does with redirects: unless a request sets `redirection` to 0,
* it follows them itself and sends the same headers to wherever they lead. `$sent` lists what left the server.
*/

beforeEach(function (): void {
$this->sent = new ArrayObject;
Functions\when('is_wp_error')->alias(fn (mixed $value): bool => $value instanceof WP_Error);
Functions\when('wp_remote_retrieve_response_code')->alias(fn (array $response): int => $response['response']['code']);
Functions\when('wp_remote_retrieve_body')->alias(fn (array $response): string => $response['body']);
Functions\when('wp_remote_retrieve_header')->alias(fn (array $response, string $name): mixed => $response['headers'][$name] ?? '');
});

/**
* @return array{response: array{code: int}, headers: array<string, mixed>, body: string}
*/
function bunnyAnswer(int $code, mixed $location = null): array
{
return ['response' => ['code' => $code], 'headers' => $location === null ? [] : ['location' => $location], 'body' => '{}'];
}

/**
* @param list<array<string, mixed>|WP_Error> $answers In turn; the last one is repeated
*/
function redirecting(array $answers, ArrayObject $sent): void
{
Functions\when('wp_remote_request')->alias(function (string $url, array $args) use (&$answers, $sent): mixed {
for ($hop = 0; ; $hop++) {
$sent->append(['url' => $url, 'args' => $args]);
$answer = count($answers) > 1 ? array_shift($answers) : $answers[0];
$location = $answer instanceof WP_Error ? null : ($answer['headers']['location'] ?? null);

if (($args['redirection'] ?? 5) === 0 || ! is_string($location) || $hop === 5) {
return $answer;
}

$url = $location;
}
});
}

function writeAClass(): void
{
(new WordPressBunnyPullZone('the-access-key'))->saveClasses('1234', [['Name' => 'card', 'Properties' => ['width' => '600']]]);
}

it('never sends the access key or the classes to another origin', function (int $status, string $location): void {
redirecting([bunnyAnswer($status, $location), bunnyAnswer(200)], $this->sent);

expect(writeAClass(...))->toThrow(BunnyRequestFailedException::class, "Bunny answered {$status} to POST")
->and($this->sent)->toHaveCount(1)
->and($this->sent[0]['url'])->toBe('https://api.bunny.net/pullzone/1234')
->and($this->sent[0]['args']['redirection'])->toBe(0);
})->with([301, 302, 303, 307, 308])->with([
'another host' => 'https://other.example/pullzone/1234',
'a host that starts alike' => 'https://api.bunny.net.other.example/pullzone/1234',
'the host as a user name' => 'https://api.bunny.net@other.example/',
'another subdomain' => 'https://storage.bunny.net/',
'another scheme' => 'http://api.bunny.net/pullzone/1234',
'another port' => 'https://api.bunny.net:8443/pullzone/1234',
'no scheme' => '//other.example/pullzone/1234',
'a relative path' => 'pullzone/5678',
'an empty value' => '',
]);

it('follows no redirect that names no single location', function (mixed $location): void {
redirecting([bunnyAnswer(302, $location), bunnyAnswer(200)], $this->sent);

expect(fn () => (new WordPressBunnyPullZone('k'))->classes('1234'))->toThrow(BunnyRequestFailedException::class, '302')
->and($this->sent)->toHaveCount(1);
})->with([
'no header' => [null],
'two headers' => [['https://api.bunny.net/a', 'https://other.example/b']],
]);

it('follows a redirect within the API, with the access key', function (int $status, string $location): void {
redirecting([bunnyAnswer($status, $location), bunnyAnswer(200)], $this->sent);

(new WordPressBunnyPullZone('the-access-key'))->classes('1234');

expect($this->sent)->toHaveCount(2)
->and($this->sent[1]['url'])->toBe('https://api.bunny.net/pullzone/5678')
->and($this->sent[1]['args']['headers']['AccessKey'])->toBe('the-access-key')
->and($this->sent[1]['args']['redirection'])->toBe(0);
})->with([301, 302, 303, 307, 308])->with([
'a full URL' => 'https://api.bunny.net/pullzone/5678',
'a path' => '/pullzone/5678',
]);

it('writes again where a redirect that keeps the method leads', function (int $status): void {
redirecting([bunnyAnswer($status, '/pullzone/5678'), bunnyAnswer(200)], $this->sent);

writeAClass();

expect($this->sent[1]['args']['method'])->toBe('POST')
->and($this->sent[1]['args']['headers']['Content-Type'])->toBe('application/json')
->and($this->sent[1]['args']['body'])->toBe($this->sent[0]['args']['body']);
})->with([301, 307, 308]);

it('does not take a write answered by a 302 or a 303 for done, even within the API', function (int $status, string $location): void {
redirecting([bunnyAnswer($status, $location), bunnyAnswer(200)], $this->sent);

expect(writeAClass(...))->toThrow(BunnyRequestFailedException::class, "Bunny answered {$status} to POST")
->and($this->sent)->toHaveCount(1)
->and($this->sent[0]['args']['redirection'])->toBe(0);
})->with([302, 303])->with([
'a full URL' => 'https://api.bunny.net/pullzone/5678',
'a path' => '/pullzone/5678',
]);

it('does not take such an answer for done either after a redirect it followed', function (int $status): void {
redirecting([bunnyAnswer(307, '/pullzone/5678'), bunnyAnswer($status, '/pullzone/9'), bunnyAnswer(200)], $this->sent);

expect(writeAClass(...))->toThrow(BunnyRequestFailedException::class, "Bunny answered {$status} to POST")
->and($this->sent)->toHaveCount(2);
})->with([302, 303]);

it('takes no other status for a redirect', function (int $status): void {
redirecting([bunnyAnswer($status, '/pullzone/5678'), bunnyAnswer(200)], $this->sent);

try {
(new WordPressBunnyPullZone('k'))->classes('1234');
} catch (BunnyRequestFailedException) {
// A status that is not a success is a refusal.
}

expect($this->sent)->toHaveCount(1);
})->with([200, 201, 300, 304, 305, 306, 309, 404]);

it('follows five redirects and no more', function (int $redirects, int $requests, bool $accepted): void {
redirecting([...array_fill(0, $redirects, bunnyAnswer(307, '/pullzone/1234')), bunnyAnswer(200)], $this->sent);
$read = fn (): array => (new WordPressBunnyPullZone('k'))->classes('1234');

$accepted ? expect($read())->toBe([]) : expect($read)->toThrow(BunnyRequestFailedException::class, '307');

expect($this->sent)->toHaveCount($requests);
})->with([
'five' => [5, 6, true],
'six' => [6, 6, false],
]);

it('stops at a redirect that cannot be reached', function (): void {
redirecting([bunnyAnswer(307, '/pullzone/5678'), new WP_Error('http_request_failed', 'timed out'), bunnyAnswer(200)], $this->sent);

expect(fn () => (new WordPressBunnyPullZone('k'))->classes('1234'))->toThrow(BunnyRequestFailedException::class, 'timed out')
->and($this->sent)->toHaveCount(2);
});
Loading