firebase-tools: Firebase Cloud Functions: app/invalid-credential failed to fetch a valid Google OAuth2 access token Firebase Admin SDK

[REQUIRED] Environment info

firebase-tools: 7.5.0

Platform: macOS

[REQUIRED] Test case

[REQUIRED] Steps to reproduce

I am new to Cloud Functions. I followed the docs, and the new initialization syntax for firebase-admin, but I am getting an auth error when running the function on the server and on a localhost.

https://firebase.google.com/docs/functions/beta-v1-diff#new_initialization_syntax_for_firebase-admin

@firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND\"."}

I tried instantiating the sdk with a serviceAccountKey, same issue. https://firebase.google.com/docs/admin/setup#initialize_the_sdk

The function is being triggered on localhost and on the server, and error is being thrown once the call to the database is being made at gettingUser()

When running locally after building:

$ firebase experimental:functions:shell
firebase > const data = {some_article...}
firebase > addingNewArticle(data)
'Successfully invoked function.'
firebase > >  New article created articleId1

DEBUG: @firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND\"."}

/index.ts

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';

admin.initializeApp();

export const addingNewArticle = functions.database
.ref('/articles/{articleId}')
.onCreate(async (snapshot, context) => {
  const articleId = context.params.articleId

  const result = await gettingUser();
  console.log(`From onCreate ${result}`);


  console.log(`New article created ${articleId}`)

  const articleVal = snapshot.val()
  const name = articleVal.name
  const addedById = articleVal.addedById

  console.log(`${name} was added by: ${addedById}`);
  console.log(`burgersVal: ${articleVal}`);
  console.log(`snapshot: ${snapshot}`);


  return Promise.all([])
})


export async function gettingUser() {
    const result = await admin.database().ref(`users/fnkjasdfadsfna.d`).once('value');
    console.log(`Looging new user ${result.val()}`);
    return result.val()
}

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 9
  • Comments: 39 (10 by maintainers)

Most upvoted comments

To anyone experiencing this issue:

  • If you’re seeing it in the emulator you can fix it by either setting GOOGLE_APPLICATION_CREDENTIALS to a service account or running gcloud auth application-default login on your machine.
  • If you’re seeing this in production then it may be that someone has modified the service accounts attached to your project that a Functions service experiencing a temporary hiccup. If the problem persists, please reach out to support.

After upgrading to Mac OS Catalina I encountered this issue. What resolved it for me was running the following commands:

  • firebase login
  • export GOOGLE_APPLICATION_CREDENTIALS="<PATH_TO_YOUR_SERVICE_ACCOUNT_KEY_JSON>"

Is there a solution posted somewhere? I am getting this warning today when trying to access a database through an a cloud function running locally.

Here is how I managed to fix the issue:

Error message:

Error: Credential implementation provided to initializeApp() via the “credential” property failed to fetch a valid Google OAuth2 access token with the following error: “Error fetching access token: invalid_grant (Bad Request)”. There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.

Solution:

Step 1: SYNC the time for local pc with a time server. There was a difference of 1 second in my case, but windows 10 has a SYNC NOW button, used it, and time synced. Checked it on: https://time.is/

Step 2: Go to link https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk above. Generate a private key there. Save it to a folder on your pc. Say “D:\Path\project-101-firebase-adminsdk-cb748-fhry6shja.json”. Then on the index.ts file of your functions folder, update the code as follows:

` import * as functions from ‘firebase-functions’; import * as admin from ‘firebase-admin’;

var serviceAccount = require(“D://Path//project-101-firebase-adminsdk-cb748-fhry6shja.json”); admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: “https://project-101.firebaseio.com” }); `

Optional Step: (I am not sure if this is still required) - we can set the GOOGLE_APPLICATION_CREDENTIALS on pc as follows:

set GOOGLE_APPLICATION_CREDENTIALS="D:\Path\project-101-firebase-adminsdk-cb748-fhry6shja.json"

Test that it’s done correctly using - set GOOGLE_APPLICATION_CREDENTIALS


Finally to test run the cloud functions on emulator, I followed this nicely written article: https://medium.com/@moki298/test-your-firebase-cloud-functions-locally-using-cloud-functions-shell-32c821f8a5ce

Basically -

  1. Open CMD in administrator mode, and navigate to your functions folder.
  2. Run transpile command for your function ts file. This will be required everytime we make a change in our code.

npm run-script build

  1. Enter firebase functions shell with command:

firebase functions:shell

  1. Run your function and see that it works well (hopefully!). Say the function is http cloud function with name TestFunc - so in functions shell type:

TestFunc()

That should do it.

Same issue as well

Same problem here, still unsolved.

The error message is cryptic, but the fix (at least in my case) was simple. As pointed out by @hiranya911 in this related issue, the error occurs if your config/environment variables are not setup correctly, you want to double-check your GOOGLE_APPLICATION_CREDENTIALS specifically.

Same to me [2019-12-21T11:21:35.790Z] @firebase/database: FIREBASE WARNING: {"code":"app/invalid-credential","message":"Credential implementation provided to initializeApp() via the \"credential\" property failed to fetch a valid Google OAuth2 access token with the following error: \"Error fetching access token: <html>\r\n<head><title>302 Found</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>302 Found</h1></center>\r\n<hr><center>nginx/1.14.2</center>\r\n</body>\r\n</html>\r\n\"."}

Same issue here! on my linux desktop works fine. Deployed on EKS (alpine) outputs infinitely:

[2019-12-20T20:28:27.137Z] @firebase/database: FIREBASE WARNING: {“code”:“app/invalid-credential”,“message”:“Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: invalid_grant (Invalid issuer: Not a service account.)". There are two likely causes: (1) your server time is not properly synced or (2) your certificate key file has been revoked. To solve (1), re-sync the time on your server. To solve (2), make sure the key ID for your key file is still present at https://console.firebase.google.com/iam-admin/serviceaccounts/project. If not, generate a new key file at https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk.”}

New key has been generated and works locally just fine but again not when deployed on cloud.

Please, did someone fix this?

I have the exact same problem, for the life of me can’t figure out what’s going on. I tried multiple service account jsons, resetted my project multiple times, rebooted, logged in and out, re set the GOOGLE_APPLICATION_CREDENTIALS variable and even switched OS. I thought it could be a problem with my windows machine since from there i cannot even start the emulator because it says it lacks a refresh token, Error: Failed to parse refresh token file: Error: Refresh token must contain a "client_secret" property.

so i did a clean install of Linux and set up the project. The first time it worked ok after setting the service account, but after reboting the linux machine i have the exact same problem back again. Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".

Here’s my options from the cloud function:

{
    "credential": {
        "credential_": {
            "httpClient": {
                "retry": {
                    "maxRetries": 4,
                    "statusCodes": [
                        503
                    ],
                    "ioErrorCodes": [
                        "ECONNRESET",
                        "ETIMEDOUT"
                    ],
                    "backOffFactor": 0.5,
                    "maxDelayInMillis": 60000
                }
            }
        }
    },
    "databaseURL": "https://REDACTED.firebaseio.com"
}

Initialized with:

admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: 'https://REDACTED.firebaseio.com'
});

Thanks @samtstern , I tried to test it on a completely new project and it works.

  1. Created a new project
  2. init functions
  3. executed the same code

It works fine.

Apart from creating a new project, I deleted and initiated a new functions project, and deployed the same code. This is the error I get:

@firebase/database: FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was not initialized correctly. Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project. 

The old project was created in January this year, is there anything that needs to be done on the console?