Commit 7e952a76 authored by catch's avatar catch
Browse files

task: #3223012 oEmbed system should validate that downloaded thumbnails are valid images

By: phenaproxima
By: b_sharpe
By: longwave
By: smustgrave
(cherry picked from commit 89973d2d)
parent fff4a403
Loading
Loading
Loading
Loading
Loading
+35 −3
Changes for core/modules/media/src/Plugin/media/Source/OEmbed.php: 35 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -16,6 +16,7 @@
use Drupal\Core\File\FileSystemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\GeneratedUrl;
use Drupal\Core\Image\ImageFactory;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
@@ -137,6 +138,11 @@ class OEmbed extends MediaSourceBase implements OEmbedInterface {
   */
  protected $token;

  /**
   * The image factory service.
   */
  protected ImageFactory $imageFactory;

  /**
   * Constructs a new OEmbed instance.
   *
@@ -170,8 +176,10 @@ class OEmbed extends MediaSourceBase implements OEmbedInterface {
   *   The file system.
   * @param \Drupal\Core\Utility\Token $token
   *   The token replacement service.
   * @param \Drupal\Core\Image\ImageFactory|null $image_factory
   *   The image factory service.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, FieldTypePluginManagerInterface $field_type_manager, LoggerInterface $logger, MessengerInterface $messenger, ClientInterface $http_client, ResourceFetcherInterface $resource_fetcher, UrlResolverInterface $url_resolver, IFrameUrlHelper $iframe_url_helper, FileSystemInterface $file_system, Token $token) {
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityFieldManagerInterface $entity_field_manager, ConfigFactoryInterface $config_factory, FieldTypePluginManagerInterface $field_type_manager, LoggerInterface $logger, MessengerInterface $messenger, ClientInterface $http_client, ResourceFetcherInterface $resource_fetcher, UrlResolverInterface $url_resolver, IFrameUrlHelper $iframe_url_helper, FileSystemInterface $file_system, Token $token, ?ImageFactory $image_factory = NULL) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $entity_field_manager, $field_type_manager, $config_factory);
    $this->logger = $logger;
    $this->messenger = $messenger;
@@ -181,6 +189,11 @@ public function __construct(array $configuration, $plugin_id, $plugin_definition
    $this->iFrameUrlHelper = $iframe_url_helper;
    $this->fileSystem = $file_system;
    $this->token = $token;
    if (!$image_factory) {
      @trigger_error('Calling ' . __CLASS__ . '::__construct() without the $image_factory argument is deprecated in drupal:11.4.0 and the $image_factory argument will be required in drupal:12.0.0. See https://www.drupal.org/node/9999999', E_USER_DEPRECATED);
      $image_factory = \Drupal::service('image.factory');
    }
    $this->imageFactory = $image_factory;
  }

  /**
@@ -202,7 +215,8 @@ public static function create(ContainerInterface $container, array $configuratio
      $container->get('media.oembed.url_resolver'),
      $container->get('media.oembed.iframe_url_helper'),
      $container->get('file_system'),
      $container->get('token')
      $container->get('token'),
      $container->get('image.factory'),
    );
  }

@@ -455,8 +469,26 @@ protected function getLocalThumbnailUri(Resource $resource, MediaInterface $medi
    try {
      $response = $this->httpClient->request('GET', $remote_thumbnail_url);
      if ($response->getStatusCode() === 200) {
        $local_thumbnail_uri = $directory . DIRECTORY_SEPARATOR . $hash . '.' . $this->getThumbnailFileExtensionFromUrl($remote_thumbnail_url, $response);
        // Only accept extensions that the active image toolkit supports.
        $extension = $this->getThumbnailFileExtensionFromUrl($remote_thumbnail_url, $response);
        if (!$extension || !in_array($extension, $this->imageFactory->getSupportedExtensions(), TRUE)) {
          $this->logger->warning('Could not determine a supported image extension for the remote thumbnail at @url.', [
            '@url' => $remote_thumbnail_url,
          ]);
          return NULL;
        }
        $local_thumbnail_uri = $directory . DIRECTORY_SEPARATOR . $hash . '.' . $extension;
        $this->fileSystem->saveData((string) $response->getBody(), $local_thumbnail_uri, FileExists::Replace);

        // Confirm the saved file is actually a valid image.
        if (!$this->imageFactory->get($local_thumbnail_uri)->isValid()) {
          $this->fileSystem->delete($local_thumbnail_uri);
          $this->logger->warning('The remote thumbnail at @url is not a valid image.', [
            '@url' => $remote_thumbnail_url,
          ]);
          return NULL;
        }

        return $local_thumbnail_uri;
      }
    }
+1 −1
Changes for core/modules/media/tests/src/Kernel/MediaSourceValidationTest.php: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -61,7 +61,7 @@ protected function setUp(): void {
    $this->installEntitySchema('user');
    $this->installEntitySchema('media');
    $this->installSchema('file', ['file_usage']);
    $this->installConfig(['media']);
    $this->installConfig(['system', 'media']);
    $this->mediaType = $this->createMediaType('oembed:video');
    $this->fieldName = $this->mediaType->getSource()
      ->getSourceFieldDefinition($this->mediaType)
+108 −8
Changes for core/modules/media/tests/src/Kernel/OEmbedSourceTest.php: 108 added lines, 8 removed lines.
Original line number Diff line number Diff line
@@ -6,6 +6,8 @@

use Drupal\Component\Utility\Crypt;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Logger\RfcLoggerTrait;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\Core\Render\RenderContext;
use Drupal\media\Entity\Media;
use Drupal\media\OEmbed\Resource;
@@ -21,7 +23,9 @@
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
use PHPUnit\Framework\Attributes\RunTestsInSeparateProcesses;
use PHPUnit\Framework\Attributes\TestWith;
use Prophecy\Argument;
use Psr\Log\LoggerInterface;

/**
 * Tests Drupal\media\Plugin\media\Source\OEmbed.
@@ -29,13 +33,29 @@
#[CoversClass(OEmbed::class)]
#[Group('media')]
#[RunTestsInSeparateProcesses]
class OEmbedSourceTest extends MediaKernelTestBase {
class OEmbedSourceTest extends MediaKernelTestBase implements LoggerInterface {

  use RfcLoggerTrait;

  /**
   * {@inheritdoc}
   */
  protected static $modules = ['media'];

  /**
   * The log messages captured during the test, keyed by log level.
   *
   * @var array<string, string[]>
   */
  protected array $logMessages = [];

  /**
   * {@inheritdoc}
   */
  public function log($level, string|\Stringable $message, array $context = []): void {
    $this->logMessages[$level][] = (string) $message;
  }

  /**
   * Tests get metadata.
   */
@@ -88,7 +108,7 @@ public static function providerThumbnailUri(): array {
      'no query string, MIME type, or extension in URL' => [
        'internal:/core/misc/druplicon',
        [],
        '',
        NULL,
      ],
    ];
  }
