5
votes

I have the following code sample that receives a bufferedImage along with it's mimeType and then uploads it to Google Cloud Storage.

Everything works fine, but for some reason my Google Cloud Function is getting an 403 error from the Storage API.

What do i have to do so that my GC Function has access to GC Storage?

I couldn't find anything in the documentation that would show me how to do this.

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

// Creates a client
const storage = new Storage();

// Lists all buckets in the current project
const buckets = storage.getBuckets();

exports.uploadImage = (bucketName, fileName, imageBuffer, mimeType) => {
  return new Promise((resolve, reject) => {

    let bucket = storage.bucket(bucketName);

    let file = bucket.file(fileName);
    file.save(imageBuffer,
        {
            metadata: { contentType: `image/${mimeType}` },
        },
        ((error) => {
            error ? reject(error) : resolve()
        })
    );
  })
}

here is the error I'm getting

{"code":403,"errors":[{"domain":"global","reason":"forbidden","message":"[email protected] does not have storage.objects.create access to blog/e33f9c9d-65f0-4a7f-8332-29846f770e6d."}],"message":"[email protected] does not have storage.objects.create access to blog/e33f9c9d-65f0-4a7f-8332-29846f770e6d."}

2

2 Answers

5
votes

A Cloud Function (CF) is executed by a specific service account (in your case [email protected]). From Runtime service account:

During function execution, Cloud Functions uses the service account [email protected] as an identity.

Since you're getting 403 error when accessing your buckets/files it means they aren't publicly accessible, so you need to give the above-mentioned service account the necessary access permission(s) (at least storage.objects.create, mentioned in the error message) according to the Access Control Option you selected and configured for your storage.

2
votes

So apparently Google Cloud has some glitches in it. For some reason, I’m not allowed to write to a bucket unless it has already been created. I changed the bucketName to an already existing bucket and I received a 200 response. Google Cloud should have sent a 404 response instead of a 403. 403 is misleading because 1. My service does have bucket creation privileges and 2. The bucket never existed in the first place. That’s means that 404 Not Found would be the appropriate response. I hope this helps somebody.