# Security - Firebase Implementation

Firebase-specific implementation of the principles defined in [SECURITY_CORE.md](../core/SECURITY_CORE.md).

## Authentication & Authorization

- **Firebase Authentication:** Use Firebase Auth as the identity provider. Enable only the sign-in methods your app requires -- disable unused providers to reduce attack surface. Enforce email verification before granting access to protected resources.
- **Custom Claims for RBAC:** Implement role-based access using Firebase Auth custom claims (e.g., `admin: true`, `role: "editor"`). Set claims exclusively via the Admin SDK in a Cloud Function or secure backend -- never from the client. Check claims in Security Rules and client-side for UI gating.
- **Session Management:** Use short-lived ID tokens (default 1 hour) with silent refresh. For sensitive operations, call `getIdToken(true)` to force a fresh token and verify the `auth_time` claim in Security Rules to ensure recent authentication.
- **Multi-Factor Authentication:** Enable MFA in Firebase Auth for privileged accounts. Use `multiFactor.enroll()` for enrollment and handle `FirebaseAuthMultiFactorException` during sign-in to prompt for the second factor.
- **Anonymous Auth Migration:** If using anonymous authentication for onboarding flows, implement account linking (`linkWithCredential`) to convert anonymous users to permanent accounts. Set up a Cloud Function to periodically clean up orphaned anonymous accounts.
- **Token Revocation:** On password change, account compromise, or user deactivation, revoke refresh tokens via the Admin SDK (`revokeRefreshTokens`). In Security Rules, check `request.auth.token.auth_time` against the revocation timestamp to reject stale tokens.

## Input Validation & Sanitization

- **Security Rules as the Enforcement Layer:** All input validation in Security Rules is the security boundary. Client-side validation is for UX only. Every Firestore document write and RTDB node update must be validated in rules using `request.resource.data` type checks, string length constraints, and value range enforcement.
- **Schema Validation in Rules:** Enforce document schemas in Firestore Security Rules. Validate that only expected fields are present (`request.resource.data.keys().hasOnly(['name', 'email', 'role'])`), that types are correct (`is string`, `is int`, `is timestamp`), and that required fields exist.
- **Cloud Function Input Validation:** For callable Cloud Functions, validate every field of `data` before processing. Use a validation library (Zod, Joi, or superstruct) in the function body. Reject requests with missing, extra, or malformed fields with clear error codes.
- **Firestore Data Sanitization:** Strip HTML and script tags from user-generated text before writing to Firestore if the content will ever be rendered in a web context. Sanitize in a Cloud Function trigger (`onDocumentCreated`) as a safety net even if the client validates.
- **Storage Upload Validation:** Validate file uploads in Storage Security Rules by checking `request.resource.contentType` and `request.resource.size`. In a Cloud Function trigger (`onObjectFinalized`), verify content by inspecting magic bytes -- do not trust the client-provided MIME type alone.

## Data Protection

- **Firestore Security Rules as Default Deny:** Start all Firestore Security Rules with `allow read, write: if false;` and explicitly open access per collection. Never use `allow read, write: if true;` in production. Audit rules before every deployment.
- **Sensitive Field Isolation:** Store sensitive data (PII, payment tokens, auth secrets) in a separate Firestore subcollection or document with stricter Security Rules. Keep profile display data in a publicly readable document and private data in a restricted sibling.
- **No Secrets in Client Code:** Never embed Firebase Admin SDK credentials, service account keys, or third-party API secrets in client-side code. Use Cloud Functions as a proxy for operations requiring secrets. Store secrets in Secret Manager and access them via `defineSecret()` in Cloud Functions.
- **Environment Separation:** Use separate Firebase projects for development, staging, and production. Never share Firestore databases, Auth user pools, or Storage buckets across environments. Use the Firebase CLI's project aliasing (`firebase use`) to prevent accidental cross-environment deployments.
- **Firestore Field-Level Encryption:** For highly sensitive fields (SSN, payment data), encrypt at the application level before writing to Firestore. Store encryption keys in Secret Manager, not in Firestore. Decrypt only in Cloud Functions or on the client after secure key retrieval.
- **Data Retention & TTL:** Implement automated data purging using Firestore TTL policies or scheduled Cloud Functions. Delete expired sessions, stale logs, and orphaned data. Configure TTL at the collection level using the `expireAt` field pattern with Firestore's built-in TTL.
- **Logging PII Controls:** Configure Cloud Logging to exclude sensitive fields. Use structured logging in Cloud Functions and redact PII (emails, phone numbers, tokens) before writing to logs. Set up log sinks with retention policies that comply with your data governance requirements.

## Error Handling

- **Security Rule Failures:** When a Firestore or Storage operation is denied by Security Rules, the client receives a `PERMISSION_DENIED` error. Log the operation context for debugging but display a generic message to the user. Never expose rule logic or denied field names in the UI.
- **Cloud Function Error Handling:** In callable Cloud Functions, use `HttpsError` with standard codes (`unauthenticated`, `permission-denied`, `invalid-argument`, `not-found`). Never return raw exception messages or stack traces. Log the full error server-side with context.
- **Fail Secure on Auth Errors:** If Firebase Auth token verification fails in a Cloud Function (`verifyIdToken` throws), reject the request immediately. Do not fall back to unauthenticated access or weaker validation. Treat all auth verification failures as access denied.
- **Crash Reporting Configuration:** If using Firebase Crashlytics, configure it to strip PII from crash reports. Disable automatic data collection in production until user consent is obtained. Use `setCustomKey` for debugging context but never log tokens or passwords.

## AI Agent Security

