Prevent deployment of insecure rules on Firebase or Firestore - firebase

#askfirebase
Is there any solution to prevent deployment of insecure rules ?
Getting notified after 24 hours mite be a little to late!

There is nothing built into Firebase to detect/prevent deploying rules that would be marked as insecure. It's an interesting idea though, so I recommend you file a feature request for it.
If you'd like this feature to catch mistakes by yourself or collaborators on your project, the easiest way to implement this yourself would probably to check the size of the rules file. The default rules are quite small compared to most actual rules, so setting a minimum threshold before you call firebase deploy might be a good quick check.

My proposed solution is to use unit testing for the rules and npm script pre hook in the firebase.json file
"firestore": {
"predeploy":mocha spec --exclude spec/_tools.mjs",
"rules": "firestore.rules"
},
however ....
the hook works but mocha is not available in that context
$ firebase deploy --only firestore:rules
=== Deploying to 'project-v2'...
i deploying firestore
Running command: echo $(pwd) && mocha spec --exclude spec/_tools.mjs
/home/user/project
/bin/sh: 1: mocha: not found
it is strange because echo $(pwd) prints the same result when used in package.json and in firebase.json
PS: could someone explain why mocha is not available in this context ?

Related

How do I deploy Cloud Functions while ignoring existing functions?

Say I have the following four functions in my Firebase projects:
openDoor(europe-west1)
closeDoor(europe-west1)
openWindow(europe-west1)
closeWindow(europe-west1)
Now, these functions live in two separate Node packages, i.e. one that contains openDoor and closeDoor and another one that contains openWindow and closeWindow.
Error
If I try to run firebase deploy from the package with the door functions, the following error will be thrown (in non-interactive mode):
Error: The following functions are found in your project but do not exist in your local source code:
openWindow(europe-west1)
closeWindow(europe-west1)
This is a problem because it will cancel any CD workflow that tries to deploy these functions.
Force delete
There is an option to force-delete any existing functions:
-f, --force delete Cloud Functions missing from the current
working directory without confirmation
However, I want the opposite. I want to keep all existing functions.
Theoretical workaround
There is one workaround that I found would work in theory, which is:
yes N | firebase deploy --interactive
Piping N into the interactive deploy command, which will answer N to the deletion prompt:
The following functions are found in your project but do not exist in your local source code:
openWindow(europe-west1)
closeWindow(europe-west1)
If you are renaming a function or changing its region, it is recommended that you create the new function first before deleting the old one to prevent event loss. For more info, visit https://firebase.google.com/docs/functions/manage-functions#modify
? Would you like to proceed with deletion? Selecting no will continue the rest of the deployments. (y/N)
The problem now is that I am using https://github.com/w9jds/firebase-action to deploy the functions, which means that I need to have a built-in Firebase solution.
You can make use of the new codebases feature in Firebase.
By specifying a codebase in your firebase.json functions configuration, this problem is solved. The Firebase CLI will no longer prompt you to delete other functions as it only considers the functions of the same codebase.
If your firebase.json previously looked like this:
{
"functions": {
"source": "cloud_functions",
"ignore": [...],
"predeploy": [...],
"postdeploy": [...]
}
}
You only need to add "codebase": "<name>" to the config:
{
"functions": {
"source": "cloud_functions",
"codebase": "window",
"ignore": [...],
"predeploy": [...],
"postdeploy": [...]
}
}
The deploy will now look like this:
i functions: updating Node.js 16 function window:openWindow(europe-west1)...
i functions: updating Node.js 16 function window:closeWindow(europe-west1)...
Note that the actual function name does not change, i.e. the function will still only be called openWindow (without the prefix) in the Firebase / Google Cloud Console. So this is basically the perfect solution to the problem.
Alternatively, you can also specify the function names when performing deployment.
firebase deploy --only functions:openDoor,functions:closeDoor

Firebase CLI suddenly ignoring environment variables on Functions deployment

