- Enforce least-privilege access for every collection.
- Prevent cross-user data access and ownership spoofing.
- Restrict writes to expected schema only.
- Lock immutable fields and deny unknown collections by default.
Current firestore.rules now enforces:
userscollection:- Read only by owner (
request.auth.uid == userId). - Create requires exact keys and type checks (
uid,email,username,createdAt). - Update only allows
usernamemutation;uid,email,createdAtare immutable. - Delete denied.
favoritescollection:- Read/delete only for owner (
resource.data.userId == request.auth.uid). - Create requires strict schema (
userId,itemId,type,title,poster,savedAt). typelimited tomovieortv.- Update denied.
metricsandtvMetricscollections:- Public read allowed.
- Create requires strict schema and
count == 1. - Update only allows
countincrement by exactly+1; all other fields immutable. - Delete denied.
- Catch-all deny rule for all undeclared collections.
Use Firebase Emulator Suite to validate allow/deny behavior before deploy:
firebase emulators:start --only firestoreValidation matrix to run manually from app or test scripts:
users:- Owner can create/read/update username.
- Non-owner cannot read or write.
- Owner cannot change
email/uid/createdAt. favorites:- Auth user can create favorite for own
userId. - Auth user cannot create favorite for another
userId. - Non-owner cannot read/delete other user favorite.
metrics/tvMetrics:- Auth user can create metric document with valid fields.
- Update with
count + 1succeeds. - Update changing title/id/searchTerm fails.
- Unauthenticated write fails.
firebase deploy --only firestore:rules
firebase deploy --only firestore:indexesTest file: tests/firestore.rules.test.cjs
Run:
npm run test:firestore-rulesNote: Firestore emulator requires Java installed and available on PATH.
The test suite runs against Firestore emulator and verifies both allow and deny paths for users, favorites, and metrics.
- Add automated Firestore rules tests in CI (
@firebase/rules-unit-testing). - Add Firebase App Check enforcement for abuse resistance.
- Move metrics writes to Cloud Functions if stricter anti-abuse controls are needed.
- Keep OpenAI key only in Firebase Functions secrets (
OPENAI_API_KEY).