unable to access the cloud Firestore in Project A from cloud function in Project B - '403 Missing or insufficient permissions'

Viewed 75

Cloud Firestore in Project A, Cloud Functions in Project B

I'm able to access the cloud Firestore of 'Project A' from cloud shell of 'Project B' but not through cloud functions of 'Project B'. Here's the code of the cloud function uses

from google.cloud import firestore 
import firebase_admin
from firebase_admin import credentials

def function_a(request):

cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, {
    'projectId': 'project-a',
    })
db = firestore.client()
try:
    doc_ref=db.collection('COLLECTION_SAMPLE').document('documentA').set({"foo":"bar"})
except Exception as e:
    print("error::", e)
    
return "success"

Cloud functions in Project B use the service account project-b@appspot.gserviceaccount.com the service account has roles (Cloud Datastore User, Cloud Functions Developer, Editor) in Project B and has the role of (Cloud Datastore Import Export Admin) in project A.

I encounter 403 Missing or insufficient permissions.

1 Answers
  1. Change your code as
    db = firestore.Client(project='project-a')
  1. Find the service account of your Cloud Function. As you mentioned, usually it should be project-b@appspot.gserviceaccount.com. Copy the service account ID.

  2. In the GCP console of project project-a > IAM & Admin > IAM, add the service account mentioned in step 2 as its member and grant it the roles needed, i.e. Cloud Datastore Viewer.

Related