1
votes

I am trying to upload files to google cloud storage using a cloud function which is triggered by HTTP. However when the cloud function sends the file to be uploaded I often (although not always) get the following error

ERROR uploading to storage: { ApiError: Anonymous caller does not have storage.objects.create access to bucket_name/folder/test.jpg.

I am not sure why this error occurs - and why only some of the time

Here is the code:

const storage      = require('@google-cloud/storage')();

function uploadToStorage(filepath, folder, filename) {
  const options = {
    destination: bucket.file(`${folder}/${filename}`),
    public: false,
    resumable: false
  };

  storage
    .bucket(BUCKET_NAME)
    .upload(filepath, options)
    .then(function () {
      console.log(`${filename} uploaded to ${BUCKET_NAME}`);
    })
    .catch((err) => {
      console.error('ERROR uploading to storage: ', err);
    });
}

Thanks

1
How is your function triggered, is it via pubsub?Oliver
@Oliver HTTP trigger - added it to the questioncseagull
Have you created a signed-URL function?Oliver

1 Answers

1
votes

I had the same error after adding a return statement at the end of my function that performed file deletes on storage objects. This is what I was doing:

  1. Make a database call to get some data
  2. Once that request comes back, delete some files out of cloud storage (GCS)

The code structurally looked like this:

deleteStuffOutStorage() {

    admin.firestore().doc(`My-doc-ref`).get()
        .then(snapshot => { 
            // Do the deleting here {Interacting with GCS}
            return deleteFile(snapshot.data().path); // Deletes file
        })

        .then(success => {
           // Worked
        })

        .catch(error => {
          // Error = ApiError: Anonymous caller does not have storage.objects...
        })

    return;   // This statement was creating the problems
}

When I removed the return statement, I no longer got the error. I thought in my case it may have something to do with firebase-admin object instance getting deallocated and re-allocated between asynchronous operations (steps 1 and 2 above), or at least its GCS auth token?

All FCF instances should have access to GCS via a service account that is auto-generated. You can confirm this in the GCP console : https://console.cloud.google.com/iam-admin/serviceaccounts/

From the code snippet you posted I can't see anything that would cause the same issue I was getting, but maybe have a think about any time-based events that could cause this behaviour. That may explain the inconsistent behaviour you elude to.

Hope that's some sort of help.