4. Security Rules: Firestore & Storage Access Control
Security Rules: The Most Important Feature in Firebase
Security Rules are the primary mechanism for access control in Firebase. They determine who can read and write data in Firestore, Realtime Database, and Storage. Security Rules are written in a custom language that evaluates access based on the authenticated user, the data being accessed, and the current state of the database.
The key insight is that Security Rules are evaluated on the server for every read and write. This means even if someone uses your API key, they can't access data unless the rules allow it. Security Rules are the single source of truth for data access. They protect your data from unauthorized access, ensure data integrity, and enforce business logic. Understanding Security Rules is essential for building secure Firebase applications. Rules are evaluated as boolean expressions — true allows access, false denies it. You can use variables, functions, and conditionals to build complex authorization logic.
The Security Rules Language
Security Rules are written in a custom language that supports variables, functions, and conditionals. The language includes built-in variables like request, resource, and auth. request contains the incoming data and metadata. resource contains the existing data in the database. auth contains the authenticated user's information. The validate function allows you to enforce data structure constraints. The get() and exists() functions allow you to read other documents in the database. Rules are evaluated from top to bottom. The match statement defines which documents the rules apply to. Understanding the language is essential for writing effective Security Rules.
service cloud.firestore {
match /databases/{database}/documents {
// Helper function: Is the user authenticated?
function isAuthenticated() {
return request.auth != null;
}
// Helper function: Is the user the author of the document?
function isAuthor() {
return request.auth.uid == resource.data.authorId;
}
// Match all documents in the 'users' collection
match /users/{userId} {
// Users can read their own profile
allow read: if request.auth.uid == userId;
// Users can update their own profile
allow update: if request.auth.uid == userId;
// Users can create their own profile
allow create: if request.auth.uid == userId;
}
// Match all documents in the 'posts' collection
match /posts/{postId} {
// Anyone can read published posts
allow read: if resource.data.published == true;
// Authors can read all their posts
allow read: if isAuthor();
// Users can create posts as themselves
allow create: if isAuthenticated() && request.auth.uid == request.resource.data.authorId;
// Authors can update their own posts
allow update: if isAuthor();
// Authors can delete their own posts
allow delete: if isAuthor();
}
}
}
Data Validation with Security Rules
Security Rules can validate incoming data to ensure it meets your schema requirements. The request.resource.data object contains the new data being written. You can check fields, types, and values. For example, you can require that a post has a title, that the title is a string, and that it's not empty. Data validation in Security Rules complements client-side validation. It ensures that even if someone bypasses your client code, they can't write invalid data. This is essential for data integrity. Use the validate function for complex validation. Keep rules simple for performance — complex rules take longer to evaluate.
function validatePost() { let data = request.resource.data; return data.title is string && data.title.size() > 0 && data.body is string && data.body.size() > 0 && data.authorId is string && data.published is bool; } function validateUser() { let data = request.resource.data; return data.name is string && data.name.size() > 0 && data.email is string && data.email.size() > 0 && data.email.matches('^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'); } match /posts/{postId} { allow create: if isAuthenticated() && request.auth.uid == request.resource.data.authorId && validatePost(); }
Storage Security Rules
Storage Security Rules control access to files in Firebase Cloud Storage. They work similarly to Firestore rules but apply to files and folders. You can restrict access based on file path, metadata, and authentication. For example, you can allow users to upload files only to their own folder. Storage rules support wildcards for path matching. You can use functions to check file types, sizes, and content types. Storage rules also support metadata validation. Understanding Storage rules is essential for securing user-uploaded files. Always validate file types and sizes to prevent abuse. Use signed URLs for temporary access to private files.
service firebase.storage {
match /b/{bucket}/o {
// Allow users to upload files to their own folder
match /users/{userId}/{allPaths=**} {
allow read, write: if request.auth.uid == userId;
}
// Public files are readable by everyone
match /public/{allPaths=**} {
allow read: if true;
allow write: if request.auth != null;
}
// Validate file uploads
match /uploads/{userId}/{fileName} {
allow write: if request.auth.uid == userId &&
request.resource.size < 5 * 1024 * 1024 && // 5MB limit
(request.resource.contentType.matches('image/.*') ||
request.resource.contentType.matches('application/pdf'));
}
}
}
Testing Security Rules
Testing Security Rules is essential for maintaining security. The Firebase Emulator Suite allows you to test rules locally without affecting production. You can simulate authenticated and unauthenticated requests. The Firestore emulator runs the same rules as production. Integration tests can verify that rules work as expected. Unit tests can test specific rule conditions. The Firebase CLI provides commands for testing rules. Continuous integration can run tests automatically. Testing Security Rules catches issues before they reach production. It also documents your security requirements. Use the emulator suite for development and testing. This is the best way to ensure your rules are correct.
# Start the Firebase Emulator Suite firebase emulators:start # Run security rules tests (JavaScript) npx mocha --require @firebase/rules-unit-testing
Knowledge Check
Ready to test your understanding of 4. Security Rules: Firestore & Storage Access Control?