Firestore Rules Creation
>-
- Skill ID
- firebase/agent-skills/firestore-rules-creation
- Publisher
- firebase
- Repository
- agent-skills
- Installs
- 626
- Files
- 1
- Synced
- Sep 16, 2026
Open any RiverX project, open the Skills panel in the chat, and search for this identifier. The files are fetched from the source repository at install time.
firebase/agent-skills/firestore-rules-creationInstalls these files- SKILL.md
What this skill tells the agent
Firestore Security Rules Creation
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 <explain reasons here>. 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(), andlimit()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
- Document your findings in a untracked file. Refer to this file 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 BOTHcreateandupdaterules. - 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