From e90ea17a11e7f0b0307c9ecfd467778804111a1d Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 14:19:59 +0100 Subject: [PATCH 01/17] fix(stream-wrapper): never delete the library through a dot or backslash spelling of its root --- CHANGELOG.md | 1 + .../WordPress/StreamWrapper.php | 12 ++++++++-- tests/Unit/StreamWrapperTest.php | 24 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3936e09..abdc7dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Security: `rmdir('pollora://uploads/.')`, `pollora://.` and spellings with a backslash deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first - Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release - A file is treated as private when the database query that looks its media up fails, instead of public - A personal data export archive that cannot be read is no longer copied to the disk as an empty file before a `TypeError`: `PrivacyExportFailedException` is thrown and the disk is left alone diff --git a/src/Infrastructure/WordPress/StreamWrapper.php b/src/Infrastructure/WordPress/StreamWrapper.php index c7c8951..4936362 100644 --- a/src/Infrastructure/WordPress/StreamWrapper.php +++ b/src/Infrastructure/WordPress/StreamWrapper.php @@ -126,19 +126,27 @@ public static function forgetCopies(): void */ public static function keyOf(string $url): ?string { - $key = trim(substr($url, strlen(self::SCHEME.'://')), '/'); + // The disk reads a backslash as a separator and drops `.` segments: both are done here first, so + // that a spelling of the root is never taken for a folder inside it. + $key = trim(str_replace('\\', '/', substr($url, strlen(self::SCHEME.'://'))), '/'); if ($key === 'uploads' || str_starts_with($key, 'uploads/')) { $key = ltrim(substr($key, strlen('uploads')), '/'); } + $segments = []; + foreach (explode('/', $key) as $segment) { if ($segment === '..') { return null; } + + if ($segment !== '' && $segment !== '.') { + $segments[] = $segment; + } } - return preg_replace('#/{2,}#', '/', $key); + return implode('/', $segments); } public function stream_open(string $path, string $mode, int $options, ?string &$openedPath): bool diff --git a/tests/Unit/StreamWrapperTest.php b/tests/Unit/StreamWrapperTest.php index 9b29daa..c06e9bb 100644 --- a/tests/Unit/StreamWrapperTest.php +++ b/tests/Unit/StreamWrapperTest.php @@ -503,3 +503,27 @@ function withoutWarnings(Closure $call): mixed ->and(implode('', $output))->toBe((string) strlen($marker)) ->and(localCopiesOf($marker))->toBe([]); }); + +it('does not take a dot or a backslash spelling of the root for a folder, which would delete the whole library', function (string $url): void { + $this->disk->storage->write('2026/10/a.jpg', 'x'); + + set_error_handler(static fn (): bool => true); + + try { + $removed = rmdir($url); + } finally { + restore_error_handler(); + } + + expect($removed)->toBeFalse() + ->and(file_exists($this->disk->root.'/2026/10/a.jpg'))->toBeTrue() + ->and(is_dir($this->disk->root))->toBeTrue(); +})->with([ + 'the root of the uploads' => ['pollora://uploads'], + 'the bare scheme' => ['pollora://'], + 'a dot' => ['pollora://.'], + 'a dot under uploads' => ['pollora://uploads/.'], + 'dots and slashes' => ['pollora://uploads/././/'], + 'a backslash' => ['pollora://uploads/\\'], + 'a climb written with backslashes' => ['pollora://uploads/2026\\..'], +]); From 3a5116a871487bf456c43037621164a3be9d03f0 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 14:36:18 +0100 Subject: [PATCH 02/17] fix(private-media): make private the sizes the module writes for a private media --- CHANGELOG.md | 1 + .../WordPress/DeclaredSizes.php | 30 +++- src/Infrastructure/WordPress/SizeWarmer.php | 1 + tests/Unit/PrivateMediaUploadTest.php | 129 ++++++++++++++++++ 4 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 tests/Unit/PrivateMediaUploadTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index abdc7dd..e063e8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Security: the sizes of a private media made at upload, when its image is edited, when its focal point moves or by `thumbs warm` were left with the default visibility of the disk, so readable by their public URL on an object store. They are now made private - Security: `rmdir('pollora://uploads/.')`, `pollora://.` and spellings with a backslash deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first - Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release - A file is treated as private when the database query that looks its media up fails, instead of public diff --git a/src/Infrastructure/WordPress/DeclaredSizes.php b/src/Infrastructure/WordPress/DeclaredSizes.php index 126a840..db53f39 100644 --- a/src/Infrastructure/WordPress/DeclaredSizes.php +++ b/src/Infrastructure/WordPress/DeclaredSizes.php @@ -42,7 +42,7 @@ final class DeclaredSizes private array $focalFiles = []; /** - * @param (Closure(int): bool)|null $isPrivate Whether an attachment is private: a private media never goes to a service that makes the sizes + * @param (Closure(int): bool)|null $isPrivate Whether an attachment is private: a private media never goes to a service that makes the sizes, and its files are private */ public function __construct( private readonly ImageSizes $sizes, @@ -139,7 +139,7 @@ public function focalChanged(mixed $metaId, mixed $attachmentId, mixed $metaKey) return; } - $remade = $this->withEagerSizes($metadata, $this->focalOf($id)); + $remade = $this->withEagerSizes($metadata, $id, $this->focalOf($id)); if ($remade !== $metadata) { \wp_update_attachment_metadata($id, $remade); @@ -168,7 +168,7 @@ public function generate(array $metadata, int $attachmentId, string $context = ' return $metadata; } - return $this->withEagerSizes($metadata, $this->focalOf($attachmentId)); + return $this->withEagerSizes($metadata, $attachmentId, $this->focalOf($attachmentId)); } /** @@ -198,7 +198,7 @@ public function remake(mixed $metadata, int $attachmentId): mixed return $metadata; } - return $this->withEagerSizes($metadata, $this->focalOf($attachmentId)); + return $this->withEagerSizes($metadata, $attachmentId, $this->focalOf($attachmentId)); } /** @@ -309,6 +309,25 @@ public function make(array $metadata, ImageSizeSpec $spec, ?FocalPoint $focal = return ['file' => basename($destination), 'width' => $made['width'], 'height' => $made['height'], 'mime-type' => $made['mime'], 'filesize' => $made['filesize']]; } + /** + * Makes a file just made of a private media private on the disk: it is written with the visibility the disk + * gives every file. A disk that refuses is reported, and does not fail what made the file. + * + * @param string $file The path of the file, relative to the library + */ + public function protect(int $attachmentId, string $file): void + { + if (! $this->isPrivate instanceof Closure || ! ($this->isPrivate)($attachmentId)) { + return; + } + + try { + $this->storage->setVisibility($file, 'private'); + } catch (Throwable $throwable) { + \error_log(sprintf('pollora/media: %s of a private media was not made private: %s', $file, $throwable->getMessage())); + } + } + /** * The path of the file a size makes of an original, relative to the library. * @@ -382,7 +401,7 @@ public function isMakeable(array $metadata): bool * @param array $metadata * @return array */ - private function withEagerSizes(array $metadata, ?FocalPoint $focal = null): array + private function withEagerSizes(array $metadata, int $attachmentId, ?FocalPoint $focal = null): array { foreach ($this->known() as $spec) { if (! $spec->eager || ! $this->driverFor($spec->focusedOn($focal))->makesFiles()) { @@ -392,6 +411,7 @@ private function withEagerSizes(array $metadata, ?FocalPoint $focal = null): arr $entry = $this->make($metadata, $spec, $focal); if ($entry !== null) { + $this->protect($attachmentId, $this->fileFor($metadata, $spec, $focal)); $sizes = is_array($metadata['sizes'] ?? null) ? $metadata['sizes'] : []; $sizes[$spec->name] = $entry; $metadata['sizes'] = $sizes; diff --git a/src/Infrastructure/WordPress/SizeWarmer.php b/src/Infrastructure/WordPress/SizeWarmer.php index 389a424..c275a22 100644 --- a/src/Infrastructure/WordPress/SizeWarmer.php +++ b/src/Infrastructure/WordPress/SizeWarmer.php @@ -92,6 +92,7 @@ private function warmOne(int $id, array $specs, array &$report): void continue; } + $this->declared->protect($id, $this->declared->fileFor($metadata, $spec, $focal)); $metadata['sizes'][$spec->name] = $entry; $report['made']++; $changed = true; diff --git a/tests/Unit/PrivateMediaUploadTest.php b/tests/Unit/PrivateMediaUploadTest.php new file mode 100644 index 0000000..9ac4a28 --- /dev/null +++ b/tests/Unit/PrivateMediaUploadTest.php @@ -0,0 +1,129 @@ +storage); + $disk->storage->write('2026/10/photo.jpg', 'original'); + $sizes = new ImageSizes(fn (): string => 'secret-key'); + $sizes->add('card')->cover(600, 400)->eager(); + $metadata = ['file' => '2026/10/photo.jpg', 'width' => 3000, 'height' => 2000, 'sizes' => []]; + Functions\when('did_action')->justReturn(0); + Functions\when('get_post_meta')->justReturn(''); + Functions\when('update_post_meta')->justReturn(true); + // As during an upload: what the filter returns is not saved yet + Functions\when('wp_get_attachment_metadata')->justReturn($metadata); + Filters\expectApplied('pollora/media/is_private')->andReturn(true); + $callbacks = []; + Filters\expectAdded('wp_generate_attachment_metadata')->zeroOrMoreTimes()->whenHappen(function (callable $callback, int $priority = 10) use (&$callbacks): void { + $callbacks[$priority][] = $callback; + }); + + (new WordPressMedia($storage, new MediaConfig('https://media.client.fr'), null, $sizes, new FakeImageProcessor($storage)))->register(); + ksort($callbacks); + + foreach (array_merge(...$callbacks) as $callback) { + $metadata = $callback($metadata, 7, 'create'); + } + + $files = array_column(array_filter($disk->storage->list('', true), static fn (array $entry): bool => $entry['type'] === 'file'), 'path'); + + expect($files)->toHaveCount(2); + + foreach ($files as $file) { + expect($storage->visibility($file))->toBe('private', $file); + } +}); + +describe('the sizes made after the upload of a private media', function (): void { + beforeEach(function (): void { + $this->disk = new TemporaryStorage; + $this->storage = new SigningStorage($this->disk->storage); + $this->disk->storage->write('2026/10/photo.jpg', 'original'); + $this->sizes = new ImageSizes(fn (): string => 'secret-key'); + $this->sizes->add('card')->cover(600, 400)->eager(); + $this->metadata = ['file' => '2026/10/photo.jpg', 'width' => 3000, 'height' => 2000, 'sizes' => []]; + $this->private = true; + $this->postMeta = ''; + Functions\when('get_post_meta')->alias(fn (): mixed => $this->postMeta); + Functions\when('wp_get_attachment_metadata')->justReturn($this->metadata); + Functions\when('wp_update_attachment_metadata')->justReturn(true); + $this->declared = new DeclaredSizes($this->sizes, new MediaConfig('https://m.test'), $this->storage, new FakeImageProcessor($this->storage), null, fn (int $id): bool => $this->private, new FocalPoints); + $this->card = $this->declared->fileFor($this->metadata, $this->sizes->get('card')); + }); + + it('are private when its image is edited', function (): void { + $edited = ['file' => '2026/10/photo-e1.jpg', 'width' => 2000, 'height' => 2000, 'sizes' => []]; + $this->disk->storage->write('2026/10/photo-e1.jpg', 'edited'); + + $this->declared->remake($edited, 7); + + expect($this->storage->visibility($this->declared->fileFor($edited, $this->sizes->get('card'))))->toBe('private'); + }); + + it('are private when its focal point moves', function (): void { + $this->postMeta = ['x' => 0.25, 'y' => 0.75]; + + $this->declared->focalChanged(1, 7, '_pollora_focal_point'); + + expect($this->storage->visibility($this->declared->fileFor($this->metadata, $this->sizes->get('card'), new FocalPoint(0.25, 0.75))))->toBe('private'); + }); + + it('are private when the library is warmed', function (): void { + Functions\when('get_posts')->justReturn([7]); + + (new SizeWarmer($this->declared, $this->storage))->warm(); + + expect($this->storage->visibility($this->card))->toBe('private'); + }); + + it('are left as the disk makes them for a public media', function (): void { + $this->private = false; + + $this->declared->generate($this->metadata, 7); + + expect($this->storage->visibilities)->toBe([]); + }); + + it('do not fail the upload when the disk refuses the visibility, and the log says so', function (): void { + // This storage refuses the visibility of a file it does not hold, as a disk without access lists would + $storage = new SigningStorage((new TemporaryStorage)->storage); + $declared = new DeclaredSizes($this->sizes, new MediaConfig('https://m.test'), $storage, new FakeImageProcessor($this->disk->storage), null, static fn (int $id): bool => true); + $log = tempnam(sys_get_temp_dir(), 'media-log'); + $previous = ini_set('error_log', $log); + + try { + $metadata = $declared->generate($this->metadata, 7); + } finally { + ini_set('error_log', (string) $previous); + } + + expect($metadata['sizes'])->toHaveKey('card') + ->and(file_get_contents($log))->toContain($this->card, 'not made private'); + unlink($log); + }); +}); From 0de00ea7d4f322eba86d5c0e7ddca0a636b1b393 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 14:54:57 +0100 Subject: [PATCH 03/17] fix(private-media): keep every file of a private media private, and out of the fallback route A media that is not an image has no file in its metadata, so it was never made private. Files written after the marking, the files kept of an image before its edit and the copy the block editor makes stayed public. The fallback route served the existing sizes of a private media, and thumbs warm skipped them. --- CHANGELOG.md | 8 + README.md | 26 +- src/Application/Services/ThumbnailService.php | 16 +- .../WordPress/AttachmentFiles.php | 88 ++++- .../WordPress/DeclaredSizes.php | 2 + src/Infrastructure/WordPress/PrivateMedia.php | 80 ++++- src/Infrastructure/WordPress/SizeWarmer.php | 9 +- tests/Integration/PrivateMediaTest.php | 123 +++++++ tests/Unit/PrivateMediaGapsTest.php | 303 ++++++++++++++++++ tests/Unit/PrivateMediaTest.php | 3 + 10 files changed, 642 insertions(+), 16 deletions(-) create mode 100644 tests/Integration/PrivateMediaTest.php create mode 100644 tests/Unit/PrivateMediaGapsTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index e063e8a..51f666c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,8 +14,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- Security: a private media that is not an image (PDF, archive, video, audio) was never made private on the disk, neither at upload nor by `wp pollora media visibility --private`, which reported a success with no file changed +- Security: the files written after a media was made private (an edit in the media library, sizes made later, the new media the block editor saves a crop or a rotation as) were left public. They are made private when the metadata is saved, and the copy made by the editor is private +- Security: the files WordPress keeps of an image before its edit, and its other companions (`source_image`, `animated_video`, `animated_video_poster`), did not follow the visibility of the media +- Security: the fallback route served the file of a size of a private media when that file existed, and made or served sizes of the original a private image had before its edit +- Security: while the server is saturated, the fallback route could answer with a size of another media whose name starts like the one asked for, private or not +- Security: `thumbs warm` leaves the sizes that exist of a private media private + - Security: the sizes of a private media made at upload, when its image is edited, when its focal point moves or by `thumbs warm` were left with the default visibility of the disk, so readable by their public URL on an object store. They are now made private - Security: `rmdir('pollora://uploads/.')`, `pollora://.` and spellings with a backslash deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first +- Repairing existing sites: run `wp pollora media visibility --private` for each private media, then `wp pollora media thumbs prune --execute`, and purge the CDN. See *Repairing media left public* in the README - Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release - A file is treated as private when the database query that looks its media up fails, instead of public - A personal data export archive that cannot be read is no longer copied to the disk as an empty file before a `TypeError`: `PrivacyExportFailedException` is thrown and the disk is left alone diff --git a/README.md b/README.md index 11e5245..a96665c 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,8 @@ add_filter('pollora/media/filesystem', fn () => new Filesystem(new SftpAdapter(/ | `wp_privacy_exports_dir`, `wp_privacy_exports_url`, `wp_privacy_personal_data_export_file_created`, `wp_privacy_delete_old_export_files` | The personal data export builds its archive locally (`ZipArchive` cannot write to a wrapper), copies it to the disk, links it through the public URL, and the old archives are deleted from the disk | | `wp_get_attachment_url`, `wp_get_attachment_image_src`, `wp_calculate_image_srcset` | Private media only: the URL, the URL of a size and every source of a `srcset` are signed and expire. A public media keeps its plain URL, and nothing is asked of the disk to tell them apart | -| `wp_generate_attachment_metadata` | A media created private (see below) is private on the disk from the start | +| `wp_generate_attachment_metadata` | A media created private (see below) is made private on the disk | +| `wp_update_attachment_metadata`, `wp_edited_image_metadata` | Private media only: the files written since are made private, and the copy the editor makes of a private image is private | The `pollora://` wrapper sends a file to the disk when its stream is closed, in one write. Directories do not exist on an object store, so they are virtual and answer without asking the disk (a path with an extension is a file); what is asked about a file is remembered for the rest of the request. A file written or read during a request, up to 16 MiB, is also kept in a local copy until the request ends: WordPress reads an uploaded image again for its size, its EXIF data, its sizes and its metadata, and none of it goes back to the disk. One upload of an image with nine sizes costs ten writes and a handful of existence checks; a read of the original, a stat or a listing never happens. Both the GD and the Imagick editors of WordPress work on the wrapper as they are. @@ -234,6 +235,29 @@ Hooks to build on it: A disk that cannot sign a URL (a plain local disk) serves the plain URL of a private media, rather than a broken one: a private media needs an object store, or a signature of your own through `pollora/media/signed_url`. +A file written for a media that is already private is written with the visibility of the disk, then made private when the metadata of the media is saved. A file a plugin writes without saving the metadata stays as written: declare it with `pollora/media/attachment_files` and run the command above. A flag set directly in the post meta, or a filter whose answer changes, does not touch the disk by itself either. + +Visibility is the one the disk keeps for each file (on S3, the ACL of the object). A bucket with ACLs disabled (*Bucket owner enforced*), a bucket policy or a CDN that makes every object public, or a provider without object ACLs keeps a private media readable by its plain URL, whatever the module does. + +### Repairing media left public + +Up to 0.10.0, some files of private media were left public (see the CHANGELOG). Making each private media private again changes every file of it, and can be repeated: + +```bash +# The media flagged private +for id in $(wp post list --post_type=attachment --post_status=any --meta_key=_pollora_media_private --meta_value=1 --field=ID); do + wp pollora media visibility "$id" --private +done + +# The media private by a `pollora/media/is_private` rule only. The command also flags them, which a rule that +# lets a media become public again has to take into account +for id in $(wp post list --post_type=attachment --post_status=any --field=ID); do + wp pollora media files "$id" | grep -q "Media $id is private" && wp pollora media visibility "$id" --private +done +``` + +In Pollora, the Artisan commands of the framework do the same. Then run `wp pollora media thumbs prune --execute`, which deletes the files of the sizes that were changed or removed since (no command knows which media they were made of), and purge the CDN, which may keep what it already read. Run the first loop again after a `migrate`: files copied from a local folder keep the visibility they had there. + ## Commands ```bash diff --git a/src/Application/Services/ThumbnailService.php b/src/Application/Services/ThumbnailService.php index 82b13c9..b82b814 100644 --- a/src/Application/Services/ThumbnailService.php +++ b/src/Application/Services/ThumbnailService.php @@ -92,11 +92,19 @@ public function serve(string $key): ThumbnailResult */ private function produce(string $key, string $original, array $parsed, ImageSizeSpec $spec): ThumbnailResult { - if ($this->storage->exists($key)) { + $made = $this->storage->exists($key); + + // Also for a file already there: this route reads the disk with the credentials of the site, and what it + // answers is cached for everyone + if (($this->isPrivate)($original)) { + return ThumbnailResult::notFound(); + } + + if ($made) { return $this->file($key, $parsed['extension']); } - if (strtolower(pathinfo($original, PATHINFO_EXTENSION)) === 'gif' || ! $this->storage->exists($original) || ($this->isPrivate)($original)) { + if (strtolower(pathinfo($original, PATHINFO_EXTENSION)) === 'gif' || ! $this->storage->exists($original)) { return ThumbnailResult::notFound(); } @@ -179,7 +187,9 @@ private function nearest(string $original, array $parsed): ThumbnailResult $name = basename($entry['path']); - if (preg_match('/^'.preg_quote($parsed['stem'], '/').'-(?:[a-z0-9_]+-)?(\d+)x(\d+)(?:-f\d{4}_\d{4})?(?:-[0-9a-f]{12})?\.(jpe?g|png|webp|avif)$/D', $name, $match) === 1) { + // A size of WordPress is `stem-WxH`, one of the module has a name and a signature. A word between the stem + // and the dimensions without a signature is the name of another media, which may be private. + if (preg_match('/^'.preg_quote($parsed['stem'], '/').'-(?:(?:[a-z0-9_]+(?:-\d+w)?-)(?=\d+x\d+(?:-f\d{4}_\d{4})?-[0-9a-f]{12}\.))?(\d+)x\d+(?:-f\d{4}_\d{4})?(?:-[0-9a-f]{12})?\.(?:jpe?g|png|webp|avif)$/D', $name, $match) === 1) { $candidates[$entry['path']] = (int) $match[1]; } } diff --git a/src/Infrastructure/WordPress/AttachmentFiles.php b/src/Infrastructure/WordPress/AttachmentFiles.php index 76b66f2..934ffd0 100644 --- a/src/Infrastructure/WordPress/AttachmentFiles.php +++ b/src/Infrastructure/WordPress/AttachmentFiles.php @@ -8,32 +8,40 @@ /** * Every file of a media on the disk: the original, each size, the original - * image of a scaled one, and the files a plugin keeps next to it + * image of a scaled one and the other companions WordPress records, what it keeps + * of an image before its edit, and the files a plugin keeps next to it * (`pollora/media/attachment_files`). Paths are relative to the library. + * + * A media that is not an image (PDF, archive, video, audio) has no file in its + * metadata: its original is the attached file. */ final class AttachmentFiles { + /** The metadata entries that name a file kept beside the original. */ + private const array COMPANIONS = ['original_image', 'source_image', 'animated_video', 'animated_video_poster', 'thumb']; + /** * @param (\Closure(array, int): list)|null $declared The files of the declared sizes that exist for an original, with its metadata and its id */ public function __construct(private readonly ?\Closure $declared = null) {} /** + * @param array|null $metadata The metadata to read the files from, when it is about to be saved. Default: the saved one * @return list */ - public function for(int $attachmentId): array + public function for(int $attachmentId, ?array $metadata = null): array { - $metadata = \wp_get_attachment_metadata($attachmentId); - $metadata = is_array($metadata) ? $metadata : []; - - $file = (string) ($metadata['file'] ?? ''); + $metadata ??= \wp_get_attachment_metadata($attachmentId); + $metadata = $this->named(is_array($metadata) ? $metadata : []); + $attached = $this->attachedFile($attachmentId); + $file = Cast::text($metadata['file'] ?? '') ?: $attached; if ($file === '') { return $this->declaredBy($attachmentId, []); } $directory = dirname($file) === '.' ? '' : dirname($file).'/'; - $files = [$file]; + $files = $attached === '' ? [$file] : [$file, $attached]; foreach ((array) ($metadata['sizes'] ?? []) as $size) { $name = $this->fileOf($size); @@ -43,17 +51,79 @@ public function for(int $attachmentId): array } } - if (isset($metadata['original_image'])) { - $files[] = $directory.$metadata['original_image']; + foreach (self::COMPANIONS as $companion) { + $name = Cast::text($metadata[$companion] ?? ''); + + if ($name !== '') { + $files[] = $directory.$name; + } } if ($this->declared instanceof \Closure) { $files = [...$files, ...($this->declared)($metadata, $attachmentId)]; } + $files = [...$files, ...$this->beforeEdit($attachmentId, $directory)]; + return $this->declaredBy($attachmentId, array_values(array_unique($files))); } + /** + * Attachment metadata, whose keys are names: the same array, typed as such. + * + * @param array $metadata + * @return array + */ + private function named(array $metadata): array + { + $named = []; + + foreach ($metadata as $name => $value) { + $named[(string) $name] = $value; + } + + return $named; + } + + /** + * The attached file, when it is a path of the library: not one outside the uploads folder, nor a URL. + */ + private function attachedFile(int $attachmentId): string + { + $file = Cast::text(\get_post_meta($attachmentId, '_wp_attached_file', true)); + + return str_starts_with($file, '/') || str_contains($file, '://') ? '' : $file; + } + + /** + * What WordPress keeps to restore an edited image: the previous originals and sizes, and the declared + * sizes that were made of those originals. + * + * @return list + */ + private function beforeEdit(int $attachmentId, string $directory): array + { + $backups = \get_post_meta($attachmentId, '_wp_attachment_backup_sizes', true); + $files = []; + + foreach (is_array($backups) ? $backups : [] as $key => $backup) { + $name = $this->fileOf($backup); + + if ($name === null) { + continue; + } + + $files[] = $directory.$name; + + // The entries of a previous original are `full-orig` and `full-{time of the edit}` + if ($this->declared instanceof \Closure && is_array($backup) && str_starts_with((string) $key, 'full-')) { + $files = [...$files, ...($this->declared)(['file' => $directory.$name, 'width' => $backup['width'] ?? null, 'height' => $backup['height'] ?? null], $attachmentId)]; + } + } + + return $files; + } + private function fileOf(mixed $size): ?string { return is_array($size) && is_string($size['file'] ?? null) ? $size['file'] : null; diff --git a/src/Infrastructure/WordPress/DeclaredSizes.php b/src/Infrastructure/WordPress/DeclaredSizes.php index db53f39..43fa388 100644 --- a/src/Infrastructure/WordPress/DeclaredSizes.php +++ b/src/Infrastructure/WordPress/DeclaredSizes.php @@ -313,6 +313,8 @@ public function make(array $metadata, ImageSizeSpec $spec, ?FocalPoint $focal = * Makes a file just made of a private media private on the disk: it is written with the visibility the disk * gives every file. A disk that refuses is reported, and does not fail what made the file. * + * @internal Shared with the warmer of the sizes + * * @param string $file The path of the file, relative to the library */ public function protect(int $attachmentId, string $file): void diff --git a/src/Infrastructure/WordPress/PrivateMedia.php b/src/Infrastructure/WordPress/PrivateMedia.php index 4aaefbd..0202efb 100644 --- a/src/Infrastructure/WordPress/PrivateMedia.php +++ b/src/Infrastructure/WordPress/PrivateMedia.php @@ -44,6 +44,9 @@ public function register(): void \add_filter('wp_get_attachment_image_src', [$this, 'imageSrc'], 10, 2); \add_filter('wp_calculate_image_srcset', [$this, 'srcset'], 10, 5); \add_filter('wp_generate_attachment_metadata', [$this, 'generated'], 5, 3); + // Last: what the other callbacks added to the metadata is made private too + \add_filter('wp_update_attachment_metadata', [$this, 'saving'], PHP_INT_MAX, 2); + \add_filter('wp_edited_image_metadata', [$this, 'edited'], 10, 3); } public function isPrivate(int $attachmentId): bool @@ -127,6 +130,32 @@ public function isPrivateFile(string $file): bool $id = $wpdb->get_var($wpdb->prepare("SELECT post_id FROM %i WHERE meta_key = '_wp_attached_file' AND meta_value = %s LIMIT 1", $wpdb->postmeta, $file)); // No row and a failed query both read as null: only the first one means the file is not private + if ($id !== null) { + return $this->isPrivate((int) $id); + } + + return $wpdb->last_error !== '' || $this->wasPrivateFile($file); + } + + /** + * Whether the file is one a private image had before its edit, which WordPress keeps to restore it: the + * attached file of that media is another one now. + */ + private function wasPrivateFile(string $file): bool + { + /** @var \wpdb $wpdb The global WordPress sets, which has no declared type */ + global $wpdb; + + $directory = dirname($file) === '.' ? '' : addcslashes(dirname($file), '_%\\').'/'; + + $id = $wpdb->get_var($wpdb->prepare( + "SELECT b.post_id FROM %i b INNER JOIN %i a ON a.post_id = b.post_id AND a.meta_key = '_wp_attached_file' WHERE b.meta_key = '_wp_attachment_backup_sizes' AND b.meta_value LIKE %s AND a.meta_value LIKE %s LIMIT 1", + $wpdb->postmeta, + $wpdb->postmeta, + '%"'.addcslashes(basename($file), '_%\\').'"%', + $directory.'%', + )); + return $id === null ? $wpdb->last_error !== '' : $this->isPrivate((int) $id); } @@ -139,7 +168,51 @@ public function isPrivateFile(string $file): bool public function generated(array $metadata, int $attachmentId, string $context = 'create'): array { if ($context === 'create' && $this->isPrivate($attachmentId)) { - $this->setPrivate($attachmentId, true); + foreach ($this->setPrivate($attachmentId, true)['failed'] as $file) { + $this->report($file); + } + } + + return $metadata; + } + + /** + * WordPress and the module write files of a media after it was made private: an edit, a size made later, + * a plugin. They are written with the visibility the disk gives every file, and made private when the + * metadata that tells of them is saved. + * + * @internal Callback of `wp_update_attachment_metadata` + * + * @param mixed $metadata What is about to be saved + */ + public function saving(mixed $metadata, int $attachmentId): mixed + { + if (! $this->isPrivate($attachmentId)) { + return $metadata; + } + + foreach ($this->files->for($attachmentId, is_array($metadata) ? $metadata : null) as $file) { + try { + $this->storage->setVisibility($file, 'private'); + } catch (Throwable) { + $this->report($file); + } + } + + return $metadata; + } + + /** + * The editor saves an edit of an image as a new media: the one made of a private media is private. + * + * @internal Callback of `wp_edited_image_metadata` + * + * @param mixed $metadata The metadata of the new media + */ + public function edited(mixed $metadata, int $newAttachmentId, int $attachmentId): mixed + { + if ($this->isPrivate($attachmentId)) { + $this->setPrivate($newAttachmentId, true); } return $metadata; @@ -171,6 +244,11 @@ public function setPrivate(int $attachmentId, bool $private): array return ['changed' => $changed, 'failed' => $failed]; } + private function report(string $file): void + { + \error_log(sprintf('pollora/media: %s of a private media was not made private', $file)); + } + private function sign(string $url, int $attachmentId): string { $prefix = $this->config->url.'/'; diff --git a/src/Infrastructure/WordPress/SizeWarmer.php b/src/Infrastructure/WordPress/SizeWarmer.php index c275a22..bf7a7f3 100644 --- a/src/Infrastructure/WordPress/SizeWarmer.php +++ b/src/Infrastructure/WordPress/SizeWarmer.php @@ -80,7 +80,12 @@ private function warmOne(int $id, array $specs, array &$report): void $changed = false; foreach ($specs as $spec) { - if ($this->storage->exists($this->declared->fileFor($metadata, $spec, $focal))) { + $file = $this->declared->fileFor($metadata, $spec, $focal); + + if ($this->storage->exists($file)) { + // A file left public by an earlier version, or made before the media was made private + $this->declared->protect($id, $file); + continue; } @@ -92,7 +97,7 @@ private function warmOne(int $id, array $specs, array &$report): void continue; } - $this->declared->protect($id, $this->declared->fileFor($metadata, $spec, $focal)); + $this->declared->protect($id, $file); $metadata['sizes'][$spec->name] = $entry; $report['made']++; $changed = true; diff --git a/tests/Integration/PrivateMediaTest.php b/tests/Integration/PrivateMediaTest.php new file mode 100644 index 0000000..73ba840 --- /dev/null +++ b/tests/Integration/PrivateMediaTest.php @@ -0,0 +1,123 @@ +getPathname()); + + if (str_starts_with($file->getFilename(), $stem) && ($file->getPerms() & 0004) !== 0) { + $files[] = $file->getFilename(); + } + } + + return $files; +} + +function uploadMedia(string $name, string $bytes, string $mime): int +{ + $upload = wp_upload_bits($name, null, $bytes); + $id = wp_insert_attachment(['post_mime_type' => $mime, 'post_title' => $name, 'post_status' => 'inherit'], $upload['file']); + wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file'])); + + return $id; +} + +function photo(): string +{ + $image = imagecreatetruecolor(2000, 1500); + ob_start(); + imagejpeg($image); + + return (string) ob_get_clean(); +} + +beforeEach(function (): void { + $this->media = Library::boot(); + + foreach (['image', 'image-edit', 'file', 'media'] as $file) { + require_once ABSPATH.'wp-admin/includes/'.$file.'.php'; + } + + wp_set_current_user(1); + $this->stem = 'private'.bin2hex(random_bytes(4)); + $this->edit = function (int $id): void { + $_REQUEST['history'] = wp_slash((string) wp_json_encode([['r' => 90]])); + $_REQUEST['target'] = 'all'; + $_REQUEST['do'] = 'save'; + wp_save_image($id); + unset($_REQUEST['history'], $_REQUEST['target'], $_REQUEST['do']); + }; +}); + +it('makes private a PDF, an archive, a video and an audio file created private', function (string $extension, string $mime): void { + add_filter('pollora/media/is_private', $all = static fn (): bool => true); + + try { + uploadMedia($this->stem.'.'.$extension, 'secret', $mime); + } finally { + remove_filter('pollora/media/is_private', $all); + } + + expect(publicFiles($this->stem))->toBe([]); +})->with([['pdf', 'application/pdf'], ['zip', 'application/zip'], ['mp4', 'video/mp4'], ['mp3', 'audio/mpeg']]); + +it('keeps private what an edit, a later making of the sizes and a copy of the editor write', function (): void { + add_filter('intermediate_image_sizes_advanced', $none = static fn (): array => [], 200); + $id = uploadMedia($this->stem.'.jpg', photo(), 'image/jpeg'); + remove_filter('intermediate_image_sizes_advanced', $none, 200); + $this->media->privateMedia()->setPrivate($id, true); + + wp_update_image_subsizes($id); + expect(publicFiles($this->stem))->toBe([]); + + ($this->edit)($id); + expect(get_post_meta($id, '_wp_attached_file', true))->toContain('-e') + ->and(publicFiles($this->stem))->toBe([]); + + $request = new WP_REST_Request('POST', "/wp/v2/media/{$id}/edit"); + $request->set_body_params(['src' => Library::URL.'/'.get_post_meta($id, '_wp_attached_file', true), 'rotation' => 90]); + $response = rest_do_request($request); + + expect($response->get_status())->toBe(201) + ->and($this->media->privateMedia()->isPrivate($response->get_data()['id']))->toBeTrue() + ->and(publicFiles($this->stem))->toBe([]); +}); + +it('does not serve through the fallback route the sizes of the original a private image had before its edit', function (): void { + $id = uploadMedia($this->stem.'.jpg', photo(), 'image/jpeg'); + $this->media->privateMedia()->setPrivate($id, true); + $sizes = $this->media->declaredSizes(); + $metadata = wp_get_attachment_metadata($id); + $square = $sizes->fileFor($metadata, $sizes->specs()['square']); + $card = $sizes->fileFor($metadata, $sizes->specs()['card']); + expect($this->media->thumbnailService()->serve($square)->status)->toBe(404); + + ($this->edit)($id); + + expect($this->media->thumbnailService()->serve($square)->status)->toBe(404) + ->and($this->media->thumbnailService()->serve($card)->status)->toBe(404) + ->and(publicFiles($this->stem))->toBe([]); +}); + +it('repairs the files left public of a media edited before it was made private', function (): void { + $id = uploadMedia($this->stem.'.jpg', photo(), 'image/jpeg'); + ($this->edit)($id); + // Flagged without a change on the disk, as the files left by an earlier version are + update_post_meta($id, '_pollora_media_private', '1'); + expect(publicFiles($this->stem))->toContain($this->stem.'.jpg'); + + $report = $this->media->privateMedia()->setPrivate($id, true); + + expect($report['failed'])->toBe([])->and(publicFiles($this->stem))->toBe([]); +}); diff --git a/tests/Unit/PrivateMediaGapsTest.php b/tests/Unit/PrivateMediaGapsTest.php new file mode 100644 index 0000000..140a5a3 --- /dev/null +++ b/tests/Unit/PrivateMediaGapsTest.php @@ -0,0 +1,303 @@ +disk = new TemporaryStorage; + $this->storage = new SigningStorage($this->disk->storage); + $this->config = new MediaConfig('https://media.client.fr'); + $this->meta = []; + $this->metadata = []; + Functions\when('get_post_meta')->alias(fn (int $id, string $key): mixed => $this->meta[$id][$key] ?? ''); + Functions\when('update_post_meta')->alias(function (int $id, string $key, mixed $value): bool { + $this->meta[$id][$key] = $value; + + return true; + }); + Functions\when('delete_post_meta')->justReturn(true); + Functions\when('wp_get_attachment_metadata')->alias(fn (int $id): mixed => $this->metadata[$id] ?? false); + $this->private = new PrivateMedia($this->storage, $this->config, new AttachmentFiles); + $this->put = function (string ...$files): void { + foreach ($files as $file) { + $this->disk->storage->write($file, 'x'); + } + }; +}); + +it('makes private the file of a media that has no file in its metadata', function (mixed $metadata): void { + $this->meta[7]['_wp_attached_file'] = '2026/10/secret.bin'; + $this->metadata[7] = $metadata; + ($this->put)('2026/10/secret.bin'); + + $report = $this->private->setPrivate(7, true); + + expect($report['changed'])->toBe(['2026/10/secret.bin']) + ->and($this->storage->visibility('2026/10/secret.bin'))->toBe('private'); +})->with([ + 'a zip, a video or an audio file' => [['filesize' => 4]], + 'no metadata at all' => [false], +]); + +it('makes private the preview images of a PDF beside the PDF', function (): void { + $this->meta[7]['_wp_attached_file'] = '2026/10/doc.pdf'; + $this->metadata[7] = ['sizes' => ['full' => ['file' => 'doc-pdf.jpg'], 'thumbnail' => ['file' => 'doc-pdf-106x150.jpg']]]; + ($this->put)('2026/10/doc.pdf', '2026/10/doc-pdf.jpg', '2026/10/doc-pdf-106x150.jpg'); + + $this->private->setPrivate(7, true); + + expect($this->storage->visibilities)->toHaveCount(3)->each->toBe('private'); +}); + +it('lists the files WordPress keeps of an image before its edit, and the companions it keeps beside it', function (): void { + $this->meta[7] = [ + '_wp_attached_file' => '2026/10/photo-e1.jpg', + '_wp_attachment_backup_sizes' => [ + 'full-orig' => ['file' => 'photo.jpg', 'width' => 3000, 'height' => 2000], + 'thumbnail-orig' => ['file' => 'photo-150x150.jpg'], + 'broken' => 'not a size', + ], + ]; + $this->metadata[7] = ['file' => '2026/10/photo-e1.jpg', 'source_image' => 'photo.heic', 'animated_video' => 'photo.mp4', 'animated_video_poster' => 'photo-poster.jpg', 'thumb' => 'photo-thumb.jpg']; + $declared = static fn (array $metadata): array => [$metadata['file'].'.card']; + + expect((new AttachmentFiles($declared))->for(7))->toEqualCanonicalizing([ + '2026/10/photo-e1.jpg', + '2026/10/photo.heic', + '2026/10/photo.mp4', + '2026/10/photo-poster.jpg', + '2026/10/photo-thumb.jpg', + '2026/10/photo.jpg', + '2026/10/photo-150x150.jpg', + '2026/10/photo-e1.jpg.card', + // the declared sizes of the original as it was before the edit + '2026/10/photo.jpg.card', + ]); +}); + +it('leaves out an attached file that is not a path of the library', function (string $attached): void { + $this->meta[7]['_wp_attached_file'] = $attached; + + expect((new AttachmentFiles)->for(7))->toBe([]); +})->with(['/var/www/outside.pdf', 'https://elsewhere.test/outside.pdf']); + +it('makes private the files a save of the metadata of a private media tells of', function (): void { + $this->meta[7] = [PrivateMedia::META => '1', '_wp_attached_file' => '2026/10/photo-e1.jpg']; + $saved = ['file' => '2026/10/photo-e1.jpg', 'sizes' => ['thumbnail' => ['file' => 'photo-e1-150x150.jpg']]]; + ($this->put)('2026/10/photo-e1.jpg', '2026/10/photo-e1-150x150.jpg', '2026/10/photo-e1.webp'); + Filters\expectApplied('pollora/media/attachment_files')->andReturn(['2026/10/photo-e1.webp']); + + // The metadata is not saved yet: what the filter receives says which files there are + expect($this->private->saving($saved, 7))->toBe($saved) + ->and($this->storage->visibilities)->toBe([ + '2026/10/photo-e1.jpg' => 'private', + '2026/10/photo-e1-150x150.jpg' => 'private', + '2026/10/photo-e1.webp' => 'private', + ]); +}); + +it('touches nothing when the metadata of a public media is saved', function (): void { + $this->meta[7]['_wp_attached_file'] = '2026/10/photo.jpg'; + ($this->put)('2026/10/photo.jpg'); + + $this->private->saving(['file' => '2026/10/photo.jpg'], 7); + + expect($this->storage->visibilities)->toBe([]); +}); + +it('logs a file the disk refuses to make private, and lets the metadata be saved', function (string $method): void { + $this->meta[7] = [PrivateMedia::META => '1', '_wp_attached_file' => '2026/10/gone.jpg']; + $log = tempnam(sys_get_temp_dir(), 'media-log'); + $previous = ini_set('error_log', $log); + + try { + $method === 'saving' ? $this->private->saving(false, 7) : $this->private->generated([], 7, 'create'); + } finally { + ini_set('error_log', (string) $previous); + } + + expect(file_get_contents($log))->toContain('2026/10/gone.jpg', 'not made private'); + unlink($log); +})->with(['saving', 'generated']); + +it('hooks the saves of the metadata after the sizes are made, and the copies the editor makes', function (): void { + Filters\expectAdded('wp_update_attachment_metadata')->once()->with(Mockery::type('array'), PHP_INT_MAX, 2); + Filters\expectAdded('wp_edited_image_metadata')->once()->with(Mockery::type('array'), 10, 3); + + $this->private->register(); +}); + +it('makes private the new media the editor saves an edit of a private one as', function (): void { + $this->meta[7][PrivateMedia::META] = '1'; + $this->meta[8]['_wp_attached_file'] = '2026/10/photo-edited.jpg'; + ($this->put)('2026/10/photo-edited.jpg'); + // Asked while WordPress makes the sizes of the copy, before it is known to come from a private media + expect($this->private->isPrivate(8))->toBeFalse(); + + $this->private->edited(['file' => '2026/10/photo-edited.jpg'], 8, 7); + + expect($this->private->isPrivate(8))->toBeTrue() + ->and($this->meta[8][PrivateMedia::META])->toBe('1') + ->and($this->storage->visibility('2026/10/photo-edited.jpg'))->toBe('private'); +}); + +it('leaves the copy of a public media public', function (): void { + $this->private->edited([], 8, 7); + + expect($this->meta)->toBe([]); +}); + +it('makes private the sizes of a private media that are there already when the library is warmed', function (): void { + $sizes = new ImageSizes(fn (): string => 'secret-key'); + $sizes->add('card')->cover(600, 400); + $metadata = ['file' => '2026/10/photo.jpg', 'width' => 3000, 'height' => 2000, 'sizes' => []]; + $this->metadata[7] = $metadata; + $declared = new DeclaredSizes($sizes, $this->config, $this->storage, new FakeImageProcessor($this->disk->storage), null, static fn (): bool => true); + $card = $declared->fileFor($metadata, $sizes->get('card')); + ($this->put)('2026/10/photo.jpg', $card); + Functions\when('get_posts')->justReturn([7]); + + $report = (new SizeWarmer($declared, $this->storage))->warm(); + + expect($report['made'])->toBe(0)->and($this->storage->visibility($card))->toBe('private'); +}); + +it('repairs a private media left public with the visibility command', function (): void { + $this->meta[7] = [PrivateMedia::META => '1', '_wp_attached_file' => '2026/10/doc.pdf']; + $this->metadata[7] = ['filesize' => 1]; + ($this->put)('2026/10/doc.pdf'); + $command = new MediaCommand($this->storage, $this->config, '/nowhere', 'https://nowhere.test', $this->private, new AttachmentFiles); + + $command->visibility(['7'], ['private' => true]); + + expect($this->storage->visibility('2026/10/doc.pdf'))->toBe('private'); +}); + +describe('the fallback route', function (): void { + beforeEach(function (): void { + $this->sizes = new ImageSizes(fn (): string => 'secret-key'); + $this->sizes->add('card')->cover(600, 400); + $this->key = $this->sizes->names()->for('2026/10/photo.jpg', $this->sizes->get('card'), 3000, 2000); + $this->lockDir = sys_get_temp_dir().'/pollora-media-gaps-'.bin2hex(random_bytes(4)); + $this->service = fn (bool $private): ThumbnailService => new ThumbnailService( + $this->disk->storage, + $this->sizes, + new FakeImageProcessor($this->disk->storage), + new FlockGenerationLock($this->lockDir), + new ThumbnailLimits(concurrency: 1, wait: 0), + static fn (string $original): bool => $private, + ); + }); + + afterEach(function (): void { + array_map(unlink(...), glob($this->lockDir.'/*') ?: []); + is_dir($this->lockDir) && rmdir($this->lockDir); + }); + + it('does not serve the file of a size that is there when the media is private', function (): void { + ($this->put)('2026/10/photo.jpg', $this->key); + + expect(($this->service)(true)->serve($this->key)->status)->toBe(404) + ->and(($this->service)(false)->serve($this->key)->status)->toBe(200); + }); + + it('still stands in for a size with another size of the module of the same image', function (string $candidate): void { + $this->disk->storage->write('2026/10/photo.jpg', 'original'); + $this->disk->storage->write('2026/10/'.$candidate, 'another size'); + $busy = (new FlockGenerationLock($this->lockDir))->slot(1, 0); + + $result = ($this->service)(false)->serve($this->key); + + expect(stream_get_contents($result->body))->toBe('another size'); + $busy?->release(); + })->with(['photo-wide-1600x1067-0123456789ab.jpg', 'photo-hero-640w-640x427-0123456789ab.webp', 'photo-card-600x400-f0250_0750-0123456789ab.webp']); + + it('does not stand in for a size with the file of another media whose name starts the same', function (): void { + $this->disk->storage->write('2026/10/photo.jpg', 'original'); + $this->disk->storage->write('2026/10/photo-secret-1024x683.jpg', 'another media'); + $busy = (new FlockGenerationLock($this->lockDir))->slot(1, 0); + + $result = ($this->service)(false)->serve($this->key); + + expect(stream_get_contents($result->body))->toBe('original'); + $busy?->release(); + }); +}); + +describe('the media a file belongs to', function (): void { + beforeEach(function (): void { + $this->previous = $GLOBALS['wpdb'] ?? null; + $this->meta[7][PrivateMedia::META] = '1'; + // Answers the query on the attached file with nothing, and the one on the files before an edit with a media + $GLOBALS['wpdb'] = new class + { + public string $postmeta = 'wp_postmeta'; + + public string $last_error = ''; + + public ?string $beforeEdit = '7'; + + public string $failure = ''; + + /** @var array */ + public array $values = []; + + public function prepare(string $query, mixed ...$values): string + { + $this->values = $values; + + return $query; + } + + public function get_var(string $query): ?string + { + if (! str_contains($query, '_wp_attachment_backup_sizes')) { + return null; + } + + $this->last_error = $this->failure; + + return $this->beforeEdit; + } + }; + }); + + afterEach(function (): void { + $GLOBALS['wpdb'] = $this->previous; + }); + + it('is private when the file is the one a private image had before its edit', function (): void { + expect($this->private->isPrivateFile('2026/10/my_photo.jpg'))->toBeTrue() + ->and($GLOBALS['wpdb']->values)->toBe(['wp_postmeta', 'wp_postmeta', '%"my\\_photo.jpg"%', '2026/10/%']); + }); + + it('is public when no media had the file', function (): void { + $GLOBALS['wpdb']->beforeEdit = null; + + expect($this->private->isPrivateFile('photo.jpg'))->toBeFalse() + ->and($GLOBALS['wpdb']->values[3])->toBe('%'); + }); + + it('is treated as private when that query fails', function (): void { + $GLOBALS['wpdb']->beforeEdit = null; + $GLOBALS['wpdb']->failure = 'gone'; + + expect($this->private->isPrivateFile('2026/10/photo.jpg'))->toBeTrue(); + }); +}); diff --git a/tests/Unit/PrivateMediaTest.php b/tests/Unit/PrivateMediaTest.php index 63753ba..516e59f 100644 --- a/tests/Unit/PrivateMediaTest.php +++ b/tests/Unit/PrivateMediaTest.php @@ -295,6 +295,7 @@ public function get_var(string $query): ?string }); it('lists each file once, whatever the shape of the metadata and of what a plugin adds', function (): void { + $this->meta[7]['_wp_attached_file'] = 'photo.jpg'; Functions\when('wp_get_attachment_metadata')->justReturn([ 'file' => 'photo.jpg', 'sizes' => ['broken' => 'not a size', 'nameless' => ['width' => 1], 'numbered' => ['file' => 12], 'a' => ['file' => 'photo-1x1.jpg'], 'b' => ['file' => 'photo-1x1.jpg']], @@ -306,6 +307,8 @@ public function get_var(string $query): ?string }); it('still lists what a plugin declares for a media without metadata', function (mixed $metadata, mixed $declared, array $files): void { + // Nothing attached either: only the filter has files to tell of + $this->meta = []; Functions\when('wp_get_attachment_metadata')->justReturn($metadata); Filters\expectApplied('pollora/media/attachment_files')->andReturn($declared); From 021be938fbf46a0c31f1054afb2f7358a7355b80 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 15:16:46 +0100 Subject: [PATCH 04/17] fix(private-media): protect the private media of a site of a network WordPress records the files of such a site relative to its own folder: the disk was given the paths of the main site, so nothing was made private there. --- CHANGELOG.md | 1 + README.md | 2 +- .../WordPress/AttachmentFiles.php | 23 ++++- tests/Pest.php | 2 + tests/Unit/PrivateMediaGapsTest.php | 84 ++++++++++++++++++- 5 files changed, 106 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 51f666c..d3ecf30 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Security: the sizes of a private media made at upload, when its image is edited, when its focal point moves or by `thumbs warm` were left with the default visibility of the disk, so readable by their public URL on an object store. They are now made private - Security: `rmdir('pollora://uploads/.')`, `pollora://.` and spellings with a backslash deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first +- Security: on a site of a network other than the main one, no file of a private media was made private, and the file of the same name of the main site was the one changed - Repairing existing sites: run `wp pollora media visibility --private` for each private media, then `wp pollora media thumbs prune --execute`, and purge the CDN. See *Repairing media left public* in the README - Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release - A file is treated as private when the database query that looks its media up fails, instead of public diff --git a/README.md b/README.md index a96665c..6baa002 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ for id in $(wp post list --post_type=attachment --post_status=any --field=ID); d done ``` -In Pollora, the Artisan commands of the framework do the same. Then run `wp pollora media thumbs prune --execute`, which deletes the files of the sizes that were changed or removed since (no command knows which media they were made of), and purge the CDN, which may keep what it already read. Run the first loop again after a `migrate`: files copied from a local folder keep the visibility they had there. +On a network, run the loops once per site (`--url=`). In Pollora, the Artisan commands of the framework do the same. Then run `wp pollora media thumbs prune --execute`, which deletes the files of the sizes that were changed or removed since (no command knows which media they were made of), and purge the CDN, which may keep what it already read. Run the first loop again after a `migrate`: files copied from a local folder keep the visibility they had there. ## Commands diff --git a/src/Infrastructure/WordPress/AttachmentFiles.php b/src/Infrastructure/WordPress/AttachmentFiles.php index 934ffd0..766ce58 100644 --- a/src/Infrastructure/WordPress/AttachmentFiles.php +++ b/src/Infrastructure/WordPress/AttachmentFiles.php @@ -14,6 +14,9 @@ * * A media that is not an image (PDF, archive, video, audio) has no file in its * metadata: its original is the attached file. + * + * WordPress records the files of a site of a network relative to the folder of that site: its folder is put + * back, except before what a plugin declares, which is relative to the library already. */ final class AttachmentFiles { @@ -40,8 +43,9 @@ public function for(int $attachmentId, ?array $metadata = null): array return $this->declaredBy($attachmentId, []); } - $directory = dirname($file) === '.' ? '' : dirname($file).'/'; - $files = $attached === '' ? [$file] : [$file, $attached]; + $site = $this->siteFolder(); + $directory = $site.(dirname($file) === '.' ? '' : dirname($file).'/'); + $files = $attached === '' ? [$site.$file] : [$site.$file, $site.$attached]; foreach ((array) ($metadata['sizes'] ?? []) as $size) { $name = $this->fileOf($size); @@ -59,7 +63,8 @@ public function for(int $attachmentId, ?array $metadata = null): array } } - if ($this->declared instanceof \Closure) { + // The declared sizes are not made for a site of a network: their paths would be those of the main site + if ($this->declared instanceof \Closure && $site === '') { $files = [...$files, ...($this->declared)($metadata, $attachmentId)]; } @@ -68,6 +73,16 @@ public function for(int $attachmentId, ?array $metadata = null): array return $this->declaredBy($attachmentId, array_values(array_unique($files))); } + /** + * The folder of the current site of a network (`sites/2/`), empty for the main site and a single one. + */ + private function siteFolder(): string + { + $base = Cast::text(\wp_get_upload_dir()['basedir'] ?? ''); + + return str_starts_with($base, StreamWrapper::ROOT.'/') ? substr($base, strlen(StreamWrapper::ROOT) + 1).'/' : ''; + } + /** * Attachment metadata, whose keys are names: the same array, typed as such. * @@ -116,7 +131,7 @@ private function beforeEdit(int $attachmentId, string $directory): array $files[] = $directory.$name; // The entries of a previous original are `full-orig` and `full-{time of the edit}` - if ($this->declared instanceof \Closure && is_array($backup) && str_starts_with((string) $key, 'full-')) { + if ($this->declared instanceof \Closure && $this->siteFolder() === '' && is_array($backup) && str_starts_with((string) $key, 'full-')) { $files = [...$files, ...($this->declared)(['file' => $directory.$name, 'width' => $backup['width'] ?? null, 'height' => $backup['height'] ?? null], $attachmentId)]; } } diff --git a/tests/Pest.php b/tests/Pest.php index b3d3133..9e0fe05 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -20,6 +20,8 @@ pest()->beforeEach(function (): void { Monkey\setUp(); Monkey\Functions\stubTranslationFunctions(); + // A single site: the module's folder is the root of the library. A test of a network stubs it again. + Monkey\Functions\when('wp_get_upload_dir')->justReturn(['basedir' => 'pollora://uploads']); })->afterEach(function (): void { if ($container = Mockery::getContainer()) { $this->addToAssertionCount($container->mockery_getExpectationCount()); diff --git a/tests/Unit/PrivateMediaGapsTest.php b/tests/Unit/PrivateMediaGapsTest.php index 140a5a3..a7ef1c8 100644 --- a/tests/Unit/PrivateMediaGapsTest.php +++ b/tests/Unit/PrivateMediaGapsTest.php @@ -91,12 +91,65 @@ ]); }); +it('lists once each file of the metadata and of the attached file when they differ, as during an edit', function (): void { + $this->meta[7]['_wp_attached_file'] = '2026/10/photo-e1.jpg'; + $this->metadata[7] = ['file' => '2026/10/photo.jpg', 'sizes' => ['a' => ['file' => 'photo.jpg']]]; + + expect((new AttachmentFiles)->for(7))->toBe(['2026/10/photo.jpg', '2026/10/photo-e1.jpg']); +}); + +it('asks for the declared sizes of each original kept before an edit, with its dimensions, past a broken entry', function (): void { + $this->meta[7] = [ + '_wp_attached_file' => '2026/10/photo-e2.jpg', + '_wp_attachment_backup_sizes' => [ + 'broken' => 'not a size', + 'full-orig' => ['file' => 'photo.jpg', 'width' => 3000, 'height' => 2000], + 'full-1700000000000' => ['file' => 'photo-e1.jpg', 'width' => 2000, 'height' => 3000], + 'medium-orig' => ['file' => 'photo-300x200.jpg', 'width' => 300, 'height' => 200], + 12 => ['file' => 'photo-12.jpg'], + ], + ]; + $asked = []; + $declared = function (array $metadata) use (&$asked): array { + $asked[] = $metadata; + + return []; + }; + + (new AttachmentFiles($declared))->for(7); + + expect($asked)->toBe([ + [], + ['file' => '2026/10/photo.jpg', 'width' => 3000, 'height' => 2000], + ['file' => '2026/10/photo-e1.jpg', 'width' => 2000, 'height' => 3000], + ]); +}); + it('leaves out an attached file that is not a path of the library', function (string $attached): void { $this->meta[7]['_wp_attached_file'] = $attached; expect((new AttachmentFiles)->for(7))->toBe([]); })->with(['/var/www/outside.pdf', 'https://elsewhere.test/outside.pdf']); +it('finds the files of a media of a site of a network in the folder of that site', function (): void { + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => 'pollora://uploads/sites/2']); + $this->meta[7] = [ + '_wp_attached_file' => '2026/10/photo.jpg', + '_wp_attachment_backup_sizes' => ['full-orig' => ['file' => 'old.jpg', 'width' => 3000, 'height' => 2000]], + ]; + $this->metadata[7] = ['file' => '2026/10/photo.jpg', 'sizes' => ['thumbnail' => ['file' => 'photo-150x150.jpg']]]; + Filters\expectApplied('pollora/media/attachment_files')->andReturn(['sites/2/2026/10/photo.webp']); + // A declared size would be looked for in the folder of the main site: none is + $declared = static fn (): array => ['2026/10/the-main-site.webp']; + + expect((new AttachmentFiles($declared))->for(7))->toBe([ + 'sites/2/2026/10/photo.jpg', + 'sites/2/2026/10/photo-150x150.jpg', + 'sites/2/2026/10/old.jpg', + 'sites/2/2026/10/photo.webp', + ]); +}); + it('makes private the files a save of the metadata of a private media tells of', function (): void { $this->meta[7] = [PrivateMedia::META => '1', '_wp_attached_file' => '2026/10/photo-e1.jpg']; $saved = ['file' => '2026/10/photo-e1.jpg', 'sizes' => ['thumbnail' => ['file' => 'photo-e1-150x150.jpg']]]; @@ -189,6 +242,20 @@ expect($this->storage->visibility('2026/10/doc.pdf'))->toBe('private'); }); +it('warms the sizes that follow one that is there already', function (): void { + $sizes = new ImageSizes(fn (): string => 'secret-key'); + $sizes->add('card')->cover(600, 400); + $sizes->add('wide')->scale(width: 1600); + $metadata = ['file' => '2026/10/photo.jpg', 'width' => 3000, 'height' => 2000, 'sizes' => []]; + $this->metadata[7] = $metadata; + $declared = new DeclaredSizes($sizes, $this->config, $this->storage, new FakeImageProcessor($this->disk->storage)); + ($this->put)('2026/10/photo.jpg', $declared->fileFor($metadata, $sizes->get('card'))); + Functions\when('get_posts')->justReturn([7]); + Functions\when('wp_update_attachment_metadata')->justReturn(true); + + expect((new SizeWarmer($declared, $this->storage))->warm()['made'])->toBe(1); +}); + describe('the fallback route', function (): void { beforeEach(function (): void { $this->sizes = new ImageSizes(fn (): string => 'secret-key'); @@ -210,6 +277,13 @@ is_dir($this->lockDir) && rmdir($this->lockDir); }); + it('serves the file of a size that is there as it is, without making it again', function (): void { + $this->disk->storage->write('2026/10/photo.jpg', 'original'); + $this->disk->storage->write($this->key, 'made before'); + + expect(stream_get_contents(($this->service)(false)->serve($this->key)->body))->toBe('made before'); + }); + it('does not serve the file of a size that is there when the media is private', function (): void { ($this->put)('2026/10/photo.jpg', $this->key); @@ -251,6 +325,8 @@ public string $last_error = ''; + public ?string $attached = null; + public ?string $beforeEdit = '7'; public string $failure = ''; @@ -268,7 +344,7 @@ public function prepare(string $query, mixed ...$values): string public function get_var(string $query): ?string { if (! str_contains($query, '_wp_attachment_backup_sizes')) { - return null; + return $this->attached; } $this->last_error = $this->failure; @@ -287,6 +363,12 @@ public function get_var(string $query): ?string ->and($GLOBALS['wpdb']->values)->toBe(['wp_postmeta', 'wp_postmeta', '%"my\\_photo.jpg"%', '2026/10/%']); }); + it('is not looked for among the files before an edit when it is the attached file of a media', function (): void { + $GLOBALS['wpdb']->attached = '8'; + + expect($this->private->isPrivateFile('2026/10/photo.jpg'))->toBeFalse(); + }); + it('is public when no media had the file', function (): void { $GLOBALS['wpdb']->beforeEdit = null; From 2d379f19ef03290fbee1f027ccc8477ea326d7ef Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 15:20:54 +0100 Subject: [PATCH 05/17] fix(multisite): never touch the files of other sites from a site of a network Deleting a site whose uploads are the root of the library emptied it. On a site of a network, the declared sizes used the paths of the main site: they could be deleted, or served by the fallback route although private there. --- CHANGELOG.md | 2 + README.md | 4 +- .../WordPress/AttachmentFiles.php | 14 +-- .../WordPress/DeclaredSizes.php | 10 ++- src/Infrastructure/WordPress/PrivateMedia.php | 3 +- src/Infrastructure/WordPress/SiteFolder.php | 23 +++++ .../WordPress/WordPressMedia.php | 19 ++++ tests/Unit/NetworkSitesTest.php | 87 +++++++++++++++++++ 8 files changed, 144 insertions(+), 18 deletions(-) create mode 100644 src/Infrastructure/WordPress/SiteFolder.php create mode 100644 tests/Unit/NetworkSitesTest.php diff --git a/CHANGELOG.md b/CHANGELOG.md index d3ecf30..9365846 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Security: the sizes of a private media made at upload, when its image is edited, when its focal point moves or by `thumbs warm` were left with the default visibility of the disk, so readable by their public URL on an object store. They are now made private - Security: `rmdir('pollora://uploads/.')`, `pollora://.` and spellings with a backslash deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first - Security: on a site of a network other than the main one, no file of a private media was made private, and the file of the same name of the main site was the one changed +- Security: deleting a site of a network whose uploads are not under `sites/N` (a network created before WordPress 3.5, a custom `upload_path`) deleted every file of the library. Nothing is deleted then +- Security: on a site of a network, the declared sizes used the paths of the main site: deleting a media could delete the main site's files, and the fallback route could serve a private size of the main site. No declared size is made or served for such a site, which gets the sizes of WordPress and the original - Repairing existing sites: run `wp pollora media visibility --private` for each private media, then `wp pollora media thumbs prune --execute`, and purge the CDN. See *Repairing media left public* in the README - Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release - A file is treated as private when the database query that looks its media up fails, instead of public diff --git a/README.md b/README.md index 6baa002..31d200b 100644 --- a/README.md +++ b/README.md @@ -201,6 +201,8 @@ wp pollora media thumbs export --driver=imgproxy # the configuration to For Bunny, the classes are read, merged by name and written back: the ones you made are kept, nothing is deleted, and the forced classes setting is never changed. The merge matters: Bunny replaces the whole list of classes with the one it is sent. The access key is only ever sent in the `AccessKey` header. imgproxy has no API for presets: the command prints `IMGPROXY_PRESETS`, `IMGPROXY_ONLY_PRESETS=true`, `IMGPROXY_MAX_SRC_RESOLUTION` (in megapixels) and `IMGPROXY_ALLOWED_SOURCES`, never the key or the salt. +**Networks.** The declared sizes are made for the main site only: another site gets the sizes of WordPress, and the original under a declared name. A network whose sites do not upload under `sites/N` (created before WordPress 3.5, or with an `upload_path` of its own) shares the root of the library, which is not supported: its sites can overwrite each other's files, and deleting one deletes nothing from the disk. + ## Private media A media is private when its post meta `_pollora_media_private` is `1`, or when the `pollora/media/is_private` filter says so. A private media is served through a signed URL (`Flysystem`'s `temporaryUrl()`: an S3 pre-signed URL) that expires after `POLLORA_MEDIA_PRIVATE_EXPIRY` (`+6 hours` by default). The flag is read with the attachment and asked once per media in a request: the signature is computed for private media only, and no call to the disk is made to tell a private media from a public one. @@ -256,7 +258,7 @@ for id in $(wp post list --post_type=attachment --post_status=any --field=ID); d done ``` -On a network, run the loops once per site (`--url=`). In Pollora, the Artisan commands of the framework do the same. Then run `wp pollora media thumbs prune --execute`, which deletes the files of the sizes that were changed or removed since (no command knows which media they were made of), and purge the CDN, which may keep what it already read. Run the first loop again after a `migrate`: files copied from a local folder keep the visibility they had there. +On a network, run the loops once per site (`--url=`), and `thumbs prune` on the main site only. In Pollora, the Artisan commands of the framework do the same. Then run `wp pollora media thumbs prune --execute`, which deletes the files of the sizes that were changed or removed since (no command knows which media they were made of), and purge the CDN, which may keep what it already read. Run the first loop again after a `migrate`: files copied from a local folder keep the visibility they had there. ## Commands diff --git a/src/Infrastructure/WordPress/AttachmentFiles.php b/src/Infrastructure/WordPress/AttachmentFiles.php index 766ce58..6fc1864 100644 --- a/src/Infrastructure/WordPress/AttachmentFiles.php +++ b/src/Infrastructure/WordPress/AttachmentFiles.php @@ -43,7 +43,7 @@ public function for(int $attachmentId, ?array $metadata = null): array return $this->declaredBy($attachmentId, []); } - $site = $this->siteFolder(); + $site = SiteFolder::current(); $directory = $site.(dirname($file) === '.' ? '' : dirname($file).'/'); $files = $attached === '' ? [$site.$file] : [$site.$file, $site.$attached]; @@ -73,16 +73,6 @@ public function for(int $attachmentId, ?array $metadata = null): array return $this->declaredBy($attachmentId, array_values(array_unique($files))); } - /** - * The folder of the current site of a network (`sites/2/`), empty for the main site and a single one. - */ - private function siteFolder(): string - { - $base = Cast::text(\wp_get_upload_dir()['basedir'] ?? ''); - - return str_starts_with($base, StreamWrapper::ROOT.'/') ? substr($base, strlen(StreamWrapper::ROOT) + 1).'/' : ''; - } - /** * Attachment metadata, whose keys are names: the same array, typed as such. * @@ -131,7 +121,7 @@ private function beforeEdit(int $attachmentId, string $directory): array $files[] = $directory.$name; // The entries of a previous original are `full-orig` and `full-{time of the edit}` - if ($this->declared instanceof \Closure && $this->siteFolder() === '' && is_array($backup) && str_starts_with((string) $key, 'full-')) { + if ($this->declared instanceof \Closure && SiteFolder::current() === '' && is_array($backup) && str_starts_with((string) $key, 'full-')) { $files = [...$files, ...($this->declared)(['file' => $directory.$name, 'width' => $backup['width'] ?? null, 'height' => $backup['height'] ?? null], $attachmentId)]; } } diff --git a/src/Infrastructure/WordPress/DeclaredSizes.php b/src/Infrastructure/WordPress/DeclaredSizes.php index 43fa388..63c4d2c 100644 --- a/src/Infrastructure/WordPress/DeclaredSizes.php +++ b/src/Infrastructure/WordPress/DeclaredSizes.php @@ -208,7 +208,7 @@ public function remake(mixed $metadata, int $attachmentId): mixed */ public function downsize(mixed $short, int $attachmentId, mixed $size): mixed { - if ($short !== false || ! is_string($size) || ! isset($this->known()[$size])) { + if ($short !== false || ! is_string($size) || ! isset($this->known()[$size]) || SiteFolder::current() !== '') { return $short; } @@ -244,7 +244,7 @@ public function downsize(mixed $short, int $attachmentId, mixed $size): mixed */ public function srcset(array|false $sources, array $sizeArray, string $imageSrc, array $imageMeta, int $attachmentId): array|false { - if ($sources === false || ! $this->isImage($imageMeta)) { + if ($sources === false || ! $this->isImage($imageMeta) || SiteFolder::current() !== '') { return $sources; } @@ -284,7 +284,9 @@ public function srcset(array|false $sources, array $sizeArray, string $imageSrc, */ public function make(array $metadata, ImageSizeSpec $spec, ?FocalPoint $focal = null): ?array { - if ($this->isGif($metadata)) { + // The declared sizes are not made for a site of a network: the metadata has no folder of the site, so the + // paths would be those of the main site + if ($this->isGif($metadata) || SiteFolder::current() !== '') { return null; } @@ -396,7 +398,7 @@ public function specs(): array */ public function isMakeable(array $metadata): bool { - return $this->isImage($metadata) && ! $this->isGif($metadata); + return $this->isImage($metadata) && ! $this->isGif($metadata) && SiteFolder::current() === ''; } /** diff --git a/src/Infrastructure/WordPress/PrivateMedia.php b/src/Infrastructure/WordPress/PrivateMedia.php index 0202efb..4ff780b 100644 --- a/src/Infrastructure/WordPress/PrivateMedia.php +++ b/src/Infrastructure/WordPress/PrivateMedia.php @@ -123,7 +123,8 @@ public function isPrivateFile(string $file): bool /** @var \wpdb|null $wpdb The global WordPress sets, which has no declared type */ global $wpdb; - if (! function_exists('get_post_meta') || ! is_object($wpdb)) { + // On a site of a network, the database does not know the media of the other sites, whose files the path may be + if (! function_exists('get_post_meta') || ! is_object($wpdb) || SiteFolder::current() !== '') { return true; } diff --git a/src/Infrastructure/WordPress/SiteFolder.php b/src/Infrastructure/WordPress/SiteFolder.php new file mode 100644 index 0000000..45e6600 --- /dev/null +++ b/src/Infrastructure/WordPress/SiteFolder.php @@ -0,0 +1,23 @@ +private->register(); $this->focalPoints->register(); $this->declared->register(); @@ -148,6 +149,24 @@ public function uploadDir(array $dirs): array return $dirs; } + /** + * The folder WordPress empties, file by file, when it deletes a site of a network. A network whose sites do + * not upload under `sites/N` (one created before WordPress 3.5, a custom `upload_path`) shares the root of + * the library: nothing is deleted then, rather than the media of every site. + * + * @internal Callback of `wpmu_delete_blog_upload_dir` + */ + public function uploadDirToDelete(string $dir): string + { + if (! str_starts_with($dir, StreamWrapper::SCHEME.'://') || StreamWrapper::keyOf($dir) !== '') { + return $dir; + } + + \error_log('pollora/media: the uploads of the deleted site are the whole library: its files were not deleted'); + + return ''; + } + /** * WordPress lists the folder of a new file to find the names it must not reuse; * on a remote disk that is a listing per upload. The name itself is still checked. diff --git a/tests/Unit/NetworkSitesTest.php b/tests/Unit/NetworkSitesTest.php new file mode 100644 index 0000000..daaeb0a --- /dev/null +++ b/tests/Unit/NetworkSitesTest.php @@ -0,0 +1,87 @@ +disk = new TemporaryStorage; + $this->config = new MediaConfig('https://media.client.fr'); + $this->sizes = new ImageSizes(fn (): string => 'secret-key'); + $this->sizes->add('card')->cover(600, 400)->eager(); + $this->declared = new DeclaredSizes($this->sizes, $this->config, $this->disk->storage, new FakeImageProcessor($this->disk->storage)); + $this->metadata = ['file' => '2026/10/photo.jpg', 'width' => 3000, 'height' => 2000, 'sizes' => []]; + // The main site has an image of the same name, and its size + $this->card = $this->declared->fileFor($this->metadata, $this->sizes->get('card')); + $this->disk->storage->write('2026/10/photo.jpg', 'main'); + $this->disk->storage->write($this->card, 'main card'); + Functions\when('get_post_meta')->justReturn(''); + Functions\when('wp_get_attachment_metadata')->justReturn($this->metadata); +}); + +afterEach(function (): void { + StreamWrapper::unregister(); +}); + +it('leaves the declared sizes of the main site alone from a site of a network, whose sizes would have the same paths', function (): void { + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => 'pollora://uploads/sites/2']); + + expect($this->declared->existingFiles($this->metadata))->toBe([]) + ->and($this->declared->generate($this->metadata, 7))->toBe($this->metadata) + ->and($this->declared->make($this->metadata, $this->sizes->get('card')))->toBeNull() + ->and($this->declared->downsize(false, 7, 'card'))->toBeFalse() + ->and($this->declared->srcset([1 => ['url' => 'x']], [], $this->card, $this->metadata, 7))->toBe([1 => ['url' => 'x']]); +}); + +it('makes and finds them on the main site', function (): void { + expect($this->declared->existingFiles($this->metadata))->toBe([$this->card]) + ->and($this->declared->generate($this->metadata, 7)['sizes'])->toHaveKey('card'); +}); + +it('serves no size on demand from a site of a network, whose database does not know the media of the others', function (): void { + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => 'pollora://uploads/sites/2']); + $previous = $GLOBALS['wpdb'] ?? null; + $GLOBALS['wpdb'] = new stdClass; + + try { + expect((new PrivateMedia($this->disk->storage, $this->config, new AttachmentFiles))->isPrivateFile('2026/10/photo.jpg'))->toBeTrue(); + } finally { + $GLOBALS['wpdb'] = $previous; + } +}); + +it('does not let WordPress empty the whole library when it deletes a site whose uploads are its root', function (string $dir, string $given): void { + $log = tempnam(sys_get_temp_dir(), 'media-log'); + $previous = ini_set('error_log', $log); + + try { + expect((new WordPressMedia($this->disk->storage, $this->config, null, $this->sizes))->uploadDirToDelete($dir))->toBe($given); + } finally { + ini_set('error_log', (string) $previous); + } + + expect(str_contains((string) file_get_contents($log), 'not deleted'))->toBe($given === ''); + unlink($log); +})->with([ + 'the root' => ['pollora://uploads', ''], + 'the root, with a slash' => ['pollora://uploads/', ''], + 'the folder of a site' => ['pollora://uploads/sites/2', 'pollora://uploads/sites/2'], + 'a folder of the server' => ['/var/www/uploads', '/var/www/uploads'], +]); + +it('hooks the folder WordPress empties when it deletes a site', function (): void { + Functions\when('did_action')->justReturn(0); + Filters\expectAdded('wpmu_delete_blog_upload_dir')->once()->with(Mockery::type('array'), PHP_INT_MAX); + + (new WordPressMedia($this->disk->storage, $this->config, null, $this->sizes))->register(); +}); From 83736be32b583085f96eb9375c5b7e24223eafbb Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 19:27:44 +0100 Subject: [PATCH 06/17] fix(multisite): keep the sizes of WordPress on a site of a network, refuse to prune there A folder a plugin moves the uploads to is not the folder of a site. A site of a network keeps the sizes WordPress makes under the declared names, and is no longer told of the declared size an earlier version recorded in its metadata. --- .../WordPress/DeclaredSizes.php | 24 ++++++++- src/Infrastructure/WordPress/SiteFolder.php | 5 +- .../WordPress/ThumbsCommand.php | 5 ++ tests/Unit/NetworkSitesTest.php | 53 +++++++++++++++++++ 4 files changed, 84 insertions(+), 3 deletions(-) diff --git a/src/Infrastructure/WordPress/DeclaredSizes.php b/src/Infrastructure/WordPress/DeclaredSizes.php index 63c4d2c..61924c9 100644 --- a/src/Infrastructure/WordPress/DeclaredSizes.php +++ b/src/Infrastructure/WordPress/DeclaredSizes.php @@ -64,6 +64,7 @@ public function register(): void \add_filter('wp_generate_attachment_metadata', [$this, 'generate'], 20, 3); \add_filter('wp_update_attachment_metadata', [$this, 'remake'], 20, 2); \add_filter('image_downsize', [$this, 'downsize'], 10, 3); + \add_filter('wp_get_attachment_metadata', [$this, 'withoutForeignSizes'], 10, 1); \add_filter('wp_calculate_image_srcset', [$this, 'srcset'], 5, 5); if ($this->focalPoints instanceof FocalPoints) { @@ -152,7 +153,28 @@ public function focalChanged(mixed $metaId, mixed $attachmentId, mixed $metaKey) */ public function withoutDeclared(array $wordpressSizes): array { - return array_diff_key($wordpressSizes, $this->known()); + // A site of a network gets no declared size: WordPress keeps making its own under those names + return SiteFolder::current() === '' ? array_diff_key($wordpressSizes, $this->known()) : $wordpressSizes; + } + + /** + * Up to 0.10.0, an image uploaded on a site of a network could record a declared size, whose file is one of + * the main site. There is none under the folder of the site: WordPress is not told of it, and serves a size it has. + * + * @internal Callback of `wp_get_attachment_metadata` + */ + public function withoutForeignSizes(mixed $metadata): mixed + { + if (! is_array($metadata) || ! is_array($metadata['sizes'] ?? null) || SiteFolder::current() === '') { + return $metadata; + } + + $metadata['sizes'] = array_filter( + $metadata['sizes'], + fn (mixed $size): bool => ! is_array($size) || $this->sizes->names()->parse(Cast::text($size['file'] ?? '')) === null, + ); + + return $metadata; } /** diff --git a/src/Infrastructure/WordPress/SiteFolder.php b/src/Infrastructure/WordPress/SiteFolder.php index 45e6600..4f5633e 100644 --- a/src/Infrastructure/WordPress/SiteFolder.php +++ b/src/Infrastructure/WordPress/SiteFolder.php @@ -8,7 +8,8 @@ /** * The folder of the library the current site writes in: `sites/2/` for a site of a network, empty for the main - * site and for a single one. + * site and for a single one. Only `sites/N` counts: a plugin that moves the uploads of a site to a folder of + * its own does not make it a site of a network. * * @internal */ @@ -18,6 +19,6 @@ public static function current(): string { $base = \function_exists('wp_get_upload_dir') ? Cast::text(\wp_get_upload_dir()['basedir'] ?? '') : ''; - return str_starts_with($base, StreamWrapper::ROOT.'/') ? substr($base, strlen(StreamWrapper::ROOT) + 1).'/' : ''; + return preg_match('#^'.preg_quote(StreamWrapper::ROOT, '#').'/(sites/\d+)(?:/|$)#D', $base, $match) === 1 ? $match[1].'/' : ''; } } diff --git a/src/Infrastructure/WordPress/ThumbsCommand.php b/src/Infrastructure/WordPress/ThumbsCommand.php index c52e9e1..d9c6dd2 100644 --- a/src/Infrastructure/WordPress/ThumbsCommand.php +++ b/src/Infrastructure/WordPress/ThumbsCommand.php @@ -73,6 +73,7 @@ public function warm(array $args, array $assoc): void * Delete the sized files that no declared size stands for any more: a size that was changed or removed. * * Only files named the way the module names its sizes, next to an original that is still there. Nothing is deleted without --execute. + * On a network, only from the main site: another one does not declare the sizes, nor know the media, of the whole library. * * ## OPTIONS * @@ -86,6 +87,10 @@ public function warm(array $args, array $assoc): void */ public function prune(array $args, array $assoc): void { + if (SiteFolder::current() !== '') { + WP_CLI::error('Run this on the main site of the network: the files it looks at are those of the whole library.'); + } + $execute = isset($assoc['execute']); foreach ($this->pruner->prune(! $execute) as $path) { diff --git a/tests/Unit/NetworkSitesTest.php b/tests/Unit/NetworkSitesTest.php index daaeb0a..e96b375 100644 --- a/tests/Unit/NetworkSitesTest.php +++ b/tests/Unit/NetworkSitesTest.php @@ -5,11 +5,18 @@ use Brain\Monkey\Filters; use Brain\Monkey\Functions; use Pollora\Media\Application\Services\ImageSizes; +use Pollora\Media\Application\Services\SizePruner; +use Pollora\Media\Application\Services\ThumbnailExporter; +use Pollora\Media\Application\Services\ThumbnailLimits; use Pollora\Media\Domain\Models\MediaConfig; +use Pollora\Media\Domain\Models\ThumbnailDriverSettings; +use Pollora\Media\Infrastructure\ThumbnailDrivers; use Pollora\Media\Infrastructure\WordPress\AttachmentFiles; use Pollora\Media\Infrastructure\WordPress\DeclaredSizes; use Pollora\Media\Infrastructure\WordPress\PrivateMedia; +use Pollora\Media\Infrastructure\WordPress\SizeWarmer; use Pollora\Media\Infrastructure\WordPress\StreamWrapper; +use Pollora\Media\Infrastructure\WordPress\ThumbsCommand; use Pollora\Media\Infrastructure\WordPress\WordPressMedia; use Pollora\Media\Tests\Fixtures\FakeImageProcessor; use Pollora\Media\Tests\Fixtures\TemporaryStorage; @@ -85,3 +92,49 @@ (new WordPressMedia($this->disk->storage, $this->config, null, $this->sizes))->register(); }); + +it('does not take a folder a plugin moves the uploads to for the folder of a site, which would leave files public', function (string $basedir): void { + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => $basedir]); + $this->disk->storage->write('2026/10/secret.pdf', 'x'); + Functions\when('get_post_meta')->alias(static fn (int $id, string $key): mixed => $key === '_wp_attached_file' ? '2026/10/secret.pdf' : ''); + Functions\when('wp_get_attachment_metadata')->justReturn(false); + + expect((new AttachmentFiles)->for(7))->toBe(['2026/10/secret.pdf']); +})->with(['pollora://uploads/protected', 'pollora://uploads/sites', 'pollora://uploads/sites/two', 'pollora://uploads/my-sites/2']); + +it('lets WordPress make its own sizes under the declared names on a site of a network, which gets no declared one', function (string $basedir, array $made): void { + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => $basedir]); + + expect($this->declared->withoutDeclared(['card' => [], 'medium' => []]))->toBe($made); +})->with([ + 'the main site' => ['pollora://uploads', ['medium' => []]], + 'another site' => ['pollora://uploads/sites/2', ['card' => [], 'medium' => []]], +]); + +it('refuses to prune from a site of a network, which would delete the sizes of the main one', function (): void { + WP_CLI::reset(); + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => 'pollora://uploads/sites/2']); + // A size this site does not declare: the main one does + $other = new ImageSizes(fn (): string => 'secret-key'); + $command = new ThumbsCommand( + new SizeWarmer($this->declared, $this->disk->storage), + new SizePruner($this->disk->storage, $other), + ThumbnailDrivers::make(new ThumbnailDriverSettings, $other, $this->config), + new ThumbnailExporter($other, new ThumbnailDriverSettings, new ThumbnailLimits, $this->config), + ); + + expect(fn () => $command->prune([], ['execute' => true]))->toThrow(RuntimeException::class, 'main site') + ->and($this->disk->storage->exists($this->card))->toBeTrue(); +}); + +it('forgets, on a site of a network, the declared size an earlier version recorded, whose file is not under its folder', function (string $basedir, array $kept): void { + Functions\when('wp_get_upload_dir')->justReturn(['basedir' => $basedir]); + $metadata = ['file' => '2026/10/photo.jpg', 'sizes' => ['card' => ['file' => basename($this->card)], 'medium' => ['file' => 'photo-300x200.jpg']]]; + + expect(array_keys($this->declared->withoutForeignSizes($metadata)['sizes']))->toBe($kept) + ->and($this->declared->withoutForeignSizes(false))->toBeFalse() + ->and($this->declared->withoutForeignSizes(['file' => 'a.pdf']))->toBe(['file' => 'a.pdf']); +})->with([ + 'the main site' => ['pollora://uploads', ['card', 'medium']], + 'another site' => ['pollora://uploads/sites/2', ['medium']], +]); From 2947c12fe736f89b771ee8942e23466e080cc669 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 19:27:44 +0100 Subject: [PATCH 07/17] fix(thumbnails): serve no size without its original, nor the size of a namesake when saturated --- src/Application/Services/ThumbnailService.php | 17 ++++++++++- tests/Unit/ThumbnailServiceTest.php | 29 +++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/Application/Services/ThumbnailService.php b/src/Application/Services/ThumbnailService.php index b82b814..742389e 100644 --- a/src/Application/Services/ThumbnailService.php +++ b/src/Application/Services/ThumbnailService.php @@ -100,11 +100,17 @@ private function produce(string $key, string $original, array $parsed, ImageSize return ThumbnailResult::notFound(); } + // A size whose original is gone (a media deleted, an edit overwritten) belongs to nobody who could be asked + // whether it is private + if (! $this->storage->exists($original)) { + return ThumbnailResult::notFound(); + } + if ($made) { return $this->file($key, $parsed['extension']); } - if (strtolower(pathinfo($original, PATHINFO_EXTENSION)) === 'gif' || ! $this->storage->exists($original)) { + if (strtolower(pathinfo($original, PATHINFO_EXTENSION)) === 'gif') { return ThumbnailResult::notFound(); } @@ -179,6 +185,7 @@ private function nearest(string $original, array $parsed): ThumbnailResult { $directory = $parsed['directory']; $candidates = []; + $namesake = false; foreach ($this->storage->list($directory) as $entry) { if ($entry['type'] !== 'file') { @@ -187,6 +194,12 @@ private function nearest(string $original, array $parsed): ThumbnailResult $name = basename($entry['path']); + // `scan.jpg` and `scan.png` give their sizes names that cannot be told apart: with a private one, only + // the original asked for stands in + $namesake = $namesake || ($name !== basename($original) + && preg_match('/^'.preg_quote($parsed['stem'], '/').'\.(?:jpe?g|png|webp|avif|gif)$/iD', $name) === 1 + && ($this->isPrivate)($entry['path'])); + // A size of WordPress is `stem-WxH`, one of the module has a name and a signature. A word between the stem // and the dimensions without a signature is the name of another media, which may be private. if (preg_match('/^'.preg_quote($parsed['stem'], '/').'-(?:(?:[a-z0-9_]+(?:-\d+w)?-)(?=\d+x\d+(?:-f\d{4}_\d{4})?-[0-9a-f]{12}\.))?(\d+)x\d+(?:-f\d{4}_\d{4})?(?:-[0-9a-f]{12})?\.(?:jpe?g|png|webp|avif)$/D', $name, $match) === 1) { @@ -194,6 +207,8 @@ private function nearest(string $original, array $parsed): ThumbnailResult } } + $candidates = $namesake ? [] : $candidates; + asort($candidates); $bigEnough = array_filter($candidates, fn (int $width): bool => $width >= $parsed['width']); $chosen = $bigEnough !== [] ? array_key_first($bigEnough) : ($candidates === [] ? $original : array_key_last($candidates)); diff --git a/tests/Unit/ThumbnailServiceTest.php b/tests/Unit/ThumbnailServiceTest.php index 1224463..2e1d87c 100644 --- a/tests/Unit/ThumbnailServiceTest.php +++ b/tests/Unit/ThumbnailServiceTest.php @@ -233,3 +233,32 @@ public function slot(int $concurrency, int $wait): ?LockHandle expect(stream_get_contents($service->serve($this->file)->body))->toBe('made meanwhile') ->and($this->processor->made)->toBe([]); }); + +it('serves no size whose original is gone, since nobody can be asked whether it was private', function (): void { + ($this->make)()->serve($this->file); + $this->disk->storage->delete('2026/10/photo.png'); + + expect(($this->make)()->serve($this->file)->status)->toBe(404); +}); + +it('hands over the original only, when saturated, if another image of the same name and a different type is private', function (string $other, bool $private, string $served): void { + $this->disk->storage->write('2026/10/photo-1024x683.png', 'maybe not ours'); + $this->disk->storage->write($other, 'x'); + $lock = new FlockGenerationLock($this->lockDir); + $busy = [$lock->slot(2, 0), $lock->slot(2, 0)]; + + $result = ($this->make)(static fn (string $key): bool => $private && $key === $other)->serve($this->file); + $body = (string) stream_get_contents($result->body); + + expect($body === 'maybe not ours' ? 'a size' : 'the original')->toBe($served) + ->and($result->headers['Cache-Control'])->toBe('no-store'); + + foreach ($busy as $slot) { + $slot?->release(); + } +})->with([ + 'private' => ['2026/10/photo.jpg', true, 'the original'], + 'private, in capitals' => ['2026/10/photo.JPEG', true, 'the original'], + 'public' => ['2026/10/photo.jpg', false, 'a size'], + 'another name' => ['2026/10/photos.jpg', true, 'a size'], +]); From 54b5e903c7e98a39a038fee89400c4bac7e46994 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 19:27:44 +0100 Subject: [PATCH 08/17] fix(private-media): do not show a private media to whoever does not see the library Over REST, on its attachment page, its embed and feed, and over oEmbed. --- .../WordPress/PrivateMediaAccess.php | 163 ++++++++++++++++++ .../WordPress/WordPressMedia.php | 1 + tests/Fixtures/WpRest.php | 96 +++++++++++ tests/Integration/PrivateMediaAccessTest.php | 112 ++++++++++++ tests/Unit/PrivateMediaAccessTest.php | 159 +++++++++++++++++ tests/bootstrap.php | 1 + 6 files changed, 532 insertions(+) create mode 100644 src/Infrastructure/WordPress/PrivateMediaAccess.php create mode 100644 tests/Fixtures/WpRest.php create mode 100644 tests/Integration/PrivateMediaAccessTest.php create mode 100644 tests/Unit/PrivateMediaAccessTest.php diff --git a/src/Infrastructure/WordPress/PrivateMediaAccess.php b/src/Infrastructure/WordPress/PrivateMediaAccess.php new file mode 100644 index 0000000..12cf1ba --- /dev/null +++ b/src/Infrastructure/WordPress/PrivateMediaAccess.php @@ -0,0 +1,163 @@ +private->isPrivate($attachmentId) + || \current_user_can('upload_files') + || \current_user_can('edit_post', $attachmentId); + } + + /** + * Every route of one media: `/wp/v2/media/{id}`, and what is asked of it. The handler and the id are the + * ones WordPress is about to use, so no spelling of the path goes around. + */ + public function restItem(mixed $response, mixed $handler, mixed $request): mixed + { + $callback = is_array($handler) ? ($handler['callback'] ?? null) : null; + + if (! is_array($callback) || ! ($callback[0] ?? null) instanceof \WP_REST_Attachments_Controller || ! $request instanceof \WP_REST_Request) { + return $response; + } + + $id = Cast::integer($request['id']); + + if ($id <= 0 || $this->allows($id)) { + return $response; + } + + return new \WP_Error('rest_forbidden', 'Sorry, you are not allowed to view this media.', ['status' => \rest_authorization_required_code()]); + } + + /** + * Marks the query of a REST collection of media, for a user who does not see every media. + * + * @param array $args + * @return array + */ + public function restQuery(array $args): array + { + if (\current_user_can('upload_files')) { + unset($args[self::GUARD]); + + return $args; + } + + $args[self::GUARD] = true; + + return $args; + } + + /** + * Leaves the flagged media out in the database, so the totals of the collection do not count them: a search + * would tell that a private media matches. A `pollora/media/is_private` rule cannot be written in SQL, and may + * make a flagged media public: with one, the results alone are filtered. + */ + public function where(string $where, \WP_Query $query): string + { + /** @var \wpdb $wpdb The global WordPress sets, which has no declared type */ + global $wpdb; + + if (! $query->get(self::GUARD) || \has_filter('pollora/media/is_private') !== false) { + return $where; + } + + $clause = $wpdb->prepare( + ' AND (%i.ID NOT IN (SELECT post_id FROM %i WHERE meta_key = %s AND meta_value = %s) OR %i.post_author = %d)', + $wpdb->posts, + $wpdb->postmeta, + PrivateMedia::META, + '1', + $wpdb->posts, + // No post has this author: an anonymous request (user 0) must not match the media without one + \get_current_user_id() ?: -1, + ); + + return $where.Cast::text($clause); + } + + /** + * The authority on what a guarded collection returns: the filter included. + * + * @param array $posts + * @return array + */ + public function results(array $posts, \WP_Query $query): array + { + if (! $query->get(self::GUARD)) { + return $posts; + } + + return array_values(array_filter($posts, fn (mixed $post): bool => ! $post instanceof \WP_Post || $this->allows($post->ID))); + } + + /** + * The attachment page of a private media, its embed and its feed are not found. + */ + public function attachmentPage(): void + { + /** @var \WP_Query $wp_query The main query */ + global $wp_query; + + if (! \is_attachment() || $this->allows((int) \get_queried_object_id())) { + return; + } + + // `set_404()` keeps what the query found, which the feed and the embed would still print + $wp_query->set_404(); + $wp_query->posts = []; + $wp_query->post_count = 0; + $wp_query->found_posts = 0; + $wp_query->post = null; + $wp_query->queried_object = null; + $wp_query->queried_object_id = null; + $GLOBALS['post'] = null; + \status_header(404); + \nocache_headers(); + } + + /** + * The oEmbed answer for an image gives the URL of a thumbnail of it. Not 0 for no post: WordPress would take + * the current one. + */ + public function oembed(mixed $postId): mixed + { + $id = Cast::integer($postId); + + return $id > 0 && \get_post_type($id) === 'attachment' && ! $this->allows($id) ? -1 : $postId; + } +} diff --git a/src/Infrastructure/WordPress/WordPressMedia.php b/src/Infrastructure/WordPress/WordPressMedia.php index ac86bd6..2cdfe64 100644 --- a/src/Infrastructure/WordPress/WordPressMedia.php +++ b/src/Infrastructure/WordPress/WordPressMedia.php @@ -90,6 +90,7 @@ public function register(): void \add_action('deleted_post', [$this, 'deletedPost'], 10, 2); \add_filter('wpmu_delete_blog_upload_dir', [$this, 'uploadDirToDelete'], PHP_INT_MAX); $this->private->register(); + (new PrivateMediaAccess($this->private))->register(); $this->focalPoints->register(); $this->declared->register(); diff --git a/tests/Fixtures/WpRest.php b/tests/Fixtures/WpRest.php new file mode 100644 index 0000000..c6d060b --- /dev/null +++ b/tests/Fixtures/WpRest.php @@ -0,0 +1,96 @@ + */ + public array $vars = []; + + public bool $notFound = false; + + /** @var array */ + public array $posts = []; + + public int $post_count = 0; + + public int $found_posts = 0; + + public mixed $post = null; + + public mixed $queried_object = null; + + public mixed $queried_object_id = null; + + /** @param array $vars */ + public function __construct(array $vars = []) + { + $this->vars = $vars; + } + + public function get(string $name): mixed + { + return $this->vars[$name] ?? ''; + } + + public function set_404(): void + { + $this->notFound = true; + } + } + } + + if (! class_exists('WP_Error', false)) { + final class WP_Error + { + /** @param array $data */ + public function __construct(public string $code = '', public string $message = '', public array $data = []) {} + } + } + + if (! class_exists('WP_REST_Request', false)) { + /** @implements ArrayAccess */ + final class WP_REST_Request implements ArrayAccess + { + /** @param array $params */ + public function __construct(private array $params = []) {} + + public function offsetExists(mixed $offset): bool + { + return isset($this->params[$offset]); + } + + public function offsetGet(mixed $offset): mixed + { + return $this->params[$offset] ?? null; + } + + public function offsetSet(mixed $offset, mixed $value): void + { + $this->params[$offset] = $value; + } + + public function offsetUnset(mixed $offset): void + { + unset($this->params[$offset]); + } + } + } + + if (! class_exists('WP_REST_Attachments_Controller', false)) { + class WP_REST_Attachments_Controller + { + public function get_item(): void {} + } + } +} diff --git a/tests/Integration/PrivateMediaAccessTest.php b/tests/Integration/PrivateMediaAccessTest.php new file mode 100644 index 0000000..b84ec58 --- /dev/null +++ b/tests/Integration/PrivateMediaAccessTest.php @@ -0,0 +1,112 @@ +media = Library::boot(); + $this->word = 'access'.bin2hex(random_bytes(4)); + wp_set_current_user(1); + + $this->upload = function (string $suffix, int $parent = 0): int { + $upload = wp_upload_bits($this->word.$suffix.'.pdf', null, '%PDF-1.4'); + + return wp_insert_attachment(['post_mime_type' => 'application/pdf', 'post_title' => $this->word.$suffix, 'post_status' => 'inherit'], $upload['file'], $parent); + }; + $this->secret = ($this->upload)('secret'); + $this->open = ($this->upload)('open'); + $this->media->privateMedia()->setPrivate($this->secret, true); + + $this->rest = static function (string $route, array $params = [], string $method = 'GET'): WP_REST_Response { + $request = new WP_REST_Request($method, $route); + $request->set_query_params($params); + + // As the server does for a request over HTTP + return rest_get_server()->dispatch($request); + }; + $this->listed = fn (array $params = []): WP_REST_Response => ($this->rest)('/wp/v2/media', ['search' => $this->word] + $params); + + $this->role = static function (string $role): int { + $id = wp_insert_user(['user_login' => $role.bin2hex(random_bytes(4)), 'user_pass' => wp_generate_password(), 'role' => $role]); + wp_set_current_user($id); + + return $id; + }; +}); + +afterEach(function (): void { + wp_set_current_user(0); +}); + +it('gives neither a private media nor its count to a visitor or a user who does not see the library', function (?string $role, int $status): void { + $role === null ? wp_set_current_user(0) : ($this->role)($role); + + foreach (['/wp/v2/media/'.$this->secret, '/WP/V2/MEDIA/'.$this->secret] as $route) { + expect(($this->rest)($route)->get_status())->toBe($status); + } + + // The id of the query string is the one WordPress reads + expect(($this->rest)('/wp/v2/media/'.$this->open, ['id' => $this->secret])->get_status())->toBe($status) + ->and(($this->rest)('/wp/v2/media/'.$this->open)->get_status())->toBe(200); + + $list = ($this->listed)(); + expect(array_column($list->get_data(), 'id'))->toBe([$this->open]) + ->and((int) $list->get_headers()['X-WP-Total'])->toBe(1); + + expect(($this->listed)(['include' => [$this->secret]])->get_data())->toBe([]); +})->with([ + 'a visitor' => [null, 401], + 'a subscriber' => ['subscriber', 403], + 'a contributor' => ['contributor', 403], +]); + +it('keeps the media library and the block editor working for whoever can upload', function (string $role): void { + ($this->role)($role); + + expect(($this->rest)('/wp/v2/media/'.$this->secret)->get_status())->toBe(200) + ->and(array_column(($this->listed)()->get_data(), 'id'))->toContain($this->secret, $this->open); +})->with(['author', 'editor', 'administrator']); + +it('filters the collection when a rule makes a media private', function (): void { + add_filter('pollora/media/is_private', $rule = fn (bool $private, int $id): bool => $private || $id === $this->open, 10, 2); + // The flag is asked once per media in a request + $other = ($this->upload)('ruled'); + remove_filter('pollora/media/is_private', $rule, 10); + add_filter('pollora/media/is_private', $rule = static fn (bool $private, int $id): bool => $private || $id === $other, 10, 2); + wp_set_current_user(0); + + try { + expect(array_column(($this->listed)()->get_data(), 'id'))->toBe([$this->open]) + ->and(($this->rest)('/wp/v2/media/'.$other)->get_status())->toBe(401); + } finally { + remove_filter('pollora/media/is_private', $rule, 10); + } +}); + +it('does not embed a private media in a post that anyone reads', function (): void { + require_once ABSPATH.'wp-admin/includes/image.php'; + $post = wp_insert_post(['post_title' => $this->word, 'post_status' => 'publish', 'post_content' => 'x']); + $upload = wp_upload_bits($this->word.'attached.jpg', null, (string) file_get_contents(Library::jpeg())); + $attached = wp_insert_attachment(['post_mime_type' => 'image/jpeg', 'post_title' => 'attached', 'post_status' => 'inherit'], $upload['file'], $post); + wp_update_attachment_metadata($attached, wp_generate_attachment_metadata($attached, $upload['file'])); + $this->media->privateMedia()->setPrivate($attached, true); + set_post_thumbnail($post, $attached); + wp_set_current_user(0); + + $response = ($this->rest)('/wp/v2/posts/'.$post); + $embedded = (string) wp_json_encode(rest_get_server()->response_to_data($response, true)['_embedded'] ?? []); + + expect($embedded)->not->toContain($this->word.'attached')->toContain('rest_forbidden'); +}); + +it('answers no oEmbed request about a private media', function (): void { + wp_set_current_user(0); + $ask = fn (int $id): int => ($this->rest)('/oembed/1.0/embed', ['url' => home_url('/?attachment_id='.$id)])->get_status(); + + expect($ask($this->secret))->toBe(404)->and($ask($this->open))->toBe(200); +}); diff --git a/tests/Unit/PrivateMediaAccessTest.php b/tests/Unit/PrivateMediaAccessTest.php new file mode 100644 index 0000000..c995c88 --- /dev/null +++ b/tests/Unit/PrivateMediaAccessTest.php @@ -0,0 +1,159 @@ +disk = new TemporaryStorage; + $this->caps = []; + $this->user = 0; + Functions\when('get_post_meta')->alias(static fn (int $id): string => $id === 7 ? '1' : ''); + Functions\when('current_user_can')->alias(fn (string $cap, ?int $id = null): bool => in_array($id === null ? $cap : $cap.':'.$id, $this->caps, true)); + Functions\when('rest_authorization_required_code')->justReturn(401); + Functions\when('get_current_user_id')->alias(fn (): int => $this->user); + $this->access = new PrivateMediaAccess(new PrivateMedia($this->disk->storage, new MediaConfig('https://media.client.fr'), new AttachmentFiles)); + $this->handler = ['callback' => [new WP_REST_Attachments_Controller, 'get_item']]; +}); + +afterEach(function (): void { + StreamWrapper::unregister(); + unset($GLOBALS['wp_query'], $GLOBALS['wpdb']); +}); + +it('is hooked by the module, before WordPress redirects the attachment page to the file', function (): void { + Functions\when('did_action')->justReturn(0); + Filters\expectAdded('rest_request_before_callbacks')->once()->with(Mockery::type('array'), 10, 3); + Filters\expectAdded('rest_attachment_query')->once(); + Filters\expectAdded('posts_where')->once()->with(Mockery::type('array'), 10, 2); + Filters\expectAdded('posts_results')->once()->with(Mockery::type('array'), 10, 2); + Filters\expectAdded('oembed_request_post_id')->once(); + Actions\expectAdded('template_redirect')->once()->with(Mockery::type('array'), 0); + + (new WordPressMedia($this->disk->storage, new MediaConfig('https://media.client.fr')))->register(); +}); + +it('shows a media to anyone when it is public, and a private one to whoever sees the library or edits it', function (int $id, array $caps, bool $allowed): void { + $this->caps = $caps; + + expect($this->access->allows($id))->toBe($allowed); +})->with([ + 'a public media, anonymously' => [8, [], true], + 'a private media, anonymously' => [7, [], false], + 'a private media, someone who sees the library' => [7, ['upload_files'], true], + 'a private media, someone who can edit it' => [7, ['edit_post:7'], true], + 'a private media, someone who can edit another one' => [7, ['edit_post:8'], false], +]); + +it('refuses the REST routes of a private media with the status WordPress uses', function (mixed $id): void { + $result = $this->access->restItem(null, $this->handler, new WP_REST_Request(['id' => $id])); + + expect($result)->toBeInstanceOf(WP_Error::class) + ->and($result->code)->toBe('rest_forbidden') + ->and($result->data)->toBe(['status' => 401]); +})->with(['a number' => [7], 'a string' => ['7']]); + +it('leaves alone a public media, a route with no media, another controller and whoever may see it', function (mixed $handler, mixed $request, array $caps): void { + $this->caps = $caps; + + expect($this->access->restItem('untouched', $handler ?? $this->handler, $request))->toBe('untouched'); +})->with(fn (): array => [ + 'a public media' => [null, new WP_REST_Request(['id' => 8]), []], + 'a collection' => [null, new WP_REST_Request, []], + 'another controller' => [['callback' => [new stdClass, 'get_item']], new WP_REST_Request(['id' => 7]), []], + 'a closure' => [['callback' => static fn () => null], new WP_REST_Request(['id' => 7]), []], + 'no handler' => ['nothing', new WP_REST_Request(['id' => 7]), []], + 'no request' => [null, null, []], + 'an editor' => [null, new WP_REST_Request(['id' => 7]), ['upload_files']], +]); + +it('marks the collections of whoever does not see the library, whatever the request already says', function (): void { + expect($this->access->restQuery(['a' => 1]))->toBe(['a' => 1, 'pollora_media_guard' => true]); + + $this->caps = ['upload_files']; + expect($this->access->restQuery(['a' => 1, 'pollora_media_guard' => true]))->toBe(['a' => 1]); +}); + +it('takes the private media out of a marked collection only', function (): void { + $posts = [new WP_Post(7), new WP_Post(8)]; + + expect($this->access->results($posts, new WP_Query))->toBe($posts) + ->and($this->access->results($posts, new WP_Query(['pollora_media_guard' => true])))->toEqual([new WP_Post(8)]); +}); + +it('leaves the flagged media out in the database too, for the totals, unless a rule decides who is private', function (int $user, int $author): void { + $this->user = $user; + $GLOBALS['wpdb'] = $database = new class + { + public string $posts = 'wp_posts'; + + public string $postmeta = 'wp_postmeta'; + + /** @var list */ + public array $values = []; + + public function prepare(string $query, mixed ...$values): string + { + $this->values = $values; + + return $query; + } + }; + $marked = new WP_Query(['pollora_media_guard' => true]); + Functions\when('has_filter')->justReturn(false); + + expect($this->access->where(' WHERE 1', new WP_Query))->toBe(' WHERE 1') + ->and($this->access->where(' WHERE 1', $marked))->toStartWith(' WHERE 1 AND (%i.ID NOT IN (SELECT post_id FROM %i') + ->and($database->values)->toBe(['wp_posts', 'wp_postmeta', '_pollora_media_private', '1', 'wp_posts', $author]); + + Functions\when('has_filter')->justReturn(true); + expect($this->access->where(' WHERE 1', $marked))->toBe(' WHERE 1'); +})->with(['anonymous, never the media without an author' => [0, -1], 'a user, whose own media stay' => [5, 5]]); + +it('does not find the attachment page of a private media', function (bool $attachment, int $id, array $caps, bool $notFound): void { + $this->caps = $caps; + $GLOBALS['wp_query'] = $query = new WP_Query; + $query->posts = [$post = new WP_Post($id)]; + $query->post_count = 1; + $query->post = $GLOBALS['post'] = $query->queried_object = $post; + Functions\when('is_attachment')->justReturn($attachment); + Functions\when('get_queried_object_id')->justReturn($id); + Functions\expect('status_header')->times($notFound ? 1 : 0)->with(404); + Functions\expect('nocache_headers')->times($notFound ? 1 : 0); + + $this->access->attachmentPage(); + + expect($query->notFound)->toBe($notFound) + ->and($query->posts)->toBe($notFound ? [] : [$post]) + ->and($query->post_count)->toBe($notFound ? 0 : 1) + ->and($query->post)->toBe($notFound ? null : $post) + ->and($query->queried_object)->toBe($notFound ? null : $post) + ->and($GLOBALS['post'])->toBe($notFound ? null : $post); + unset($GLOBALS['post']); +})->with([ + 'a private media' => [true, 7, [], true], + 'a public media' => [true, 8, [], false], + 'another page' => [false, 7, [], false], + 'an editor' => [true, 7, ['upload_files'], false], +]); + +it('gives no oEmbed answer about a private media', function (mixed $id, string $type, mixed $answer): void { + Functions\when('get_post_type')->justReturn($type); + + expect($this->access->oembed($id))->toBe($answer); +})->with([ + 'a private media' => [7, 'attachment', -1], + 'a public media' => [8, 'attachment', 8], + 'a post with the same id' => [7, 'post', 7], + 'nothing found' => [0, 'attachment', 0], +]); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index d980c64..4b78bf4 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -12,6 +12,7 @@ */ require_once dirname(__DIR__).'/vendor/autoload.php'; require_once __DIR__.'/Fixtures/WpCli.php'; +require_once __DIR__.'/Fixtures/WpRest.php'; /* * The process of a mutant (`pest --mutate`): Pest serves the mutated source through a stream wrapper on `file`. That From 87e53389ab0c5542c0f7c5661f3839d15328cf35 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 19:27:44 +0100 Subject: [PATCH 09/17] docs: security notes, behaviour changes and verified repair steps --- CHANGELOG.md | 52 +++++++++++++++++++++++++++++++++++++--------------- README.md | 44 +++++++++++++++++++++++++++++++++----------- 2 files changed, 70 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9365846..9267a2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,30 +7,53 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +Next version: 0.11.0. + +### Security + +**Upgrading changes nothing on the disk by itself.** Follow *Repairing media left public* in the README: make each private media private again, then purge the CDN. + +Private media (since 0.3.0 unless said otherwise): + +- Anyone could read a private media attached to no post, and get its signed URL: over REST (`GET /wp/v2/media/{id}` and the collection), on its attachment page, in its embed and feed, and in the oEmbed answer +- A private media that is not an image (PDF, archive, video, audio) was never made private on the disk, neither at upload nor by `wp pollora media visibility --private`, which reported a success with no file changed +- The files written after a media was made private (an edit in the media library, sizes made later, the new media the block editor saves a crop or a rotation as) were left public. They are made private when the metadata is saved, and the copy made by the editor is private +- The files WordPress keeps of an image before its edit, and its other companions (`source_image`, `animated_video`, `animated_video_poster`), did not follow the visibility of the media +- The sizes of a private media made at upload, when its image is edited, when its focal point moves or by `thumbs warm` kept the default visibility of the disk (declared sizes, since 0.4.0) +- The fallback route served the file of a declared size of a private media when that file existed, with a public cache of one year, and made or served sizes of the original a private image had before its edit (since 0.5.0) +- While the server is saturated, the fallback route could answer with a size of another media whose name starts like the one asked for, or that has the same name with another extension, private or not (since 0.5.0) + +Networks: + +- On a site other than the main one, no file of a private media was made private, and the files of the main site with the same names were changed instead +- Deleting a site whose uploads are the root of the library (a network created before WordPress 3.5, uploads moved out of `sites/N`) deleted every file of the library (since 0.1.0) +- On a site other than the main one, the declared sizes used the paths of the main site: deleting a media could delete the main site's files (since 0.4.0), `thumbs prune` run there could delete them too (since 0.4.0), and the fallback route could serve a private size of the main site (since 0.5.0) + +Stream wrapper: + +- `rmdir('pollora://.')` (since 0.1.0), `pollora://uploads/.` and spellings with a backslash (since 0.2.0) deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first + ### Changed +Behaviour changes to check before upgrading: + +- **REST**: for a user without `upload_files` who cannot edit it, a private media answers `401` or `403` on `/wp/v2/media/{id}`, and is left out of the collection and of `_embed`. A headless front-end that reads private media anonymously, or a custom role that relied on it, has to authenticate or be given the capability +- **Attachment page and oEmbed**: for the same users, the attachment page of a private media, its embed and its feed are not found, and oEmbed answers `404`. A plugin that gates a download through that page has to give its users `edit_post` on the media, or serve it elsewhere +- **Networks**: a site other than the main one gets no declared size, including the images uploaded before: WordPress serves its own sizes, and the original under a declared name it has no size for. The declared size recorded in the metadata of such an image is no longer read +- **Networks**: on a site other than the main one, the fallback route serves nothing, and `wp pollora media thumbs prune` refuses to run +- **Networks**: when the uploads of a deleted site are the whole library, its files stay on the disk +- **Fallback route**: a size whose original is no longer on the disk is a `404`, even when its file exists. The route asks the database and the disk for a size already made, where it only asked the disk +- Making a media private or public now changes the files kept of it before its edits too, and `pollora/media/deleted` and `wp pollora media files` list them +- Saving the metadata of a private media sets the visibility of each of its files, one call to the disk per file - PHPStan runs at level 10. A value without a type from WordPress, WP-CLI, a filter or a constant that is neither a scalar nor stringable now reads as `''` or `0` - `UrlReplacement` and the private media lookup pass table and column names to `$wpdb->prepare()` as `%i` identifiers (WordPress 6.2 or later) ### Fixed -- Security: a private media that is not an image (PDF, archive, video, audio) was never made private on the disk, neither at upload nor by `wp pollora media visibility --private`, which reported a success with no file changed -- Security: the files written after a media was made private (an edit in the media library, sizes made later, the new media the block editor saves a crop or a rotation as) were left public. They are made private when the metadata is saved, and the copy made by the editor is private -- Security: the files WordPress keeps of an image before its edit, and its other companions (`source_image`, `animated_video`, `animated_video_poster`), did not follow the visibility of the media -- Security: the fallback route served the file of a size of a private media when that file existed, and made or served sizes of the original a private image had before its edit -- Security: while the server is saturated, the fallback route could answer with a size of another media whose name starts like the one asked for, private or not -- Security: `thumbs warm` leaves the sizes that exist of a private media private - -- Security: the sizes of a private media made at upload, when its image is edited, when its focal point moves or by `thumbs warm` were left with the default visibility of the disk, so readable by their public URL on an object store. They are now made private -- Security: `rmdir('pollora://uploads/.')`, `pollora://.` and spellings with a backslash deleted the whole media library, because the disk reads them as its root after the wrapper had taken them for a folder. `.` segments and backslashes are now resolved by the wrapper first -- Security: on a site of a network other than the main one, no file of a private media was made private, and the file of the same name of the main site was the one changed -- Security: deleting a site of a network whose uploads are not under `sites/N` (a network created before WordPress 3.5, a custom `upload_path`) deleted every file of the library. Nothing is deleted then -- Security: on a site of a network, the declared sizes used the paths of the main site: deleting a media could delete the main site's files, and the fallback route could serve a private size of the main site. No declared size is made or served for such a site, which gets the sizes of WordPress and the original -- Repairing existing sites: run `wp pollora media visibility --private` for each private media, then `wp pollora media thumbs prune --execute`, and purge the CDN. See *Repairing media left public* in the README -- Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release - A file is treated as private when the database query that looks its media up fails, instead of public - A personal data export archive that cannot be read is no longer copied to the disk as an empty file before a `TypeError`: `PrivacyExportFailedException` is thrown and the disk is left alone - A write through `pollora://` no longer ends in a `TypeError` when the temporary directory cannot be written: the file is stored, only its local copy is given up +- Development only: `antecedent/patchwork` is required at commit `d588654` of its `master` branch (antecedent/patchwork#235), aliased as 2.2.6, so that Pest mutants are no longer counted as caught when tests hang. This pin is temporary until the next Patchwork release ## [0.10.0] - 2026-11-24 @@ -43,7 +66,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **BREAKING**: `PolloraThumbnailDriver` takes the declared sizes (`ImageSizes`) as a third constructor argument and `ImgproxyThumbnailDriver` as its third, before the base URL (`new ImgproxyThumbnailDriver($signer, $config, $sizes, $baseUrl, $bucket)`), to recognise only declared sizes as `BunnyThumbnailDriver` already does. `ThumbnailDrivers::make()` and `DeclaredSizes` pass them; only code that builds these drivers by hand changes. -||||||| d54194b - The unit suite loads its stand-in for WP-CLI from `tests/bootstrap.php` instead of `tests/Pest.php`, which the integration suite also loads (a real WordPress must not find a `WP_CLI` that is not WP-CLI). No change to the package. ### Security diff --git a/README.md b/README.md index 31d200b..4146afa 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,8 @@ add_filter('pollora/media/filesystem', fn () => new Filesystem(new SftpAdapter(/ | `wp_get_attachment_url`, `wp_get_attachment_image_src`, `wp_calculate_image_srcset` | Private media only: the URL, the URL of a size and every source of a `srcset` are signed and expire. A public media keeps its plain URL, and nothing is asked of the disk to tell them apart | | `wp_generate_attachment_metadata` | A media created private (see below) is made private on the disk | | `wp_update_attachment_metadata`, `wp_edited_image_metadata` | Private media only: the files written since are made private, and the copy the editor makes of a private image is private | +| `rest_request_before_callbacks`, `rest_attachment_query`, `posts_where`, `posts_results`, `template_redirect`, `oembed_request_post_id` | Private media only: [who WordPress tells about it](#who-wordpress-tells-about-a-private-media) | +| `wpmu_delete_blog_upload_dir` | On a network, nothing is deleted when the folder of the deleted site is the whole library | The `pollora://` wrapper sends a file to the disk when its stream is closed, in one write. Directories do not exist on an object store, so they are virtual and answer without asking the disk (a path with an extension is a file); what is asked about a file is remembered for the rest of the request. A file written or read during a request, up to 16 MiB, is also kept in a local copy until the request ends: WordPress reads an uploaded image again for its size, its EXIF data, its sizes and its metadata, and none of it goes back to the disk. One upload of an image with nine sizes costs ten writes and a handful of existence checks; a read of the original, a stat or a listing never happens. Both the GD and the Imagick editors of WordPress work on the wrapper as they are. @@ -158,7 +160,7 @@ A size is made at upload only if it is declared `eager()`. The same goes for an - **S3 or compatible service behind a CDN.** The origin of the CDN for the library is the site: one rule at the CDN. PHP sees each file the first time the CDN asks, then the cache lasts a year. - **S3 without a CDN.** There is no fallback: declare the sizes you use `eager()` and run `thumbs warm`. The URL stays the same. -What the URL says is not trusted. First, without asking the disk: the name is one of a declared size, the signature is the one the site would have made, the extension is an image's, and the path does not climb out of the library. Then, against the original: its dimensions are those the name gives (nobody can name a size of their own), it is not private, it is not a GIF. A request that fails a check gets a 404 and costs nothing. +What the URL says is not trusted. First, without asking the disk: the name is one of a declared size, the signature is the one the site would have made, the extension is an image's, and the path does not climb out of the library. Then, against the original, for a size already made too: it is still there and it is not private. Before a size is made: the dimensions of the original give those of the name (nobody can name a size of their own), and it is not a GIF. A request that fails a check gets a 404 and costs nothing. Making a size costs CPU, so it is limited, per server: one process per file (ten simultaneous requests for the same missing size make one), at most `POLLORA_MEDIA_THUMBNAILS_CONCURRENCY` sizes at the same time (4), and an original above `POLLORA_MEDIA_THUMBNAILS_MAX_PIXELS` (50 million pixels, imgproxy's default) or `POLLORA_MEDIA_THUMBNAILS_MAX_BYTES` (30 MiB) gets no size at all: it stays downloadable. A request that cannot get a place within `POLLORA_MEDIA_THUMBNAILS_WAIT` seconds (10) is handed a size that already exists, the smallest that is at least as wide, the original at worst, with `Cache-Control: no-store`: the visitor sees an image, the CDN does not keep the stand-in, and the real size is made on a later request. The answer for a size made is `200` with `Cache-Control: public, max-age=31536000, immutable`, never a redirect. @@ -201,7 +203,7 @@ wp pollora media thumbs export --driver=imgproxy # the configuration to For Bunny, the classes are read, merged by name and written back: the ones you made are kept, nothing is deleted, and the forced classes setting is never changed. The merge matters: Bunny replaces the whole list of classes with the one it is sent. The access key is only ever sent in the `AccessKey` header. imgproxy has no API for presets: the command prints `IMGPROXY_PRESETS`, `IMGPROXY_ONLY_PRESETS=true`, `IMGPROXY_MAX_SRC_RESOLUTION` (in megapixels) and `IMGPROXY_ALLOWED_SOURCES`, never the key or the salt. -**Networks.** The declared sizes are made for the main site only: another site gets the sizes of WordPress, and the original under a declared name. A network whose sites do not upload under `sites/N` (created before WordPress 3.5, or with an `upload_path` of its own) shares the root of the library, which is not supported: its sites can overwrite each other's files, and deleting one deletes nothing from the disk. +**Networks.** The declared sizes are made for the main site only: another site gets the sizes of WordPress, and the original under a declared name WordPress has no size for. On another site, the fallback route serves nothing and `thumbs prune` refuses to run. A network whose sites do not upload under `sites/N` (created before WordPress 3.5, or with an `upload_path` of its own) shares the root of the library, which is not supported: its sites can overwrite each other's files, and deleting one deletes nothing from the disk. ## Private media @@ -241,24 +243,44 @@ A file written for a media that is already private is written with the visibilit Visibility is the one the disk keeps for each file (on S3, the ACL of the object). A bucket with ACLs disabled (*Bucket owner enforced*), a bucket policy or a CDN that makes every object public, or a provider without object ACLs keeps a private media readable by its plain URL, whatever the module does. +### Who WordPress tells about a private media + +WordPress shows a media attached to no post to anyone, with its URL, and that URL is signed for whoever asks. The module keeps a private media to the users who can upload files (`upload_files`, the ones the media library shows every media to) and to whoever can edit that media: + +- over REST, `/wp/v2/media/{id}` and what lies under it answers `401` (not logged in) or `403`, and the collection leaves the media out, an `_embed` included; +- the attachment page, its embed and its feed are not found, and oEmbed does not answer about it. + +This is not access control over the content that uses the media: a published page that displays a private media hands its signed URL to every visitor, and so does a theme or a plugin that lists attachments. A headless front-end that reads private media over REST has to authenticate as a user who may. With a `pollora/media/is_private` rule, the totals of a REST collection (`X-WP-Total`) still count the media the rule hides. + ### Repairing media left public -Up to 0.10.0, some files of private media were left public (see the CHANGELOG). Making each private media private again changes every file of it, and can be repeated: +Up to 0.10.0, some files of private media were left public (see the CHANGELOG). Upgrading changes nothing on the disk by itself: making each private media private again changes every file of it, and can be repeated. ```bash -# The media flagged private -for id in $(wp post list --post_type=attachment --post_status=any --meta_key=_pollora_media_private --meta_value=1 --field=ID); do - wp pollora media visibility "$id" --private +# The media flagged private, the trashed ones included +for id in $(wp post list --post_type=attachment --post_status=inherit,private,trash --meta_key=_pollora_media_private --meta_value=1 --field=ID); do + wp pollora media visibility "$id" --private || echo "Not repaired: media $id" done -# The media private by a `pollora/media/is_private` rule only. The command also flags them, which a rule that -# lets a media become public again has to take into account -for id in $(wp post list --post_type=attachment --post_status=any --field=ID); do - wp pollora media files "$id" | grep -q "Media $id is private" && wp pollora media visibility "$id" --private +# Only with a `pollora/media/is_private` rule: the media private by the rule. It looks at every media, which takes +# a while on a large library. The command also flags them, which a rule that lets a media become public again has +# to take into account +for id in $(wp post list --post_type=attachment --post_status=inherit,private,trash --field=ID); do + if wp pollora media files "$id" | grep "Media $id is private" > /dev/null; then + wp pollora media visibility "$id" --private || echo "Not repaired: media $id" + fi done ``` -On a network, run the loops once per site (`--url=`), and `thumbs prune` on the main site only. In Pollora, the Artisan commands of the framework do the same. Then run `wp pollora media thumbs prune --execute`, which deletes the files of the sizes that were changed or removed since (no command knows which media they were made of), and purge the CDN, which may keep what it already read. Run the first loop again after a `migrate`: files copied from a local folder keep the visibility they had there. +A file the command reports as not changed is missing from the disk, or is still as it was: check it. Run the first loop again after a `migrate`, since files copied from a local folder keep the visibility they had there. + +Then: + +- `wp pollora media thumbs prune` lists the files of the declared sizes that were changed or removed since, which no command can attribute to a media; `--execute` deletes them. On a network, run it from the main site only. +- On a network, run the loops once per site (`--url=`). Up to 0.10.0, making private a media of another site changed the files of the main site that have the same names: for a media of the main site whose files are private by mistake, `wp pollora media visibility --public`. +- Purge the CDN, which may keep what it already read. + +The files of the declared sizes made on demand for an image as it was before an edit stay on the disk once the media is deleted. The module no longer serves them, but a web server or a bucket that makes files public does. ## Commands From 09f0b4845a32c8557fba6d74b819342dca427a95 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 20:06:58 +0100 Subject: [PATCH 10/17] fix(private-media): close the ways around who WordPress tells about a private media - a single page is looked at for what it holds, not for is_attachment() and the queried object - no canonical redirect from a request that names a private media (its slug or its signed file) - parse-media-shortcode answers only users of the library or editors of the post named - the two filters that run on every query accept a call without the query --- CHANGELOG.md | 3 + README.md | 9 +- .../WordPress/PrivateMediaAccess.php | 73 +++++++++++++--- tests/Fixtures/WpRest.php | 4 + tests/Integration/PrivateMediaAccessTest.php | 34 ++++++++ tests/Unit/PrivateMediaAccessTest.php | 86 +++++++++++++++---- 6 files changed, 178 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9267a2a..cf0d389 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ Next version: 0.11.0. Private media (since 0.3.0 unless said otherwise): - Anyone could read a private media attached to no post, and get its signed URL: over REST (`GET /wp/v2/media/{id}` and the collection), on its attachment page, in its embed and feed, and in the oEmbed answer +- The same page, reached as a single post (`?post_type=attachment&p=N`, an attached media included) or with the posts page in the query, showed the private media; when WordPress has no attachment pages, it redirected to the signed URL of the file, and otherwise to its slug +- Any signed-in user, a subscriber included, could get the signed URL of a private media by asking WordPress to preview a `[gallery]` shortcode (`admin-ajax.php?action=parse-media-shortcode`) - A private media that is not an image (PDF, archive, video, audio) was never made private on the disk, neither at upload nor by `wp pollora media visibility --private`, which reported a success with no file changed - The files written after a media was made private (an edit in the media library, sizes made later, the new media the block editor saves a crop or a rotation as) were left public. They are made private when the metadata is saved, and the copy made by the editor is private - The files WordPress keeps of an image before its edit, and its other companions (`source_image`, `animated_video`, `animated_video_poster`), did not follow the visibility of the media @@ -39,6 +41,7 @@ Behaviour changes to check before upgrading: - **REST**: for a user without `upload_files` who cannot edit it, a private media answers `401` or `403` on `/wp/v2/media/{id}`, and is left out of the collection and of `_embed`. A headless front-end that reads private media anonymously, or a custom role that relied on it, has to authenticate or be given the capability - **Attachment page and oEmbed**: for the same users, the attachment page of a private media, its embed and its feed are not found, and oEmbed answers `404`. A plugin that gates a download through that page has to give its users `edit_post` on the media, or serve it elsewhere +- **Shortcode preview**: `parse-media-shortcode` is refused to a user without `upload_files` who names no post they can edit - **Networks**: a site other than the main one gets no declared size, including the images uploaded before: WordPress serves its own sizes, and the original under a declared name it has no size for. The declared size recorded in the metadata of such an image is no longer read - **Networks**: on a site other than the main one, the fallback route serves nothing, and `wp pollora media thumbs prune` refuses to run - **Networks**: when the uploads of a deleted site are the whole library, its files stay on the disk diff --git a/README.md b/README.md index 4146afa..5c4c683 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ add_filter('pollora/media/filesystem', fn () => new Filesystem(new SftpAdapter(/ | `wp_get_attachment_url`, `wp_get_attachment_image_src`, `wp_calculate_image_srcset` | Private media only: the URL, the URL of a size and every source of a `srcset` are signed and expire. A public media keeps its plain URL, and nothing is asked of the disk to tell them apart | | `wp_generate_attachment_metadata` | A media created private (see below) is made private on the disk | | `wp_update_attachment_metadata`, `wp_edited_image_metadata` | Private media only: the files written since are made private, and the copy the editor makes of a private image is private | -| `rest_request_before_callbacks`, `rest_attachment_query`, `posts_where`, `posts_results`, `template_redirect`, `oembed_request_post_id` | Private media only: [who WordPress tells about it](#who-wordpress-tells-about-a-private-media) | +| `rest_request_before_callbacks`, `rest_attachment_query`, `posts_where`, `posts_results`, `template_redirect`, `redirect_canonical`, `oembed_request_post_id`, `wp_ajax_parse-media-shortcode` | Private media only (the last one: signed-in users who write nothing): [who WordPress tells about it](#who-wordpress-tells-about-a-private-media) | | `wpmu_delete_blog_upload_dir` | On a network, nothing is deleted when the folder of the deleted site is the whole library | The `pollora://` wrapper sends a file to the disk when its stream is closed, in one write. Directories do not exist on an object store, so they are virtual and answer without asking the disk (a path with an extension is a file); what is asked about a file is remembered for the rest of the request. A file written or read during a request, up to 16 MiB, is also kept in a local copy until the request ends: WordPress reads an uploaded image again for its size, its EXIF data, its sizes and its metadata, and none of it goes back to the disk. One upload of an image with nine sizes costs ten writes and a handful of existence checks; a read of the original, a stat or a listing never happens. Both the GD and the Imagick editors of WordPress work on the wrapper as they are. @@ -248,9 +248,12 @@ Visibility is the one the disk keeps for each file (on S3, the ACL of the object WordPress shows a media attached to no post to anyone, with its URL, and that URL is signed for whoever asks. The module keeps a private media to the users who can upload files (`upload_files`, the ones the media library shows every media to) and to whoever can edit that media: - over REST, `/wp/v2/media/{id}` and what lies under it answers `401` (not logged in) or `403`, and the collection leaves the media out, an `_embed` included; -- the attachment page, its embed and its feed are not found, and oEmbed does not answer about it. +- the attachment page, its embed and its feed are not found, however the request names the media, and WordPress does not redirect to its slug or its file; +- oEmbed does not answer about it. -This is not access control over the content that uses the media: a published page that displays a private media hands its signed URL to every visitor, and so does a theme or a plugin that lists attachments. A headless front-end that reads private media over REST has to authenticate as a user who may. With a `pollora/media/is_private` rule, the totals of a REST collection (`X-WP-Total`) still count the media the rule hides. +WordPress also renders any shortcode a signed-in user sends to `admin-ajax.php?action=parse-media-shortcode`: only whoever can upload files, or edit the post the request names, gets an answer. + +This is not access control over the content that uses the media: a published page that displays a private media hands its signed URL to every visitor, and so does a theme or a plugin that lists attachments. Whoever can write content, a contributor included, can display a private media in it by its id (a gallery in a draft and its preview, for instance). A headless front-end that reads private media over REST has to authenticate as a user who may. With a `pollora/media/is_private` rule, the totals of a REST collection (`X-WP-Total`) still count the media the rule hides. ### Repairing media left public diff --git a/src/Infrastructure/WordPress/PrivateMediaAccess.php b/src/Infrastructure/WordPress/PrivateMediaAccess.php index 12cf1ba..20dbc5f 100644 --- a/src/Infrastructure/WordPress/PrivateMediaAccess.php +++ b/src/Infrastructure/WordPress/PrivateMediaAccess.php @@ -33,6 +33,9 @@ public function register(): void // Before `redirect_canonical()`, which sends the attachment page to the URL of the file \add_action('template_redirect', [$this, 'attachmentPage'], 0); \add_filter('oembed_request_post_id', [$this, 'oembed'], PHP_INT_MAX); + // Last: WordPress redirects to the slug of a media, or to its file, from what the request names + \add_filter('redirect_canonical', [$this, 'canonical'], PHP_INT_MAX); + \add_action('wp_ajax_parse-media-shortcode', [$this, 'mediaShortcode'], 0); } public function allows(int $attachmentId): bool @@ -86,13 +89,15 @@ public function restQuery(array $args): array * Leaves the flagged media out in the database, so the totals of the collection do not count them: a search * would tell that a private media matches. A `pollora/media/is_private` rule cannot be written in SQL, and may * make a flagged media public: with one, the results alone are filtered. + * + * Untyped: these two run on every query, and a plugin may apply their filters without the query. */ - public function where(string $where, \WP_Query $query): string + public function where(mixed $where, mixed $query = null): mixed { /** @var \wpdb $wpdb The global WordPress sets, which has no declared type */ global $wpdb; - if (! $query->get(self::GUARD) || \has_filter('pollora/media/is_private') !== false) { + if (! $query instanceof \WP_Query || ! $query->get(self::GUARD) || \has_filter('pollora/media/is_private') !== false) { return $where; } @@ -107,18 +112,15 @@ public function where(string $where, \WP_Query $query): string \get_current_user_id() ?: -1, ); - return $where.Cast::text($clause); + return Cast::text($where).Cast::text($clause); } /** * The authority on what a guarded collection returns: the filter included. - * - * @param array $posts - * @return array */ - public function results(array $posts, \WP_Query $query): array + public function results(mixed $posts, mixed $query = null): mixed { - if (! $query->get(self::GUARD)) { + if (! is_array($posts) || ! $query instanceof \WP_Query || ! $query->get(self::GUARD)) { return $posts; } @@ -126,14 +128,17 @@ public function results(array $posts, \WP_Query $query): array } /** - * The attachment page of a private media, its embed and its feed are not found. + * A single page that is, or names, a private media is not found: the attachment page, its embed and its feed. + * + * Neither `is_attachment()` nor the queried object tell them all: `?post_type=attachment&p=N` is a single post + * to WordPress, and with the posts page in the query the queried object is that page. */ public function attachmentPage(): void { /** @var \WP_Query $wp_query The main query */ global $wp_query; - if (! \is_attachment() || $this->allows((int) \get_queried_object_id())) { + if ((! $wp_query->is_singular && ! $wp_query->is_attachment) || ! $this->withholds($wp_query)) { return; } @@ -150,6 +155,54 @@ public function attachmentPage(): void \nocache_headers(); } + /** + * No redirection from a request that names a private media: the target is its slug or, when WordPress has no + * attachment pages, its file, with a signed URL. + */ + public function canonical(mixed $url): mixed + { + /** @var \WP_Query|null $wp_query The main query */ + global $wp_query; + + return $wp_query instanceof \WP_Query && $this->withholds($wp_query) ? false : $url; + } + + /** + * WordPress renders any shortcode a signed-in user sends it, `[gallery ids="N"]` included, whatever their + * role. The editor sends the post it edits: without one they can edit, only users of the library are answered. + */ + public function mediaShortcode(): void + { + $postId = Cast::integer($_POST['post_ID'] ?? 0); + + if (\current_user_can('upload_files') || ($postId > 0 && \current_user_can('edit_post', $postId))) { + return; + } + + \wp_send_json_error(); + } + + /** + * Whether the query names a private media the user may not see, or is a single page that found one. What a + * list shows is the choice of whoever lists it. + */ + private function withholds(\WP_Query $query): bool + { + $ids = array_map(static fn (string $name): int => Cast::integer($query->get($name)), ['attachment_id', 'p', 'page_id']); + + foreach ($query->is_singular || $query->is_attachment ? (array) $query->posts : [] as $post) { + $ids[] = $post instanceof \WP_Post ? $post->ID : 0; + } + + foreach ($ids as $id) { + if ($id > 0 && \get_post_type($id) === 'attachment' && ! $this->allows($id)) { + return true; + } + } + + return false; + } + /** * The oEmbed answer for an image gives the URL of a thumbnail of it. Not 0 for no post: WordPress would take * the current one. diff --git a/tests/Fixtures/WpRest.php b/tests/Fixtures/WpRest.php index c6d060b..5fcd4f5 100644 --- a/tests/Fixtures/WpRest.php +++ b/tests/Fixtures/WpRest.php @@ -19,6 +19,10 @@ class WP_Query public bool $notFound = false; + public bool $is_singular = false; + + public bool $is_attachment = false; + /** @var array */ public array $posts = []; diff --git a/tests/Integration/PrivateMediaAccessTest.php b/tests/Integration/PrivateMediaAccessTest.php index b84ec58..1de3aeb 100644 --- a/tests/Integration/PrivateMediaAccessTest.php +++ b/tests/Integration/PrivateMediaAccessTest.php @@ -2,6 +2,7 @@ declare(strict_types=1); +use Pollora\Media\Infrastructure\WordPress\PrivateMediaAccess; use Pollora\Media\Tests\Integration\Support\Library; /* @@ -110,3 +111,36 @@ expect($ask($this->secret))->toBe(404)->and($ask($this->open))->toBe(200); }); + +it('does not find a private media however the main query reaches it', function (Closure $vars, bool $postsPage): void { + $page = wp_insert_post(['post_type' => 'page', 'post_title' => 'blog'.$this->word, 'post_status' => 'publish']); + $parent = wp_insert_post(['post_title' => $this->word, 'post_status' => 'publish', 'post_content' => 'x']); + $attached = ($this->upload)('attached', $parent); + $this->media->privateMedia()->setPrivate($attached, true); + if ($postsPage) { + add_filter('pre_option_show_on_front', $front = static fn (): string => 'page'); + add_filter('pre_option_page_for_posts', $posts = static fn (): int => $page); + } + wp_set_current_user(0); + $previous = $GLOBALS['wp_query']; + + try { + $GLOBALS['wp_query'] = $query = new WP_Query; + $query->query($vars($this->secret, $attached, $page)); + $access = new PrivateMediaAccess($this->media->privateMedia()); + + // Both before and after the page is refused: WordPress then redirects a 404 to the media asked for + expect($access->canonical('https://example.test/there'))->toBeFalse(); + $access->attachmentPage(); + expect($query->is_404())->toBeTrue()->and($query->posts)->toBe([]); + } finally { + $GLOBALS['wp_query'] = $previous; + if ($postsPage) { + remove_filter('pre_option_show_on_front', $front); + remove_filter('pre_option_page_for_posts', $posts); + } + } +})->with([ + 'the type and the id of an attached media' => [static fn (int $secret, int $attached): array => ['post_type' => 'attachment', 'p' => $attached], false], + 'with the posts page' => [static fn (int $secret, int $attached, int $page): array => ['attachment_id' => $secret, 'page_id' => $page], true], +]); diff --git a/tests/Unit/PrivateMediaAccessTest.php b/tests/Unit/PrivateMediaAccessTest.php index c995c88..c52b784 100644 --- a/tests/Unit/PrivateMediaAccessTest.php +++ b/tests/Unit/PrivateMediaAccessTest.php @@ -19,6 +19,8 @@ $this->caps = []; $this->user = 0; Functions\when('get_post_meta')->alias(static fn (int $id): string => $id === 7 ? '1' : ''); + // 7 and 8 are media, the others are pages + Functions\when('get_post_type')->alias(static fn (int $id): string => in_array($id, [7, 8], true) ? 'attachment' : 'page'); Functions\when('current_user_can')->alias(fn (string $cap, ?int $id = null): bool => in_array($id === null ? $cap : $cap.':'.$id, $this->caps, true)); Functions\when('rest_authorization_required_code')->justReturn(401); Functions\when('get_current_user_id')->alias(fn (): int => $this->user); @@ -28,7 +30,7 @@ afterEach(function (): void { StreamWrapper::unregister(); - unset($GLOBALS['wp_query'], $GLOBALS['wpdb']); + unset($GLOBALS['wp_query'], $GLOBALS['wpdb'], $GLOBALS['post'], $_POST['post_ID']); }); it('is hooked by the module, before WordPress redirects the attachment page to the file', function (): void { @@ -39,6 +41,8 @@ Filters\expectAdded('posts_results')->once()->with(Mockery::type('array'), 10, 2); Filters\expectAdded('oembed_request_post_id')->once(); Actions\expectAdded('template_redirect')->once()->with(Mockery::type('array'), 0); + Filters\expectAdded('redirect_canonical')->once()->with(Mockery::type('array'), PHP_INT_MAX); + Actions\expectAdded('wp_ajax_parse-media-shortcode')->once()->with(Mockery::type('array'), 0); (new WordPressMedia($this->disk->storage, new MediaConfig('https://media.client.fr')))->register(); }); @@ -120,33 +124,79 @@ public function prepare(string $query, mixed ...$values): string expect($this->access->where(' WHERE 1', $marked))->toBe(' WHERE 1'); })->with(['anonymous, never the media without an author' => [0, -1], 'a user, whose own media stay' => [5, 5]]); -it('does not find the attachment page of a private media', function (bool $attachment, int $id, array $caps, bool $notFound): void { +it('does not find a single page that is, or names, a private media', function (array $flags, array $vars, array $posts, array $caps, bool $notFound): void { $this->caps = $caps; - $GLOBALS['wp_query'] = $query = new WP_Query; - $query->posts = [$post = new WP_Post($id)]; - $query->post_count = 1; - $query->post = $GLOBALS['post'] = $query->queried_object = $post; - Functions\when('is_attachment')->justReturn($attachment); - Functions\when('get_queried_object_id')->justReturn($id); + $GLOBALS['wp_query'] = $query = new WP_Query($vars); + foreach ($flags as $flag) { + $query->{$flag} = true; + } + $query->posts = $found = array_map(static fn (int $id): WP_Post => new WP_Post($id), $posts); + $query->post_count = count($found); + $query->post = $GLOBALS['post'] = $query->queried_object = $found[0] ?? null; Functions\expect('status_header')->times($notFound ? 1 : 0)->with(404); Functions\expect('nocache_headers')->times($notFound ? 1 : 0); $this->access->attachmentPage(); expect($query->notFound)->toBe($notFound) - ->and($query->posts)->toBe($notFound ? [] : [$post]) - ->and($query->post_count)->toBe($notFound ? 0 : 1) - ->and($query->post)->toBe($notFound ? null : $post) - ->and($query->queried_object)->toBe($notFound ? null : $post) - ->and($GLOBALS['post'])->toBe($notFound ? null : $post); - unset($GLOBALS['post']); + ->and($query->posts)->toBe($notFound ? [] : $found) + ->and($query->post_count)->toBe($notFound ? 0 : count($found)) + ->and($query->post)->toBe($notFound ? null : ($found[0] ?? null)) + ->and($query->queried_object)->toBe($notFound ? null : ($found[0] ?? null)) + ->and($GLOBALS['post'])->toBe($notFound ? null : ($found[0] ?? null)); })->with([ - 'a private media' => [true, 7, [], true], - 'a public media' => [true, 8, [], false], - 'another page' => [false, 7, [], false], - 'an editor' => [true, 7, ['upload_files'], false], + 'its attachment page' => [['is_singular', 'is_attachment'], [], [7], [], true], + 'a single post to WordPress, as `?post_type=attachment&p=7` is' => [['is_singular'], ['p' => 7], [7], [], true], + 'found by its name only' => [['is_singular'], [], [7], [], true], + 'asked for with the posts page, which found nothing' => [['is_singular', 'is_attachment'], ['attachment_id' => 7, 'page_id' => 3], [], [], true], + 'a public media' => [['is_singular', 'is_attachment'], ['attachment_id' => 8], [8], [], false], + 'a page' => [['is_singular'], ['page_id' => 3], [3], [], false], + 'a list a theme puts media in' => [[], [], [7], [], false], + 'an editor' => [['is_singular', 'is_attachment'], ['attachment_id' => 7], [7], ['upload_files'], false], ]); +it('redirects nobody to a private media, its slug or its file', function (array $vars, array $caps, bool $kept): void { + $this->caps = $caps; + // As on the 404 WordPress redirects to the permalink of the id asked for + $GLOBALS['wp_query'] = new WP_Query($vars); + + expect($this->access->canonical('https://client.fr/there'))->toBe($kept ? 'https://client.fr/there' : false); +})->with([ + 'p' => [['p' => 7], [], false], + 'page_id' => [['page_id' => '7'], [], false], + 'attachment_id, with a page' => [['attachment_id' => 7, 'page_id' => 3], [], false], + 'a public media' => [['attachment_id' => 8], [], true], + 'a page' => [['page_id' => 3], [], true], + 'nothing asked' => [[], [], true], + 'an editor' => [['p' => 7], ['upload_files'], true], +]); + +it('redirects as WordPress says when there is no main query', function (): void { + expect($this->access->canonical('https://client.fr/there'))->toBe('https://client.fr/there'); +}); + +it('renders no media shortcode for a signed-in user who writes nothing', function (?int $post, array $caps, bool $refused): void { + $this->caps = $caps; + if ($post !== null) { + $_POST['post_ID'] = (string) $post; + } + Functions\expect('wp_send_json_error')->times($refused ? 1 : 0); + + $this->access->mediaShortcode(); +})->with([ + 'a subscriber' => [null, [], true], + 'a subscriber naming a post of someone else' => [3, [], true], + 'no post, a capability on post 0' => [0, ['edit_post:0'], true], + 'whoever edits the post' => [3, ['edit_post:3'], false], + 'whoever sees the library' => [null, ['upload_files'], false], +]); + +it('leaves alone a query filter another plugin applies without its query', function (): void { + expect($this->access->where(' WHERE 1'))->toBe(' WHERE 1') + ->and($this->access->results(null))->toBeNull() + ->and($this->access->where(null, new WP_Query))->toBeNull(); +}); + it('gives no oEmbed answer about a private media', function (mixed $id, string $type, mixed $answer): void { Functions\when('get_post_type')->justReturn($type); From b6b1948cc9c69e923aa1e04cd545ed239a5844bc Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 20:19:24 +0100 Subject: [PATCH 11/17] fix(private-media): do nothing when template_redirect runs with no main query --- src/Infrastructure/WordPress/PrivateMediaAccess.php | 4 ++-- tests/Unit/PrivateMediaAccessTest.php | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/Infrastructure/WordPress/PrivateMediaAccess.php b/src/Infrastructure/WordPress/PrivateMediaAccess.php index 20dbc5f..073d88a 100644 --- a/src/Infrastructure/WordPress/PrivateMediaAccess.php +++ b/src/Infrastructure/WordPress/PrivateMediaAccess.php @@ -135,10 +135,10 @@ public function results(mixed $posts, mixed $query = null): mixed */ public function attachmentPage(): void { - /** @var \WP_Query $wp_query The main query */ + /** @var \WP_Query|null $wp_query The main query */ global $wp_query; - if ((! $wp_query->is_singular && ! $wp_query->is_attachment) || ! $this->withholds($wp_query)) { + if (! $wp_query instanceof \WP_Query || (! $wp_query->is_singular && ! $wp_query->is_attachment) || ! $this->withholds($wp_query)) { return; } diff --git a/tests/Unit/PrivateMediaAccessTest.php b/tests/Unit/PrivateMediaAccessTest.php index c52b784..9de3aa2 100644 --- a/tests/Unit/PrivateMediaAccessTest.php +++ b/tests/Unit/PrivateMediaAccessTest.php @@ -175,6 +175,12 @@ public function prepare(string $query, mixed ...$values): string expect($this->access->canonical('https://client.fr/there'))->toBe('https://client.fr/there'); }); +it('does nothing when `template_redirect` runs with no main query', function (): void { + Functions\expect('status_header')->never(); + + $this->access->attachmentPage(); +}); + it('renders no media shortcode for a signed-in user who writes nothing', function (?int $post, array $caps, bool $refused): void { $this->caps = $caps; if ($post !== null) { From d1a000a05edcd963539b979be0dfd4fda407783c Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 21:38:14 +0100 Subject: [PATCH 12/17] test(private-media): pin the hook priorities, the first id and the list of files --- tests/Unit/DeclaredSizesTest.php | 12 +++++++----- tests/Unit/PrivateMediaAccessTest.php | 11 +++++++++++ tests/Unit/PrivateMediaGapsTest.php | 7 +++++++ tests/Unit/PrivateMediaTest.php | 11 ++++++----- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/tests/Unit/DeclaredSizesTest.php b/tests/Unit/DeclaredSizesTest.php index 0c8b8a8..78a3fa4 100644 --- a/tests/Unit/DeclaredSizesTest.php +++ b/tests/Unit/DeclaredSizesTest.php @@ -25,11 +25,13 @@ }); it('hooks the sizes WordPress makes, the metadata, the URL of a size and the srcset', function (): void { - Filters\expectAdded('intermediate_image_sizes_advanced')->once(); - Filters\expectAdded('wp_generate_attachment_metadata')->once(); - Filters\expectAdded('wp_update_attachment_metadata')->once(); - Filters\expectAdded('image_downsize')->once(); - Filters\expectAdded('wp_calculate_image_srcset')->once(); + Filters\expectAdded('intermediate_image_sizes_advanced')->once()->with(Mockery::type('array'), 100, 1); + Filters\expectAdded('wp_generate_attachment_metadata')->once()->with(Mockery::type('array'), 20, 3); + Filters\expectAdded('wp_update_attachment_metadata')->once()->with(Mockery::type('array'), 20, 2); + Filters\expectAdded('image_downsize')->once()->with(Mockery::type('array'), 10, 3); + // Without it, a site of a network would still be told of the sizes of the main site + Filters\expectAdded('wp_get_attachment_metadata')->once()->with(Mockery::type('array'), 10, 1); + Filters\expectAdded('wp_calculate_image_srcset')->once()->with(Mockery::type('array'), 5, 5); $this->declared->register(); }); diff --git a/tests/Unit/PrivateMediaAccessTest.php b/tests/Unit/PrivateMediaAccessTest.php index 9de3aa2..fec7ee9 100644 --- a/tests/Unit/PrivateMediaAccessTest.php +++ b/tests/Unit/PrivateMediaAccessTest.php @@ -152,6 +152,7 @@ public function prepare(string $query, mixed ...$values): string 'a public media' => [['is_singular', 'is_attachment'], ['attachment_id' => 8], [8], [], false], 'a page' => [['is_singular'], ['page_id' => 3], [3], [], false], 'a list a theme puts media in' => [[], [], [7], [], false], + 'a list that names it' => [[], ['p' => 7], [7], [], false], 'an editor' => [['is_singular', 'is_attachment'], ['attachment_id' => 7], [7], ['upload_files'], false], ]); @@ -213,3 +214,13 @@ public function prepare(string $query, mixed ...$values): string 'a post with the same id' => [7, 'post', 7], 'nothing found' => [0, 'attachment', 0], ]); + +it('keeps a private media whose id is the first of the library', function (): void { + Functions\when('get_post_meta')->alias(static fn (int $id): string => $id === 1 ? '1' : ''); + Functions\when('get_post_type')->justReturn('attachment'); + $GLOBALS['wp_query'] = new WP_Query(['p' => 1]); + + expect($this->access->restItem(null, $this->handler, new WP_REST_Request(['id' => 1])))->toBeInstanceOf(WP_Error::class) + ->and($this->access->canonical('https://client.fr/there'))->toBeFalse() + ->and($this->access->oembed(1))->toBe(-1); +}); diff --git a/tests/Unit/PrivateMediaGapsTest.php b/tests/Unit/PrivateMediaGapsTest.php index a7ef1c8..6b366a7 100644 --- a/tests/Unit/PrivateMediaGapsTest.php +++ b/tests/Unit/PrivateMediaGapsTest.php @@ -196,6 +196,13 @@ $this->private->register(); }); +it('lists each file once, and as a list, when the metadata and the attached file name the same one', function (): void { + $this->meta[7]['_wp_attached_file'] = '2026/10/photo.jpg'; + $this->metadata[7] = ['file' => '2026/10/photo.jpg', 'sizes' => ['thumbnail' => ['file' => 'photo-150x150.jpg']]]; + + expect((new AttachmentFiles)->for(7))->toBe(['2026/10/photo.jpg', '2026/10/photo-150x150.jpg']); +}); + it('makes private the new media the editor saves an edit of a private one as', function (): void { $this->meta[7][PrivateMedia::META] = '1'; $this->meta[8]['_wp_attached_file'] = '2026/10/photo-edited.jpg'; diff --git a/tests/Unit/PrivateMediaTest.php b/tests/Unit/PrivateMediaTest.php index 516e59f..834738c 100644 --- a/tests/Unit/PrivateMediaTest.php +++ b/tests/Unit/PrivateMediaTest.php @@ -41,11 +41,12 @@ }); it('hooks the URL of a media, of an image size, and the srcset, and the creation of a media', function (): void { - Filters\expectAdded('image_downsize')->once(); - Filters\expectAdded('wp_get_attachment_url')->once(); - Filters\expectAdded('wp_get_attachment_image_src')->once(); - Filters\expectAdded('wp_calculate_image_srcset')->once(); - Filters\expectAdded('wp_generate_attachment_metadata')->once(); + // The id of the attachment, which tells a private media, is not the first argument of every filter + Filters\expectAdded('image_downsize')->once()->with(Mockery::type('array'), 0, 1); + Filters\expectAdded('wp_get_attachment_url')->once()->with(Mockery::type('array'), 10, 2); + Filters\expectAdded('wp_get_attachment_image_src')->once()->with(Mockery::type('array'), 10, 2); + Filters\expectAdded('wp_calculate_image_srcset')->once()->with(Mockery::type('array'), 10, 5); + Filters\expectAdded('wp_generate_attachment_metadata')->once()->with(Mockery::type('array'), 5, 3); $this->private->register(); }); From 59e92a4534897517a03292720a87e38aaad753d7 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 21:40:35 +0100 Subject: [PATCH 13/17] chore: release v0.10.1 --- CHANGELOG.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf0d389..94feb29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -Next version: 0.11.0. +## [0.10.1] - 2026-11-27 + +A security release. Every version before it is affected: upgrade, then repair what is already on the disk. Read *Changed* first: some behaviour changes. ### Security @@ -39,6 +41,7 @@ Stream wrapper: Behaviour changes to check before upgrading: +- **WordPress 6.2 or later** is required: the database queries use the `%i` placeholder - **REST**: for a user without `upload_files` who cannot edit it, a private media answers `401` or `403` on `/wp/v2/media/{id}`, and is left out of the collection and of `_embed`. A headless front-end that reads private media anonymously, or a custom role that relied on it, has to authenticate or be given the capability - **Attachment page and oEmbed**: for the same users, the attachment page of a private media, its embed and its feed are not found, and oEmbed answers `404`. A plugin that gates a download through that page has to give its users `edit_post` on the media, or serve it elsewhere - **Shortcode preview**: `parse-media-shortcode` is refused to a user without `upload_files` who names no post they can edit @@ -46,10 +49,11 @@ Behaviour changes to check before upgrading: - **Networks**: on a site other than the main one, the fallback route serves nothing, and `wp pollora media thumbs prune` refuses to run - **Networks**: when the uploads of a deleted site are the whole library, its files stay on the disk - **Fallback route**: a size whose original is no longer on the disk is a `404`, even when its file exists. The route asks the database and the disk for a size already made, where it only asked the disk -- Making a media private or public now changes the files kept of it before its edits too, and `pollora/media/deleted` and `wp pollora media files` list them +- **Larger file list**: the files of a media now include the file of a media that is not an image, the attached file when it differs from the one of the metadata, the companions WordPress records and the files kept from before an edit. Making a media private or public changes them all, `wp pollora media files` lists them, and the `$paths` of the `pollora/media/deleted` action (and the `MediaDeleted` event of an application that relays it) holds them +- **`wp pollora media visibility` can report new failures**: a file WordPress still records for a media but that is no longer on the disk, such as one kept from before an edit, is reported as not changed, and the command then exits with `1`. A script that stops on a failure has to expect it - Saving the metadata of a private media sets the visibility of each of its files, one call to the disk per file - PHPStan runs at level 10. A value without a type from WordPress, WP-CLI, a filter or a constant that is neither a scalar nor stringable now reads as `''` or `0` -- `UrlReplacement` and the private media lookup pass table and column names to `$wpdb->prepare()` as `%i` identifiers (WordPress 6.2 or later) +- `UrlReplacement` and the private media lookup pass table and column names to `$wpdb->prepare()` as `%i` identifiers ### Fixed From a54a319c03d9126717c18b7b47fb0c6fc8ae1b4e Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 21:51:14 +0100 Subject: [PATCH 14/17] fix(private-media): check the main query with or without themes --- CHANGELOG.md | 1 + README.md | 2 +- .../WordPress/PrivateMediaAccess.php | 5 +++-- tests/Integration/PrivateMediaAccessTest.php | 20 +++++++++++++++++++ tests/Unit/PrivateMediaAccessTest.php | 6 +++--- 5 files changed, 28 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 94feb29..a677adc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ A security release. Every version before it is affected: upgrade, then repair wh Private media (since 0.3.0 unless said otherwise): - Anyone could read a private media attached to no post, and get its signed URL: over REST (`GET /wp/v2/media/{id}` and the collection), on its attachment page, in its embed and feed, and in the oEmbed answer +- The feed of a private media was also printed to a request that runs without themes, such as a direct one to `wp-blog-header.php` - The same page, reached as a single post (`?post_type=attachment&p=N`, an attached media included) or with the posts page in the query, showed the private media; when WordPress has no attachment pages, it redirected to the signed URL of the file, and otherwise to its slug - Any signed-in user, a subscriber included, could get the signed URL of a private media by asking WordPress to preview a `[gallery]` shortcode (`admin-ajax.php?action=parse-media-shortcode`) - A private media that is not an image (PDF, archive, video, audio) was never made private on the disk, neither at upload nor by `wp pollora media visibility --private`, which reported a success with no file changed diff --git a/README.md b/README.md index 5c4c683..d9ea582 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ add_filter('pollora/media/filesystem', fn () => new Filesystem(new SftpAdapter(/ | `wp_get_attachment_url`, `wp_get_attachment_image_src`, `wp_calculate_image_srcset` | Private media only: the URL, the URL of a size and every source of a `srcset` are signed and expire. A public media keeps its plain URL, and nothing is asked of the disk to tell them apart | | `wp_generate_attachment_metadata` | A media created private (see below) is made private on the disk | | `wp_update_attachment_metadata`, `wp_edited_image_metadata` | Private media only: the files written since are made private, and the copy the editor makes of a private image is private | -| `rest_request_before_callbacks`, `rest_attachment_query`, `posts_where`, `posts_results`, `template_redirect`, `redirect_canonical`, `oembed_request_post_id`, `wp_ajax_parse-media-shortcode` | Private media only (the last one: signed-in users who write nothing): [who WordPress tells about it](#who-wordpress-tells-about-a-private-media) | +| `rest_request_before_callbacks`, `rest_attachment_query`, `posts_where`, `posts_results`, `wp`, `redirect_canonical`, `oembed_request_post_id`, `wp_ajax_parse-media-shortcode` | Private media only (the last one: signed-in users who write nothing): [who WordPress tells about it](#who-wordpress-tells-about-a-private-media) | | `wpmu_delete_blog_upload_dir` | On a network, nothing is deleted when the folder of the deleted site is the whole library | The `pollora://` wrapper sends a file to the disk when its stream is closed, in one write. Directories do not exist on an object store, so they are virtual and answer without asking the disk (a path with an extension is a file); what is asked about a file is remembered for the rest of the request. A file written or read during a request, up to 16 MiB, is also kept in a local copy until the request ends: WordPress reads an uploaded image again for its size, its EXIF data, its sizes and its metadata, and none of it goes back to the disk. One upload of an image with nine sizes costs ten writes and a handful of existence checks; a read of the original, a stat or a listing never happens. Both the GD and the Imagick editors of WordPress work on the wrapper as they are. diff --git a/src/Infrastructure/WordPress/PrivateMediaAccess.php b/src/Infrastructure/WordPress/PrivateMediaAccess.php index 073d88a..d6650ea 100644 --- a/src/Infrastructure/WordPress/PrivateMediaAccess.php +++ b/src/Infrastructure/WordPress/PrivateMediaAccess.php @@ -30,8 +30,9 @@ public function register(): void \add_filter('rest_attachment_query', [$this, 'restQuery'], PHP_INT_MAX); \add_filter('posts_where', [$this, 'where'], 10, 2); \add_filter('posts_results', [$this, 'results'], 10, 2); - // Before `redirect_canonical()`, which sends the attachment page to the URL of the file - \add_action('template_redirect', [$this, 'attachmentPage'], 0); + // As soon as the main query ran, not on `template_redirect`: that one does not fire without themes, and + // feeds are printed all the same. It is also before `redirect_canonical()` + \add_action('wp', [$this, 'attachmentPage'], 0); \add_filter('oembed_request_post_id', [$this, 'oembed'], PHP_INT_MAX); // Last: WordPress redirects to the slug of a media, or to its file, from what the request names \add_filter('redirect_canonical', [$this, 'canonical'], PHP_INT_MAX); diff --git a/tests/Integration/PrivateMediaAccessTest.php b/tests/Integration/PrivateMediaAccessTest.php index 1de3aeb..6f9df54 100644 --- a/tests/Integration/PrivateMediaAccessTest.php +++ b/tests/Integration/PrivateMediaAccessTest.php @@ -144,3 +144,23 @@ 'the type and the id of an attached media' => [static fn (int $secret, int $attached): array => ['post_type' => 'attachment', 'p' => $attached], false], 'with the posts page' => [static fn (int $secret, int $attached, int $page): array => ['attachment_id' => $secret, 'page_id' => $page], true], ]); + +// The suite runs without themes, as a request that does: `template_redirect` never fires then, and feeds are still printed +it('holds no private media in the main query of a feed asked for without themes', function (): void { + global $wp, $wp_query, $wp_the_query; + + wp_set_current_user(0); + $previous = [$wp_query, $wp_the_query]; + + try { + $wp_query = $wp_the_query = new WP_Query; + $wp->main(['attachment_id' => $this->secret, 'feed' => 'rss2', 'withoutcomments' => 1]); + + expect(wp_using_themes())->toBeFalse() + ->and($wp_query->is_404())->toBeTrue() + ->and($wp_query->posts)->toBe([]); + } finally { + [$wp_query, $wp_the_query] = $previous; + $wp->query_vars = []; + } +}); diff --git a/tests/Unit/PrivateMediaAccessTest.php b/tests/Unit/PrivateMediaAccessTest.php index fec7ee9..f88d56e 100644 --- a/tests/Unit/PrivateMediaAccessTest.php +++ b/tests/Unit/PrivateMediaAccessTest.php @@ -33,14 +33,14 @@ unset($GLOBALS['wp_query'], $GLOBALS['wpdb'], $GLOBALS['post'], $_POST['post_ID']); }); -it('is hooked by the module, before WordPress redirects the attachment page to the file', function (): void { +it('is hooked by the module on the main query, with or without themes, before any redirection', function (): void { Functions\when('did_action')->justReturn(0); Filters\expectAdded('rest_request_before_callbacks')->once()->with(Mockery::type('array'), 10, 3); Filters\expectAdded('rest_attachment_query')->once(); Filters\expectAdded('posts_where')->once()->with(Mockery::type('array'), 10, 2); Filters\expectAdded('posts_results')->once()->with(Mockery::type('array'), 10, 2); Filters\expectAdded('oembed_request_post_id')->once(); - Actions\expectAdded('template_redirect')->once()->with(Mockery::type('array'), 0); + Actions\expectAdded('wp')->once()->with(Mockery::type('array'), 0); Filters\expectAdded('redirect_canonical')->once()->with(Mockery::type('array'), PHP_INT_MAX); Actions\expectAdded('wp_ajax_parse-media-shortcode')->once()->with(Mockery::type('array'), 0); @@ -176,7 +176,7 @@ public function prepare(string $query, mixed ...$values): string expect($this->access->canonical('https://client.fr/there'))->toBe('https://client.fr/there'); }); -it('does nothing when `template_redirect` runs with no main query', function (): void { +it('does nothing when it runs with no main query', function (): void { Functions\expect('status_header')->never(); $this->access->attachmentPage(); From b13ff454bbfcf2f929f3f4da6f1a12a7b7072f46 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Fri, 27 Nov 2026 21:58:45 +0100 Subject: [PATCH 15/17] docs: the trackback redirect of a private media --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d9ea582..a719b26 100644 --- a/README.md +++ b/README.md @@ -248,7 +248,7 @@ Visibility is the one the disk keeps for each file (on S3, the ACL of the object WordPress shows a media attached to no post to anyone, with its URL, and that URL is signed for whoever asks. The module keeps a private media to the users who can upload files (`upload_files`, the ones the media library shows every media to) and to whoever can edit that media: - over REST, `/wp/v2/media/{id}` and what lies under it answers `401` (not logged in) or `403`, and the collection leaves the media out, an `_embed` included; -- the attachment page, its embed and its feed are not found, however the request names the media, and WordPress does not redirect to its slug or its file; +- the attachment page, its embed and its feed are not found, however the request names the media, and WordPress does not redirect to its slug or its file (one exception: a request to `wp-trackback.php` that names the media can still redirect to its slug, where nothing is found); - oEmbed does not answer about it. WordPress also renders any shortcode a signed-in user sends to `admin-ajax.php?action=parse-media-shortcode`: only whoever can upload files, or edit the post the request names, gets an answer. From dc5a12a905f050cfc50470dabd2aefe11eff32e4 Mon Sep 17 00:00:00 2001 From: Pollora release Date: Wed, 2 Dec 2026 10:19:21 +0100 Subject: [PATCH 16/17] chore: date the 0.10.1 release --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a677adc..dc0b983 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [0.10.1] - 2026-11-27 +## [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. From 6dc1a008ad8afe214bec75a51e3b5ed652aa9902 Mon Sep 17 00:00:00 2001 From: Pollora maintainer Date: Wed, 2 Dec 2026 10:36:56 +0100 Subject: [PATCH 17/17] fix(cli): drop the returns after WP_CLI::error, which never returns The current WP-CLI stubs declare it so, and PHPStan reports the statements as unreachable. The same failure is on main. --- src/Infrastructure/WordPress/ThumbsCommand.php | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/Infrastructure/WordPress/ThumbsCommand.php b/src/Infrastructure/WordPress/ThumbsCommand.php index d9c6dd2..4440091 100644 --- a/src/Infrastructure/WordPress/ThumbsCommand.php +++ b/src/Infrastructure/WordPress/ThumbsCommand.php @@ -60,8 +60,6 @@ public function warm(array $args, array $assoc): void $report = $this->warmer->warm(Cast::optionalText($assoc['size'] ?? null), Cast::optionalText($assoc['since'] ?? null)); } catch (InvalidArgumentException $invalidArgumentException) { WP_CLI::error($invalidArgumentException->getMessage()); - - return; } WP_CLI::log(sprintf('%d image(s) looked at; %d file(s) made; %d failed.', $report['checked'], $report['made'], $report['failed'])); @@ -130,8 +128,6 @@ public function export(array $args, array $assoc): void $report = $this->exporter->export($driver, $execute); } catch (InvalidArgumentException|RuntimeException $exception) { WP_CLI::error($exception->getMessage()); - - return; } foreach ($report->lines as $line) {