I have a Firebase code project with Functions meant to be deployed to multiple Firebase projects over multiple regions.
I used to set the deployment region like this:
return functions
.region(process.env.REGION)
// ...
and used this command to deploy:
$ REGION=us-central1 firebase deploy --only functions
it worked like a charm until recently. Now it seems to completely ignore REGION=us-central1 even if I export it before I run firebase deploy.
EDIT 2022-06-13 - Possible solution
I changed the code to dump the contents of process.env to a file during deployment. This is what I got:
{
"FIREBASE_CONFIG": "{\"projectId\":\"REDACTED\",\"storageBucket\":\"REDACTED.appspot.com\",\"locationId\":\"us-central\"}",
"GCLOUD_PROJECT": "REDACTED",
"CLOUD_RUNTIME_CONFIG": "{REDACTED}",
"__CF_USER_TEXT_ENCODING": "REDACTED"
}
so definitely is not the same list of variables I have in my local environment.
I could use the locationId from FIREBASE_CONFIG to get the target location, or CLOUD_RUNTIME_CONFIG (it contains the dump of the functions .config() object, so I could set the target there).
I also believe that I could use the .env and .env.{project alias or ID} files and their contents would be available in process.env at deployment time.
As per Osvaldo López's suggestion, here are some other details:
Running on MacOS
No errors are reported
No recent changes to the CLI
Any input would be very welcome! Thanks.

Firebase cannot understand what targets to deploy

When deploying the following hello-world equivalent code I get the error shown in the end:-
$ ls -lR
.:
total 8
-rw-r--r-- 1 hgarg hgarg 3 Aug 29 14:55 firebase.json
drwxr-xr-x 2 hgarg hgarg 4096 Aug 29 11:56 functions
./functions:
total 4
-rw-r--r-- 1 hgarg hgarg 1678 Aug 29 11:56 index.js
firebase.json looks like this:-
{}
and index.json like this:-
'use strict';
const functions = require('firebase-functions');
exports.search = functions.https.onRequest((req, res) => {
if (req.method === 'PUT') {
res.status(403).send('Forbidden!');
}
var category = 'Category';
console.log('Sending category', category);
res.status(200).send(category);
});
But deploying fails:-
$ firebase deploy
Error: Cannot understand what targets to deploy. Check that you specified valid targets if you used the --only or --except flag. Otherwise, check your firebase.json to ensure that your project is initialized for the desired features.
$ firebase deploy --only functions
Error: Cannot understand what targets to deploy. Check that you specified valid targets if you used the --only or --except flag. Otherwise, check your firebase.json to ensure that your project is initialized for the desired features.
it would be better to pre-populate the firebase with the default options. I choose that I wanted to use only hosting the firebase.json should have be created with the default hosting option.
{
"hosting": {
"public": "public"
}
}
or you try run firebase init again.
Faced similar issue. In firebase.json file (in hosting parameter), we have to give the name of directory that we want to deploy (in my case, I was already in the directory, which I wanted to deploy, hence I put "." in hosting specification). It solved the error for me.
{
"hosting": {
"public": ".",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
I was facing this issue when running:
firebase emulators:exec --only firestore 'npm tst'
The problem was that on firebase.json must have a property for the emulator you want. So in my case I added a "firestore": {} on firebase.json and worked.
I faced this problem too because at the beginning of my Firebase project setup, I only initialized the hosting feature. Later on, when I wanted to deploy firestore security rules with the Firebase CLI, my initialization process was not complete for this command to work as expected.
I could not run firebase deploy --only firestore:rules
because my firebase.json file was not initialized with defaults.
Easiest and most adequate way to fix this problem is to run the firebase init command again to setup all features you want to use. You could do it manually but you could miss details that the command line interface can setup for you in the exact way it needs to be for defaults.
Solution:
Run the firebase init command again
...and make sure to initialize every feature you are currently using. Take care not to overwrite important configs if you already have some by carefully reading the Firebase CLI instructions that are asked by the init command.
Firebase reads package.json to read details of the functions target. This file was missing from my project directory, as I had moved files around after doing an init.
Creating a clean directory and doing a firebase init functions inside it created all the required files and folders to get started.
I think you are missing on one of the following things -
a) you should run firebase init outside of the main project where index.html is.
b) select hosting option after running firebase init by pressing SPACE
c) Please give folder name which contain index.html in it.
And your project will be up running.

Firebase cloud function deploy error

