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.

Comments

ndf created an issue. See original summary.

ndf’s picture

In the patch 2 changes:

\Drupal\Core\Routing\UrlGeneratorTrait::url() conforms \Drupal\Core\Routing\UrlGeneratorInterface::generateFromRoute() by adding the collect_bubbleable_metadata attribute.

The \Drupal\Core\StreamWrapper\PrivateStream::getExternalUrlwill always pass collect_bubbleable_metadata = TRUE to \Drupal\Core\Routing\UrlGeneratorTrait::url()

ndf’s picture

Status: Active » Needs review
ndf’s picture

Added ->getGeneratedUrl() so the caller $file->url() doesn't need to implement any behavioral changes.

ndf’s picture

StatusFileSize
new603 bytes

And the interdiff between #2 and #4

ndf’s picture

StatusFileSize
new603 bytes

And the interdiff between #2 and #4 in .txt format

Status: Needs review » Needs work

The last submitted patch, 6: interdiff-2867355--02-04.diff, failed testing.

ndf’s picture

Status: Needs work » Needs review

Back to 'needs review' #6 triggered test-bot

Version: 8.4.x-dev » 8.5.x-dev

Drupal 8.4.0-alpha1 will be released the week of July 31, 2017, which means new developments and disruptive changes should now be targeted against the 8.5.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.5.x-dev » 8.6.x-dev

Drupal 8.5.0-alpha1 will be released the week of January 17, 2018, which means new developments and disruptive changes should now be targeted against the 8.6.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

ijsbrandy’s picture

Not working for version Drupal 8.5.1. Fix with small adjustment to the patch. path_processing has been added to the url method.

borisson_’s picture

Status: Needs review » Needs work
Issue tags: +Needs tests, +D8 cacheability, +API-First Initiative

We should probably write tests for this as well.,

rbayliss’s picture

Title: Add collect_bubbleable_metadata in PrivateStream::getExternalUrl() and UrlGeneratorTrait::url() » file_create_url() causes LogicException when used with certain stream wrappers

Updating 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.

rbayliss’s picture

Status: Needs work » Needs review
StatusFileSize
new8.68 KB
new9.5 KB

The 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.

Status: Needs review » Needs work

The last submitted patch, 15: 2867355-collect_bubbleable_metadata_in_stream_wrappers-15.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

rbayliss’s picture

Status: Needs work » Needs review
StatusFileSize
new9.29 KB
new631 bytes

Also patching TranslationStream.

Status: Needs review » Needs work

The last submitted patch, 17: 2867355-collect_bubbleable_metadata_in_stream_wrappers-17.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

rbayliss’s picture

Status: Needs work » Needs review
StatusFileSize
new9.99 KB
new904 bytes

One more test failure.

rbayliss’s picture

Fix code style.

ndf’s picture

#20 is quite a change from #12, therefore difficult to review.
There are tests now! That helps a lot.

Regarding #20

