Firebase tools login from command line - firebase

I'm using Codeship to deploy a firebase app.
In order to do so, I first need to login using the firebase login command. Problem is, I need to login in the browser and then return to the command line and perform the deployment.
Is there an automated way to supply credentials to Firebase?
Cheers

firebase login --no-localhost is what worked for me. You get the Authorisation code from browser which you need to paste into your terminal window.

The accepted answer is correct for the old version of firebase-tools, however this has been deprecated as of version 3. The new command to get the token is:
firebase login:ci
You should save this in some kind of environment variable, ideally, FIREBASE_TOKEN.
Then, with any command you intend to run via ci (i.e. deploy), you can run:
firebase [command] --token [FIREBASE_TOKEN]

See wvm2008's answer for a more up to date version
One option would be to mint a token for the build server and pass it into the CLI with:
firebase --token <token>
You can also get a token from a system where you interactively logged in with:
firebase login:ci
See this page for more options.

Answer: Environmental Variables.
Specifically, using a machine with a browser and firebase tools installed, run firebase login:ci --no-localhost and paste the resulting key from the firebase CLI tool into an Environmental Variable and name it FIREBASE_TOKEN (not $FIREBASE_TOKEN).
In your deployment, say
npm install -g firebase-tools
firebase deploy
Done. If you care about Why? Read on.
The firebase/firebase-tools repo README indicates the following regarding Usage with CI Systems.
The Firebase CLI requires a browser to complete authentication, but is
fully compatible with CI and other headless environments.
On a machine with a browser, install the Firebase CLI. Run firebase
login:ci to log in and print out a new access token (the current CLI
session will not be affected).
NOTE: You actually want to type firebase login:ci --no-localhost
Store the output token in a secure but accessible way in your CI
system. There are two ways to use this token when running Firebase
commands:
Store the token as the environment variable FIREBASE_TOKEN and it will
automatically be utilized. Run all commands with the --token <token>
flag in your CI system.
👉 NOTE: You MUST put your token in quotes IIF using the --token flag
🔥 👉BIGGER NOTE Do NOT prefix your environment variable with $ or you will get a nonsensical error message below!!!
Your CLI authentication needs to be updated to take advantage of new features.
Please run firebase login --reauth
Error: Command requires authentication, please run firebase login
The order of precedence for token loading is flag, environment
variable, active project.
đź‘Ś Recommendation is to use Environmental Variable so the secret token is not stored/visible in the logs.

Related

What causes typescript compile error when deploying

I roughly following this tutorial to make a cloud function with typescript. It works fine in development, but when I try to deploy it (firebase deploy --only functions), I get A LOT of typescript errors. I have no idea why. It works in dev, why can't I push the same set up to Firebase?
Follow the below steps for a successful cloud functions deployment:
After you have created a Firebase project using this step, install
the Firebase CLI using : npm install -g firebase-tools.
Run firebase login to log in via the browser and authenticate the
firebase tool.
Run firebase init firestore
Run firebase init functions
When you run firebase init functions, there will be prompts, 1st
prompt : “What language would you like to use to write Cloud
Functions?” -> Choose Typescript. 2nd prompt : Do you want to use
ESlint to catch probable bugs and enforce style (y/n)? -> Choose n.
By selecting no you will be saving yourself from the typescript
compile errors.
Once initialization is complete, uncomment the sample in index.ts and
run npm run serve to see a "Hello World" function in action. Once you
can see the output in Firebase emulator, you will know the functions
executed properly.
Now, before you deploy the functions, assign the Cloud Functions
Invoker, Cloud Functions Admin and Cloud Functions Developer role to
project-id#appspot.gserviceaccount.com
Now run firebase deploy –only functions. The deployment will be
successful but the browser might show 403 errors ( Client does not
have permission..) For that, select your cloud function (check box)
click "Add members" under the Permissions tab in the right side,
enter "allUsers" under "New members", select Role as Cloud Functions -> Cloud Functions Invoker and then save the configuration.
If you do not want to give public access to your cloud functions, you
can set up authentication, by skipping the previous step. In Cloud
Shell, run gcloud auth print-identity-token. This outputs a token
which you will be authenticating your cloud function with. Now
provide authentication credentials in your request as a
Google-generated ID token stored in an Authorization header with this
command :
curl https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME \ -H "Authorization: bearer $(gcloud auth print-identity-token)"

Error: Could not load the default credentials. context: firebase login:ci AND firebase auth:export