irregularly my firebase deployment get stuck at this log:
i functions: updating function [FUNCTION NAME]...
After canceling the deploy and retrying it throws the following error message:
⚠ functions: failed to update function resetBadgeCount
⚠ functions: HTTP Error: 400, An operation on function [FUNCTION NAME]
in region us-central1 in project [PROJECT NAME] is already in progress.
Please try again later.
So it seams like that the deploy got stuck and kept in the pipeline blocking further deploys. After a while it let me deploy the functions normally again.
But is there an explanation for this? Or maybe even a word around?
Go to Google cloud functions console and see if there is red exclamation mark against your function. Then select that particular function and try to delete. once it gets deleted from there, you can deploy again successfully. if it is showing spinner, then wait till it shows red mark.
Try this
You can fix the issue much easier by examining the actual logs using this command to open the log
firebase functions:log
The specific issue will be visible there. I sometimes even had errors as simple as a missing package in package.json
You can temporarily rename your function:
$ firebase deploy --only functions
...
i functions: deleting function onSameDataChanged...
i functions: creating function onSameDataChanged1...
...
✔ functions: all functions deployed successfully!
✔ Deploy complete!
Comment or cut your function
Deploy
Uncomment or paste back the function
Rename the function
Deploy
Rename the function back
Deploy
also you can wait a few minutes and you will get an error with {"code":10,"message":"ABORTED"}, then you can deploy again.
just copy your index.js to some where else and delete function form firebasa function console
firebase init -and overe write all file again
past index.js text again
deploy...
For me it was the node version. Turns out I had the 15.x on my machine and the 12.x on the server. Just updating it solved my upload issue
Make sure you've installed dependencies in the functions directory.
for more information about you function you can go to this page
Set your directory to your project directory \functions then run this command:
npm install -g firebase-tools

Firebase Serve Error

I am new to firebase and am trying to make a simple app that utilizes user authentication. At this point in the project I am trying to run firebase on a local server using CLI commands.
I have set up firebase init and firebase deploy. When I type firebase serve on my project folder i get the response,
"an unexpected error has occurred".
Below i am attaching the contents of my firebase-debug.log file. Any help would be appreciated. Thanks
command requires scopes:
["email","openid","https://www.googleapis.com/auth/cloudplatformprojects.readonly","https://www.googleapis.com/auth/firebase",...
[debug] [2017-06-11T17:09:09.607Z] > authorizing via signed-in user
TypeError: Cannot read property 'public' of undefined
Look in your firebase.json file, which you should have in the directory where you're running firebase serve. It should look something like this:
{
"hosting": {
"public": "app",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
}
}
If it doesn't have that "hosting" key, then you'll get that Cannot read property 'public' of undefined error because firebase serve tries to access .hosting.public.
I faced this issue today, I ran it with --debug and found out that I've installed npm/node as sudo user, running following:
firebase serve
was giving me this error:
Error: An unexpected error has occurred.
When I ran it with sudo, I was able to deploy hosting and functions locally:
sudo firebase serve --debug --only hosting,functions
1) create a folder called "public" and put your files inside.
2) edit the firebase.json and just write this:
{
"hosting": {
"public": "public"
}
}
This appears to be a bug - that ideally should be resolved with Firebase Init. I have logged a support ticket with Firebase, and would encourage others to do so as well.
I think you may have skipped an initialization step by accident (I did the same thing on my first run-through)
Try this (from your same project directory):
1) firebase init
2) When prompted for which services you'll need make sure that Database AND Hosting options have their markers highlighted green (tab to Hosting with the spacebar). It's easy to select just database and let it run its configuration and assume it configures all of the bulleted options below it if you do not watch closely because the stdout info isn't very clear. Now hit Enter
3) Accept the default database settings as you probably did before, and when asked "What do you want to use as your public directory? (public)", hit Enter.
At this point you should be good to go spin up a local firebase web server...
4) try 'firebase serve', hit Enter, and you should get a verification that hosting files are being served from /public
Hope this helps. Good luck.
As for me the error is (--debug attr)
Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/firebase-tools/node_modules/#google-cloud/functions-emulator/logs'
So the solution will be to run with sudo

Resources