Auth, Security Rules, App Check and Quotas

Article · 6:00

Firebase Auth and custom claims, writing and testing Security Rules properly, App Check, IAM and the Admin SDK bypass, and billing alerts and quotas.

This lesson has 1 runnable example. Press Try yourself! under any of them to open it in the editor.

Your Security Rules are your backend. With a client talking directly to the database, rules are the whole of your authorisation layer, and the mental shift that makes this work is to treat firestore.rules as production code: reviewed, version-controlled, and covered by tests.

Firebase Auth provides identity. In rules, request.auth is null for an anonymous caller and otherwise carries uid and token. Custom claims - set server-side with the Admin SDK - are the right place for roles, because they arrive inside the token and need no document read. Claims are cached in the token until it refreshes (an hour, or on a forced refresh), so a revoked role takes effect late, which is a real limitation to design around.

Writing rules well comes down to a few things:

  • Default deny. Write rules that grant specific access; never leave a allow read, write: if true from the quickstart anywhere.
  • Rules are not filters. A rule cannot say "return only the documents this user may see". If a query could return a document the rules forbid, the whole query fails. So your queries must be shaped so that the rule can be evaluated against the query itself - which is why where("memberIds", "array-contains", request.auth.uid) patterns are so common.
  • get() and exists() cost reads and are limited. You get 10 document access calls per single-document request and 20 per query, and each one is billed. A rule that does a get() on every read doubles your read cost - which is why membership is often denormalised into an array on the document itself.
  • Validate writes, not just authorise them. Rules can enforce required fields, types, immutability, value ranges and that request.auth.uid matches the author. Without that, an authorised user can write any shape they like.
  • Test them. The rules unit testing library with the emulator is the only credible way.

App Check verifies that requests come from your genuine application, not from a script with your (public) config. It is not authorisation - it is anti-abuse, and it is the thing that stops someone pointing a loop at your database because they found your API key in your bundle. Enable it, and note that it has an enforcement-off monitoring mode for rollout.

IAM and the Admin SDK bypass. The Admin SDK ignores Security Rules completely. So anything running with a service account - your Cloud Functions, your backend - must do its own authorisation, and the service account should have the narrowest IAM role that works. A leaked service account key is total compromise of the database with no rule to stop it.

Billing alerts and quotas are a security control, not a finance one. A rules mistake or a function loop can generate enormous cost in hours. Budget alerts tell you; App Check and a quota cap limit the damage. Configure all three before you launch.

Laboratory exercise 6 - make it defensible.

Implement Firebase Auth with at least two roles via custom claims.

Write Security Rules for the capstone enforcing: only room members may read a room's messages; only the author may edit or delete their own message; authorId must equal request.auth.uid on create; createdAt must be the server timestamp; editedAt may be set but createdAt is immutable; and only a room admin may add or remove members.

Write a rules unit test suite covering every rule, positive and negative, and get it running in CI. This is the assessed centre of the module.

Then demonstrate the rules-are-not-filters behaviour: write a query that could return a forbidden document and show the whole query failing, then reshape it so the rule can be evaluated and show it succeeding.

Measure the cost of a get() in a rule: implement membership two ways - a get() on the members subcollection, and a denormalised memberIds array - and compare the read cost of a 50-message listener under each.

Enable App Check in monitoring mode, then enforce it, and show a request from outside your app being rejected.

Configure budget alerts and a quota cap, and document what each would catch.

Deliverable: the rules file, the complete test suite with a passing CI run, the rules-as-filters demonstration, the get() cost comparison with read counts, the App Check evidence, the budget and quota configuration, and a deployment and cost checklist.

JS Example 1 155 lines
// ================= Custom claims: roles in the TOKEN ===============
// Set server-side with the Admin SDK. They arrive inside the token,
// so a rule can read them with NO DOCUMENT READ - which matters,
// because document reads in rules are billed.
//   await getAuth().setCustomUserClaims(uid, { role: "moderator" });
//
// CACHED IN THE TOKEN until it refreshes - an hour, or a forced
// refresh. So A REVOKED ROLE TAKES EFFECT LATE. Design around it:
// for anything that must revoke immediately, check a document instead
// and accept the read.
//   await getIdToken(auth.currentUser, /* forceRefresh */ true);

