fix: media upload whitelist per extension, no stray files, IPv4-only import

Empty effective whitelist is rejected instead of falling back to all types; the
whitelist is matched per extension against core's keys (mp3|m4a|m4b); a file moved
into uploads is deleted when the attachment cannot be created; the import request
resolves IPv4 only; empty temp name guard for URL imports.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01At3V6SjwbMe6eMzVGW3Hs7
This commit is contained in:
2026-09-26 02:42:45 +02:00
co-authored by Claude Opus 5.5
parent 2e29a6cd4d
commit 56f561c436
2 changed files with 204 additions and 19 deletions
@@ -4,6 +4,8 @@ declare(strict_types=1);
namespace LIT\MCP\Tests\Unit\Integrations\Media;
use Brain\Monkey\Actions;
use Brain\Monkey\Filters;
use Brain\Monkey\Functions;
use LIT\MCP\Abilities\WriteFailed;
use LIT\MCP\Integrations\Media\MediaImporter;
@@ -14,6 +16,19 @@ use WP_Error;
final class MediaImporterTest extends TestCase
{
/** Key shapes as in WordPress core's wp_get_mime_types(). */
private const CORE_MIMES = [
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'webp' => 'image/webp',
'avif' => 'image/avif',
'htm|html' => 'text/html',
'mp3|m4a|m4b' => 'audio/mpeg',
'mp4|m4v' => 'video/mp4',
'pdf' => 'application/pdf',
];
/** @var list<string> */
private array $tempFiles = [];
@@ -34,7 +49,16 @@ final class MediaImporterTest extends TestCase
Functions\when('sanitize_file_name')->returnArg();
Functions\when('wp_basename')->alias('basename');
Functions\when('wp_parse_url')->alias('parse_url');
Functions\when('get_allowed_mime_types')->justReturn(MediaImporter::MIMES);
Functions\when('get_allowed_mime_types')->justReturn(self::CORE_MIMES);
Functions\when('wp_check_filetype')->alias(static function (string $filename, array $mimes): array {
foreach ($mimes as $extensions => $mime) {
if (preg_match('!\.(' . $extensions . ')$!i', $filename, $match)) {
return ['ext' => $match[1], 'type' => $mime];
}
}
return ['ext' => false, 'type' => false];
});
}
protected function tearDown(): void
@@ -299,4 +323,96 @@ final class MediaImporterTest extends TestCase
self::assertStringContainsString('Limit 1 MB', $result->get_error_message());
$this->assertTempFilesRemoved();
}
public function testTheWhitelistIsMatchedPerExtensionAgainstCoreKeys(): void
{
Functions\expect('wp_check_filetype_and_ext')->once()
->with(Mockery::type('string'), 'song.mp3', Mockery::on(static function (array $mimes): bool {
return ($mimes['mp3'] ?? null) === 'audio/mpeg'
&& ($mimes['jpeg'] ?? null) === 'image/jpeg'
&& ($mimes['m4v'] ?? null) === 'video/mp4'
&& ! isset($mimes['m4a'], $mimes['html'], $mimes['htm']);
}))
->andReturn(['ext' => 'mp3', 'type' => 'audio/mpeg', 'proper_filename' => false]);
Functions\when('media_handle_sideload')->justReturn(60);
self::assertSame(60, $this->importer()->fromBase64(base64_encode('ID3DATA'), 'song.mp3', []));
}
public function testAnEmptyWhitelistRejectsEverythingInsteadOfFallingBackToAllTypes(): void
{
Functions\when('get_allowed_mime_types')->justReturn(['htm|html' => 'text/html']);
Functions\expect('wp_check_filetype_and_ext')->never();
Functions\expect('media_handle_sideload')->never();
$result = $this->importer()->fromBase64(base64_encode('<html></html>'), 'seite.html', []);
self::assertSame('lit_validation_failed', $result->get_error_code());
$this->assertTempFilesRemoved();
}
public function testTheMovedFileIsRemovedWhenTheAttachmentCannotBeCreated(): void
{
Functions\when('wp_check_filetype_and_ext')->justReturn(['ext' => 'png', 'type' => 'image/png', 'proper_filename' => false]);
$record = null;
Filters\expectAdded('wp_handle_upload')->once()->whenHappen(static function (callable $callback) use (&$record): void {
$record = $callback;
});
$moved = (string) tempnam(sys_get_temp_dir(), 'lit-moved');
$this->tempFiles[] = $moved;
Functions\when('media_handle_sideload')->alias(static function () use (&$record, $moved): WP_Error {
$record(['file' => $moved, 'url' => 'https://kunde.de/x.png', 'type' => 'image/png'], 'sideload');
return new WP_Error('db_insert_error', 'Datenbankfehler');
});
$result = $this->importer()->fromBase64(base64_encode('PNGDATA'), 'logo.png', []);
self::assertSame('lit_write_failed', $result->get_error_code());
self::assertFileDoesNotExist($moved);
self::assertFalse(has_filter('wp_handle_upload'));
}
public function testTheSavedFileIsKeptOnSuccess(): void
{
Functions\when('wp_check_filetype_and_ext')->justReturn(['ext' => 'png', 'type' => 'image/png', 'proper_filename' => false]);
$record = null;
Filters\expectAdded('wp_handle_upload')->once()->whenHappen(static function (callable $callback) use (&$record): void {
$record = $callback;
});
$moved = (string) tempnam(sys_get_temp_dir(), 'lit-moved');
$this->tempFiles[] = $moved;
Functions\when('media_handle_sideload')->alias(static function () use (&$record, $moved): int {
$record(['file' => $moved], 'sideload');
return 61;
});
self::assertSame(61, $this->importer()->fromBase64(base64_encode('PNGDATA'), 'logo.png', []));
self::assertFileExists($moved);
}
public function testCurlIsRestrictedToIpv4ForTheImportRequestOnly(): void
{
$this->respond('PNGDATA', 200);
Actions\expectAdded('http_api_curl')->once()->whenHappen(static function (callable $callback): void {
if (function_exists('curl_init')) {
$callback(curl_init()); // Must accept a real cURL handle without error.
}
});
Functions\when('wp_check_filetype_and_ext')->justReturn(['ext' => false, 'type' => false, 'proper_filename' => false]);
$this->importer()->fromUrl('https://example.com/logo.png', null, []);
self::assertFalse(has_action('http_api_curl'));
}
public function testAMissingTempFileNameIsAWriteFailure(): void
{
Functions\when('wp_http_validate_url')->returnArg();
Functions\when('wp_tempnam')->justReturn('');
Functions\expect('wp_safe_remote_get')->never();
$result = $this->importer()->fromUrl('https://example.com/logo.png', null, []);
self::assertSame('lit_write_failed', $result->get_error_code());
}
}