Problem/Motivation

Discovered in #2737719: EntityResource: Provide comprehensive test coverage: for every entity type, every format, every method: \Drupal\rest\RequestHandler::handle() throws a messageless UnsupportedMediaTypeHttpException when the request body contains data to denormalize in a format (i.e. request's Content-Type) is not in the list of supported formats for this resource.

Proposed resolution

Let the routing system handle the validation of the content-type, so the right HTTP response (415) is thrown automatically.

Remaining tasks

None.

User interface changes

None.

API changes

None.

Data model changes

None.

Comments

Wim Leers created an issue. See original summary.

wim leers’s picture

Status: Active » Needs review
Issue tags: +Security improvements
Related issues: +#1850734: Make serialization formats configurable
StatusFileSize
new5.08 KB

Upon further inspection, this is because RequestHandler::handle() must validate the request body's format… because \Drupal\rest\Plugin\ResourceBase::routes() does this:

      switch ($method) {
        case 'POST':
          $route->setPath($create_path);
          // Restrict the incoming HTTP Content-type header to the known
          // serialization formats.
          $route->addRequirements(array('_content_type_format' => implode('|', $this->serializerFormats)));
          $collection->add("$route_name.$method", $route);
          break;

        case 'PATCH':
          // Restrict the incoming HTTP Content-type header to the known
          // serialization formats.
          $route->addRequirements(array('_content_type_format' => implode('|', $this->serializerFormats)));
          $collection->add("$route_name.$method", $route);
          break;

        …
      }

This is blatantly incorrect. Rather than respecting a particular REST resource's configuration, we're just saying Oh, it's fine to send any format!

If this would be setting _content_type_format to the actually allowed formats, then we wouldn't even need to throw UnsupportedMediaTypeHttpException in RequestHandler::handle() because we wouldn't need to validate the request body's format, since the routing system would then handle that for us!


So I started fixing this, and turns out \Drupal\rest\Plugin\ResourceBase::routes() has no access to the REST resource configuration… hence it must make this very bad assumption. But, rather than setting this incorrect value in \Drupal\rest\Plugin\ResourceBase::routes(), we can alternatively just set the correct value in \Drupal\rest\Routing\ResourceRoutes::getRoutesForResourceConfig().

Then we can just remove the throw new UnsupportedMediaTypeHttpException. Which allowed me to remove this super scary sounding code comment from RequestHandler:

      // Only allow serialization formats that are explicitly configured. If no
      // formats are configured allow all and hope that the serializer knows the
      // format. If the serializer cannot handle it an exception will be thrown
      // that bubbles up to the client.

That was committed as part of #1850734: Make serialization formats configurable.


Attached patch includes the fix. I tested with #2737719: EntityResource: Provide comprehensive test coverage: for every entity type, every format, every method applied, no failures (and hence no BC break). So this does not need to block #2737719. This will still need separate test coverage, because it has security implications (well, really, it's a tightening of security).

wim leers’s picture

Title: \Drupal\rest\RequestHandler::handle() throws UnsupportedMediaTypeHttpException without message » PATCH + POST allowed format validation happens in RequestHandler::handle(), rather than in the routing system

Better title, to reflect what I discovered in #2.

dawehner’s picture

Issue summary: View changes

Version: 8.2.x-dev » 8.3.x-dev

Drupal 8.2.6 was released on February 1, 2017 and is the final full bugfix release for the Drupal 8.2.x series. Drupal 8.2.x will not receive any further development aside from critical and security fixes. Sites should prepare to update to 8.3.0 on April 5, 2017. (Drupal 8.3.0-alpha1 is available for testing.)

Bug reports should be targeted against the 8.3.x-dev branch from now on, and new development or disruptive changes should be targeted against the 8.4.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

wim leers’s picture

StatusFileSize
new2.43 KB

#2 no longer applies.

This is a straight reroll of the patch, minus the changes made to RequestHandler. That hunk I omitted completely for now: it's about simplifying RequestHandler, it's not necessary to fix this bug itself.

wim leers’s picture

Issue tags: -Needs tests
StatusFileSize
new1.8 KB
new4.21 KB

#7 should fail.

It should fail because it fixes the too-late validation of the request body's format. And hence the existing assertions in EntityResourceTestBase now fail.

This updates those assertions… and as you can see, there's now actually helpful error messages in there!

wim leers’s picture

StatusFileSize
new2.26 KB
new6.38 KB

And that validation that was happening too late (i.e. in RequestHandler::handle() rather than in the routing system) can now simply be deleted! Let's do that :)

The last submitted patch, 7: 2826407-7.patch, failed testing.

dawehner’s picture

Status: Needs review » Reviewed & tested by the community

This is simply a peace of beauty!

wim leers’s picture