- **Vertex AI in Firebase:** When using Vertex AI through Firebase, never pass raw user input directly to model prompts. Construct prompts in Cloud Functions with clear system instructions and delimiters. Sanitize user content before inclusion.
- **AI Response Validation:** Validate and sanitize all AI-generated content in Cloud Functions before writing to Firestore or returning to the client. Never store raw model output that could contain injection patterns in user-accessible documents.
- **Data Sent to AI APIs:** Before sending data to Vertex AI or external LLM endpoints from Cloud Functions, strip PII, auth tokens, and internal identifiers. Use a sanitization middleware that runs before the API call.
- **AI Feature Kill Switch:** Gate AI features behind Firebase Remote Config flags. If an AI feature produces unexpected output or is abused, disable it instantly via Remote Config without deploying new code or pushing an app update.
- **Audit Trail for AI Operations:** Log all AI agent actions (prompts sent, models invoked, outputs received) to a dedicated Firestore collection or Cloud Logging with structured metadata. Include user ID, timestamp, and operation context. Retain logs for incident investigation.

## Insider Threat Mitigation

- **IAM Least Privilege:** Assign Firebase project roles using the principle of least privilege. Use predefined roles (`Firebase Viewer`, `Firebase Develop`, `Firebase Admin`) over primitive roles (`Editor`, `Owner`). Grant `Firebase Admin` only to those who need it, and audit role assignments quarterly.
- **CI/CD Deployment Controls:** Restrict who can deploy Firebase Security Rules, Cloud Functions, and Hosting changes. Use separate service accounts for CI/CD with scoped permissions. Require PR approval before `firebase deploy` runs in CI.
- **Admin SDK Access Control:** The Admin SDK bypasses Security Rules entirely. Limit Admin SDK usage to Cloud Functions and trusted server environments. Never run Admin SDK code in client-accessible contexts. Audit all Admin SDK operations.
- **Audit Logging:** Enable Cloud Audit Logs for your Firebase project. Monitor Admin Activity logs (always on) and configure Data Access logs for sensitive resources. Route audit logs to a separate project or SIEM that deployers cannot modify.
- **Source Code Protection:** Require PR reviews for all changes to Security Rules (`firestore.rules`, `storage.rules`), Cloud Function code, and Firebase configuration files (`firebase.json`, `.firebaserc`). Use CODEOWNERS to enforce mandatory reviewers.

## Supply Chain Security

- **Cloud Function Dependencies:** Pin all dependencies in Cloud Function `package.json` using exact versions. Commit `package-lock.json`. Run `npm audit` in CI and block deployments that introduce known critical vulnerabilities.
- **Firebase SDK Versioning:** Use Firebase BoM (Bill of Materials) for consistent SDK versioning across all Firebase libraries. Pin the BoM version in your dependency file. Update deliberately and test after each bump.
- **Extension Review:** Before installing Firebase Extensions, review the extension source code, permissions requested, and resources it creates. Extensions run with elevated permissions and can read/write Firestore, Auth, and Storage. Only install extensions from verified publishers.
- **Build Integrity:** Deploy Cloud Functions from CI/CD, not from developer machines. Use a locked-down CI environment with verified base images. Validate that the deployed function source matches the reviewed commit hash.

## API Security

- **App Check:** Enable Firebase App Check for all Firebase services (Firestore, Storage, Cloud Functions, RTDB). Use platform-appropriate attestation providers (DeviceCheck/App Attest for iOS, Play Integrity for Android, reCAPTCHA Enterprise for web). Enforce App Check in Security Rules and Cloud Functions.
- **Rate Limiting Cloud Functions:** Firebase does not rate-limit callable functions by default. Implement rate limiting in Cloud Functions using Firestore-based counters or a distributed rate limiter. Track request counts per user/IP and reject excess requests with `resource-exhausted`.
- **CORS for Cloud Functions:** For HTTP Cloud Functions, configure CORS to allow only your known domains. Never use wildcard origins with authenticated endpoints. Use the `cors` middleware in Express-based functions or set headers explicitly.
- **Callable Function Authentication:** Always verify authentication in callable Cloud Functions by checking `context.auth`. For admin operations, verify custom claims (`context.auth.token.admin === true`). Never trust client-supplied user IDs -- use `context.auth.uid`.
- **Webhook Verification:** For incoming webhooks (Stripe, SendGrid, etc.) processed by HTTP Cloud Functions, verify the webhook signature using the provider's verification library. Reject requests with invalid or missing signatures. Store webhook secrets in Secret Manager.

## Secure Defaults & Zero Trust

- **Default-Deny Security Rules:** Every new Firestore collection and Storage bucket must start with deny-all rules. Open access incrementally with specific conditions. Review the rules diff before every `firebase deploy` and reject overly permissive changes.
- **Emulator Isolation:** Firebase Emulator Suite must never connect to production resources. Set `FIRESTORE_EMULATOR_HOST` and `FIREBASE_AUTH_EMULATOR_HOST` in development environments. Add CI checks that fail if production credentials are used during testing.
- **Service Account Hygiene:** Do not download or distribute service account key files. Use Workload Identity Federation for CI/CD and Application Default Credentials for Cloud Functions. If a key must exist, rotate it quarterly and store it in Secret Manager, never in source control.
- **Cross-Service Access:** Firestore triggers, Storage triggers, and Auth triggers in Cloud Functions run with the project's default service account. Scope this account's IAM permissions narrowly. Create separate service accounts for functions that need access to external services.
- **Firebase Hosting Headers:** Configure security headers in `firebase.json` for Hosting-deployed web apps: `Content-Security-Policy`, `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`. Enforce HTTPS -- Firebase Hosting does this by default.