Disclaimer: There are lots of similar questions mentioning the same error message but I read many and none of them pertained to my context.
I am trying to automate exporting the Firebase Authentication database using the command firebase --debug auth:export. The command executes flawlessly on my local machine. But when I try to run it on CI it fails with the following error message:
[2021-04-27T20:48:23.188Z] > 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"]
[2021-04-27T20:48:26.208Z] Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
at GoogleAuth.getApplicationDefaultAsync (/home/node/.npm-global/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 (/home/node/.npm-global/lib/node_modules/firebase-tools/node_modules/google-auth-library/build/src/auth/googleauth.js:502:17)
at async GoogleAuth.getAccessToken (/home/node/.npm-global/lib/node_modules/firebase-tools/node_modules/google-auth-library/build/src/auth/googleauth.js:524:24)
Error: An unexpected error has occurred.
I am trying to run this command in a Gitlab Scheduled Pipeline using a .gitlab-ci.yml file. For that to work I understand I need to authenticate using the firebase login:ci command. I did that and I know the token is valid because other firebase commands in my .gitlab-ci.yml work, for instance firebase use and firebase deploy.
Here is a simplified version of my .gitlab-ci.yml:
stages:
- stg_backups
jb_auth_backup:
stage: stg_backups
image: devillex/docker-firebase
only:
- schedules
script:
- firebase use --token $MY_CI_FIREBASE_DEPLOY_KEY $MY_FIREBASE_PROJECT
- mkdir backups
- firebase --debug auth:export backups/my-auth-backup.json --format=JSON
artifacts:
paths:
- backups
The environment variables are set correctly as Gitlab Project variables.
I have tried refreshing my firebase authentication token but that didn't work. I have tried reading about the error message in posts like the following, but since they talk about Google Cloud Platform service accounts, I am not sure how or if that's related to firebase authentication tokens.
Error Error: Could not load the default credentials
Could not load the default credentials? (Node.js Google Compute Engine tutorial)
Error: Could not load the default credentials (Firebase function to firestore)
I have also analyzed the permissions assigned to the role my Google user has. My Google user has "Owner" in the IAM. I found another role in the IAM that seems relevant: "Firebase Authentication Admin". That role has 15 permissions I confirmed "Owner" also has these permissions:
firebase.clients.get
firebase.clients.list
firebase.projects.get
firebaseauth.configs.create
firebaseauth.configs.get
firebaseauth.configs.getHashConfig
firebaseauth.configs.update
firebaseauth.users.create
firebaseauth.users.createSession
firebaseauth.users.delete
firebaseauth.users.get
firebaseauth.users.sendEmail
firebaseauth.users.update
resourcemanager.projects.get
resourcemanager.projects.list
However, the error message says it "requires scopes". Are "scopes" and "permissions" different? I haven't seen any documentation about "scopes" in the IAM documentation. So I'm not sure if I'm looking at the right documentation.
Does anyone know how to run firebase --debug auth:export from Gitlab Scheduled Pipeline?
As implied by the Firebase CLI reference section "Use the CLI with CI systems", the --token <token> should be passed to every firebase command:
Use this token when running firebase commands. You can use either of
the following two options:
Store the token as the environment variable FIREBASE_TOKEN. Your
system will automatically use the token.
Run all firebase commands with the --token flag in your CI
system. The order of precedence for token loading is flag, environment
variable, desired Firebase project.
Although --token <token> is passed to the firebase use command in the .gitlab-ci.yml script, it is not being passed to the firebase auth:export command. Don't assume that firebase use saves not only the active project selection but also the token. According to firebase help use, its only purpose is to "set an active Firebase project for your working directory". It says nothing about setting an active token.
I have confirmed the following .gitlab-ci.yml script does, in fact, export the Firebase authentication database successfully:
stages:
- stg_backups
jb_auth_backup:
stage: stg_backups
image: devillex/docker-firebase
only:
- schedules
script:
- firebase --token $MY_CI_FIREBASE_DEPLOY_KEY use $MY_FIREBASE_PROJECT
- mkdir backups
- firebase --token $MY_CI_FIREBASE_DEPLOY_KEY auth:export backups/my-auth-backup.json --format=JSON
artifacts:
paths:
- backups
Note that the syntax of both the firebase use and firebase auth:export commands have been changed from the original .gitlab-ci.yml. They now both put the --token <token> right after the firebase executable command. This adheres better to the documented syntax according to firebase help. There it says the correct syntax is firebase [options] [command] where --token is one of the options. 
In fact, it's not even clear whether firebase use --token <my_token> <my_project> even paid any attention to the token since it's after instead of before the use command. It's too bad firebase use --token doesn't just throw an error to let the user know that --token belongs to the [options] for firebase not the [options] for use.

Login to firebase using gcloud service account

I have functions deployed to gcloud functions and i want to configure CI/CD for deploying this functions from gitlab.
To do any operations from gitlab i need to get firebase auth token with
firebase login:ci
command.
The problem is that i need to get this token using gcloud service account, which is not displayed in browser, when i run
firebase login:ci
I have this service account data (project_id, private_key, private_key_id, etc.)
How should i authorize using this acc?
If you set an environment variable called GOOGLE_APPLICATION_CREDENTIALS as a path pointing to your service account JSON file, the Firebase CLI will automatically pick that up and use it to authorize commands. You don't need to be logged in or provide a --token argument when this is the case.
If anyone finds this and is wondering how to do it on CircleCI, this worked for me.
Generate a json file key for you service account in the GCP Console
Set the json to a CircleCI environment variable at the org level or the project level
We use one at the org level called GSA_KEY
In your workflow config, before you run the firebase command, run this command:
echo echo $GSA_KEY > "$HOME"/gcloud.json
Then run your firebase deploy command, first setting the path to GOOGLE_APPLICATION_CREDENTIALS
The deployment run looks like:
steps:
- checkout
- run:
name: Create SA key JSON
command: echo $GSA_KEY > "$HOME"/gcloud.json
- run:
name: Deploy to Firebase
command:
GOOGLE_APPLICATION_CREDENTIALS="$HOME"/gcloud.json firebase deploy [project specific stuff]
Use command:
gcloud auth activate-service-account xyz#project-id.iam.gserviceaccount.com --key-file=/path/to/file.json --project=project-id
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/file.json"
in Bash
run the following commands 1 and 2 in order
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/file.json"
"/path/to/file.json" -- the location of the file where the service account json file is saved.
npx firebase-tools deploy --json
Do not forget to use the right project when deploying like
firebase use dev or
firebase use qa
This is what worked for me:
Added the environment variable GOOGLE_APPLICATION_CREDENTIALS=/path/to/service-account.json
firebase deploy --non-interactive # needed to bypass any prompts that might stall out a CI script.
You can also set the value of the Environment variable to be the JSON in the key file.

How can I get firebase deploy --email or --token parameters to work?

I'm having trouble deploying travis CI with firebase using these firebase commands:
firebase deploy --email ${FIREBASE_USERNAME} --password ${FIREBASE_PASSWORD}
firebase deploy --token ${FIREBASE_TOKEN}
It does not like --email option and it does seem that it takes --token but does not work with my firebase auth token I can get from my firebase app. What am I doing wrong?
The email option was removed in the 2.0 release of the CLI.
Use firebase login:ci to generate a token.
On a machine with a browser, install the Firebase CLI.
Run firebase
login:ci to log in and print out a new access token (the current CLI
session will not be affected).
Store the output token in a secure but accessible way in your CI system.
Another firebase deployment option in travis-ci is to use dpl (https://github.com/travis-ci/dpl) which is a deployment provider
OPTIONS
token: Your Firebase CI Access Token (generated from firebase login:ci)
project: Deloy to a different Firebase Project than specified in firebase.json
public: Specifies which directory to upload to Firebase Hosting.
ignore: Specifies the files to ignore on deploy. (similar to .gitignore)
EXAMPLE
dpl --provider=firebase --token=<token> --project=<project>
What is really cool about using this deployment provider utility is that you can deploy to one or more firebase hosted applications from a single project commit...
after_script:
- dpl --provider=firebase --token=${FIREBASE_TOKEN} --project=${PROJECT_ONE}
- dpl --provider=firebase --token=${FIREBASE_TOKEN} --project=${PROJECT_TWO}
References:
(firebase.json) https://www.firebase.com/docs/hosting/guide/full-config.html
(dpl --provider=firebase) https://github.com/travis-ci/dpl#firebase
Note: One thing you will need to consider is how you set FIREBASE_URL as a constant in each hosted application if they need to use the same code base but a separate Firebase for storing data.

Firebase CLI Authentication through token

I followed the steps described in the official GitHub tutorial for use the Firebase CLI (Command Line) with a CI system (simple OS without browser integrate). I use my PC to login in firebase and get the token (from the browser procedure). I copied the token on the other system and I passed the token in all command but it does not work. I get the message that I need to be authenticate for doing these operations:
firebase login
firebase prefs:token
copy and use the token in other system
firebase list --token sdfgfdsg......
What's the problem?
Using a machine with a browser and firebase tools installed, run firebase login:ci --no-localhost and paste the resulting key from the firebase CLI tool into an Environmental Variable and name it FIREBASE_TOKEN (not $FIREBASE_TOKEN).
In your deployment, say
npm install -g firebase-tools
firebase deploy
Make sure not to run firebase logout on your PC, as doing so will invalidate the token (we're working on making this clearer now, actually).
If not, make sure that you're quoting the token:
firebase list --token '-K.....|.....'
The characters included in the auth token may cause shell errors that prevent the command from completing properly if it's not quoted.
I was facing the same problem with Travis, and the problem was the encryption of the token used by travis, you have to ensure you have correctly escaped the pipe symbol inside the token.
in my case something like
travis encrypt 'FIREBASE_TOKEN=-jksdjksjksdj\|ksdkjsjk'
Hope this helps, because I can ensure you that if you do:
firebase deploy --token '-jksdjksjksdj|ksdkjsjk'
in Travis it just works.
firebase is not recognizing the token in your case for some reason, you need to find that reason
Check this out:
http://docs.travis-ci.com/user/encryption-keys/

Resources