firestore-rules
Skill0 starsChanged 4 months agoMITView on GitHub
Generate or audit Firestore security rules. Use when the user asks to write Firestore rules for a new collection, review an existing rules file, or find open access patterns like `allow read, write: if true` that expose every document to the public internet.
- Installs packages
In this repository5 other files it gives its agents.
- cloud-run-deploySkill
- gcloud-debugSkill
- gke-manifestSkill
- iam-auditSkill
- terraform-gcpSkill
The file
Show its rules and text
We split this skill into the rules it gives an agent
15 rules. About 0 are common, 9 are distinctive, and 6 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈9
Distinctive · estimate
This author's own choices. Worth a look.
6
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 19
If the mode is missing, detect based on whether a firestore.rules file exists in the working directory.
- Distinctive: line 23
Read the rules file.
- Distinctive: line 24
Use Grep to find patterns that are almost always wrong:
- Very specific: line 36
Use of request.auth.uid == resource.data.userId without also checking the field exists on write with request.resource.data.userId == …
- Very specific: line 47
Test coverage: if the repo has firestore.rules but no firestore.rules.test.ts or similar, note that rules tests are missing and show the …
- Distinctive: line 51
Ask for the data model if it is not given:
- Very specific: line 57
Write firestore.rules following the required structure.
- Very specific: line 58
Write a minimal firestore.rules.test.js using the Firebase rules unit test SDK.
- Distinctive: line 63
Every rules file uses:
- Distinctive: line 194
Run the emulator in one shell:
- Distinctive: line 200
Run tests in another:
- Distinctive: line 223
Do not write rules that rely on client-supplied booleans or strings to grant access.
- Very specific: line 224
Do not mix read and write allows with different conditions into one statement.
- Distinctive: line 225
Do not deploy rules without running the emulator tests first.
- Distinctive: line 226
Do not paste Firestore document contents into the conversation during an audit if they may contain user data.
≈ “Common” is an estimate: at least 1 in 5 of the 213,895 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Generate or audit Firestore security rules
Firestore rules are the only thing between client apps and the database. A missing rule means the default allow in test mode, and a bad rule can expose every document to the internet. Treat this skill's output like production code.
Inputs
$ARGUMENTS has two modes:
generate <description>: create a newfirestore.rulesfile for the described data model.audit <path>: review an existing rules file for common mistakes. Default path isfirestore.rulesat the project root.
If the mode is missing, detect based on whether a firestore.rules file exists in the working directory.
Audit workflow
- Read the rules file.
- Use Grep to find patterns that are almost always wrong:
allow read, write: if true
allow read: if true
allow write: if true
allow read, write;Also flag:
- Any rule that does not call
request.auth != nulland does not check document ownership. - Use of
request.auth.uid == resource.data.userIdwithout also checking the field exists on write withrequest.resource.data.userId == request.auth.uid. - Wildcards at the root (
match /{document=**}) with read or write allowed. allow create: if trueon collections that should require auth.get()calls inside rules without arequest.auth != nullcheck above them.- Custom claims checks that compare to string literals without the
request.auth.tokenprefix.
- For each finding, report:
- The rule file and line.
- The exact risk in one sentence ("any unauthenticated user on the internet can read every order").
- The replacement rule.
- Test coverage: if the repo has
firestore.rulesbut nofirestore.rules.test.tsor similar, note that rules tests are missing and show the minimal setup.
Generate workflow
- Ask for the data model if it is not given:
- Top-level collections and their document id scheme.
- Which collections are user-owned (users can read and write their own docs).
- Which collections are admin-only.
- Which collections are public readable (for example a public profile directory).
- Any custom claims in use (
admin,role).
- Write
firestore.rulesfollowing the required structure. - Write a minimal
firestore.rules.test.jsusing the Firebase rules unit test SDK. - Show the deploy command and the test command.
Required structure
Every rules file uses:
rules_version = '2';on the first line. Version 1 is legacy.- A tight default-deny at the root. No wildcard read or write at the top.
- A helper function for auth and for ownership.
- One
matchblock per collection with explicitallowrules forget,list,create,update, anddelete. Do not combine intoreadandwriteunless the rules are identical for each sub-operation.
Example: user-owned notes plus a public users directory
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth != null;
}
function isOwner(userId) {
return isSignedIn() && request.auth.uid == userId;
}
function isAdmin() {
return isSignedIn() && request.auth.token.admin == true;
}
function hasRequiredFields(required) {
return request.resource.data.keys().hasAll(required);
}
match /users/{userId} {
allow get: if isSignedIn();
allow list: if isSignedIn();
allow create: if isOwner(userId)
&& hasRequiredFields(['displayName', 'createdAt'])
&& request.resource.data.createdAt == request.time;
allow update: if isOwner(userId)
&& request.resource.data.createdAt == resource.data.createdAt;
allow delete: if isAdmin();
}
match /notes/{noteId} {
allow get: if isSignedIn() && resource.data.ownerId == request.auth.uid;
allow list: if isSignedIn();
allow create: if isSignedIn()
&& request.resource.data.ownerId == request.auth.uid
&& hasRequiredFields(['ownerId', 'title', 'body', 'createdAt'])
&& request.resource.data.createdAt == request.time;
allow update: if isSignedIn()
&& resource.data.ownerId == request.auth.uid
&& request.resource.data.ownerId == resource.data.ownerId;
allow delete: if isSignedIn()
&& resource.data.ownerId == request.auth.uid;
}
match /admin/{document=**} {
allow read, write: if isAdmin();
}
}
}Key points in this example:
listonnotesis gated by sign-in but not by ownership, because clients will issue a query likewhere('ownerId', '==', uid). Thegetrule still enforces ownership per document. If your clients issue queries that could return other users' notes, tightenlistor require aownerIdfilter in the query viarequest.query.createpinsownerIdto the caller, requires all needed fields, and forcescreatedAtto server time. This prevents forging another user's document and avoids clock skew.updateforbids changingownerId(no account takeover by rewriting the field).- The admin wildcard is only reachable by admins. It is not a generic escape hatch.
Example: test harness
File firestore.rules.test.js with the Firebase rules unit testing SDK (pin the version):
const {
initializeTestEnvironment,
assertFails,
assertSucceeds,
} = require("@firebase/rules-unit-testing");
const fs = require("fs");
let testEnv;
beforeAll(async () => {
testEnv = await initializeTestEnvironment({
projectId: "demo-firestore-rules",
firestore: {
rules: fs.readFileSync("firestore.rules", "utf8"),
host: "127.0.0.1",
port: 8080,
},
});
});
afterAll(async () => {
await testEnv.cleanup();
});
beforeEach(async () => {
await testEnv.clearFirestore();
});
test("unauthenticated user cannot read notes", async () => {
const db = testEnv.unauthenticatedContext().firestore();
await assertFails(db.doc("notes/n1").get());
});
test("owner can read their own note", async () => {
await testEnv.withSecurityRulesDisabled(async (ctx) => {
await ctx.firestore().doc("notes/n1").set({ ownerId: "alice", title: "t", body: "b", createdAt: new Date() });
});
const db = testEnv.authenticatedContext("alice").firestore();
await assertSucceeds(db.doc("notes/n1").get());
});
test("other user cannot read a note they do not own", async () => {
await testEnv.withSecurityRulesDisabled(async (ctx) => {
await ctx.firestore().doc("notes/n1").set({ ownerId: "alice", title: "t", body: "b", createdAt: new Date() });
});
const db = testEnv.authenticatedContext("bob").firestore();
await assertFails(db.doc("notes/n1").get());
});Install the emulator and test SDK, pinning versions:
npm install --save-dev @firebase/rules-unit-testing@3.0.4 jest@29.7.0Run the emulator in one shell:
firebase emulators:start --only firestoreRun tests in another:
npx jest firestore.rules.test.jsDeploy
firebase deploy --only firestore:rulesCommon audit findings
- Critical:
allow read, write: if true;anywhere. Every document matched by the enclosing match block is world-readable and world-writable. - Critical:
match /{document=**} { allow read, write: if request.auth != null; }. Any authenticated user can read and write any document in the database. Authentication is not authorization. - High:
allow update: if request.auth.uid == resource.data.ownerId;without also checkingrequest.resource.data.ownerId == resource.data.ownerId. An attacker can changeownerIdon update and take over documents. - High:
allow list: if true;on any collection with sensitive fields.listdoes not run per document. It checks the query. - Medium: missing
hasAllchecks on create. Clients can write documents with unexpected fields or omit required fields. - Medium: rules that use
get()to look up another document without arequest.auth != nullguard above them. Unauthenticated traffic can still trigger theget().
Do not
- Do not write rules that rely on client-supplied booleans or strings to grant access.
- Do not mix
readandwriteallows with different conditions into one statement. Split intoget,list,create,update,deletewhen the conditions differ. - Do not deploy rules without running the emulator tests first.
- Do not paste Firestore document contents into the conversation during an audit if they may contain user data.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