+++ b/core/tests/Drupal/KernelTests/Core/File/StreamWrapperTest.php
@@ -99,6 +100,14 @@ public function testUriFunctions() {
+    // Test that file_create_url() allows collection of bubbleable metadata.
+    $generatedTemp = file_create_url('temporary://test.txt', TRUE);
+    $generatedPublic = file_create_url('public://test.txt', TRUE);
+    $generatedPrivate = file_create_url('private://test.txt', TRUE);
+    $this->assertInstanceOf(GeneratedUrl::class, $generatedTemp);
+    $this->assertInstanceOf(GeneratedUrl::class, $generatedPublic);
+    $this->assertInstanceOf(GeneratedUrl::class, $generatedPrivate);

How is this testing the 'collect_bubbleable_metadata'?

And the changes from #12

+++ b/core/lib/Drupal/Core/Routing/UrlGeneratorTrait.php
@@ -38,8 +38,8 @@
-  protected function url($route_name, $route_parameters = [], $options = []) {
-    return $this->getUrlGenerator()->generateFromRoute($route_name, $route_parameters, $options);
+  protected function url($route_name, $route_parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
+    return $this->getUrlGenerator()->generateFromRoute($route_name, $route_parameters, $options, $collect_bubbleable_metadata);

+++ b/core/lib/Drupal/Core/StreamWrapper/PrivateStream.php
@@ -48,7 +48,7 @@ public function getDirectoryPath() {
-    return $this->url('system.private_file_download', ['filepath' => $path], ['absolute' => TRUE, 'path_processing' => FALSE]);
+    return $this->url('system.private_file_download', ['filepath' => $path], ['absolute' => TRUE, 'path_processing' => FALSE], TRUE)->getGeneratedUrl();

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.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

feyp’s picture

Issue tags: -Needs tests
StatusFileSize
new8.84 KB

Answering questions from #20:

How is this testing the 'collect_bubbleable_metadata'?

It asserts that file_create_url() will return a GeneratedUrl object, if the newly introduced second parameter is TRUE. \Drupal\Core\GeneratedUrl will return generated URLs along with associated bubbleable metadata.

And the changes from #12
Seems to be missing in #20
Is that done intentional?

Yes. #20 removed UrlGeneratorTrait from the private stream wrapper and replaced with a call to Url::fromRoute, thus the changes to UrlGeneratorTrait were no longer necessary. Note that the removal of UrlGeneratorTrait has 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 the toString() method to TRUE to return a GeneratedUrl object, if the newly introduced $collect_bubbleable_metadata parameter is TRUE.

Can we add the tests (test-only) separately, to show the test baseline?

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.

Then also add those test to patch #12 so we see the difference.

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.

Status: Needs review » Needs work
feyp’s picture

Status: Needs work » Needs review
StatusFileSize
new1.29 KB
new9.83 KB

I 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.

berdir’s picture

+++ b/core/lib/Drupal/Core/StreamWrapper/StreamWrapperInterface.php
@@ -148,7 +148,7 @@ public function getUri();
    */
-  public function getExternalUrl();
+  public function getExternalUrl($collect_bubbleable_metadata = FALSE);
 

This 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.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

johnpitcairn’s picture

If I want to issue a trusted redirect response to a file in the private filesystem, it triggers this problem.

Ouch. 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?

johnpitcairn’s picture

Status: Needs review » Needs work

Patch no longer applies to 8.9.x or 9.1.x.

hardik_patel_12’s picture

Status: Needs work » Needs review
StatusFileSize
new8.96 KB

Re-rolling patch , kindly review.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

berdir’s picture

+++ b/core/lib/Drupal/Core/StreamWrapper/StreamWrapperInterface.php
@@ -148,7 +148,7 @@ public function getUri();
    *   Returns a string containing a web accessible URL for the resource.
    */
-  public function getExternalUrl();
+  public function getExternalUrl($collect_bubbleable_metadata = FALSE);
 
   /**
    * Returns canonical, absolute path of the resource.

Adding 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.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

dakwamine’s picture

In patches starting from #15, there are multiple instantiations of the GeneratedUrl class 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, GeneratedUrl is passed in functions like preg_replace in file_url_transform_relative, but an error is triggered:

NOTICE: PHP message: Error: Object of class Drupal\Core\GeneratedUrl could not be converted to string in /var/www/htdocs/drupal/web/core/includes/file.inc on line 144 #0 /var/www/htdocs/drupal/web/core/includes/file.inc(144): preg_replace('|^https?://loca...', '', Object(Drupal\Core\GeneratedUrl))

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.

dakwamine’s picture

Dumb 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.

dakwamine’s picture

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

@Berdir, did you mean something like the attached patch?

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

smustgrave’s picture

Status: Needs review » Needs work
Issue tags: +Needs issue summary update, +Needs tests, +Needs Review Queue Initiative, +Needs change record

This 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.

andypost’s picture

+++ b/core/lib/Drupal/Core/StreamWrapper/PrivateStream.php
@@ -45,8 +45,25 @@ public function getDirectoryPath() {
+   * @return \Drupal\Core\Url
+   *   A Url representation of the resource.
...
+  protected function getUrl() {
     $path = str_replace('\\', '/', $this->getTarget());
-    return Url::fromRoute('system.private_file_download', ['filepath' => $path], ['absolute' => TRUE, 'path_processing' => FALSE])->toString();
+    return Url::fromRoute('system.private_file_download', ['filepath' => $path], ['absolute' => TRUE, 'path_processing' => FALSE]);

Sounds like exactly this method should be public and its consumers will use it as string and can manage cache metadata

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 11.x-dev » main

Drupal core is now using the main branch as the primary development branch. New developments and disruptive changes should now be targeted to the main branch.

Read more in the announcement.