Search code examples
firebasegoogle-cloud-storagefirebase-security

Is it possible to prevent web clients from setting Cache-Control when they have permission to upload to Google Cloud Storage?


The client is calling ref.put(file, metadata) in order to upload an image. cacheControl is part of the SettableMetadata defined that can be passed to put and updateMetadata. Is there a way to forbid clients from setting this? I know that I can asynchronously update it with a cloud function but then the client could just call updateMetadata later, and if I have a cloud function that triggers on metadata update to update the metadata, it goes into an infinite loop (tested in emulator).


Solution

  • If a user is able to upload the files directly within Firebase storage, it is assumed they also have permission to define the meta data. You can setup a cloud function that edits the meta data post upload or handle it directly from cloud functions with your upload. it all depends on your flow within your app.

    One solution is to have a dedicated directory that users upload to and Cloud functions migrate and process the files to another directory, this would prevent the metadata from being updated by the users.

    You could always enforce it from within the client app with the following:

    / Create a reference to the file whose metadata we want to change
    var forestRef = storageRef.child('images/forest.jpg');
    
    // Create file metadata to update
    var newMetadata = {
      cacheControl: 'public,max-age=300',
      contentType: 'image/jpeg'
    };
    
    // Update metadata properties
    forestRef.updateMetadata(newMetadata)
      .then((metadata) => {
        // Updated metadata for 'images/forest.jpg' is returned in the Promise
      }).catch((error) => {
        // Uh-oh, an error occurredd!
      });
    

    Source: https://firebase.google.com/docs/storage/web/file-metadata#update_file_metadata