2
votes

I created a service account email and added cloudfunctions.invoker role to the email so I can make sure only cloud tasks can trigger cloud functions, and I removed AllUsers role. But when cloud tasks tried to run cloud function, the status code is UNAUTHENTICATED(16): HTTP status code 401 and execution failed.

My current code and console is like this.

index.ts

export const addTasks = functions.https.onCall((data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError('failed-precondition', 'You are not authenticated.')
  }

  const client = new tasks.CloudTasksClient()

  const projectId = functions.config().project.id
  const queue = 'queue'
  const location = functions.config().project.location
  const parent = client.queuePath(projectId, location, queue)
  const url = `https://${location}-${projectId}.cloudfunctions.net/executeSomething`
  const serviceAccountEmail = functions.config().project.email

  const task: tasks.protos.google.cloud.tasks.v2.ITask = {
    httpRequest: {
      httpMethod: 'POST',
      url: url,
      oidcToken: {
        serviceAccountEmail: serviceAccountEmail,
      },
    },
    scheduleTime: {
      seconds: ...,
    },
  }

  const request: tasks.protos.google.cloud.tasks.v2.ICreateTaskRequest = {
    parent: parent,
    task: task,
  }

  return client.createTask(request)
}

My cloud function's console

enter image description here

I added the cloud functions invoker role to the service account email.

My firebase project environment variables

enter image description here

When I added AllUsers role to cloud functions, it works as expected so I am sure I made a mistake when resrticting access. What am I missing?

Update:

My cloud tasks console

enter image description here enter image description here

1
This might be a longshot, but the example that was shared in the answer below has the serviceAccountEmail around quotes. Could you try using "service_account_email": service_account_email and check if it fixes the issue? - Rafael Lemos
DId you find out what was not working? - Black_Bacardi
@Black_Bacardi Not yet.. - Ooto

1 Answers

0
votes

Your OIDC token seems broken against the specification

Simply provide the email, without the attribute name like in this example, or use the snake_case like described in the spec