Pathrule

Firebase and Firestore Production

Pathrule3 Rules • 2 Memories • 1 Skill

Firebase moves authentication, synchronization, and storage close to the client, so correctness depends on a contract that spans Firestore Security Rules, query shapes, indexes, offline retries, server functions, and emulator tests. This pattern constrains deny-by-default rules and server authority, records document and query modeling decisions, separates client retries from trusted side effects, and supplies an emulator-backed release audit. It differs from Supabase RLS because Firestore authorization is evaluated against document reads and query constraints, while offline clients and optimistic local state introduce a different consistency model.

Suggested path map

Pathrule places each piece on the matching path, so your assistant only sees it where it belongs. This is the scoping you get on import; you can adjust it in your workspace.

/ workspace root
verify-firestore-contract
firestore/
Deny access unless rules can prove the entire query safe
Document shape follows read and rule boundaries
functions/
Keep privileged side effects idempotent and server-owned
src/
data/
Model offline writes as pending transitions
Every production query has an index and cost story

Rules

3
Deny access unless rules can prove the entire query safe/firestorehighstrictAuthorize from trusted identity and stored ownership, and shape queries so Firestore can prove every possible result is allowed.
1Firestore evaluates a query against its potential result set, not by filtering unauthorized documents afterward. A rule that secures a document read can still reject a list query whose constraints do not prove the same ownership condition.
2 
3- Start from no access and grant the narrow operation on the narrow match path. Separate create, update, delete, get, and list when their invariants differ.
4- Derive actor identity from authentication context and existing stored data. Never let a client grant itself ownership, role, or tenant membership by writing the field the rule later trusts.
5- Make list queries include the same tenant, owner, visibility, or status constraints the rule requires, then test both allowed and overbroad variants.
6- Validate changed fields and immutable fields explicitly on writes so a user cannot preserve an allowed document path while replacing authorization-critical content.
7 
8See /src/data for the adjacent decision or procedure that completes this constraint.
Keep privileged side effects idempotent and server-owned/functionshighstrictUse trusted functions for secrets and privileged transitions, with event identity or operation keys that make retries harmless.
1Clients can retry writes after reconnect and server functions can redeliver events. A privileged effect that assumes exactly-once execution can send duplicate email, allocate inventory twice, or charge more than once.
2 
3- Move secret-bearing and privilege-escalating operations to a trusted server environment using the Admin SDK only after verifying the caller and target resource.
4- Store a stable operation or event identifier with the side effect and reject or return the prior result when the same identifier is observed again.
5- Write domain state and the idempotency record in the same atomic boundary where the data model permits it; never mark success before the effect is durably represented.
6- Treat function retries, timeouts, and partial failures as normal paths. Log the operation key and final state so an operator can reconcile ambiguity.
7 
8See /firestore for the adjacent decision or procedure that completes this constraint.
Model offline writes as pending transitions/src/datamediumstrictExpose pending, rejected, and confirmed states in the UI instead of treating local acknowledgement as durable server success.
1Firestore can apply a write to the local cache before the server accepts it. The interface must distinguish optimistic local state from a confirmed transition, especially when rules, contention, or connectivity can reject the write later.
2 
3- Represent operations with a stable client-generated identifier and show pending state where the user might otherwise repeat the action.
4- Listen for server acknowledgement or write failure and reconcile the optimistic item by identity rather than appending a second copy.
5- Do not trigger irreversible client-side side effects merely because the local snapshot changed; wait for trusted server state or a server event.
6- Design conflict behavior for reconnect explicitly. Last-write-wins is not acceptable for counters, inventory, balances, or approval workflows without a server-owned transition.
7 
8See /functions for the adjacent decision or procedure that completes this constraint.

Memories

2
Document shape follows read and rule boundaries/firestoreDenormalize for known read paths, but keep authorization-critical facts close enough for rules to verify without client trust.
1Firestore documents are not relational rows, and joins do not appear at query time. The useful design question is which data must be read together and which facts Security Rules must inspect to decide access.
2 
3- Keep a bounded snapshot of display data with a relation when it avoids an extra read, and define how that snapshot is refreshed when the source changes.
4- Duplicate tenant or ownership identifiers where rules and queries need them, but make the trusted server the authority that writes or verifies those fields.
5- Keep documents below practical growth limits by moving unbounded collections, logs, and membership lists into subcollections with their own query strategy.
6- Choose document IDs and collection paths for stable identity, not for mutable presentation values such as names or email addresses.
7 
8See /src/data for the rule or workflow that puts this decision into practice.
Every production query has an index and cost story/src/dataQuery shape, composite indexes, pagination cursor, and expected document reads are reviewed together before a screen ships.
1Firestore pricing and latency follow document reads and index traversal. A query that works on a small emulator dataset can become expensive or require a composite index as filters and ordering are combined.
2 
3- Define filters, ordering, and cursor pagination together; avoid offset pagination that repeatedly reads skipped documents.
4- Commit required index configuration with the application so environments do not depend on a console-created index no one can reproduce.
5- Measure how listeners behave when tabs background, reconnect, or observe high-churn collections; a permanent listener is an ongoing read surface.
6- Use aggregate or maintained summary documents for dashboards that would otherwise scan large collections on every view.
7 
8See /firestore for the rule or workflow that puts this decision into practice.

Skills

1
verify-firestore-contract/rootRun an emulator-backed matrix over rules, queries, offline retries, indexes, and privileged function behavior.
1---
2name: verify-firestore-contract
3description: Verify a Firestore data-contract change before deploying rules, indexes, clients, or functions.
4---
5 
6# Verify Firestore Contract
7 
8Run this procedure when the affected surface changes, before the result is promoted to production. Record evidence for every step instead of accepting a plausible-looking result.
9 
10- [ ] Seed users, tenants, ownership combinations, and documents in the emulator, including stale and malicious client-controlled fields.
11- [ ] Run every operation as owner, member, outsider, unauthenticated caller, and privileged server; include list queries broader than the intended filter.
12- [ ] Execute the exact production query shapes against committed index configuration and confirm cursor pagination returns stable, non-duplicated pages.
13- [ ] Simulate disconnect, local optimistic write, reconnect, and server rejection; confirm the UI reconciles pending state and does not repeat side effects.
14- [ ] Redeliver the same server event and operation key, then prove the function returns the prior outcome without duplicating external or stored effects.
15 
16## Exit criteria
17 
18The change is complete only when the expected behavior, failure behavior, and rollback path have all been exercised with representative data. Preserve the evidence with the change so the next operator can repeat the same checks.

Why this pattern

AI agents often secure individual documents but issue queries the rules cannot prove safe, trust client-written ownership fields, or attach non-idempotent side effects to retried writes.

Built for Web and mobile teams using Firebase Authentication, Cloud Firestore, and server-side functions.

Keeps your assistant from:

  • Writing broad allow rules that trust client-controlled ownership fields
  • Shipping a query that cannot satisfy its Security Rules constraints
  • Charging or emailing twice when an offline write retries
  • Testing production data access without the emulator rule suite
License
Apache-2.0
Version
1.0.0
Updated
2026-08-25
View source