Awww, thanks! :D Best review message in a very long time! :D

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 9: 2826407-9.patch, failed testing.

dawehner’s picture

Status: Needs work » Needs review
StatusFileSize
new7.27 KB

Here is a try to reroll.

Status: Needs review » Needs work

The last submitted patch, 14: 2826407-14.patch, failed testing.

jofitz’s picture

Status: Needs work » Needs review
StatusFileSize
new7.32 KB

Re-roll against 8.3.x.

The last submitted patch, 14: 2826407-14.patch, failed testing.

wim leers’s picture

#14 failed because it's a 8.4.x patch that was being tested against 8.3.x. #16 then rerolled the patch in #14 so it'd apply to 8.3.x.

(#2827084: EntityNormalizer::denormalize should not throw UnexpectedValueException, but \Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException, so we get a 422 response instead of 400 changed the body of RequestHandler::handle(), and was only committed to 8.4.x.)


#14 is correct, but needed to be tested against 8.4.x Queued that test. #16 should be ignored.

We need either:

  1. different patches for 8.3.x and 8.4.x
  2. or only commit this to 8.4.x, in which #14 is sufficient

+++ b/core/modules/rest/tests/src/Functional/EntityResource/EntityResourceTestBase.php
@@ -716,10 +716,7 @@ public function testPost() {
-    $this->assertResourceErrorResponse(415, '', $response);
+    $this->assertResourceErrorResponse(415, 'No route found that matches "Content-Type: text/xml"', $response);

As this test shows, it fixes an error response. So arguably, it's a bugfix, so it should be committed ot 8.3.x too.

jofitz’s picture

So (assuming test passes) #14 is a patch for 8.4.x & #16 is a patch for 8.3.x (so should not be ignored).

EDIT: #16 has now failed testing and so should be ignored.

Status: Needs review » Needs work

The last submitted patch, 16: 2826407-16.patch, failed testing.

wim leers’s picture

#16 was never a patch for 8.3.x. It applies to 8.3.x, but it brings with it changes intentionally only committed to 8.4.x. That's where #16 goes wrong. Sorry for not making that more clear!

@Jo Fitzgerald: please know that this is not criticism of you, it's just tricky to do this kind of patch reroll, for patches that have parts that have changed between minor releases. I also sometimes struggle with this. I'm very grateful for the reroll you attempted :)

wim leers’s picture

Status: Needs work » Reviewed & tested by the community
StatusFileSize
new6.35 KB
new0 bytes

And so here are then the 8.3.x and 8.4.x patches. Then it's clear for core committers what the state of this issue is.

The 8.4.x one is identical to @dawehner's reroll in #14. The 8.3.x one I rebased.

Back to RTBC per #11.

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 22: 2826407-22-8.4.x.patch, failed testing.

wim leers’s picture

Assigned: Unassigned » wim leers

Random JS test fail for the 8.3.x patch. And 8.4.x has apparently already changed, so will need to rebase that.

wim leers’s picture

Assigned: wim leers » Unassigned
Status: Needs work » Reviewed & tested by the community
StatusFileSize
new6.35 KB
new7.59 KB

Eh, #22's 8.4.x patch was zero bytes. That was my bad.

The random fail… I can't do anything about.

Better luck this time?

Status: Reviewed & tested by the community » Needs work

The last submitted patch, 25: 2826407-25-8.4.x.patch, failed testing.

wim leers’s picture

Status: Needs work » Reviewed & tested by the community
StatusFileSize
new1.73 KB
new6.69 KB
new8 KB

HAH! A coding standards fail! :D :D <3

And less nice: a fail in Drupal\editor\Tests\EditorSecurityTest.

alexpott’s picture

Status: Reviewed & tested by the community » Needs work
  1. Sorry for taking so long to get round to reviewing this patch. Nice diff stat 4 files changed, 31 insertions, 51 deletions - and better error messages as a result.
  2. +++ b/core/modules/rest/src/Plugin/ResourceBase.php
    --- a/core/modules/rest/src/RequestHandler.php
    +++ b/core/modules/rest/src/RequestHandler.php
    

    Is there enough test coverage of the changes here? It's hard to work out exactly how much change is here. It looks mostly simplification and no functional change. Hard to be sure.

  3. +++ b/core/modules/rest/src/Routing/ResourceRoutes.php
    @@ -113,8 +113,15 @@ protected function getRoutesForResourceConfig(RestResourceConfigInterface $rest_
    +        if (!in_array($method, ['HEAD', 'GET', 'DELETE'])) {
    

    How come this is a negative assertion? Also, I think in_array() should always have strict set to TRUE. There are others (https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods) - perhaps not relevant - but this seems strange.

wim leers’s picture

Status: Needs work » Needs review

#28:

  1. :)
  2. It's removing this:
          // Only allow serialization formats that are explicitly configured. If no
          // formats are configured allow all and hope that the serializer knows the
          // format. If the serializer cannot handle it an exception will be thrown
          // that bubbles up to the client.
          $request_method = $request->getMethod();
          if (in_array($format, $resource_config->getFormats($request_method))) {
            …
          }
          else {
            throw new UnsupportedMediaTypeHttpException();
          }
    

    And because that removes an if-else-test, it's removing one indentation level for all code inside the if-case.

    We can remove that if-test-or-else-throw-a-415-HTTP-exception, because the validation of the request body's format (i.e. Content-Type request header) is now happening in the routing system instead of in the controller! In other words: this makes the REST module use the routing system the way it's meant to be used. Instead of duplicating functionality/responsibilities from the routing system in the controller, which is what it's been doing until now.

    That's the only thing that it changes in this class!

    Check \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase::testPost() + \Drupal\Tests\rest\Functional\EntityResource\EntityResourceTestBase::testPatch(): POST and PATCH receive request bodies, and those tests assert 415 responses in the appropriate case. If those tests still pass, you can be certain that it's still working correctly.

  3. Hm… that's a good question. I think I did that because PUT is something none of the REST Resource plugins in Drupal core support, but contrib/custom modules might use that. And they'd need Content Type request header validation too.

    I think this is a tiny detail in the grand scheme of things, but I'm happy to change it to if (in_array($method, ['POST', 'PATCH', 'PUT'], TRUE)) { if you prefer that.

wim leers’s picture

Status: Needs review » Reviewed & tested by the community
StatusFileSize
new991 bytes
new6.69 KB
new8.01 KB
17:18:06 <WimLeers> alexpott: replied: https://www.drupal.org/node/2826407#comment-12022428
17:18:09 <drupalbot> https://www.drupal.org/node/2826407 => PATCH + POST allowed format validation happens in RequestHandler::handle(), rather than in the routing system #2826407: PATCH + POST allowed format validation happens in RequestHandler::handle(), rather than in the routing system => 29 comments, 2 IRC mentions
17:19:58 <alexpott> WimLeers: I think we should do 3 - I think it is better form to be positive
17:20:05 <WimLeers> alexpott: happy to do that :)
17:20:11 <alexpott> WimLeers++
17:20:13 <WimLeers> alexpott: I think the answer to point 2 answered your concerns?
17:20:38 <alexpott> WimLeers: totally! I thought it might be something like that - easier to ask than to follow all the logic.

Done.

alexpott’s picture

Category: Task » Bug report
Status: Reviewed & tested by the community » Patch (to be ported)

Thanks @Wim Leers.

Committed a8fec34 and pushed to 8.4.x. Thanks!

Going to set to patch to be ported for 8.3.x - will discuss with other committers once 8.3.0 is released. Imo this is a bug because of the fix to the error messages.

  • alexpott committed a8fec34 on 8.4.x
    Issue #2826407 by Wim Leers, dawehner, Jo Fitzgerald: PATCH + POST...
wim leers’s picture

Imo this is a bug because of the fix to the error messages.

Exactly!

+++ b/core/modules/rest/tests/src/Functional/EntityResource/EntityResourceTestBase.php
@@ -716,10 +716,7 @@ public function testPost() {
-    // @todo Update this in https://www.drupal.org/node/2826407. Also move it
-    // higher, before the "no request body" test. That's impossible right now,
-    // because the format validation happens too late.
-    $this->assertResourceErrorResponse(415, '', $response);
+    $this->assertResourceErrorResponse(415, 'No route found that matches "Content-Type: text/xml"', $response);
 
 
     $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
@@ -917,10 +914,7 @@ public function testPatch() {

@@ -917,10 +914,7 @@ public function testPatch() {
 
     // DX: 415 when request body in existing but not allowed format.
     $response = $this->request('PATCH', $url, $request_options);
-    // @todo Update this in https://www.drupal.org/node/2826407. Also move it
-    // higher, before the "no request body" test. That's impossible right now,
-    // because the format validation happens too late.
-    $this->assertResourceErrorResponse(415, '', $response);
+    $this->assertResourceErrorResponse(415, 'No route found that matches "Content-Type: text/xml"', $response);

IOW: these changes prove that the bug is fixed. No error message before, helpful error message after!

alexpott’s picture

Status: Patch (to be ported) » Fixed

Discussed with @catch and we agreed to commit this to 8.3.x

Committed 943e2e7 and pushed to 8.3.x. Thanks!

  • alexpott committed 943e2e7 on 8.3.x
    Issue #2826407 by Wim Leers, dawehner, Jo Fitzgerald: PATCH + POST...

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.