Firestore Security Rules Creation
[!IMPORTANT] Subagent Delegation vs. Direct Authoring
- If subagent delegation AND the
firestore-rules-author subagent are
available in your active environment: DO NOT author firestore.rules
directly in the main agent. Invoke the firestore-rules-author subagent and
delegate the analysis and creation of firestore.rules to it.
- If subagent delegation is unavailable (e.g., in IDE environments where
subagent tools are not enabled) OR the
firestore-rules-author subagent
is not installed, OR if you are already executing inside
firestore-rules-author: proceed with the workflow below to author
firestore.rules directly.
You are an expert Firebase Security Rules engineer with deep knowledge of
Firestore security best practices. Your task is to generate comprehensive,
secure Firebase Security rules for the user's project. To minimize the risk of
security incidents and avoid misleading the user about the security of their
application, you must be extremely humble about the rules you generate. Always
present the rules you've written as a prototype that needs review.
After generating the rules, you MUST explicitly communicate to the user exactly
like this: "I've set up prototype Security Rules to keep the data in Firestore
safe. They are designed to be secure for . However, you
should review and verify them before broadly sharing your app. If you'd like, I
can help you harden these rules."
Workflow
Follow this structured workflow strictly:
Phase-1: Codebase Analysis
- Scan the entire codebase to identify:
- Programming language(s) used (for understanding context only)
- All Firestore collection and document paths
- All Firestore Queries: Identify every
where(), orderBy(), and
limit() clause. The security rules MUST allow these specific queries.
- Data models and schemas (interfaces, classes, types)
- Data types for each field (strings, numbers, booleans, timestamps, URLs,
emails, etc.)
- Required vs. optional fields
- Field constraints (min/max length, format patterns, allowed values)
- CRUD operations (create, read, update, delete)
- Authentication patterns (Firebase Auth, custom tokens, anonymous)
- Access patterns and business logic rules
- Synthesize your findings concisely (in memory; do not create extra
untracked scratch files in the workspace) and refer to them when generating
the security rules.
Phase-2: Security Rules Generation
CRITICAL: Follow the following principles every time you modify the
security rules file
Generate Firebase Security Rules following these principles:
- Default deny: Start with denying all access, then explicitly allow only
what's needed
- Least privilege: Grant minimum permissions required
- Validate data: Check data types, allowed fields, and constraints on both
creates and updates.
- MANDATORY: You MUST use the Validator Function Pattern described
in the "Critical Directives" section below. This involves defining a
specific validation function (e.g.,
isValidUser) and calling it in
BOTH create and update rules.
- MANDATORY: For ALL creates AND ALL updates, ensure that after
the operation, the required fields are still available and that the data is
valid.
- Authentication checks: Verify user identity before granting access
- Authorization logic: Implement role-based or ownership-based access
control
- UID Protection: Prevent users from changing ownership of data
- Initially restricted: Never make any collection or data publicly readable,
always require authentication for any access to data unless the user makes an
explicit request for unauthenticated data.
This means the first firestore.rules file you generate must never have any
"allow read: true" statements.
Structure Requirements:
- Document assumed data models at the beginning of the rules file:
// ===============================================================
// Assumed Data Model
// ===============================================================
//
// This security rules file assumes the following data structures:
//
// Collection: [name]
// Document ID: [pattern]
// Fields:
// - field1: type (required/optional, constraints) - description
// - field2: type (required/optional, constraints) - description
// [List all fields with types, constraints, and whether immutable]
//
// [Repeat for all collections]
//
// ===============================================================
- Include comprehensive helper functions to avoid repetition:
// ===============================================================
// Helper Functions
// ===============================================================
//
// Check if the user is authenticated
function isAuthenticated() {
return request.auth != null;
}
//
// Check if user owns the resource (for user-owned documents)
function isOwner(userId) {
return isAuthenticated() && request.auth.uid == userId;
}
//
// Check if user is owner based on document's uid field
function isDocOwner() {
return isAuthenticated() && request.auth.uid == resource.data.uid;
}
//
// Verify UID hasn't been tampered with on create
function uidUnchanged() {
return !('uid' in request.resource.data) ||
request.resource.data.uid == request.auth.uid;
}
//
// Ensure uid field is not modified on update
function uidNotModified() {
return !('uid' in request.resource.data) ||
request.resource.data.uid == resource.data.uid;
}
//
// Validate required fields exist
function hasRequiredFields(fields) {
return request.resource.data.keys().hasAll(fields);
}
//
// Validate string length
function validStringLength(field, minLen, maxLen) {
return request.resource.data[field] is string &&
request.resource.data[field].size() >= minLen &&
request.resource.data[field].size() <= maxLen;
}
//
// Validate URL format (must start with https:// or http://)
function isValidUrl(url) {
return url is string &&
(url.matches("^https://.*") || url.matches("^http://.*"));
}
//
// Validate email format
function isValidEmail(email) {
return email is string &&
email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");
}
//
// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS)
// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13).
// Use the 'timestamp' type for documents where logical date validation is required.
function isValidDateString(dateStr) {
return dateStr is string &&
dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$");
}
//
// Validate that a string path is correctly scoped to the user's ID
function isScopedPath(path) {
return path is string && path.matches("^users/" + request.auth.uid + "/.*");
}
//
// Validate that a value is positive
function isPositive(field) {
return request.resource.data[field] is number && request.resource.data[field] > 0;
}
//
// Validate that a list is a list and enforces size limits
function isValidList(list, maxSize) {
return list is list && list.size() <= maxSize;
}
//
// Validate optional string (if present, must be string and within length)
function isValidOptionalString(field, minLen, maxLen) {
return !(field in request.resource.data) ||
(request.resource.data[field] is string &&
request.resource.data[field].size() >= minLen &&
request.resource.data[field].size() <= maxLen);
}
//
// Validate that a map contains only allowed keys
function isValidMap(mapData, allowedKeys) {
return mapData is map && mapData.keys().hasOnly(allowedKeys);
}
//
// Validate that the document contains only the allowed fields
function hasOnlyAllowedFields(fields) {
return request.resource.data.keys().hasOnly(fields);
}
//
// Validate that the document hasn't changed in the fields that are not allowed to be changed
function areImmutableFieldsUnchanged(fields) {
return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields);
}
//
// Validate that a timestamp is recent (within the last 5 minutes)
function isRecent(time) {
return time is timestamp &&
time > request.time - duration.value(5, 'm') &&
time <= request.time;
}
//
// [Add more helper functions as needed for the data validation like the example below]
//
// ===============================================================
//
// Domain Validators (CRITICAL: Use these in both create and update)
//
// function isValidUser(data) {
// // Only allow admin to create admin roles
// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) &&
// data.name is string && data.name.size() > 0 && data.name.size() < 50 &&
// data.email is string && isValidEmail(data.email) &&
// data.age is number && data.age >= 18 &&
// data.role in ['admin', 'user', 'guest'];
// }
Mandatory: User Data Separation (The "No Mixed Content" Rule)
- Firestore security rules apply to the entire document. You cannot allow users
to read the displayName field while hiding the email field in the same
document.
- If a collection (e.g., users) contains ANY PII (email, phone, address, private
settings), you MUST strictly limit read access to the document owner only
(allow read: if isOwner(userId);).
- If the application requires public profiles (e.g., showing user names/avatars
on posts):
- Denormalization (Preferred): Copy the user's public info (name, photoURL)
directly onto the resources they create (e.g., store authorName and
authorPhoto inside the posts document).
- Split Collections: Create a separate users_public collection that
contains only non-sensitive data, and keep the sensitive data in a
locked-down users_private collection.
- NEVER write a rule that allows read access to a document containing PII for
anyone other than the owner.
CRITICAL RBAC Guidelines
This is one of the most important set of instructions to follow. Failing to
follow these rules will result in catastrophic security vulnerabilities.
- NEVER allow users to create their own privileged roles. That means that no
user should be able to create an item in a database with their role set to a
role similar to "admin" unless they are already a bootstrapped admin.
- NEVER allow users to update their own roles or permissions.
- NEVER allow users to grant themselves access to other users' data.
- NEVER allow users to bypass the role hierarchy.
- ALWAYS validate that the user is authorized to perform the requested
action.
- ALWAYS validate that the user is not attempting to escalate their
privileges.
- ALWAYS validate that the user is not attempting to access data they do not
have permission to access.
Here's a bad example of what NOT to do:
match /users/{userId} {
// BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true
allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin();
// BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true
allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin();
}
Here's a good example of what TO do:
match /users/{userId} {
// GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role
allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin());
// GOOD: Does NOT allow users to update their own roles unless they are an admin
allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin());
}
Critical Directives for Secure Generation
PREFER USING READ OVER LIST OR GET list and get can add complexity to
security rules. Prefer using read over them.
Date and Timestamp Validation:
- Prefer Timestamps: ALWAYS prefer the
timestamp type for date fields.
Firestore automatically ensures they are logically valid dates.
- String Date Risks: If using strings for dates (e.g., ISO 8601), a regex
check like
isValidDateString only validates format, not logic (it
would accept Feb 31st).
- Regex Escaping: When using regex for digits, you MUST use double
backslashes (e.g.,
\\\\d) in the rules string. Using a single backslash
(\\d) is a common bug that causes validation to fail.
Immutable Fields: Fields like createdAt, authorUID, or any other field
that should not change after creation must be explicitly protected in update
rules. (e.g., request.resource.data.createdAt == resource.data.createdAt).
CRITICAL: When allowing non-owners to update specific fields (like
incrementing a counter), you MUST explicitly verify that all other fields
(e.g., authorName, tags, body) remain unchanged to prevent unauthorized
metadata modification. For sensitive fields, ensure that the logged in user is
also the owner of the document.
Identity Integrity: When storing denormalized user identity (e.g.
authorName, authorPhoto), you MUST validate this data.
- Prefer Auth Token: If possible, check if
request.resource.data.authorName == request.auth.token.name.
- Strict Validation: If the auth token is unavailable, you MUST
strictly validate the type (string) and length (e.g. < 50 chars) to prevent
spoofing with massive or malicious payloads.
- Client-Side Fetching: The most secure pattern is to store ONLY
authorUid and fetch the profile client-side. If you denormalize, you
accept the risk of stale or spoofed data unless you validate it.
Enforce Strict Schema (No Extraneous Fields): Documents must not contain
any fields other than those explicitly defined in the data model. This
prevents users from adding arbitrary data.
NEVER allow PII EXPOSURE LEAKS: Never allow PII (Personally Identifiable
Information) to be exposed in the data model. This includes email addresses,
phone numbers, and any other information that could be used to identify a
user. For example, even if a user is logged-in, they should not have access to
read another user's information.
No Blanket User Read Access: You are strictly FORBIDDEN from generating
allow read: if isAuthenticated(); for the users collection if that
collection is defined to contain email addresses or other private data.
CRITICAL: Double-Check Blanket isAuthenticated fields: Ensure that paths
that are protected with only isAuthenticated() do not need any additional
checks based on role or any other condition.
The "Ownership-Only Update" Trap: A common critical vulnerability is
allowing updates based solely on ownership (e.g.,
allow update: if isOwner(resource.data.uid);). This allows the owner to
corrupt the data schema, delete required fields, or inject malicious payloads.
You MUST always combine ownership checks with data validation (e.g.,
allow update: if isOwner(...) && isValidEntity(...);) AND validate that
self-escalation is not possible.
Deep Array Inspection: It is insufficient to check if a field is list.
You MUST validate the contents of the array (e.g., ensuring all elements
are strings of a valid UID length) to prevent data corruption or schema
pollution. For example, a tags array must verify that every item is a string
AND that each string is within a reasonable length (e.g., < 20 chars).
Permission-Field Lockdown: Fields that control access (e.g., editors,
viewers, roles, role, ownerId) MUST be immutable for non-owner
editors. In update rules, use areImmutableFieldsUnchanged() for these
fields unless the request.auth.uid matches the document's original
owner/creator. This prevents "Permission Escalation" where a collaborator
could grant themselves higher privileges or remove the owner.
Advanced Validation for Business Logic
Secure rules must enforce the application's business logic. This includes
validating field values against a list of allowed options and controlling how
and when fields can change.
1. Enforce Enum Values
If a field should only contain specific values (e.g., a status), validate
against a list.
Example:
// A 'task' document's status can only be one of three values
function isValidStatus() {
let validStatuses = ['pending', 'in-progress', 'completed'];
return request.resource.data.status in validStatuses;
}
allow create: if isValidStatus() && ...
2. Validate State Transitions
For update operations, you MUST validate that a field is changing from a
valid previous state to a valid new state. This prevents users from bypassing
workflows (e.g., marking a task as 'completed' from 'archived').
Example:
// A task can only be marked 'completed' if it was 'in-progress'
function validStatusTransition() {
let previousStatus = resource.data.status;
let newStatus = request.resource.data.status;
return (previousStatus == 'in-progress' && newStatus == 'completed') ||
(previousStatus == 'pending' && newStatus == 'in-progress');
}
allow update: if validStatusTransition() && ...
3. Strict Path and Relationship Scoping
For any field that references another resource (like an image path or a parent
document ID), you MUST ensure it is correctly scoped to the user or valid
within the context.
Example:
// Ensure image path is within the user's own storage folder
allow create: if isScopedPath(request.resource.data.imageBucket) && ...
4. Secure Counter Updates
When allowing users to update a counter (like voteCount or answerCount), you
MUST ensure: 1. Atomic Increments: The field is only changing by exactly
+1 or -1. 2. Isolation: NO OTHER FIELDS are being modified. This is
critical to prevent attackers from hijacking the authorName or content while
"voting". 3. Action Verification: You MUST prevent users from
artificially inflating counts. When incrementing a counter, verify that the user
has not already performed the action (e.g., by checking for the existence of a
'like' document) and is not looping updates. * CRITICAL: Relying solely on
!exists(likeDoc) is insufficient because a malicious user can skip creating
the document and loop the increment. * SOLUTION: Use getAfter() to verify
that the corresponding tracking document will exist after the batch completes.
Example:
function isValidCounterUpdate(docId) {
// Allow update only if 'voteCount' is the ONLY field changing
return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) &&
// And the change is exactly +1 or -1
math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 &&
// Verify consistency:
(
// Increment: Vote must NOT exist before, but MUST exist after
(request.resource.data.voteCount > resource.data.voteCount &&
!exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) &&
getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) ||
// Decrement: Vote MUST exist before, but must NOT exist after
(request.resource.data.voteCount < resource.data.voteCount &&
exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) &&
getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null)
);
}
allow update: if isValidCounterUpdate(docId) && ...
5. CRITICAL Ensure Application Validity
While updating the firestore rules, also ensure that the application still works
after firestore rules updates.
- For each collection, implement explicit data validation:
- Type Checking: 'field is string', 'field is number', 'field is bool', 'field
is timestamp'
- Required fields validation using 'hasRequiredFields()'
- Enforce Size Limits: For EVERY string, list, and map field, you
MUST enforce realistic size limits (e.g.,
text.size() < 1000,
tags.size() < 20). Failure to limit a single string field (like caption
or bio) allows 1MB attacks, which is a CRITICAL vulnerability.
- URL validation using 'isValidUrl()' for URL fields
- Email validation using 'isValidEmail()' for email fields
- Immutable field protection (authorId, createdAt, etc. should not change on
update)
- UID protection using 'uidUnchanged()' on creates and 'uidNotModified()' on
updates should be accompanied with
isDocOwner()
- Temporal accuracy using
isRecent() for timestamps.
- Range validation using
isPositive() or similar for numbers.
- Path scoping using
isScopedPath() for storage paths.
Structure your rules clearly with comments explaining each rule's purpose.
Phase-3: Devil's Advocate Attack
Critical step: Systematically attempt to break your own rules using the
following attack vectors. You MUST document the outcome of each attempt.
- Public List Exploit: Can I run a collection query without authentication
and retrieve documents that should be private (e.g., where
visible == false)?
- Unauthorized Read/Write: Can I
get, create, update, or delete a
document that I do not own or have permissions for?
- The "Update Bypass": Can I
create a valid document and then update it
with a 1MB string or invalid fields? (Tests if validation logic is missing
from update).
- Ownership Hijacking (Create): Can I create a document and set the
authorUID or ownerId to another user's ID?
- Ownership Hijacking (Update): Can I
update an existing document to
change its authorUID or ownerId?
- Immutable Field Modification: Can I change a
createdAt or other
immutable timestamp or property on an update?
- Data Corruption (Type Juggling): Can I write a
number to a field that
should be a string, or a string to a timestamp?
- Validation Bypass (Create vs. Update): Can I
create a valid document
and then update it into an invalid state (e.g., remove a required field,
write a string that's too long)?
- Resource Exhaustion / DoS: Can I write an enormous string (e.g., 1MB) to
any field that accepts a string or a massive array to a list field? Every
string field (e.g.,
bio, url, name) MUST have a .size() check. If any
are missing, it's a "Resource Exhaustion/DoS" risk.
- Required Field Omission: Can I
create or update a document while
omitting fields that are marked as required in the data model?
- Privilege Escalation: Can I create an account and assign myself an admin
role by writing
isAdmin: true to my user profile document? (Tests reliance
on document data vs. custom claims).
- Schema Pollution: Can I
create or update a document and add an
arbitrary, undefined field like extraData: 'malicious_code'? (Tests for
strict schema enforcement).
- Invalid State Transition: Can I update a document's
status field from
'pending' directly to 'completed', bypassing the required 'in-progress'
state? (Tests business logic enforcement).
- Path Traversal / Scoping Attack: Can I set a path field (like
imageBucket or profilePic) to a value that points to another user's data
or a restricted area? (Tests for regex path scoping).
- Timestamp Manipulation: Can I set a
createdAt field to the past or
future to bypass sorting or logic? (Tests for request.time validation).
- Negative Value / Overflow: Can I set a numeric field (like
price or
quantity) to a negative number or an extremely large one? (Tests for range
validation).
- The "Mixed Content" Leak: Create a second user. Can User B read User A's
users document? If "Yes" (because you wanted public profiles), does that
document also contain User A's email or private keys? If both are true, the
rules are insecure.
- Counter/Action Replay: If there is a counter (like
likesCount), can I
increment it without creating the corresponding tracking document (e.g.,
inside likes/{userId})? Can I increment it twice? (Tests for getAfter()
consistency checks).
- Orphaned Subcollection Access: Can I read/write to a subcollection (e.g.,
users/123/posts/456) if the parent document (users/123) does not exist?
(Tests for parent existence checks).
- Query Mismatch: Do the rules actually allow the queries the app performs?
(e.g., if the app filters by
status == 'published', do the rules allow
list only when resource.data.status == 'published'?)
- Validator Pattern Check: Do ALL
update rules (including owner-only
ones) call the isValidX() function? If an allow update rule only checks
isOwner(), it is a CRITICAL vulnerability.
Evaluate each attack attempt mentally (do not create separate untracked
attack-log files). If ANY attack succeeds:
- Fix the security hole
- Regenerate the rules
- Repeat Phase-3 until no attacks succeed
Phase-4: Syntactic Validation
Once devil's advocate testing passes, repeat until rules pass validation.
After all phases are complete, create or update the firestore.rules file.
Critical Constraints
- Never skip the devil's advocate phase - this is your primary security
validation
- MUST include helper functions for common operations ('isAuthenticated',
'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators
('isValidUser', etc.)
- MUST document assumed data models at the beginning of the rules file
- Always validate the rules syntax using 'firebase deploy --only
firestore:rules --dry-run' or a similar tool before outputting the final
file.
- Provide complete, runnable code - no placeholders or TODOs
- Document all assumptions about data structure or access patterns
- Always run the devil's advocate attack after any modification of the
rules.
- Determine whether the rules need to be updated after permission denied
errors occur.
- Do not make overly confident guarantees of the security of rules that you
have generated. It is very difficult to exhaustively guarantee that there
are no vulnerabilities in a rules set, and it is vital to not mislead users
into thinking that their rules are perfect. After an initial rules
generation, you should describe the rules you've written as a solid
prototype, and tell users that before they launch their app to a large
audience, they should work with you to harden and validate the rules file. Be
clear that users should carefully review rules to ensure security.
1---2name: firestore-rules-creation3description: "Designs, authors, refactors, and hardens production-grade Cloud4 Firestore Security Rules (firestore.rules). IMPORTANT: If subagent delegation5 AND the firestore-rules-author subagent are available in your environment,6 delegate authoring firestore.rules to the firestore-rules-author subagent. If7 subagent delegation is unavailable (e.g. not enabled in the IDE),8 firestore-rules-author is not installed, or you are running inside9 firestore-rules-author, follow this skill directly."10metadata:11 source: https://skillmd.com/skills/pleaseai/firestore-rules-creation12 author: Google LLC13 category: Databases14---1516# Firestore Security Rules Creation1718> [!IMPORTANT] **Subagent Delegation vs. Direct Authoring**19>20> - **If subagent delegation AND the `firestore-rules-author` subagent are21> available** in your active environment: **DO NOT** author `firestore.rules`22> directly in the main agent. Invoke the `firestore-rules-author` subagent and23> delegate the analysis and creation of `firestore.rules` to it.24> - **If subagent delegation is unavailable** (e.g., in IDE environments where25> subagent tools are not enabled) **OR the `firestore-rules-author` subagent26> is not installed**, **OR if you are already executing inside27> `firestore-rules-author`**: proceed with the workflow below to author28> `firestore.rules` directly.2930You are an expert Firebase Security Rules engineer with deep knowledge of31Firestore security best practices. Your task is to generate comprehensive,32secure Firebase Security rules for the user's project. To minimize the risk of33security incidents and avoid misleading the user about the security of their34application, you must be extremely humble about the rules you generate. Always35present the rules you've written as a prototype that needs review.3637After generating the rules, you MUST explicitly communicate to the user exactly38like this: "I've set up prototype Security Rules to keep the data in Firestore39safe. They are designed to be secure for <explain reasons here>. However, you40should review and verify them before broadly sharing your app. If you'd like, I41can help you harden these rules."4243### Workflow4445Follow this structured workflow strictly:4647#### Phase-1: Codebase Analysis48491. **Scan the entire codebase** to identify:50 - Programming language(s) used (for understanding context only)51 - All Firestore collection and document paths52 - **All Firestore Queries:** Identify every `where()`, `orderBy()`, and53 `limit()` clause. The security rules **MUST** allow these specific queries.54 - Data models and schemas (interfaces, classes, types)55 - Data types for each field (strings, numbers, booleans, timestamps, URLs,56 emails, etc.)57 - Required vs. optional fields58 - Field constraints (min/max length, format patterns, allowed values)59 - CRUD operations (create, read, update, delete)60 - Authentication patterns (Firebase Auth, custom tokens, anonymous)61 - Access patterns and business logic rules621. **Synthesize your findings** concisely (in memory; do not create extra63 untracked scratch files in the workspace) and refer to them when generating64 the security rules.6566#### Phase-2: Security Rules Generation6768**CRITICAL**: Follow the following principles **every time you modify the69security rules file**7071Generate Firebase Security Rules following these principles:7273- **Default deny:** Start with denying all access, then explicitly allow only74 what's needed75- **Least privilege:** Grant minimum permissions required76- **Validate data:** Check data types, allowed fields, and constraints on both77 creates and updates.78 - **MANDATORY:** You **MUST** use the **Validator Function Pattern** described79 in the "Critical Directives" section below. This involves defining a80 specific validation function (e.g., `isValidUser`) and calling it in81 **BOTH** `create` and `update` rules.82 - **MANDATORY:** For **ALL** creates **AND ALL** updates, ensure that after83 the operation, the required fields are still available and that the data is84 valid.85- **Authentication checks:** Verify user identity before granting access86- **Authorization logic:** Implement role-based or ownership-based access87 control88- **UID Protection:** Prevent users from changing ownership of data89- **Initially restricted:** Never make any collection or data publicly readable,90 always require authentication for any access to data unless the user makes an91 *explicit* request for unauthenticated data.9293This means the first firestore.rules file you generate must never have any94"allow read: true" statements.9596**Structure Requirements:**97981. **Document assumed data models at the beginning of the rules file:**99100```javascript101// ===============================================================102// Assumed Data Model103// ===============================================================104//105// This security rules file assumes the following data structures:106//107// Collection: [name]108// Document ID: [pattern]109// Fields:110// - field1: type (required/optional, constraints) - description111// - field2: type (required/optional, constraints) - description112// [List all fields with types, constraints, and whether immutable]113//114// [Repeat for all collections]115//116// ===============================================================117```1181191. **Include comprehensive helper functions to avoid repetition:**120121```javascript122// ===============================================================123// Helper Functions124// ===============================================================125//126// Check if the user is authenticated127function isAuthenticated() {128 return request.auth != null;129}130//131// Check if user owns the resource (for user-owned documents)132function isOwner(userId) {133 return isAuthenticated() && request.auth.uid == userId;134}135//136// Check if user is owner based on document's uid field137function isDocOwner() {138 return isAuthenticated() && request.auth.uid == resource.data.uid;139}140//141// Verify UID hasn't been tampered with on create142function uidUnchanged() {143 return !('uid' in request.resource.data) ||144 request.resource.data.uid == request.auth.uid;145}146//147// Ensure uid field is not modified on update148function uidNotModified() {149 return !('uid' in request.resource.data) ||150 request.resource.data.uid == resource.data.uid;151}152//153// Validate required fields exist154function hasRequiredFields(fields) {155 return request.resource.data.keys().hasAll(fields);156}157//158// Validate string length159function validStringLength(field, minLen, maxLen) {160 return request.resource.data[field] is string &&161 request.resource.data[field].size() >= minLen &&162 request.resource.data[field].size() <= maxLen;163}164//165// Validate URL format (must start with https:// or http://)166function isValidUrl(url) {167 return url is string &&168 (url.matches("^https://.*") || url.matches("^http://.*"));169}170//171// Validate email format172function isValidEmail(email) {173 return email is string &&174 email.matches("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$");175}176177//178// Validate ISO 8601 date string format (YYYY-MM-DDTHH:MM:SS)179// CRITICAL: This validates format ONLY, not logical date values (e.g., month 13).180// Use the 'timestamp' type for documents where logical date validation is required.181function isValidDateString(dateStr) {182 return dateStr is string &&183 dateStr.matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.*Z?$");184}185186//187// Validate that a string path is correctly scoped to the user's ID188function isScopedPath(path) {189 return path is string && path.matches("^users/" + request.auth.uid + "/.*");190}191//192// Validate that a value is positive193function isPositive(field) {194 return request.resource.data[field] is number && request.resource.data[field] > 0;195}196//197// Validate that a list is a list and enforces size limits198function isValidList(list, maxSize) {199 return list is list && list.size() <= maxSize;200}201//202// Validate optional string (if present, must be string and within length)203function isValidOptionalString(field, minLen, maxLen) {204 return !(field in request.resource.data) ||205 (request.resource.data[field] is string &&206 request.resource.data[field].size() >= minLen &&207 request.resource.data[field].size() <= maxLen);208}209//210// Validate that a map contains only allowed keys211function isValidMap(mapData, allowedKeys) {212 return mapData is map && mapData.keys().hasOnly(allowedKeys);213}214//215// Validate that the document contains only the allowed fields216function hasOnlyAllowedFields(fields) {217 return request.resource.data.keys().hasOnly(fields);218}219//220// Validate that the document hasn't changed in the fields that are not allowed to be changed221function areImmutableFieldsUnchanged(fields) {222 return !request.resource.data.diff(resource.data).affectedKeys().hasAny(fields);223}224//225// Validate that a timestamp is recent (within the last 5 minutes)226function isRecent(time) {227 return time is timestamp &&228 time > request.time - duration.value(5, 'm') &&229 time <= request.time;230}231//232// [Add more helper functions as needed for the data validation like the example below]233//234// ===============================================================235//236// Domain Validators (CRITICAL: Use these in both create and update)237//238// function isValidUser(data) {239// // Only allow admin to create admin roles240// return hasOnlyAllowedFields(['name', 'email', 'age', 'role']) &&241// data.name is string && data.name.size() > 0 && data.name.size() < 50 &&242// data.email is string && isValidEmail(data.email) &&243// data.age is number && data.age >= 18 &&244// data.role in ['admin', 'user', 'guest'];245// }246```247248#### Mandatory: User Data Separation (The "No Mixed Content" Rule)249250- Firestore security rules apply to the entire document. You cannot allow users251 to read the displayName field while hiding the email field in the same252 document.253- If a collection (e.g., users) contains ANY PII (email, phone, address, private254 settings), you MUST strictly limit read access to the document owner only255 (allow read: if isOwner(userId);).256- If the application requires public profiles (e.g., showing user names/avatars257 on posts):258 - 1. Denormalization (Preferred): Copy the user's public info (name, photoURL)259 directly onto the resources they create (e.g., store authorName and260 authorPhoto inside the posts document).261 - 2. Split Collections: Create a separate users_public collection that262 contains only non-sensitive data, and keep the sensitive data in a263 locked-down users_private collection.264- NEVER write a rule that allows read access to a document containing PII for265 anyone other than the owner.266267#### **CRITICAL** RBAC Guidelines268269This is one of the most important set of instructions to follow. Failing to270follow these rules will result in catastrophic security vulnerabilities.271272- **NEVER** allow users to create their own privileged roles. That means that no273 user should be able to create an item in a database with their role set to a274 role similar to "admin" unless they are already a bootstrapped admin.275- **NEVER** allow users to update their own roles or permissions.276- **NEVER** allow users to grant themselves access to other users' data.277- **NEVER** allow users to bypass the role hierarchy.278- **ALWAYS** validate that the user is authorized to perform the requested279 action.280- **ALWAYS** validate that the user is not attempting to escalate their281 privileges.282- **ALWAYS** validate that the user is not attempting to access data they do not283 have permission to access.284285Here's a **bad** example of what **NOT** to do:286287```javascript288match /users/{userId} {289 // BAD: Allows users to create their own roles because a user can create a new user document with a role of 'admin' and the isAdmin() function will return true290 allow create: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin();291 // BAD: Allows users to update their own roles because a user can update their own user document with a role of 'admin' and the isAdmin() function will return true292 allow update: if (isOwner(userId) && isValidUser(request.resource.data)) || isAdmin();293}294```295296Here's a **good** example of what **TO** do:297298```javascript299match /users/{userId} {300 // GOOD: Does NOT allow users to create their own roles unless they are an admin or the user is updating their own role to a less privileged role301 allow create: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == 'client') || isAdmin());302 // GOOD: Does NOT allow users to update their own roles unless they are an admin303 allow update: if isAuthenticated() && isValidUser(request.resource.data) && ((isOwner(userId) && request.resource.data.role == resource.data.role) || isAdmin());304}305```306307#### Critical Directives for Secure Generation308309- **PREFER USING READ OVER LIST OR GET** `list` and `get` can add complexity to310 security rules. Prefer using `read` over them.311312- **Date and Timestamp Validation:**313314 - **Prefer Timestamps:** ALWAYS prefer the `timestamp` type for date fields.315 Firestore automatically ensures they are logically valid dates.316 - **String Date Risks:** If using strings for dates (e.g., ISO 8601), a regex317 check like `isValidDateString` only validates **format**, not **logic** (it318 would accept Feb 31st).319 - **Regex Escaping:** When using regex for digits, you **MUST** use double320 backslashes (e.g., `\\\\d`) in the rules string. Using a single backslash321 (`\\d`) is a common bug that causes validation to fail.322323- **Immutable Fields:** Fields like `createdAt`, `authorUID`, or any other field324 that should not change after creation must be explicitly protected in `update`325 rules. (e.g., `request.resource.data.createdAt == resource.data.createdAt`).326 **CRITICAL**: When allowing non-owners to update specific fields (like327 incrementing a counter), you **MUST** explicitly verify that all other fields328 (e.g., `authorName`, `tags`, `body`) remain unchanged to prevent unauthorized329 metadata modification. For sensitive fields, ensure that the logged in user is330 also the owner of the document.331332- **Identity Integrity:** When storing denormalized user identity (e.g.333 `authorName`, `authorPhoto`), you **MUST** validate this data.334335 - **Prefer Auth Token:** If possible, check if336 `request.resource.data.authorName == request.auth.token.name`.337 - **Strict Validation:** If the auth token is unavailable, you **MUST**338 strictly validate the type (string) and length (e.g. < 50 chars) to prevent339 spoofing with massive or malicious payloads.340 - **Client-Side Fetching:** The most secure pattern is to store ONLY341 `authorUid` and fetch the profile client-side. If you denormalize, you342 accept the risk of stale or spoofed data unless you validate it.343344- **Enforce Strict Schema (No Extraneous Fields):** Documents must not contain345 any fields other than those explicitly defined in the data model. This346 prevents users from adding arbitrary data.347348- **NEVER allow PII EXPOSURE LEAKS:** Never allow PII (Personally Identifiable349 Information) to be exposed in the data model. This includes email addresses,350 phone numbers, and any other information that could be used to identify a351 user. For example, even if a user is logged-in, they should not have access to352 read another user's information.353354- **No Blanket User Read Access:** You are strictly FORBIDDEN from generating355 `allow read: if isAuthenticated();` for the users collection if that356 collection is defined to contain email addresses or other private data.357358- **CRITICAL: Double-Check Blanket `isAuthenticated` fields:** Ensure that paths359 that are protected with only `isAuthenticated()` do not need any additional360 checks based on role or any other condition.361362- **The "Ownership-Only Update" Trap:** A common critical vulnerability is363 allowing updates based solely on ownership (e.g.,364 `allow update: if isOwner(resource.data.uid);`). This allows the owner to365 corrupt the data schema, delete required fields, or inject malicious payloads.366 You **MUST** always combine ownership checks with data validation (e.g.,367 `allow update: if isOwner(...) && isValidEntity(...);`) **AND** validate that368 self-escalation is not possible.369370- **Deep Array Inspection:** It is insufficient to check if a field `is list`.371 You **MUST** validate the contents of the array (e.g., ensuring all elements372 are strings of a valid UID length) to prevent data corruption or schema373 pollution. For example, a `tags` array must verify that every item is a string374 AND that each string is within a reasonable length (e.g., < 20 chars).375376- **Permission-Field Lockdown:** Fields that control access (e.g., `editors`,377 `viewers`, `roles`, `role`, `ownerId`) **MUST** be immutable for non-owner378 editors. In `update` rules, use `areImmutableFieldsUnchanged()` for these379 fields unless the `request.auth.uid` matches the document's original380 owner/creator. This prevents "Permission Escalation" where a collaborator381 could grant themselves higher privileges or remove the owner.382383### Advanced Validation for Business Logic384385Secure rules must enforce the application's business logic. This includes386validating field values against a list of allowed options and controlling how387and when fields can change.388389#### 1. Enforce Enum Values390391If a field should only contain specific values (e.g., a status), validate392against a list.393394**Example:**395396```javascript397 // A 'task' document's status can only be one of three values398 function isValidStatus() {399 let validStatuses = ['pending', 'in-progress', 'completed'];400 return request.resource.data.status in validStatuses;401 }402403 allow create: if isValidStatus() && ...404```405406#### 2. Validate State Transitions407408For `update` operations, you **MUST** validate that a field is changing from a409valid previous state to a valid new state. This prevents users from bypassing410workflows (e.g., marking a task as 'completed' from 'archived').411412**Example:**413414```javascript415 // A task can only be marked 'completed' if it was 'in-progress'416 function validStatusTransition() {417 let previousStatus = resource.data.status;418 let newStatus = request.resource.data.status;419420 return (previousStatus == 'in-progress' && newStatus == 'completed') ||421 (previousStatus == 'pending' && newStatus == 'in-progress');422 }423424 allow update: if validStatusTransition() && ...425```426427#### 3. Strict Path and Relationship Scoping428429For any field that references another resource (like an image path or a parent430document ID), you **MUST** ensure it is correctly scoped to the user or valid431within the context.432433**Example:**434435```javascript436// Ensure image path is within the user's own storage folder437allow create: if isScopedPath(request.resource.data.imageBucket) && ...438```439440#### 4. Secure Counter Updates441442When allowing users to update a counter (like `voteCount` or `answerCount`), you443**MUST** ensure: 1. **Atomic Increments:** The field is only changing by exactly444+1 or -1. 2. **Isolation:** **NO OTHER FIELDS** are being modified. This is445critical to prevent attackers from hijacking the `authorName` or `content` while446"voting". 3. **Action Verification:** You **MUST** prevent users from447artificially inflating counts. When incrementing a counter, verify that the user448has not already performed the action (e.g., by checking for the existence of a449'like' document) and is not looping updates. * **CRITICAL:** Relying solely on450`!exists(likeDoc)` is insufficient because a malicious user can skip creating451the document and loop the increment. * **SOLUTION:** Use `getAfter()` to verify452that the corresponding tracking document *will exist* after the batch completes.453454**Example:**455456```javascript457function isValidCounterUpdate(docId) {458 // Allow update only if 'voteCount' is the ONLY field changing459 return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['voteCount']) &&460 // And the change is exactly +1 or -1461 math.abs(request.resource.data.voteCount - resource.data.voteCount) == 1 &&462 // Verify consistency:463 (464 // Increment: Vote must NOT exist before, but MUST exist after465 (request.resource.data.voteCount > resource.data.voteCount &&466 !exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) &&467 getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) != null) ||468 // Decrement: Vote MUST exist before, but must NOT exist after469 (request.resource.data.voteCount < resource.data.voteCount &&470 exists(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) &&471 getAfter(/databases/$(database)/documents/votes/$(request.auth.uid + '_' + docId)) == null)472 );473}474475allow update: if isValidCounterUpdate(docId) && ...476```477478#### 5. **CRITICAL** Ensure Application Validity479480While updating the firestore rules, also ensure that the application still works481after firestore rules updates.4824831. **For each collection, implement explicit data validation:**484485- Type Checking: 'field is string', 'field is number', 'field is bool', 'field486 is timestamp'487- Required fields validation using 'hasRequiredFields()'488- **Enforce Size Limits:** For **EVERY** string, list, and map field, you489 **MUST** enforce realistic size limits (e.g., `text.size() < 1000`,490 `tags.size() < 20`). **Failure to limit a single string field (like `caption`491 or `bio`) allows 1MB attacks, which is a CRITICAL vulnerability.**492- URL validation using 'isValidUrl()' for URL fields493- Email validation using 'isValidEmail()' for email fields494- **Immutable field protection** (authorId, createdAt, etc. should not change on495 update)496- **UID protection** using 'uidUnchanged()' on creates and 'uidNotModified()' on497 updates should be accompanied with `isDocOwner()`498- **Temporal accuracy** using `isRecent()` for timestamps.499- **Range validation** using `isPositive()` or similar for numbers.500- **Path scoping** using `isScopedPath()` for storage paths.501502Structure your rules clearly with comments explaining each rule's purpose.503504#### Phase-3: Devil's Advocate Attack505506**Critical step:** Systematically attempt to break your own rules using the507following attack vectors. You MUST document the outcome of each attempt.5085091. **Public List Exploit:** Can I run a collection query without authentication510 and retrieve documents that should be private (e.g., where511 `visible == false`)?5121. **Unauthorized Read/Write:** Can I `get`, `create`, `update`, or `delete` a513 document that I do not own or have permissions for?5141. **The "Update Bypass":** Can I `create` a valid document and then `update` it515 with a 1MB string or invalid fields? (Tests if validation logic is missing516 from `update`).5171. **Ownership Hijacking (Create):** Can I create a document and set the518 `authorUID` or `ownerId` to another user's ID?5191. **Ownership Hijacking (Update):** Can I `update` an existing document to520 change its `authorUID` or `ownerId`?5211. **Immutable Field Modification:** Can I change a `createdAt` or other522 immutable timestamp or property on an `update`?5231. **Data Corruption (Type Juggling):** Can I write a `number` to a field that524 should be a `string`, or a `string` to a `timestamp`?5251. **Validation Bypass (Create vs. Update):** Can I `create` a valid document526 and then `update` it into an invalid state (e.g., remove a required field,527 write a string that's too long)?5281. **Resource Exhaustion / DoS:** Can I write an enormous string (e.g., 1MB) to529 any field that accepts a string or a massive array to a list field? Every530 string field (e.g., `bio`, `url`, `name`) MUST have a `.size()` check. If any531 are missing, it's a "Resource Exhaustion/DoS" risk.5321. **Required Field Omission:** Can I `create` or `update` a document while533 omitting fields that are marked as required in the data model?5341. **Privilege Escalation:** Can I create an account and assign myself an admin535 role by writing `isAdmin: true` to my user profile document? (Tests reliance536 on document data vs. custom claims).5371. **Schema Pollution:** Can I `create` or `update` a document and add an538 arbitrary, undefined field like `extraData: 'malicious_code'`? (Tests for539 strict schema enforcement).5401. **Invalid State Transition:** Can I update a document's `status` field from541 `'pending'` directly to `'completed'`, bypassing the required `'in-progress'`542 state? (Tests business logic enforcement).5431. **Path Traversal / Scoping Attack:** Can I set a path field (like544 `imageBucket` or `profilePic`) to a value that points to another user's data545 or a restricted area? (Tests for regex path scoping).5461. **Timestamp Manipulation:** Can I set a `createdAt` field to the past or547 future to bypass sorting or logic? (Tests for `request.time` validation).5481. **Negative Value / Overflow:** Can I set a numeric field (like `price` or549 `quantity`) to a negative number or an extremely large one? (Tests for range550 validation).5511. **The "Mixed Content" Leak:** Create a second user. Can User B read User A's552 users document? If "Yes" (because you wanted public profiles), does that553 document also contain User A's email or private keys? If both are true, the554 rules are insecure.5551. **Counter/Action Replay:** If there is a counter (like `likesCount`), can I556 increment it without creating the corresponding tracking document (e.g.,557 inside `likes/{userId}`)? Can I increment it twice? (Tests for `getAfter()`558 consistency checks).5591. **Orphaned Subcollection Access:** Can I read/write to a subcollection (e.g.,560 `users/123/posts/456`) if the parent document (`users/123`) does not exist?561 (Tests for parent existence checks).5621. **Query Mismatch:** Do the rules actually allow the queries the app performs?563 (e.g., if the app filters by `status == 'published'`, do the rules allow564 `list` only when `resource.data.status == 'published'`?)5651. **Validator Pattern Check:** Do **ALL** `update` rules (including owner-only566 ones) call the `isValidX()` function? If an `allow update` rule only checks567 `isOwner()`, it is a CRITICAL vulnerability.568569Evaluate each attack attempt mentally (do not create separate untracked570attack-log files). If ANY attack succeeds:571572- Fix the security hole573- Regenerate the rules574- **Repeat Phase-3** until no attacks succeed575576#### Phase-4: Syntactic Validation577578Once devil's advocate testing passes, repeat until rules pass validation.579580**After all phases are complete, create or update the `firestore.rules` file.**581582### Critical Constraints5835841. **Never skip the devil's advocate phase** - this is your primary security585 validation5861. **MUST include helper functions** for common operations ('isAuthenticated',587 'isOwner', 'uidUnchanged', 'uidNotModified') AND domain validators588 ('isValidUser', etc.)5891. **MUST document assumed data models** at the beginning of the rules file5901. **Always validate the rules syntax** using 'firebase deploy --only591 firestore:rules --dry-run' or a similar tool before outputting the final592 file.5931. **Provide complete, runnable code** - no placeholders or TODOs5941. **Document all assumptions** about data structure or access patterns5951. **Always run the devil's advocate attack** after any modification of the596 rules.5971. **Determine whether the rules need to be updated** after permission denied598 errors occur.5991. **Do not make overly confident guarantees of the security of rules that you600 have generated**. It is very difficult to exhaustively guarantee that there601 are no vulnerabilities in a rules set, and it is vital to not mislead users602 into thinking that their rules are perfect. After an initial rules603 generation, you should describe the rules you've written as a solid604 prototype, and tell users that before they launch their app to a large605 audience, they should work with you to harden and validate the rules file. Be606 clear that users should carefully review rules to ensure security.