Chapter 13 · Advanced Security Rules, Query Compatibility, App Check, and Rules Testing
App Check for Abuse Reduction: Attestation Concepts, Enforcement Boundaries, and Why It Is Not Authorization
Add App Check as a distinct abuse-reduction layer, with explicit attestation, metrics, enforcement, debug-provider, replay, pricing, and authorization boundaries.
Learning outcomes
Explain App Check attestation, token issuance, metrics, enforcement, debug providers and provider-specific cost without treating App Check as identity authorization.
Design a staged Cloud Firestore App Check rollout that monitors legitimate traffic before enforcement.
Separate baseline App Check replay properties from product-specific replay protection and application idempotency.
Identify which App Check claims can be proven only in a real isolated project rather than the local Firestore emulator.
Use the Emulator Suite, a Firebase demo project, or an isolated test project for destructive, security-sensitive, billing-sensitive, migration, backup/restore, or write-heavy exercises unless the lesson explicitly marks managed verification as required. Treat shown output as expected evidence unless it is explicitly identified as captured output, and re-check current Firebase/Google Cloud edition, mode, quota, pricing, and security documentation before production execution.
AtlasMart continues the same mandatory environment used in
Chapters 01–12: project ID
demo-atlasmart-firestore, Standard edition /
Native mode / (default) database, Firestore
emulator 127.0.0.1:8080, Authentication emulator
127.0.0.1:9099, Emulator UI
127.0.0.1:4000, Firebase CLI
15.30.0, Firebase JavaScript SDK
12.19.0, Firebase Admin Node SDK
14.4.0 with
@google-cloud/firestore 9.1.0,
@firebase/rules-unit-testing 5.0.2, and Node.js
22+. Mandatory work remains local/no-cost. The canonical lab
is Standard Native Core; Enterprise Native Pipeline
differences are labeled explicitly, and Firestore with MongoDB
compatibility is not silently treated as the same client/rules
surface.
Firebase JavaScript SDK 12.19.0 was released 9 September 2026;
Firebase Admin Node.js 14.4.0 was released 10 September 2026
and carries @google-cloud/firestore 9.1.0;
Firebase CLI 15.30.0 was released 9 September 2026. Admin SDK
14.x requires Node.js 22 or higher. Keep these pins in the
course lab instead of replacing them with floating
latest tags.
The Firestore emulator can prove deterministic evaluation of the rules source it loads, including mock Firebase Authentication identities/claims, query/rule compatibility, field validation, wildcard behavior, and a rules-coverage report. It does not prove production App Check attestation/enforcement, IAM/service-account policy, production index state, billing, abuse resistance, or regional latency. Mobile/web client SDK requests are governed by Security Rules. Admin/server libraries bypass Security Rules and must be constrained through IAM plus application-layer authorization. App Check is an additional app/device attestation signal; it is not user authorization.
1. The AtlasMart problem: valid credentials do not prove a request came from your app
Security Rules can correctly require Alice’s UID and tenant claim, yet automated abuse can still originate from scripts that obtain valid user credentials or call public Firebase APIs directly. App Check adds a separate assertion about the app/device environment. On Web, a common provider is reCAPTCHA Enterprise; on Apple/Android there are platform attestation providers. When Cloud Firestore App Check enforcement is enabled, requests without a valid App Check token are rejected before they become ordinary accepted product requests.
| Signal | Answers | Does not answer |
|---|---|---|
| Firebase Auth ID token | Who is the signed-in user and what trusted custom claims are in the token? | Whether the app binary/device context is genuine |
| Security Rules | Is this client operation authorized for this path/data/query? | Whether the client came from an authentic app installation |
| App Check token | Does the request have accepted app/device attestation for this Firebase app? | Whether this user may read/write a particular Firestore document |
| IAM/service identity | What may trusted server workloads do? | Authorization of direct mobile/web requests |
2. App Check is defense in depth, not authorization
A valid App Check token must never replace
request.auth.uid, tenant checks, immutable owner
fields, or server IAM. If an attacker controls an authentic app
instance or valid device, App Check can succeed while the user
is still unauthorized for a target order. Conversely, a
legitimate user on an unsupported/misconfigured client can fail
App Check even though their Firebase Auth identity is valid.
Keep those failure domains separate in UI, telemetry, and
incident response.
App Check establishes app/device authenticity context, not document ownership or role. Keep the Chapter 12/13 Security Rules predicates. Enable App Check in addition to, not instead of, user/data authorization.
3. Staged rollout: register → observe → enforce
Firebase recommends registering apps/providers, shipping the App Check-enabled client, reviewing App Check request metrics, and then enabling enforcement when legitimate traffic is sufficiently covered. Cloud Firestore supports App Check enforcement. After enabling enforcement, documentation notes that it can take up to about 15 minutes to take effect. Treat that propagation time as an operational transition, not an instant switch.
| Phase | AtlasMart action | Evidence |
|---|---|---|
| 1. Integrate | Initialize App Check before Firestore use in the real client | Client begins sending tokens |
| 2. Observe | Use Firebase console App Check metrics | Verified / outdated / unknown / invalid request categories |
| 3. Enforce | Enable Cloud Firestore enforcement in an isolated project first | Unverified requests rejected after propagation |
| 4. Operate | Watch metrics and support signals | Detect old clients, invalid origins and rollout regressions |
4. Web example: reCAPTCHA Enterprise provider
import { initializeApp } from "firebase/app";import { initializeAppCheck, ReCaptchaEnterpriseProvider} from "firebase/app-check";import { getFirestore } from "firebase/firestore";const app = initializeApp(firebaseConfig);const appCheck = initializeAppCheck(app, { provider: new ReCaptchaEnterpriseProvider(RECAPTCHA_ENTERPRISE_SITE_KEY), isTokenAutoRefreshEnabled: true});const db = getFirestore(app);// Security Rules still authorize Firestore data access.// App Check is an additional accepted-app/device signal.
reCAPTCHA Enterprise assessments have their own quotas/pricing. The Web provider documentation explains that assessment requests above the no-cost quota can be charged, and risk-threshold tuning can affect legitimate users. Do not copy a universal threshold into a course. Measure your own score distribution and abuse tolerance.
5. Debug provider: powerful and dangerous
Localhost and CI typically do not qualify as production-attested environments. Firebase provides a debug provider so a registered debug token can be accepted. That token is effectively a bypass for production attestation and must be treated as a secret: do not commit it, expose it in public CI logs, or ship a debug build. Revoke a compromised debug token.
// DEVELOPMENT/CI ONLY — never commit a real registered debug token.self.FIREBASE_APPCHECK_DEBUG_TOKEN = true;const appCheck = initializeAppCheck(app, { provider: new ReCaptchaEnterpriseProvider(RECAPTCHA_ENTERPRISE_SITE_KEY), isTokenAutoRefreshEnabled: true});// Read the generated debug token from the local console and register it// in the Firebase console for the isolated development project.
The Chapter 13 mandatory lab does not require a billing-enabled real project or a registered App Check provider. It tests Security Rules locally and documents the App Check integration/enforcement runbook. Actual App Check metrics/enforcement must be verified in an isolated real project because the Firestore emulator test suite is not proof of production attestation.
6. Replay: do not overclaim what App Check solves
Baseline App Check session tokens are reusable until expiration. Firebase has limited-use-token replay protection for selected product/custom-backend scenarios, but current App Check metrics documentation states that standard replay-protection monitoring is available for Firebase AI Logic, while custom-backend replay protection is beta and requires your own monitoring. Do not claim that Cloud Firestore App Check makes every database operation one-time-only. For business actions such as checkout or coupon redemption, keep the idempotency keys and durable workflow state introduced in Chapter 10.
| Threat | App Check contribution | Still required |
|---|---|---|
| Generic scripts without accepted attestation | Can reduce/deny this traffic when enforcement is enabled | Security Rules and rate/abuse monitoring |
| Authenticated user reading another user’s order | No authorization decision | Rules owner/tenant/role predicates |
| Replay of a business intent | Baseline token does not make Firestore write semantically one-time | Idempotency key / transaction/workflow state |
| Compromised privileged backend credential | Not the primary control | IAM, workload identity, secret/key hygiene, app authorization |
7. Auth claims have their own lifecycle
AtlasMart uses tenantId and
role custom claims. Firebase requires custom claims
to be set only from a privileged server environment; payload is
limited to 1000 bytes and should contain access-control data,
not a user profile. A claim change appears when a new ID token
is issued—after sign-in/re-authentication, normal refresh after
expiration, or explicit getIdToken(true). This
means role revocation is not the same mechanism as App Check
revocation and should be tested independently.
// Trusted backend:await getAuth().setCustomUserClaims(uid, { tenantId: "t-acme", role: "support"});// Existing client session: after backend confirms the role change,// force a fresh ID token if immediate propagation is required.await auth.currentUser.getIdToken(true);
8. Optional isolated-project verification checklist
| Check | Expected evidence | Not safe to infer from emulator |
|---|---|---|
| App registered with provider | App appears under App Check Apps | Attestation validity |
| Client deployed with App Check | Metrics show verified requests | Security Rules correctness |
| Enforcement off → on | Unverified requests transition to rejection after propagation | Business authorization |
| Debug token test | Only registered secret debug token succeeds in dev environment | Production provider risk score |
| Rollback plan | Operator can disable enforcement if legitimate traffic is unexpectedly blocked | Root cause of every invalid request |
Use a disposable/staging Firebase project and bounded traffic. Never enable production enforcement as an unreviewed course exercise.
Production judgment
App Check is most valuable when combined with strong Rules, safe claims issuance, bounded queries, IAM-separated server paths, telemetry, and an incident runbook. Monitor legitimate-client adoption before enforcement. Treat provider pricing, token TTL, risk threshold and failure rates as workload-specific parameters. Do not publish “one correct” threshold or infer p95/p99 request latency from the emulator.
Lesson 4 converts the Rules contract into CI so query broadening, forged fields and claim-policy regressions fail before deployment.
Knowledge check
- What does App Check prove?
- Should App Check replace Security Rules?
- Why monitor before enforcing?
- Can baseline Cloud Firestore App Check be described as exactly-once replay protection?
- When do changed custom claims reach a client?
Review the answers
1. Accepted app/device attestation context for a registered Firebase app/provider—not user ownership or role authorization.
2. No. It is defense in depth and must be combined with Rules for client data authorization.
3. To detect legitimate clients that are unverified/misconfigured and avoid an avoidable production outage.
4. No. Keep application idempotency/workflow controls; current product replay-protection availability is narrower.
5. When a new ID token is issued, including sign-in/re-authentication, normal refresh, or a forced refresh.
Summary
AtlasMart now has a clear layered model: Auth identifies the user, Rules authorize data operations, App Check reduces untrusted-client abuse, and IAM secures trusted server paths. None of these layers is allowed to masquerade as another.
Authoritative references
- Securely query data with Cloud Firestore Security Rules
- Writing conditions for Cloud Firestore Security Rules
- Structuring Cloud Firestore Security Rules
- Control access to specific fields
- Test Cloud Firestore Security Rules with the emulator
- Build unit tests for Firebase Security Rules
- Generate Security Rules test reports
- @firebase/rules-unit-testing reference
- Control access with Firebase Authentication custom claims
- Firebase App Check overview
- Enable App Check enforcement
- Monitor App Check request metrics
- App Check with reCAPTCHA Enterprise on Web
- App Check debug provider for Web
- Security Rules for Enterprise Pipeline operations
- Cloud Firestore client/server library trust boundaries
- Cloud Firestore IAM
- Firebase JavaScript SDK release notes
- Firebase Admin Node.js release notes
- Firebase CLI release notes