// ================= SECURITY RULES: your entire backend =============
/*
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {

    // ---- helpers ----
    function isSignedIn() { return request.auth != null; }
    function uid() { return request.auth.uid; }

    // A DOCUMENT READ, billed, and limited to 10 per single-document
    // request / 20 per query. A rule that does this on every read
    // DOUBLES your read cost:
    function isMemberByGet(roomId) {
      return exists(/databases/$(database)/documents/rooms/$(roomId)/members/$(uid()));
    }
    // FREE - the membership is denormalised onto the room, which is
    // already loaded. Prefer this. It is why memberIds exists.
    function isMemberByArray(roomId) {
      return uid() in get(/databases/$(database)/documents/rooms/$(roomId)).data.memberIds;
    }

    match /rooms/{roomId} {
      allow read:   if isSignedIn() && uid() in resource.data.memberIds;
      allow create: if isSignedIn()
                    && request.resource.data.createdBy == uid()
                    && request.resource.data.memberIds == [uid()]
                    && request.resource.data.createdAt == request.time;
      // Only an admin, and the immutable fields stay immutable:
      allow update: if isSignedIn()
                    && uid() in resource.data.adminIds
                    && request.resource.data.createdBy == resource.data.createdBy
                    && request.resource.data.createdAt == resource.data.createdAt;
      allow delete: if isSignedIn() && uid() in resource.data.adminIds;

      match /messages/{messageId} {
        allow read: if isSignedIn() && isMemberByArray(roomId);

        // AUTHORISE *AND* VALIDATE. Without validation an authorised
        // user can write any shape they like.
        allow create: if isSignedIn()
          && isMemberByArray(roomId)
          && request.resource.data.authorId == uid()        // not someone else
          && request.resource.data.createdAt == request.time // the SERVER's time
          && request.resource.data.text is string
          && request.resource.data.text.size() > 0
          && request.resource.data.text.size() <= 4000
          && request.resource.data.keys().hasOnly(
               ['text','authorId','authorName','createdAt','editedAt'])
          && request.resource.data.editedAt == null;

        // Only the author, only the text, and createdAt is immutable:
        allow update: if isSignedIn()
          && resource.data.authorId == uid()
          && request.resource.data.authorId == resource.data.authorId
          && request.resource.data.createdAt == resource.data.createdAt
          && request.resource.data.editedAt == request.time
          && request.resource.data.diff(resource.data)
               .affectedKeys().hasOnly(['text','editedAt']);

        allow delete: if isSignedIn() && (
          resource.data.authorId == uid()
          || uid() in get(/databases/$(database)/documents/rooms/$(roomId)).data.adminIds
        );
      }

      match /members/{memberId} {
        allow read:  if isSignedIn() && isMemberByArray(roomId);
        allow write: if isSignedIn()
          && uid() in get(/databases/$(database)/documents/rooms/$(roomId)).data.adminIds;
      }
    }

    // A COLLECTION GROUP query needs its OWN rule, or every read is
    // denied - and the error does not say that is why:
    match /{path=**}/messages/{messageId} {
      allow read: if isSignedIn() && resource.data.authorId == uid();
    }

    // DEFAULT DENY, last. Never leave `allow read, write: if true`
    // from the quickstart anywhere in this file.
    match /{document=**} { allow read, write: if false; }
  }
}
*/

// ================= RULES ARE NOT FILTERS ===========================
// A rule cannot say "return only the documents this user may see". If
// a query COULD return a forbidden document, THE WHOLE QUERY FAILS.
//
// Rule: allow read: if uid() in resource.data.memberIds;
//
// FAILS - the query could match rooms the user is not in:
const bad = query(collection(db, "rooms"), orderBy("name"));
//   FirebaseError: Missing or insufficient permissions.
//
// SUCCEEDS - the query itself proves the rule holds:
const good = query(collection(db, "rooms"),
  where("memberIds", "array-contains", uid), orderBy("name"));
//
// This is WHY the array-contains membership pattern is everywhere in
// Firestore schemas. The rule and the query are designed together.

// ================= APP CHECK: anti-abuse, not authorisation ========
// Your API key is PUBLIC - it is in your bundle, by design. App Check
// verifies the request comes from your GENUINE app, which is what
// stops someone pointing a loop at your database.
import { initializeAppCheck, ReCaptchaEnterpriseProvider }
  from "firebase/app-check";
initializeAppCheck(app, {
  provider: new ReCaptchaEnterpriseProvider("site-key"),
  isTokenAutoRefreshEnabled: true
});
// Roll it out in MONITORING mode first (console shows verified vs
// unverified traffic), then enforce. Enforcing first breaks every
// client you have not updated.

// ================= IAM and the ADMIN SDK BYPASS =====================
// The Admin SDK IGNORES Security Rules. Completely.
//   * Cloud Functions and your backend must do their OWN authorisation
//   * the service account gets the NARROWEST IAM role that works
//     (roles/datastore.user, not roles/owner)
//   * A LEAKED SERVICE ACCOUNT KEY IS TOTAL COMPROMISE of the
//     database, with no rule to stop it. Prefer workload identity
//     and no downloaded key at all.

// ================= Billing alerts and quotas: SECURITY controls =====
// A rules mistake or a function loop generates enormous cost in hours.
//   * BUDGET ALERTS at 50 / 90 / 100% -> tells you
//   * APP CHECK                        -> limits who can
//   * QUOTA CAP on reads/writes        -> limits how much
// Configure all three BEFORE launch. Afterwards is a conversation
// with finance.
//
//   gcloud alpha billing budgets create --billing-account=... \
//     --display-name="firestore-chat" --budget-amount=200USD \
//     --threshold-rule=percent=0.5 --threshold-rule=percent=0.9
//
//   Cloud Monitoring alerts on:
//     firestore.googleapis.com/document/read_count
//     firestore.googleapis.com/document/write_count
//     firebaserules.googleapis.com/... deny rate  <- a spike in
//        denials is either an attack or a broken deploy. Both matter.

Open this example in the editor and change it. Nothing you type is saved.

Discussion

No questions on this topic yet. Sign in to ask the first one.