@@ -105,13 +125,15 @@ public static function providerThumbnailUri(): array {
   *   Content-Type header. This array contains the headers that should be
   *   returned with the thumbnail response, where the keys are header names and
   *   the values are arrays of strings.
   * @param string $expected_extension
   *   The extension that the downloaded thumbnail should have.
   * @param string|null $expected_extension
   *   The extension that the downloaded thumbnail should have, or NULL if no
   *   extension can be determined and the source should fall back to the
   *   default thumbnail.
   *
   * @legacy-covers ::getLocalThumbnailUri
   */
  #[DataProvider('providerThumbnailUri')]
  public function testThumbnailUri(string $remote_thumbnail_url, array $thumbnail_headers, string $expected_extension): void {
  public function testThumbnailUri(string $remote_thumbnail_url, array $thumbnail_headers, ?string $expected_extension): void {
    // Create a fake resource with the given thumbnail URL.
    $resource = Resource::rich('<html></html>', 16, 16, NULL, 'Test resource', NULL, NULL, NULL, $remote_thumbnail_url, 16, 16);
    $thumbnail_url = $resource->getThumbnailUrl()->toString();
@@ -164,7 +186,9 @@ public function testThumbnailUri(string $remote_thumbnail_url, array $thumbnail_
    // default configuration of the oEmbed source plugin.
    $date = date('Y-m', $this->container->get('datetime.time')->getRequestTime());

    // The thumbnail should have a file extension, even if it wasn't in the URL.
    if ($expected_extension !== NULL) {
      // The thumbnail should have a file extension, even if it wasn't in the
      // URL.
      $expected_uri = "public://oembed_thumbnails/$date/this&that/" . Crypt::hashBase64($thumbnail_url) . ".$expected_extension";
      $this->assertSame($expected_uri, $source->getMetadata($media, 'thumbnail_uri'));

@@ -179,8 +203,8 @@ public function testThumbnailUri(string $remote_thumbnail_url, array $thumbnail_
      $image = $this->container->get('image.factory')->get($expected_uri);
      $this->assertTrue($image->isValid());

    // Check that the current date token as per the default configuration of the
    // oEmbed source plugin doesn't make a render context uncacheable.
      // Check that the current date token as per the default configuration of
      // the oEmbed source plugin doesn't make a render context uncacheable.
      $context = new RenderContext();
      \Drupal::service('renderer')->executeInRenderContext($context, function () use ($source, $media) {
        return $source->getMetadata($media, 'thumbnail_uri');
@@ -189,5 +213,81 @@ public function testThumbnailUri(string $remote_thumbnail_url, array $thumbnail_
      $bubbleable_metadata = $context->pop();
      $this->assertSame(Cache::PERMANENT, $bubbleable_metadata->getCacheMaxAge());
    }
    else {
      // When no usable extension can be derived, the local download should
      // have been rejected during save(): no file was written, and the media
      // entity's thumbnail points to the source plugin's default icon.
      $directory = "public://oembed_thumbnails/$date/this&that";
      $this->assertEmpty($this->container->get('file_system')->scanDirectory($directory, '/.*/'));
      $default_filename = $source->getPluginDefinition()['default_thumbnail_filename'];
      $default_uri = $this->config('media.settings')->get('icon_base_uri') . '/' . $default_filename;
      $this->assertSame($default_uri, $media->thumbnail->entity->getFileUri());
    }
  }

  /**
   * Tests that unsafe or invalid remote thumbnails are rejected.
   *
   * @param string $remote_thumbnail_url
   *   The URL of the remote thumbnail.
   * @param string $content_type
   *   The Content-Type header to return with the response.
   * @param string $expected_warning
   *   The warning message that should be logged.
   */
  #[TestWith([
    'internal:/malicious.php',
    'application/x-php',
    'Could not determine a supported image extension for the remote thumbnail at @url.',
  ])]
  #[TestWith([
    'internal:/imposter.png',
    'image/png',
    'The remote thumbnail at @url is not a valid image.',
  ])]
  public function testThumbnailRejected(string $remote_thumbnail_url, string $content_type, string $expected_warning): void {
    $resource = Resource::rich('<html></html>', 16, 16, NULL, 'Test resource', NULL, NULL, NULL, $remote_thumbnail_url, 16, 16);

    $this->container->set(
      'media.oembed.url_resolver',
      $this->prophesize(UrlResolverInterface::class)->reveal(),
    );

    $resource_fetcher = $this->prophesize(ResourceFetcherInterface::class);
    $resource_fetcher->fetchResource(Argument::any())->willReturn($resource);
    $this->container->set('media.oembed.resource_fetcher', $resource_fetcher->reveal());

    $response = new Response(200, ['Content-Type' => [$content_type]], "<?php echo 'pwned'; ?>");
    $client = new Client([
      'handler' => new HandlerStack(new MockHandler([$response])),
    ]);
    $this->container->set('http_client', $client);

    // Capture log messages so the test can assert on them.
    $this->container->get('logger.factory')->addLogger($this);

    $media_type = $this->createMediaType('oembed:video');
    /** @var \Drupal\media\Plugin\media\Source\OEmbed $source */
    $source = $media_type->getSource();
    $media_type->save();

    $media = Media::create([
      'bundle' => $media_type->id(),
      $source->getSourceFieldDefinition($media_type)->getName() => $this->randomString(),
    ]);
    $media->save();

    // The source should fall back to the default thumbnail URI.
    $default_filename = $source->getPluginDefinition()['default_thumbnail_filename'];
    $default_uri = $this->config('media.settings')->get('icon_base_uri') . '/' . $default_filename;
    $this->assertSame($default_uri, $media->thumbnail->entity->getFileUri());

    // No file should remain in the thumbnails directory: either it was never
    // saved, or it was saved and then deleted after toolkit validation failed.
    $date = date('Y-m', $this->container->get('datetime.time')->getRequestTime());
    $this->assertEmpty($this->container->get('file_system')->scanDirectory("public://oembed_thumbnails/$date", '/.*/'));

    $this->assertContains($expected_warning, $this->logMessages[RfcLogLevel::WARNING] ?? []);
  }

}