I'm trying to setup a Firebase project on Codeship CI/CD and I cannot seem to get the service credentials JSON key to work with my project when it's stored in an environment variable.
MVCE
Dev environment startup script
export FIREBASE_CREDENTIAL=BASE64ENCODED_credentials_json
export DATABASE_URL=https://my-project.firebaseio.com
echo $FIREBASE_CREDENTIAL | base64 -D > FIREBASE_CREDENTIAL.json
npm start
index.ts
import * as admin from "firebase-admin";
const credentials = require("../FIREBASE_CREDENTIAL.json");
const databaseURL = process.env.DATABASE_URL;
console.log(credentials.project_id); // succeeds
console.log(databaseURL); // is correct
admin.initializeApp({
...credentials,
databaseURL,
databaseAuthVariableOverride: { uid: "scraper" }
});
admin
.database()
.ref("/test")
.set(admin.database.ServerValue.TIMESTAMP);
Codeship script
echo $FIREBASE_CREDENTIAL | base64 -di > FIREBASE_CREDENTIAL.json
nvm install 8
npm install
npm test
Results
On dev machine, the write succeeds as expected
On Codeship CI container, I get this error.
console.warn node_modules/#firebase/logger/dist/index.cjs.js:66
[2018-10-05T12:53:51.316Z] #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: \"Failed to parse access token response: Error: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND\"."}
Related
I followed this tutorial to deploy my web project using firebase and Gitlab CI.
I use this conf to deploy on firebase:
# .gitlab-ci.yml
deploy:
stage: deploy
environment: production
before_script:
- npm i -g firebase-tools
script:
- firebase deploy --token "$FIREBASE_TOKEN" -P "$PROJECT_NAME" --debug
only:
refs:
- master
changes:
- src/**/*
I stored the FIREBASE_TOKEN variable in my GitLab as protected and masked.
But when it's run in the pipeline it failed and return this error message:
$ firebase deploy --token "$FIREBASE_TOKEN" -P "$PROJECT_NAME" --debug
[2020-06-27T21:26:52.339Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
[2020-06-27T21:26:55.356Z] Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/usr/local/lib/node_modules/firebase-tools/node_modules/google-auth-library/build/src/auth/googleauth.js:160:19)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at runNextTicks (internal/process/task_queues.js:66:3)
at listOnTimeout (internal/timers.js:518:9)
at processTimers (internal/timers.js:492:7)
at async GoogleAuth.getClient (/usr/local/lib/node_modules/firebase-tools/node_modules/google-auth-library/build/src/auth/googleauth.js:502:17)
at async GoogleAuth.getAccessToken (/usr/local/lib/node_modules/firebase-tools/node_modules/google-auth-library/build/src/auth/googleauth.js:524:24)
Error: Failed to authenticate, have you run firebase login?
ERROR: Job failed: exit code 1
I don't know why I get:
Failed to authenticate, have you run firebase login?
because I use a token to authenticate using the --token flag.
Have someone an idea why I get this error?
Ok so it was a dummy error. My variable $FIREBASE_TOKEN was not taken into account because I checked the Protect variable (Export variable to pipelines running on protected branches and tags only.) option. But I was working on a feature branch to test it that was not protected.
I encountered the same error, but through GitHub Actions. The solution was to run the command firebase init hosting:github locally, as indicated by the documentation at https://github.com/marketplace/actions/deploy-to-firebase-hosting. After signing in, this will set a GitHub Secret for you in your repository.
The following was taken from the above-mentioned documentation:
"It's important to store this token as an encrypted secret to prevent unintended access to your Firebase project. Set it in the "Secrets" area of your repository settings and add it as FIREBASE_SERVICE_ACCOUNT: https://github.com/USERNAME/REPOSITORY/settings/secrets. "
I already have some firebase cloud functions that runs fine, and now I try to add SendGrid functionality to one of the functions as described in https://youtu.be/JVy0JpCOuNI. The firebase CLI won't run my code because it says it has a TypeError
The code is written in Typescript and the transpiler doesn't give any error. I am using the latest versions of the CLI and the SDK.
admin.initializeApp();
const firebaseConfig = JSON.parse(process.env.FIREBASE_CONFIG);
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
const sgMail = require(‘#sendgrid/mail’);
sgMail.setApiKey(SENDGRID_API_KEY);
I have checked that the firebase config contains the sendgrid key:
$ firebase functions:config:get
{
"sendgrid": {
"key": "MY_SEND_GRID_KEY"
}
}
I get this output when I try to deploy --only functions:
functions: Failed to load functions source code. Ensure that you have the latest SDK by running npm i --save firebase-functions inside the functions directory. :warning: functions: Error from emulator. Error occurred while parsing your function triggers.
TypeError: Cannot read property ‘key’ of undefined
It is this line that has the error:
const SENDGRID_API_KEY = firebaseConfig.sendgrid.key;
What can I change so I don't get this error?
The variables that you set using the CLI via firebase functions:config:get don't end up in process.env.FIREBASE_CONFIG. They end up in functions.config().
import * as functions from 'firebase-functions'
const key = functions.config().sendgrid.key
FIREBASE_CONFIG just determines how the admin SDK should be initialized with no parameters passed to admin.initializeApp().
Please read the documentation for more information.
This is a continuation of troubleshooting this problem and a separate issue related to implementing a suggested solution.
I am attempting to consume Firebase function configuration from a locally-served environment as outlined here but I get an unexpected error.
I create a ".runtimeconfig.json" file within my functions directory containing this:
{
"auth": {
"clientid": MY_CLIENT_ID,
"signoutreturnto": SOME_URL,
"responsetype": SOME_URL,
"redirecturi": SOME_OTHER_URL,
"scope": SOME_OTHER_STRING,
"domain": SOME_DOMAIN
}
}
I execute the following commands from the firebase CLI (within the functions directory):
firebase functions:config:get > .runtimeconfig.json
firebase experimental:functions:shell
I execute my config function via the cli:
config()
I get the following error output in the console:
config()
TypeError: config is not a function
at repl:1:1
at ContextifyScript.Script.runInContext (vm.js:32:29)
at REPLServer.defaultEval (repl.js:341:29)
at bound (domain.js:280:14)
at REPLServer.runBound [as eval] (domain.js:293:12)
at REPLServer.onLine (repl.js:536:10)
at emitOne (events.js:96:13)
at REPLServer.emit (events.js:191:7)
at REPLServer.Interface._onLine (readline.js:241:10)
at REPLServer.Interface._line (readline.js:590:8)
my other functions, bigben & firebaseConfig execute as expected from the CLI
If you want to see your functions config at the the CLI emulator prompt, you should run the emulator command from your functions directory:
$ cd functions
$ firebase experimental:functions:shell
Then, at the firebase prompt, you can access your config like this:
firebase> const functions = require('firebase-functions')
firebase> functions.config()
That should print your config. Normally you don't need to do something like this - you would instead just read the config from inside the emulated function using functions.config().
Are you sure you are on the latest version of firebase-tools? You can update by running 'npm install -g firebase-tools'. You should be on v3.17.4, there was a known bug that was resolved in that version.
I am using Firebase Functions. I set a environment variable by command:
firebase functions:config:set my.token="abcde"
I verified it by command:
firebase functions:config:get
which returns me:
{
"my": {
"token": "abcde"
}
}
in my index.js , I try to get the set token by:
const tok = functions.config().my.token
I would like to test my functions locally instructed by this document, so I run command:
firebase serve --only functions
But it gives me error:
Error from emulator. FirebaseError: Error occurred while parsing your function triggers.
TypeError: Cannot read property 'token' of undefined
Why I can't access the token I set in environment variable of Firebase?
This was a bug in the Firebase CLI that was fixed in version 3.17.4. Please update your firebase-tools module:
npm install -g firebase-tools
Also, don't forget to follow the instructions in the documentation and copy your configs to a local file before running the emulator:
cd functions
firebase functions:config:get > .runtimeconfig.json
I am trying automate Deployment to Firebase Hosting via Wercker and I am continously getting this error.
Following this tutorial
https://medium.com/#pradeep1991singh/integrate-wercker-with-bitbucket-firebase-and-slack-7eb3bc38543d
Stack Trace
> export WERCKER_STEP_ROOT="/pipeline/script-5ea4a2c6-b11f-4972-991a-eec61b3d43af"
export WERCKER_STEP_ID="script-5ea4a2c6-b11f-4972-991a-eec61b3d43af"
export WERCKER_STEP_OWNER="wercker"
export WERCKER_STEP_NAME="script"
export WERCKER_REPORT_NUMBERS_FILE="/report/script-5ea4a2c6-b11f-4972-991a-eec61b3d43af/numbers.ini"
export WERCKER_REPORT_MESSAGE_FILE="/report/script-5ea4a2c6-b11f-4972-991a-eec61b3d43af/message.txt"
export WERCKER_REPORT_ARTIFACTS_DIR="/report/script-5ea4a2c6-b11f-4972-991a-eec61b3d43af/artifacts"
source "/pipeline/script-5ea4a2c6-b11f-4972-991a-eec61b3d43af/run.sh" < /dev/null
[2017-08-15T13:38:45.071Z] ----------------------------------------------------------------------
[2017-08-15T13:38:45.076Z] Command: /usr/local/bin/node /usr/local/bin/firebase deploy --project --token --debug
[2017-08-15T13:38:45.076Z] CLI Version: 3.9.2
[2017-08-15T13:38:45.076Z] Platform: linux
[2017-08-15T13:38:45.076Z] Node Version: v7.10.1
[2017-08-15T13:38:45.077Z] Time: Tue Aug 15 2017 13:38:45 GMT+0000 (UTC)
[2017-08-15T13:38:45.077Z] ----------------------------------------------------------------------
[2017-08-15T13:38:45.091Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase","https://www.googleapis.com/auth/cloud-platform"]
[2017-08-15T13:38:45.091Z] > no authorization credentials were supplied or found
⚠ Your CLI authentication needs to be updated to take advantage of new features.
⚠ Please run firebase login --reauth
[2017-08-15T13:38:45.093Z] > command requires scopes: ["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase"]
[2017-08-15T13:38:45.093Z] > no authorization credentials were supplied or found
The Issue was related to the Wercker.yml file. The Step was not defined properly and it seems the environment variable wasnt getting read properly.
Steps to narrow down the issue
Log out of Fire base on local and then try to perform a firebase list - should get an error
try same with --token passing token and will get a list of all the valid projects if token is valid.
Take the valid Project name and token and then hardcode it in yml and try once to make sure the build executes properly
Finally when all are working , expose as protected variables and everything works like a charm!!.