In this tutorial, we will be writing unit tests for Firebase Security Rules. These rules are crucial for protecting your Firebase Cloud Firestore, Firebase Realtime Database, and Cloud Storage in your web application.
By the end of this tutorial, you will have learned how to write, run, and debug unit tests for Firebase Security Rules using the Firebase Emulator Suite and the Firebase Security Rules unit testing API.
Prerequisites:
- Basic knowledge of JavaScript and Firebase
- Node.js and npm installed on your machine
- A Firebase project set up on the Firebase console
Firebase Security Rules are written in a custom, JSON-like language. They provide granular, attribute-based access control to your Firebase services.
To write unit tests for these rules, we will use Firebase's local emulator suite, which includes Firestore and the Rules testing API.
Step 1: Install the Firebase CLI and initialize your project by running the following commands in your terminal:
npm install -g firebase-tools
firebase init
Step 2: To start the emulator suite, run:
firebase emulators:start
This will allow you to run your tests locally.
Step 3: Install the @firebase/rules-unit-testing
module to write and run unit tests against your security rules. Run:
npm install --save-dev @firebase/rules-unit-testing
Step 4: Write your unit tests. Create a file named rules.test.js
and use the @firebase/rules-unit-testing
module to write your tests.
Best practices when writing unit tests include:
- Always test both positive (the rule allows the operation) and negative (the rule denies the operation) cases.
- Test all important sub-paths. For example, if you have a rule that applies to /users/{userId}
, test the rule with multiple different userId
s.
Let's say our Firestore database has a collection users
where each document's ID is the user's ID, and each document has a field email
.
If we want to write a rule that only allows a user to read their own document, our rule might look like this:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read: if request.auth.uid == userId;
}
}
}
And a simple unit test for this rule would look like:
const { assertFails, assertSucceeds } = require('@firebase/rules-unit-testing');
describe("users collection rules", () => {
it("Allow read if user is reading their own data", async () => {
const db = getFirestoreWithAuth({ uid: "user1" });
const doc = db.collection("users").doc("user1");
await assertSucceeds(doc.get());
});
it("Do not allow read if user is reading someone else's data", async () => {
const db = getFirestoreWithAuth({ uid: "user1" });
const doc = db.collection("users").doc("user2");
await assertFails(doc.get());
});
});
In these tests, getFirestoreWithAuth
is a helper function that returns a Firestore client authenticated with the given auth object.
In this tutorial, you've learned how to write, run, and debug unit tests for Firebase Security Rules. This process is important for ensuring the security of your Firebase web application.
Next, you might want to learn more about advanced Firebase Security Rules concepts, such as using functions and custom claims. Check out the Firebase Security Rules documentation for more details.
Write a rule that allows write access to a posts
collection only if the user is authenticated. Write tests to confirm your rule works as expected.
Write a rule that allows a user to delete a document in a comments
collection only if they are the author of that comment (the authorId
field in the document matches their user ID). Write tests to confirm your rule works as expected.
Write a rule that allows read access to a privateMessages
document only if the recipients
array field in the document contains the user's ID. Write tests to confirm your rule works as expected.
As you're working on these exercises, remember to always test both positive and negative cases. Happy testing!