diff --git a/src/Integrations/Media/MediaImporter.php b/src/Integrations/Media/MediaImporter.php index 59312b6..12335c7 100644 --- a/src/Integrations/Media/MediaImporter.php +++ b/src/Integrations/Media/MediaImporter.php @@ -61,6 +61,10 @@ class MediaImporter AdminIncludes::load(); $tmp = (string) wp_tempnam('lit-mcp-import'); + if ($tmp === '') { + return Errors::writeFailed('Die temporäre Datei konnte nicht angelegt werden.'); + } + try { $response = $this->download($url, $tmp); if ($response instanceof WP_Error) { @@ -112,12 +116,26 @@ class MediaImporter /** @return array|WP_Error The response (body streamed into $tmp). */ private function download(string $url, string $tmp): array|WP_Error { - $response = wp_safe_remote_get($url, [ - 'timeout' => self::TIMEOUT, - 'stream' => true, - 'filename' => $tmp, - 'limit_response_size' => $this->limits->uploadBytes() + 1, - ]); + // IPv4 only, for this request only: wp_http_validate_url() checks the IPv4 address + // (gethostbyname), so an AAAA record must not lead cURL to an unchecked IPv6 target. + $ipv4 = static function ($handle): void { + if (defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) { + // phpcs:ignore WordPress.WP.AlternativeFunctions.curl_curl_setopt -- http_api_curl hands us the handle. + curl_setopt($handle, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + } + }; + add_action('http_api_curl', $ipv4); + try { + $response = wp_safe_remote_get($url, [ + 'timeout' => self::TIMEOUT, + 'stream' => true, + 'filename' => $tmp, + 'limit_response_size' => $this->limits->uploadBytes() + 1, + ]); + } finally { + remove_action('http_api_curl', $ipv4); + } + if ($response instanceof WP_Error) { return $this->downloadFailed($response->get_error_message()); } @@ -145,12 +163,21 @@ class MediaImporter } $mimes = $this->allowedMimes(); + if ($mimes === []) { + // An empty list would make wp_check_filetype() fall back to every type WordPress allows. + return Errors::invalidInput( + 'Auf dieser Website sind keine Dateitypen zum Hochladen freigegeben.', + ['filename' => 'kein Dateityp erlaubt'], + 'Administrator fragen (Filter lit_mcp_upload_mimes bzw. erlaubte Dateitypen von WordPress).' + ); + } + $name = sanitize_file_name($filename !== '' ? $filename : 'datei'); $check = wp_check_filetype_and_ext($tmp, $name, $mimes); if (empty($check['type']) || empty($check['ext'])) { return Errors::invalidInput( 'Dateityp nicht erlaubt oder Inhalt passt nicht zur Endung.', - ['filename' => 'erlaubt: ' . str_replace('|', ', ', implode(', ', array_keys($mimes)))], + ['filename' => 'erlaubt: ' . implode(', ', array_keys($mimes))], 'Nur erlaubte Dateitypen hochladen (Bilder, PDF, MP4, MP3) und die passende Endung verwenden.' ); } @@ -160,18 +187,13 @@ class MediaImporter } $title = isset($meta['title']) ? sanitize_text_field((string) $meta['title']) : null; - $attachmentId = media_handle_sideload( - ['name' => $name, 'tmp_name' => $tmp], - (int) ($meta['post_id'] ?? 0), - $title - ); + $attachmentId = $this->sideload($name, $tmp, (int) ($meta['post_id'] ?? 0), $title); if ($attachmentId instanceof WP_Error) { $reason = 'WordPress hat die Datei nicht übernommen: ' . $attachmentId->get_error_message(); return Errors::writeFailed($reason); } - $attachmentId = (int) $attachmentId; if (isset($meta['alt']) && $meta['alt'] !== '') { $this->saveAlt($attachmentId, sanitize_text_field((string) $meta['alt'])); } @@ -179,6 +201,35 @@ class MediaImporter return $attachmentId; } + /** + * media_handle_sideload() moves the file into uploads before it creates the attachment; + * if that fails, WordPress leaves the file behind. The moved file is recorded (one-shot + * wp_handle_upload filter) and removed on error, so "nothing was saved" holds. + */ + private function sideload(string $name, string $tmp, int $postId, ?string $title): int|WP_Error + { + $moved = null; + $record = static function ($upload, $context = '') use (&$moved) { + if ($context === 'sideload' && is_array($upload) && isset($upload['file'])) { + $moved = (string) $upload['file']; + } + + return $upload; + }; + add_filter('wp_handle_upload', $record, 10, 2); + try { + $result = media_handle_sideload(['name' => $name, 'tmp_name' => $tmp], $postId, $title); + } finally { + remove_filter('wp_handle_upload', $record, 10); + } + + if ($result instanceof WP_Error && is_string($moved) && $moved !== '' && file_exists($moved)) { + wp_delete_file($moved); + } + + return $result instanceof WP_Error ? $result : (int) $result; + } + /** @throws WriteFailed When the alt text cannot be saved (attachment deleted again if possible). */ private function saveAlt(int $attachmentId, string $alt): void { @@ -217,17 +268,35 @@ class MediaImporter } /** - * Whitelist (filterable) restricted to what WordPress allows the current user. + * Whitelist (filterable) restricted to what WordPress allows the current user, per + * extension: core groups extensions differently (e.g. 'mp3|m4a|m4b'), so each of our + * extensions is kept only if WordPress maps it to the same MIME type. * - * @return array + * @return array Single extension => MIME type. */ private function allowedMimes(): array { $mimes = apply_filters('lit_mcp_upload_mimes', self::MIMES); $mimes = is_array($mimes) ? $mimes : self::MIMES; $allowed = get_allowed_mime_types(); + $allowed = is_array($allowed) ? $allowed : []; - return array_intersect_key($mimes, is_array($allowed) ? $allowed : []); + $effective = []; + foreach ($mimes as $extensions => $mime) { + foreach (explode('|', (string) $extensions) as $extension) { + $extension = strtolower(trim($extension)); + if ($extension === '' || $allowed === []) { + continue; + } + + $core = wp_check_filetype('x.' . $extension, $allowed); + if (($core['type'] ?? false) === $mime) { + $effective[$extension] = (string) $mime; + } + } + } + + return $effective; } /** @@ -243,9 +312,9 @@ class MediaImporter } $type = strtolower(trim(explode(';', (string) wp_remote_retrieve_header($response, 'content-type'))[0])); - foreach ($this->allowedMimes() as $extensions => $mime) { + foreach ($this->allowedMimes() as $extension => $mime) { if ($mime === $type) { - return ($name !== '' ? $name : 'datei') . '.' . explode('|', $extensions)[0]; + return ($name !== '' ? $name : 'datei') . '.' . $extension; } } diff --git a/tests/Unit/Integrations/Media/MediaImporterTest.php b/tests/Unit/Integrations/Media/MediaImporterTest.php index 1931932..1fbb6f5 100644 --- a/tests/Unit/Integrations/Media/MediaImporterTest.php +++ b/tests/Unit/Integrations/Media/MediaImporterTest.php @@ -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 */ 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(''), '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()); + } }