'Google Calendar API code not authenticating in Cloud Run

I've written a simple Calendar API call using the official NodeJS client: https://github.com/googleapis/google-api-nodejs-client#service-account-credentials

It works fine on my local machine, using a Service Account set up with Domain-Wide Delegation to create the event and invite a list of attendees on my behalf.

I set the credentials location using GOOGLE_APPLICATION_CREDENTIALS env var on my local machine, but do not set this on the Google Cloud Run service because it's supposedly automatic since I've associated the Service Account. This assumption seems true because I can call GoogleAuth functions and get back the expected service account name.

However, once I try to run it in Cloud Run, it throws the error:

Error: Service accounts cannot invite attendees without Domain-Wide Delegation of Authority.

At first I thought this was an issue with default credentials somehow loading the wrong service account.

I added logging directly before the event is called to see what account it is using:

  const auth = new googleClient.auth.GoogleAuth({
    clientOptions: {
      subject: eventOwner
    },
    scopes: calendarScopes,
  })

  const serviceAcctName = (await auth.getCredentials())?.client_email

  googleClient.options({
    auth: auth
  })
  
  logger.info(`${serviceAcctName} acting as ${eventOwner}, using calendar ${calendarId}`)

  const calendar = googleClient.calendar('v3')

  const response = await calendar.events.insert(event)

The log output is exactly as expected, with the correct service account acting as the correct user on the correct calendar id.

I've double-checked that the account has domain-wide delegation of authority and the proper scopes, and it works fine on my local machine, so the only thing I can think of is something about the library's feature of grabbing default credentials in a Google environment is overwriting my googleClient.options() call. But I'm still confused because GoogleAuth functions still give the expected service account info when it grabs the 'default'.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source