sebastian
sebastian

Reputation: 2890

Access secret from firestore triggered cloud function

I'm using Googles Secret Manager for accessing secrets in my cloud functions. This was working fine until now for all my functions - that are https and pubsub functions. Now I wrote a function that gets triggered by a firestore document change:

exports.onDocumentUpdated = functions
  .runWith({ secrets: ["MY_SECRET"] })
  .firestore
  .document('documents/{documentId}')
  .onUpdate(async (change: func.Change<QueryDocumentSnapshot>, context)

In this case process.env.MY_SECRET is undefined. When I look up the secrets of the functions in the Cloud Console I see that it has access to a completely different secret that I'm using in another function. When adding MY_SECRET here the cloud functions work, but only until I redeploy via cli - then MY_SECRET is again removed.

I checked the permissions of the other secrets, all of them show exactly the same Roles/Principals. It's literally all the same the only difference is that this function is a firestore trigger function. What am I missing?

Edit: Did another test with following two functions:

exports.testSecret1 = functions
  .runWith({ secrets: ["TEST_SECRET"] })
  .https.onCall(async (data, context) => {
    func.logger.info(`${process.env.TEST_SECRET}`);
  })

exports.testSecret2 = functions
  .runWith({ secrets: ["TEST_SECRET"] })
  .firestore
  .document('documents/{documentId}')
  .onUpdate(async (change: func.Change<QueryDocumentSnapshot>, context) => {
    func.logger.info(`${process.env.TEST_SECRET}`);
  })

testSecret1 has access to TEST_SECRET testSecret2 has no access to TEST_SECRET, prints undefined

Upvotes: 4

Views: 2337

Answers (2)

xskull.greymonx
xskull.greymonx

Reputation: 101

I wasn't able to find any solutions using the syntax in your question. However, if you alter your code to use the style of syntax below, you can use secrets in Firestore triggers like this

exports.myUpdate = onDocumentCreated({
    document: "/collection/{docID}",
    secrets: [SECRET_KEY]
  },
  async (event) => {
    const secretKey = SECRET_KEY.value()
    // code
    }
);

This answer explains it more thoroughly and provides documentation.

Upvotes: 1

Roopa M
Roopa M

Reputation: 3029

Run the following command to give access to your secret TEST_SECRET

firebase functions:secrets:access TEST_SECRET

If you are newly creating secrets use the following command

firebase functions:secrets:set SECRET_NAME

Before deploying, make sure your functions code allows the function to access the secret using the runWith parameter.

Check this documentation for more information.

Also make sure that you are using latest version of firebase-tools

Upvotes: 2

Related Questions