1

I am creating a live image preview system for customizable products that needs to send a user's temporary file to a remote server.

I have a token-based system to protect the file but the problem seems to be that the file is temporary. I've created a hook_file_download() to return the headers as required to allow access when approved but the file access is still being denied somewhere.

It does not seem to be a module weight issue as I've made my custom module have the lowest weight and verified via debug code that it fires after core file_file_download()

EDIT: Further troubleshooting shows the the headers array is getting a key value set to "-1" somewhere after hook_file_download() and core "FileDownloadController" which is where the file is getting denied. Any ideas where this [0] = -1 header value is getting set and how to override it?

If I strip it down to the basics for testing as shown below the 'allow' headers are returned but the file is still being blocked when viewed from an anonymous browser:

function MYMODULE_file_download($uri) {

  // Check to see if this is a config download.
  $scheme = StreamWrapperManager::getScheme($uri);

  if ($scheme == 'temporary'){
    if ($files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $uri])){

      $file = reset($files) ?: NULL;
      
      // Access is granted.
      $headers = file_get_content_headers($file);
      return $headers;
    }
  }
}

1 Answer 1

1

Temporary files are handled by file_file_download(), an implementation of hook_file_download() done from the File module. The code it uses is the following one.

  // Find out if a temporary file is still used in the system.
  if ($file->isTemporary()) {
    $usage = \Drupal::service('file.usage')->listUsage($file);
    if (empty($usage) && $file->getOwnerId() != \Drupal::currentUser()
      ->id()) {
      // Deny access to temporary files without usage that are not owned by the
      // same user. This prevents the security issue that a private file that
      // was protected by field permissions becomes available after its usage
      // was removed and before it is actually deleted from the file system.
      // Modules that depend on this behavior should make the file permanent
      // instead.
      return -1;
    }
  }

Reading the comments, that is done on purpose to avoid a private file, protected by field permissions, is visible after the field permissions are changed, but before the file is deleted.

Looking at the code that invokes that hook, in FileDownloadController::download() for example, I don't see any way to avoid that, as the code doesn't use hook_file_download_alter().

A workaround could be setting that file as being used, since the code checks the file is not used, before blocking the access.

function mymodule_file_download($uri) {
  if (StreamWrapperManager::getScheme($uri) == 'temporary') {
    if ($files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $uri])){
      if ($file = reset($files)) {
        // Access is granted.
        \Drupal::service('file.usage')->add($file, 'mymodule', 'unexisting_entity', 10);
        $headers = file_get_content_headers($file);
        return $headers;
      }
    }
  }
}

I used 'unexisting_entity' and 10 as entity type and entity ID. If you have real values for them, you should use those.

Note that FileUsageBase::add(), the DatabaseFileUsageBackend::add() parent method, changes the file to permanent, in the case it is not already.

// Make sure that a used file is permanent.
if (!$file->isPermanent()) {
  $file->setPermanent();
  $file->save();
} 

When a file usage is decremented and becomes 0, the file is changed to temporary from FileUsageBase::delete().

// If there are no more remaining usages of this file, mark it as temporary,
// which result in a delete through system_cron().
$usage = \Drupal::service('file.usage')->listUsage($file);
if (empty($usage)) {
  $file->setTemporary();
  $file->save();
}

I would rather increase the file usage, instead of making directly a file permanent, as decreasing the file usage doesn't conflict with other modules that could set the same file as permanent.
Alternatively, I would use the following code for hook_file_download().

function mymodule_file_download($uri) {
  if (StreamWrapperManager::getScheme($uri) == 'temporary') {
    if ($files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => $uri])){
      if ($file = reset($files)) {
        // Access is granted.
        if (!$file->isPermanent()) {
          $file->setPermanent();
          $file->save();
        }
        $headers = file_get_content_headers($file);
        return $headers;
      }
    }
  }
}

In this case, to make the file temporary again, I would use the following code.

// Store the file entity reference in $file.
$usage = \Drupal::service('file.usage')->listUsage($file);
if (empty($usage) && !$file->isTemporary()) {
  $file->setTemporary();
  $file->save();
}

To achieve what you want, it would be also possible to change the controller for the system.temporary route, but that seems excessive.

5
  • Thank you, yes, that file_file_download() snippet is the culprit. I'm confused as to why I can't use hook_file_download() in my higher weighted module to override that. Dec 31, 2021 at 16:23
  • I found a workaround by setting the file to "isPermanent" but I don't like this. Do you know if that will cause files to not be deleted from the system when needed? Dec 31, 2021 at 16:34
  • hook_file_download() only receives a URL, not the headers returned by other implementations; if this were the case, a hook implementation could override the decision of another implementation. The actual code invoking them just checks one of them returned -1 as header; it doesn't check -1 is the first returned value.
    – apaderno
    Dec 31, 2021 at 16:37
  • @quantumized Permanent files will not be removed during the file garbage collection process, but a module could delete them. If the module keeps a list of file it changed to permanent, that could be possible.
    – apaderno
    Dec 31, 2021 at 16:40
  • I also added a note about what happens when a file usage is increased: The Drupal core implementation of the file.usage service automatically makes a temporary file permanent.
    – apaderno
    Jan 3, 2022 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.