core/modules/file/src/FileAccessControlHandler.php | 11 +- core/modules/file/src/FileServiceProvider.php | 24 ++ .../Plugin/rest/resource/FileUploadResource.php | 373 +++++++++++++++++++++ .../src/Functional/FileUploadJsonBasicAuthTest.php | 35 ++ .../src/Functional/FileUploadResourceTestBase.php | 218 ++++++++++++ core/modules/hal/hal.services.yml | 2 +- .../hal/src/Normalizer/FileEntityNormalizer.php | 29 +- .../tests/src/Functional/FileDenormalizeTest.php | 25 -- .../EventSubscriber/ResourceResponseSubscriber.php | 8 +- core/modules/rest/src/RequestHandler.php | 43 +++ core/modules/rest/src/Routing/ResourceRoutes.php | 20 +- .../rest/tests/src/Functional/ResourceTestBase.php | 4 +- 12 files changed, 718 insertions(+), 74 deletions(-) diff --git a/core/modules/file/src/FileAccessControlHandler.php b/core/modules/file/src/FileAccessControlHandler.php index f4bda3c..c0d5145 100644 --- a/core/modules/file/src/FileAccessControlHandler.php +++ b/core/modules/file/src/FileAccessControlHandler.php @@ -59,10 +59,11 @@ protected function checkAccess(EntityInterface $entity, $operation, AccountInter if ($operation == 'delete' || $operation == 'update') { $account = $this->prepareUser($account); - $file_uid = $entity->get('uid')->getValue(); - // Only the file owner can delete and update the file entity. - if ($account->id() == $file_uid[0]['target_id']) { - return AccessResult::allowed(); + $file_uid = $entity->get('uid')->target_id; + // Only admins or the file owner can delete and update the file entity. + // @todo Create a new permission to handle this? + if ($account->hasPermission('administer nodes') || ($account->id() == $file_uid)) { + return AccessResult::allowed()->cachePerPermissions(); } return AccessResult::forbidden(); } @@ -123,8 +124,6 @@ protected function checkCreateAccess(AccountInterface $account, array $context, // create file entities that are referenced from another entity // (e.g. an image for a article). A contributed module is free to alter // this to allow file entities to be created directly. - // @todo Update comment to mention REST module when - // https://www.drupal.org/node/1927648 is fixed. return AccessResult::neutral(); } diff --git a/core/modules/file/src/FileServiceProvider.php b/core/modules/file/src/FileServiceProvider.php new file mode 100644 index 0000000..35dd4a5 --- /dev/null +++ b/core/modules/file/src/FileServiceProvider.php @@ -0,0 +1,24 @@ +has('http_middleware.negotiation') && is_a($container->getDefinition('http_middleware.negotiation')->getClass(), NegotiationMiddleware::class, TRUE)) { + $container->getDefinition('http_middleware.negotiation')->addMethodCall('registerFormat', ['bin', ['application/octet-stream']]); + } + } + +} diff --git a/core/modules/file/src/Plugin/rest/resource/FileUploadResource.php b/core/modules/file/src/Plugin/rest/resource/FileUploadResource.php new file mode 100644 index 0000000..adae53f --- /dev/null +++ b/core/modules/file/src/Plugin/rest/resource/FileUploadResource.php @@ -0,0 +1,373 @@ +fileSystem = $file_system; + $this->entityTypeManager = $entity_type_manager; + $this->entityFieldManager = $entity_field_manager; + $this->currentUser = $current_user; + $this->mimeTypeGuesser = $mime_type_guesser; + $this->token = $token; + } + + /** + * {@inheritdoc} + */ + public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) { + return new static( + $configuration, + $plugin_id, + $plugin_definition, + $container->getParameter('serializer.formats'), + $container->get('logger.factory')->get('rest'), + $container->get('file_system'), + $container->get('entity_type.manager'), + $container->get('entity_field.manager'), + $container->get('current_user'), + $container->get('file.mime_type.guesser'), + $container->get('token') + ); + } + + /** + * Creates a file from endpoint. + * + * @param \Symfony\Component\HttpFoundation\Request $request + * @param \Drupal\file\FileInterface $file + */ + public function post(Request $request, $entity_type_id, $bundle, $field_name) { + // @todo Validate for file name too? + $field_definition = $this->validateAndLoadFieldDefinition($entity_type_id, $bundle, $field_name); + + $destination = $this->getUploadLocation($field_definition->getSettings()); + + // Grab the filename as described in Content-Disposition header. + $content_disposition = $request->headers->get('Content-Disposition'); + $filename = uniqid(); + // @todo find a better way to do this. + preg_match('/filename=\"(.*?)\"/', $content_disposition, $matches); + if ($matches) { + $filename = $matches[1]; + } + + // Check the destination file path is writable. + if (!is_writable($this->fileSystem->realpath($destination))) { + throw new HttpException(500, 'Destination file path is not writable'); + } + + // Create the file. + $file_uri = "{$destination}{$filename}"; + + $this->streamUploadData($file_uri); + + // Begin building file entity. + $values = [ + 'uid' => $this->currentUser->id(), + 'filename' => $filename, + 'uri' => $file_uri, + // Set the size. This is done in File::preSave() but we validate the file + // before it is saved. + 'size' => @filesize($file_uri), + ]; + $values['filemime'] = $this->mimeTypeGuesser->guess($values['filename']); + $file = File::create($values); + + $this->validate($file, $field_definition); + + $file->save(); + + // 201 Created responses return the newly created entity in the response + // body. These responses are not cacheable, so we add no cacheability + // metadata here. + $headers = [ + // @todo Do we want the File URI (for the actual file) like this? + 'Location' => $file->url(), + ]; + + return new ModifiedResourceResponse($file, 201, $headers); + } + + /** + * Streams file upload data to temporary file and moves to file destination. + * + * @param string $destination_uri + * + * @throws \Symfony\Component\HttpKernel\Exception\HttpException + */ + protected function streamUploadData($destination_uri) { + // 'rb' is needed so reading works correctly on windows environments too. + $file_data = fopen('php://input','rb'); + + $temp_file_name = $this->fileSystem->tempnam('temporary://', 'file'); + + if ($temp_file = fopen($temp_file_name, 'wb')) { + while (!feof($file_data)) { + fwrite($temp_file, fread($file_data, 8192)); + } + + fclose($temp_file); + + // Move the file to the correct location based on the file entity, + // replacing any existing file. + if (!file_unmanaged_move($temp_file_name, $destination_uri)) { + throw new HttpException(500, 'Temporary file could not be moved to file location'); + } + } + else { + $this->getLogger('file system')->error('Temporary file "%path" could not be opened for file upload', ['%path' => $temp_file_name]); + throw new HttpException(500, 'Temporary file could not be opened'); + } + + fclose($file_data); + } + + /** + * Validates and loads a field definition instance. + * + * @param string $entity_type_id + * The entity type ID the field is attached to. + * @param string $bundle + * The bundle the field is attached to. + * @param string $field_name + * The field name. + * + * @return \Drupal\Core\Field\FieldDefinitionInterface + * + * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException + * @throws \Symfony\Component\HttpFoundation\File\Exception\AccessDeniedException + */ + protected function validateAndLoadFieldDefinition($entity_type_id, $bundle, $field_name) { + $field_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type_id, $bundle); + + if (!isset($field_definitions[$field_name])) { + throw new BadRequestHttpException(sprintf('Field "%s" does not exist', $field_name)); + } + + // @todo check the definition is a file field. + $field_definition = $field_definitions[$field_name]; + + if (!$this->entityTypeManager->getAccessControlHandler($entity_type_id)->fieldAccess('create', $field_definition)) { + throw new AccessDeniedHttpException(sprintf('Access denied for field "%s"', $field_name)); + } + + return $field_definition; + } + + /** + * Validates the file. + * + * @param \Drupal\file\FileInterface $file + * The file entity to validate. + * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition + * The field definition to validate against. + * + * @throws \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException + */ + protected function validate(FileInterface $file, FieldDefinitionInterface $field_definition) { + $this->resourceValidate($file); + + // Validate the file based on the field definition configuration. + $errors = file_validate($file, $this->getUploadValidators($field_definition)); + + if (!empty($errors)) { + $message = "Unprocessable Entity: file validation failed.\n"; + $message .= implode("\n", $errors); + + throw new UnprocessableEntityHttpException($message); + } + } + + /** + * Determines the URI for a file field. + * + * @param array $settings + * The array of field settings. + * + * @return string + * An unsanitized file directory URI with tokens replaced. The result of + * the token replacement is then converted to plain text and returned. + */ + protected function getUploadLocation(array $settings) { + $destination = trim($settings['file_directory'], '/'); + + // Replace tokens. As the tokens might contain HTML we convert it to plain + // text. + $destination = PlainTextOutput::renderFromHtml($this->token->replace($destination, [])); + return $settings['uri_scheme'] . '://' . $destination; + } + + /** + * Retrieves the upload validators for a field definition. + * + * @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition + * + * @return array + * An array suitable for passing to file_save_upload() or the file field + * element's '#upload_validators' property. + * + * This is copied from \Drupal\file\Plugin\Field\FieldType\FileItem as there + * is no entity instance available here that that a FileItem would exist for. + */ + protected function getUploadValidators($field_definition) { + $validators = [ + // Add in our check of the file name length. + 'file_validate_name_length' => [], + ]; + $settings = $field_definition->getSettings(); + + // Cap the upload size according to the PHP limit. + $max_filesize = Bytes::toInt(file_upload_max_size()); + if (!empty($settings['max_filesize'])) { + $max_filesize = min($max_filesize, Bytes::toInt($settings['max_filesize'])); + } + + // There is always a file size limit due to the PHP server limit. + $validators['file_validate_size'] = [$max_filesize]; + + // Add the extension check if necessary. + if (!empty($settings['file_extensions'])) { + $validators['file_validate_extensions'] = [$settings['file_extensions']]; + } + + return $validators; + } + + /** + * {@inheritdoc} + */ + protected function getBaseRoute($canonical_path, $method) { + return new Route($canonical_path, [ + '_controller' => 'Drupal\rest\RequestHandler::handleRaw', + ], + $this->getBaseRouteRequirements($method), + [], + '', + [], + // The HTTP method is a requirement for this route. + [$method] + ); + } + + /** + * {@inheritdoc} + */ + protected function getBaseRouteRequirements($method) { + $requirements = parent::getBaseRouteRequirements($method); + + // Add the content type format access check. This will enforce that all + // incoming requests can only use the 'application/octet-stream' + // Content-Type header. + $requirements['_content_type_format'] = 'bin'; + $requirements['_format'] = implode('|', $this->serializerFormats); + + return $requirements; + } + + +} diff --git a/core/modules/file/tests/src/Functional/FileUploadJsonBasicAuthTest.php b/core/modules/file/tests/src/Functional/FileUploadJsonBasicAuthTest.php new file mode 100644 index 0000000..29a6bd3 --- /dev/null +++ b/core/modules/file/tests/src/Functional/FileUploadJsonBasicAuthTest.php @@ -0,0 +1,35 @@ +serializer = $this->container->get('serializer'); + + // Add a file field. + FieldStorageConfig::create([ + 'entity_type' => 'entity_test', + 'field_name' => 'field_rest_file_test', + 'type' => 'file', + 'settings' => [ + 'uri_scheme' => 'public', + ], + ]) + ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) + ->save(); + + FieldConfig::create([ + 'entity_type' => 'entity_test', + 'field_name' => 'field_rest_file_test', + 'bundle' => 'entity_test', + 'settings' => [ + 'file_directory' => '', + 'file_extensions' => 'txt', + 'max_filesize' => '', + ], + ]) + ->setLabel('Test file field') + ->setTranslatable(FALSE) + ->save(); + + // Create an entity that a file can be attached to. + $this->entity = EntityTest::create([ + 'name' => 'Llama', + 'type' => 'entity_test', + ]); + $this->entity->setOwnerId($this->account->id()); + $this->entity->save(); + + $this->refreshTestStateAfterRestConfigChange(); + } + + /** + * {@inheritdoc} + */ + protected function setUpAuthorization($method) { + switch ($method) { + case 'GET': + $this->grantPermissionsToTestedRole(['view test entity']); + break; + case 'POST': + $this->grantPermissionsToTestedRole(['create entity_test entity_test entities', 'restful post file:upload']); + break; + } + } + + /** + * {@inheritdoc} + */ + protected function assertResponseWhenMissingAuthentication(ResponseInterface $response) { + // TODO: Implement assertResponseWhenMissingAuthentication() method. + } + + /** + * {@inheritdoc} + */ + protected function assertNormalizationEdgeCases($method, Url $url, array $request_options) { + // TODO: Implement assertNormalizationEdgeCases() method. + } + + /** + * {@inheritdoc} + */ + protected function assertAuthenticationEdgeCases($method, Url $url, array $request_options) { + // TODO: Implement assertAuthenticationEdgeCases() method. + } + + /** + * {@inheritdoc} + */ + protected function getExpectedUnauthorizedAccessMessage($method) { + // TODO: Implement getExpectedUnauthorizedAccessMessage() method. + } + + /** + * {@inheritdoc} + */ + protected function getExpectedBcUnauthorizedAccessMessage($method) { + // TODO: Implement getExpectedBcUnauthorizedAccessMessage() method. + } + + + /** + * Tests using the file upload POST route. + */ + public function testPostFileUpload() { + $this->initAuthentication(); + + $this->provisionResource([static::$format], static::$auth ? [static::$auth] : [], ['POST']); + + $this->setUpAuthorization('POST'); + + $file_data = 'TEST WITH NEW DATA'; + + $uri = Url::fromUri('base:' . static::$postUri); + + // The wrong content type should return a 415 code. + $response = $this->fileRequest($uri, $file_data, static::$mimeType); + $this->assertSame(415, $response->getStatusCode()); + + // This request will have the default 'application/octet-stream' content type. + $response = $this->fileRequest($uri, $file_data); + + $this->assertSame(201, $response->getStatusCode()); + + // @todo Assert created file entity in response. + + // Check the actual file data. + $this->assertSame($file_data, file_get_contents('public://example.txt')); + } + + /** + * Performs a file upload request. Wraps the Guzzle HTTP client. + * + * @see \GuzzleHttp\ClientInterface::request() + * + * @param string $method + * HTTP method. + * @param \Drupal\Core\Url $url + * URL to request. + * @param array $request_options + * Request options to apply. + * + * @return \Psr\Http\Message\ResponseInterface + */ + protected function fileRequest(Url $url, $file_contents, $content_type = 'application/octet-stream') { + $url->setOption('query', ['_format' => static::$format]); + + $request_options = []; + $request_options[RequestOptions::HTTP_ERRORS] = FALSE; + $request_options['headers']['Content-Type'] = $content_type; + // @todo change when we settle on the header for the file name. + $request_options['headers']['Content-Disposition'] = 'file; filename="example.txt"'; + $request_options['body'] = $file_contents; + + $request_options = NestedArray::mergeDeep($request_options, $this->getAuthenticationRequestOptions('POST')); + + $session = $this->getSession(); + $this->prepareRequest(); + + $client = $session->getDriver()->getClient()->getClient(); + return $client->request('POST', $url->setAbsolute(TRUE)->toString(), $request_options); + } + +} diff --git a/core/modules/hal/hal.services.yml b/core/modules/hal/hal.services.yml index b2c898f..a2badfa 100644 --- a/core/modules/hal/hal.services.yml +++ b/core/modules/hal/hal.services.yml @@ -16,7 +16,7 @@ services: class: Drupal\hal\Normalizer\FileEntityNormalizer tags: - { name: normalizer, priority: 20 } - arguments: ['@entity.manager', '@http_client', '@hal.link_manager', '@module_handler'] + arguments: ['@entity.manager', '@hal.link_manager', '@module_handler'] serializer.normalizer.timestamp_item.hal: class: Drupal\hal\Normalizer\TimestampItemNormalizer tags: diff --git a/core/modules/hal/src/Normalizer/FileEntityNormalizer.php b/core/modules/hal/src/Normalizer/FileEntityNormalizer.php index ec870e9..5e45d59 100644 --- a/core/modules/hal/src/Normalizer/FileEntityNormalizer.php +++ b/core/modules/hal/src/Normalizer/FileEntityNormalizer.php @@ -4,8 +4,8 @@ use Drupal\Core\Entity\EntityManagerInterface; use Drupal\Core\Extension\ModuleHandlerInterface; +use Drupal\file\FileInterface; use Drupal\hal\LinkManager\LinkManagerInterface; -use GuzzleHttp\ClientInterface; /** * Converts the Drupal entity object structure to a HAL array structure. @@ -17,31 +17,20 @@ class FileEntityNormalizer extends ContentEntityNormalizer { * * @var string */ - protected $supportedInterfaceOrClass = 'Drupal\file\FileInterface'; - - /** - * The HTTP client. - * - * @var \GuzzleHttp\ClientInterface - */ - protected $httpClient; + protected $supportedInterfaceOrClass = FileInterface::class; /** * Constructs a FileEntityNormalizer object. * * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager * The entity manager. - * @param \GuzzleHttp\ClientInterface $http_client - * The HTTP Client. * @param \Drupal\hal\LinkManager\LinkManagerInterface $link_manager * The hypermedia link manager. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler * The module handler. */ - public function __construct(EntityManagerInterface $entity_manager, ClientInterface $http_client, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler) { + public function __construct(EntityManagerInterface $entity_manager, LinkManagerInterface $link_manager, ModuleHandlerInterface $module_handler) { parent::__construct($link_manager, $entity_manager, $module_handler); - - $this->httpClient = $http_client; } /** @@ -55,16 +44,4 @@ public function normalize($entity, $format = NULL, array $context = []) { return $data; } - /** - * {@inheritdoc} - */ - public function denormalize($data, $class, $format = NULL, array $context = []) { - $file_data = (string) $this->httpClient->get($data['uri'][0]['value'])->getBody(); - - $path = 'temporary://' . drupal_basename($data['uri'][0]['value']); - $data['uri'] = file_unmanaged_save_data($file_data, $path); - - return $this->entityManager->getStorage('file')->create($data); - } - } diff --git a/core/modules/hal/tests/src/Functional/FileDenormalizeTest.php b/core/modules/hal/tests/src/Functional/FileDenormalizeTest.php index 05ee234..8202a36 100644 --- a/core/modules/hal/tests/src/Functional/FileDenormalizeTest.php +++ b/core/modules/hal/tests/src/Functional/FileDenormalizeTest.php @@ -41,35 +41,10 @@ public function testFileDenormalize() { $this->assertTrue($denormalized instanceof File, 'A File instance was created.'); - $this->assertIdentical('temporary://' . $file->getFilename(), $denormalized->getFileUri(), 'The expected file URI was found.'); - $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.'); - $this->assertIdentical($file->uuid(), $denormalized->uuid(), 'The expected UUID was found'); $this->assertIdentical($file->getMimeType(), $denormalized->getMimeType(), 'The expected MIME type was found.'); $this->assertIdentical($file->getFilename(), $denormalized->getFilename(), 'The expected filename was found.'); $this->assertTrue($denormalized->isPermanent(), 'The file has a permanent status.'); - - // Try to denormalize with the file uri only. - $file_name = 'test_2.txt'; - $file_path = 'public://' . $file_name; - - file_put_contents($file_path, 'hello world'); - $file_uri = file_create_url($file_path); - - $data = [ - 'uri' => [ - ['value' => $file_uri], - ], - ]; - - $denormalized = $serializer->denormalize($data, 'Drupal\file\Entity\File', 'hal_json'); - - $this->assertIdentical('temporary://' . $file_name, $denormalized->getFileUri(), 'The expected file URI was found.'); - $this->assertTrue(file_exists($denormalized->getFileUri()), 'The temporary file was found.'); - - $this->assertIdentical('text/plain', $denormalized->getMimeType(), 'The expected MIME type was found.'); - $this->assertIdentical($file_name, $denormalized->getFilename(), 'The expected filename was found.'); - $this->assertFalse($denormalized->isPermanent(), 'The file has a permanent status.'); } } diff --git a/core/modules/rest/src/EventSubscriber/ResourceResponseSubscriber.php b/core/modules/rest/src/EventSubscriber/ResourceResponseSubscriber.php index df77281..58a863e 100644 --- a/core/modules/rest/src/EventSubscriber/ResourceResponseSubscriber.php +++ b/core/modules/rest/src/EventSubscriber/ResourceResponseSubscriber.php @@ -96,7 +96,7 @@ public function getResponseFormat(RouteMatchInterface $route_match, Request $req $route = $route_match->getRouteObject(); $acceptable_request_formats = $route->hasRequirement('_format') ? explode('|', $route->getRequirement('_format')) : []; $acceptable_content_type_formats = $route->hasRequirement('_content_type_format') ? explode('|', $route->getRequirement('_content_type_format')) : []; - $acceptable_formats = $request->isMethodCacheable() ? $acceptable_request_formats : $acceptable_content_type_formats; + $fallback_acceptable_formats = $request->isMethodCacheable() ? $acceptable_request_formats : $acceptable_content_type_formats; $requested_format = $request->getRequestFormat(); $content_type_format = $request->getContentType(); @@ -104,7 +104,7 @@ public function getResponseFormat(RouteMatchInterface $route_match, Request $req // If an acceptable format is requested, then use that. Otherwise, including // and particularly when the client forgot to specify a format, then use // heuristics to select the format that is most likely expected. - if (in_array($requested_format, $acceptable_formats)) { + if (in_array($requested_format, $acceptable_request_formats)) { return $requested_format; } // If a request body is present, then use the format corresponding to the @@ -114,8 +114,8 @@ public function getResponseFormat(RouteMatchInterface $route_match, Request $req return $content_type_format; } // Otherwise, use the first acceptable format. - elseif (!empty($acceptable_formats)) { - return $acceptable_formats[0]; + elseif (!empty($fallback_acceptable_formats)) { + return $fallback_acceptable_formats[0]; } // Sometimes, there are no acceptable formats, e.g. DELETE routes. else { diff --git a/core/modules/rest/src/RequestHandler.php b/core/modules/rest/src/RequestHandler.php index e5437cc..6731c26 100644 --- a/core/modules/rest/src/RequestHandler.php +++ b/core/modules/rest/src/RequestHandler.php @@ -139,4 +139,47 @@ public function handle(RouteMatchInterface $route_match, Request $request) { return $response; } + public function handleRaw(RouteMatchInterface $route_match, Request $request) { + // Symfony is built to transparently map HEAD requests to a GET request. In + // the case of the REST module's RequestHandler though, we essentially have + // our own light-weight routing system on top of the Drupal/symfony routing + // system. So, we have to respect the decision that the routing system made: + // we look not at the request method, but at the route's method. All REST + // routes are guaranteed to have _method set. + // Response::prepare() will transform it to a HEAD response at the very last + // moment. + // @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.4 + // @see \Symfony\Component\Routing\Matcher\UrlMatcher::matchCollection() + // @see \Symfony\Component\HttpFoundation\Response::prepare() + $method = strtolower($route_match->getRouteObject()->getMethods()[0]); + assert(count($route_match->getRouteObject()->getMethods()) === 1); + + + $resource_config_id = $route_match->getRouteObject()->getDefault('_rest_resource_config'); + /** @var \Drupal\rest\RestResourceConfigInterface $resource_config */ + $resource_config = $this->resourceStorage->load($resource_config_id); + $resource = $resource_config->getResourcePlugin(); + + // Determine the request parameters that should be passed to the resource + // plugin. + $route_parameters = $route_match->getParameters(); + $parameters = []; + // Filter out all internal parameters starting with "_". + foreach ($route_parameters as $key => $parameter) { + if ($key{0} !== '_') { + $parameters[] = $parameter; + } + } + + // Invoke the operation on the resource plugin. + $response = call_user_func_array([$resource, $method], array_merge([$request], $parameters)); + + if ($response instanceof CacheableResponseInterface) { + // Add rest config's cache tags. + $response->addCacheableDependency($resource_config); + } + + return $response; + } + } diff --git a/core/modules/rest/src/Routing/ResourceRoutes.php b/core/modules/rest/src/Routing/ResourceRoutes.php index 5ba4c5d..33c21de 100644 --- a/core/modules/rest/src/Routing/ResourceRoutes.php +++ b/core/modules/rest/src/Routing/ResourceRoutes.php @@ -108,20 +108,20 @@ protected function getRoutesForResourceConfig(RestResourceConfigInterface $rest_ continue; } - // If the route has a format requirement, then verify that the - // resource has it. - $format_requirement = $route->getRequirement('_format'); - if ($format_requirement && !in_array($format_requirement, $rest_resource_config->getFormats($method))) { - continue; - } - // The configuration has been validated, so we update the route to: + // - set the allowed response body content types/formats for methods + // that may send response bodies // - set the allowed request body content types/formats for methods that // allow request bodies to be sent // - set the allowed authentication providers - if (in_array($method, ['POST', 'PATCH', 'PUT'], TRUE)) { - // Restrict the incoming HTTP Content-type header to the allowed - // formats. + // @todo Remove this in Drupal 9. @RestResource plugins should be + // given the RESTResourceConfig entity, and should generate the + // appropriate routes in ::routes() based on that. But doing so + // would be a BC break. This is the next best thing we can do. + if (in_array($method, ['GET', 'HEAD', 'POST', 'PUT', 'PATCH'], TRUE)) { + $route->addRequirements(['_format' => implode('|', $rest_resource_config->getFormats($method))]); + } + if (in_array($method, ['POST', 'PATCH', 'PUT'], TRUE) && !$route->hasRequirement('_content_type_format')) { $route->addRequirements(['_content_type_format' => implode('|', $rest_resource_config->getFormats($method))]); } $route->setOption('_auth', $rest_resource_config->getAuthenticationProviders($method)); diff --git a/core/modules/rest/tests/src/Functional/ResourceTestBase.php b/core/modules/rest/tests/src/Functional/ResourceTestBase.php index 59d7bcb..0446e76 100644 --- a/core/modules/rest/tests/src/Functional/ResourceTestBase.php +++ b/core/modules/rest/tests/src/Functional/ResourceTestBase.php @@ -144,12 +144,12 @@ public function setUp() { * @param string[] $authentication * The allowed authentication providers for this resource. */ - protected function provisionResource($formats = [], $authentication = []) { + protected function provisionResource($formats = [], $authentication = [], array $methods = ['GET', 'POST', 'PATCH', 'DELETE']) { $this->resourceConfigStorage->create([ 'id' => static::$resourceConfigId, 'granularity' => RestResourceConfigInterface::RESOURCE_GRANULARITY, 'configuration' => [ - 'methods' => ['GET', 'POST', 'PATCH', 'DELETE'], + 'methods' => $methods, 'formats' => $formats, 'authentication' => $authentication, ],