While working on a Rest-resource we have an issue with rendering Url's to private files.
We used $file->url() and that resulted in this error:
The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early.
Diving into it looks like PrivateStream::getExternalUrl() and UrlGeneratorTrait::url() are here to blame, because these functions do not pass the collect_bubbleable_metadata attribute when rendering the url.
We used:
$file->url()
This will call file_create_url() located in /core/includes/file.inc
At some point in file_create_url() the appropriate wrapper is loaded and the method getExternalUrl() will be called.
// Attempt to return an external URL using the appropriate wrapper.
if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
return $wrapper->getExternalUrl();
}
else {
return FALSE;
}
The function getExternalUrl on the PrivateStreamWrapper calls
url() in Drupal/Core/Routing/UrlGeneratorTrait.php
This doc-comment says that \Drupal\Core\Routing\UrlGeneratorTrait::url() follows \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute(), but it does not.
The collect_bubbleable_metadata attribute is missing.
| Comment | File | Size | Author |
|---|---|---|---|
| #40 | file_url_collect_bubbleable_metadata-2867355-40.patch | 7.07 KB | dakwamine |
| #32 | 2867355-32.patch | 8.96 KB | hardik_patel_12 |
Comments
Comment #2
ndf commentedIn the patch 2 changes:
\Drupal\Core\Routing\UrlGeneratorTrait::url()conforms\Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute()by adding thecollect_bubbleable_metadataattribute.The
\Drupal\Core\StreamWrapper\PrivateStream::getExternalUrlwill always passcollect_bubbleable_metadata = TRUEto\Drupal\Core\Routing\UrlGeneratorTrait::url()Comment #3
ndf commentedComment #4
ndf commentedAdded
->getGeneratedUrl()so the caller$file->url()doesn't need to implement any behavioral changes.Comment #6
ndf commentedAnd the interdiff between #2 and #4
Comment #7
ndf commentedAnd the interdiff between #2 and #4 in .txt format
Comment #9
ndf commentedBack to 'needs review' #6 triggered test-bot
Comment #12
ijsbrandy commentedNot working for version Drupal 8.5.1. Fix with small adjustment to the patch. path_processing has been added to the url method.
Comment #13
borisson_We should probably write tests for this as well.,
Comment #14
rbayliss commentedUpdating the title to reflect the fact that this is a bug, not a feature.
This will definitely need tests. Just to reiterate the issue, it's impossible to call file_create_url() for the private stream wrapper on any kind of response that doesn't involve Twig rendering. Eg: If I want to issue a trusted redirect response to a file in the private filesystem, it triggers this problem.
Comment #15
rbayliss commentedThe patch above does prevent the error from occurring, but it doesn't actually bubble up the cache metadata that was used to generate the URL. Specifically, the url.domain context is bubbled up due to the fact that private file URLs are output as absolute. Without collecting that cache context, file_create_url() could technically allow absolute urls to be returned for the wrong domain. This patch allows file_create_url() to return a GeneratedUrl, which can contain cache metadata. This is kind of a far-reaching change that will impact contrib stream wrappers (we change an interface method), but I'm not sure how else this could work reliably.
This also adds some really basic tests to make sure that file_create_url(TRUE) returns a GeneratedURL.
Comment #17
rbayliss commentedAlso patching TranslationStream.
Comment #19
rbayliss commentedOne more test failure.
Comment #20
rbayliss commentedFix code style.
Comment #21
ndf commented#20 is quite a change from #12, therefore difficult to review.
There are tests now! That helps a lot.
Regarding #20
How is this testing the 'collect_bubbleable_metadata'?
And the changes from #12
Seems to be missing in #20
Is that done intentional?
Can we add the tests (test-only) separately, to show the test baseline?
Then also add those test to patch #12 so we see the difference.
Comment #24
feyp commentedAnswering questions from #20:
It asserts that
file_create_url()will return aGeneratedUrlobject, if the newly introduced second parameter isTRUE.\Drupal\Core\GeneratedUrlwill return generated URLs along with associated bubbleable metadata.Yes. #20 removed
UrlGeneratorTraitfrom the private stream wrapper and replaced with a call toUrl::fromRoute, thus the changes toUrlGeneratorTraitwere no longer necessary. Note that the removal ofUrlGeneratorTraithas since been committed as part of #3001309: Replace usages of UrlGeneratorTrait in non-api classes, so with the re-roll we just set the parameter of thetoString()method toTRUEto return aGeneratedUrlobject, if the newly introduced$collect_bubbleable_metadataparameter isTRUE.Yes, we could, but since the test is only testing the newly introduced second parameter it is kind of evident that it would fail without the patch. No need to waste precious test cycles for that, I think.
Can't do that, unfortunately, see above.
Attached is a straight re-roll of #20 for 8.8.x. We would probably need to work on the patch a bit more. At least we need to add documentation to the doc blocks for the newly introduced parameters. To ease review, I'll just do a straight reroll for now to allow for a proper interdiff for any additional changes on top of #20 later. Also, I'll leave the issue status alone for now so that we can see what the test bot thinks about the new patch.
Removing "Needs tests" tag, since basic testing is there.
Comment #26
feyp commentedI forgot to include the GeneratedUrl class in the test file and the RSS test tries to pass an options array as the second parameter to file_create_url() that doesn't exist. New patch attached.
Comment #27
berdirThis is an API change, so that's problematic. Adding an optional argument to an interface requires all implementations to respect it.
Also, note that file_create_url() id rewritten into a service in #2669074: Convert file_create_url() & file_url_transform_relative() to service, deprecate it and it is currently being discussed whether it should only allow Url objects as return value, but it won't solve this problem yet, as it doesn't actually pass this information through yet.
Maybe we could find a way to make the return value relative here and leave it to the caller to make it absolute if necessary. But again, not sure how to approach that without a BC break. Idea: A separate method to set options/absole similar to the Url object, that could be on a new optional interface that would be required with D9. Or not adding the new argument to the interface until D9.
Comment #30
johnpitcairn commentedOuch. Bitten by this trying to redirect from a custom media controller to an external google docs viewer with an absolute url to the local file, which is in the private filesystem but allows anonymous access. There doesn't seem to be any way to generate the local file url and redirect without the patch at #26, but I'm reluctant to patch core on production just for this.
Should this still be at needs review, or are we postponed, or what?
Comment #31
johnpitcairn commentedPatch no longer applies to 8.9.x or 9.1.x.
Comment #32
hardik_patel_12 commentedRe-rolling patch , kindly review.
Comment #35
daffie commented#2669074: Convert file_create_url() & file_url_transform_relative() to service, deprecate it has landed.
Comment #36
berdirAdding an optional new argument on an interface is a BC break, it is not possible to get it committed like this.
I've been thinking about a new method that returns a URL object, so that we have fewer things to convert back and forth in the new FileUrlGenerator, that could, for now, be an optional interface for stream wrappers. Then watever calls it can take care of bubbleable metadata and we don't need to pass it through.
Comment #38
dakwamineIn patches starting from #15, there are multiple instantiations of the
GeneratedUrlclass with 1 argument, but the constructor signature does not contain any argument (as says my IDE) in any D8 version. PHP does not crash on this though, but I suspect there is a chunk missing from the initial patch.Additionally, in the latest available patch, in some places,
GeneratedUrlis passed in functions likepreg_replaceinfile_url_transform_relative, but an error is triggered:And with #2669074: Convert file_create_url() & file_url_transform_relative() to service, deprecate it, the patch doesn't work at all now. I'm looking at what could be done with the new service.
Comment #39
dakwamineDumb question: does this bug still exist in latest core releases? I don't have the error anymore in my use cases, and the metadata bubbling looks OK in refactorized file / URL system.
Repro steps needed.
Comment #40
dakwamine@Berdir, did you mean something like the attached patch?
Comment #43
smustgrave commentedThis issue is being reviewed by the kind folks in Slack, #needs-review-queue-initiative. We are working to keep the size of Needs Review queue [2700+ issues] to around 400 (1 month or less), following Review a patch or merge request as a guide.
Seems at some point test coverage was lost so adding back the tests tag.
This could use an issue summary update to show what the proposed solution, remaining tasks, api changes, etc.
New functions should be typehinted for 10
Adding a new interface will require a change record to announce to others.
Thanks.
Comment #44
andypostSounds like exactly this method should be public and its consumers will use it as string and can manage cache metadata
Comment #45
andypostComment #46
andypost