Firebase 配置审计 Prompt:规则与函数模板

15 个可直接复制的 Prompt,审计 Firebase 安全规则、索引、Cloud Functions、Auth 与 App Check——已按 2nd-gen 函数更新(2026 年 6 月)。

让 AI”审一下我的 Firebase”,它只会把 console 里的告警原样念给你听。真正的配置 bug 藏在缝隙里:一条 Storage rule 让任何登录用户都能读到每一个对象、一个公开的 HTTP 函数没接 App Check、一个缺失的复合索引只在生产流量下才崩。下面 15 个 Prompt 各打一个 Firebase 面,每次只盯一种问题。

把它们贴进 Claude Opus 4.7、GPT-5.5 或 Gemini 3.1 Pro——这三个模型都有 1M token 上下文(截至 2026 年 6 月),所以你可以一条消息里塞进整个 firestore.rulesstorage.rulesfirebase.jsonfunctions/ 目录,让模型把规则和真正在跑的查询交叉对照。

TL;DR

  • 先跑规则审计(模板 1-3)。大多数 Firebase 泄漏出在安全规则上,这里一漏,其他检查全失效。
  • 每个 Prompt 只锚定一个文件一种问题(访问控制、数据结构、索引、触发器)。“全都 review 一遍”的宽泛 Prompt 只会给你含糊的输出。
  • Firebase 在你脚下变了:Cloud Functions 现在默认 2nd genNode 18 已于 2025 年 10 月下线,而旧的 functions.config() 配置存储在 Cloud Runtime Configuration API 于 2025 年 12 月 31 日关停后已经取不到值了。模板 5、6、12、13 都对应了这些变化。
  • 给 callable 开 App Check 强制需要 firebase-functions 4.0.0+ 和 enforceAppCheck: true;部署后最长要等 15 分钟才生效。

适合哪些人

发 Firebase 后端的独立开发者、审 rule 改动的 reviewer、准备应对上线日流量峰值的创业者、审 Cloud Functions 的安全工程师。只用 Firebase Analytics / Remote Config 的应用可以跳过——这套是面向 Firestore、Realtime Database、Storage、Cloud Functions 和 Auth 的。

安全规则能做什么、不能做什么

下面每个 Prompt 都建立在两个事实上,直接取自 Firebase 安全检查清单

  • 安全规则能做身份认证、字段级授权、类型检查和字段不可变约束。它做不到跨文档查询、调外部 API、限流。超出这个范围的,归 Cloud Function 管。
  • Cloud Functions 默认对 Firestore 有完全、不受限的写权限。一个处理多用户请求的函数,必须在碰数据之前确认调用者是谁、有没有权限——规则在这里保护不了你。

正因为这条分界,这套 Prompt 同时审两个面:模板 1-4 和 11 管规则,模板 5-7 和 10 管函数侧。

怎么把材料喂给模型

下面每个 Prompt 都最好在消息里带上六样东西:

  • 角色:Firebase 安全审计员(不是”乐于助人的助手”)。
  • 上下文:真实的 *.rulesfirebase.jsonfunctions/ 源码——贴文件,别贴摘要。
  • 目标:一个交付物(findings 表格、部署 checklist、测试文件)。
  • 限制:别重写、别自动 format、别瞎猜 SDK 版本。
  • 输出格式:编号清单或带 file:line 的 markdown 表格。
  • 信号:告诉它什么是糟糕规则(比如 if request.auth != null),让它认这个模式。

15 个可直接复制的 Prompt 模板

1. Firestore rules 覆盖审计

第一个跑——大多数 Firebase 泄漏在 rules。

You are a Firebase security reviewer. Audit `firestore.rules` below. For each collection / subcollection: (1) Is there a `match` block? (2) For each command (read / get / list / create / update / delete) — what condition gates it? (3) Are there overly broad `match /{document=**}` wildcards? (4) Where do rules use `request.auth.uid` correctly vs incorrectly? Output: path | read | write | risks.

2. Storage rules 审计

Audit `storage.rules`. For each bucket path: (1) Read / write conditions, (2) Does the path encode ownership (e.g., `users/{userId}/...`) and does the rule enforce that the prefix matches `request.auth.uid`? (3) Are file size / content-type limits enforced in rules? (4) Any rules using `request.auth != null` (too loose — any signed-in user can read)? File:line.

3. Realtime Database rules 审计

If `database.rules.json` exists, audit it: (1) `.read` and `.write` on root — should not be `true`, (2) Per-path conditions reference `auth.uid` against the path variable, (3) `.validate` rules constrain data shape (type, length, allowed keys), (4) Are indexes (`.indexOn`) declared for queried fields? Output findings + severity.

4. Firestore 复合索引审计

Audit `firestore.indexes.json` against the query patterns in app code. For each query that combines (where + orderBy) or multiple where clauses: (1) Does a matching composite index exist? (2) Any indexes declared but never used? (3) Index fan-out cost concerns (very high write volume tables)? List: query | needed index | currently present.

5. Cloud Functions 触发器审计

这些函数现在默认 2nd gen(Cloud Run functions)——注意是 onRequest/onCall/onDocumentWritten 这种写法,不是 functions.https.onRequest

Audit Cloud Functions trigger config (assume 2nd gen / Cloud Run functions). (1) HTTP triggers — which are public? Which need App Check or auth middleware? (2) Firestore / RTDB triggers — could they recurse (a write that triggers another write to the same path)? (3) Scheduled / PubSub functions — frequency vs cost, (4) functions missing explicit timeout / memory / concurrency / maxInstances. Output: function | trigger | risk.

6. Cloud Functions 输入校验 review

2nd-gen callable 里,调用者落在 request.authrequest.data 上(1st gen 用 context.auth / data);让它标出代码针对的是哪套 API。

Review each callable / HTTP Cloud Function for: (1) Auth check at the top — `request.auth` (2nd gen onCall) or `context.auth` (1st gen) for callables, verified JWT for raw HTTP; remember functions have unrestricted DB write access so the caller MUST be checked. (2) Input schema validation (zod / valibot / manual). (3) Rate limiting or App Check enforcement (`enforceAppCheck: true`). (4) Output shape — no leaking internal fields. List findings as function | gap | fix.

7. App Check 覆盖审计

给 callable 开 App Check 强制需要 firebase-functions 4.0.0+ 和 enforceAppCheck: true;部署后最长要等 15 分钟才生效,这段窗口里别慌。

Map App Check coverage. (1) Which Firebase products have enforcement enabled (infer from code; flag what needs console confirmation)? (2) Which callable functions set `enforceAppCheck: true` (or check `request.app` for 2nd gen)? (3) Any client SDK init that calls Firebase without initializing App Check (reCAPTCHA Enterprise / App Attest / Play Integrity)? (4) Are debug tokens active in production code paths? Output: surface | enforced? | remediation.

8. Auth Provider 配置 review

Review Firebase Auth provider setup: (1) Which providers are enabled (Google, Apple, Email, Anonymous, Custom)? (2) Anonymous auth — is there a graduation path to a real account? (3) Email link / password reset — are templates customized and rate limits set? (4) Custom claims usage — is the issuer trusted (only set by admin SDK)? Output: provider | config | gap.

9. Firebase Hosting rewrites 与 headers

Review `firebase.json` hosting config: (1) Rewrites — any wildcard that masks 404s incorrectly? (2) Headers — security headers present (CSP, X-Frame-Options, Referrer-Policy)? (3) Cache-Control on static vs dynamic assets, (4) i18n config consistency. List issues.

10. Custom Claims 与 Admin SDK 审计

Find every place the Admin SDK sets custom claims. For each: (1) Is the call wrapped in a function that's admin-only? (2) Could user input flow into the claim value? (3) Are claim names colliding with reserved (aud, sub, iss)? (4) Is claim size kept under 1000 bytes? Findings.

11. Firestore 数据校验 rules 审计

Beyond access control, audit Firestore rules for DATA SHAPE validation: (1) `request.resource.data.keys()` constrained to allowed keys? (2) Types enforced (`is string`, `is timestamp`)? (3) Length / range constraints on user-supplied fields? (4) Immutable fields (e.g., createdAt, ownerId) protected from update? List gaps.

12. Cloud Functions 成本与冷启动 review

2nd-gen 函数按 100ms 计费,支持 concurrency(单实例多请求)和 minInstances——让模型把这两个杠杆都用上。

Review Cloud Functions (2nd gen) for cost / cold-start issues: (1) functions invoked on every write of a high-volume Firestore collection, (2) memory over-provisioned (e.g. 512MiB+ where 256MiB suffices), (3) minInstances set when bursty traffic doesn't need warm instances, (4) concurrency left at 1 when the handler is I/O-bound and could serve many requests per instance, (5) work better suited to a direct client SDK call. Output: function | issue | savings estimate.

13. 环境与密钥 review

functions.config() 已经废了:背后的 Cloud Runtime Configuration API 于 2025 年 12 月 31 日关停,firebase functions:config:get 再也取不到值。配置现在放在 .env 文件、参数化 param 或 Cloud Secret Manager 里——按这个来审。

Audit Firebase secrets and env (assume functions.config() is decommissioned). (1) Any leftover `functions.config()` reads or `runtimeconfig.json` that must migrate to .env / defineSecret() / Secret Manager? (2) Plaintext API keys in `.env` that belong in Secret Manager (anything that grants spend or PII access)? (3) Client-side Firebase config (apiKey) — public by design, but flag if treated as a secret. (4) `.env*` files or service-account JSONs committed to the repo? Output file:line per finding.

14. 多环境隔离审计

This project uses [projects] (dev / staging / prod). Audit: (1) Are project IDs sourced from env (not hardcoded)? (2) Are emulator configs used in dev / test? (3) Any code path that could call prod from a dev runtime? (4) Are auth users segregated per project? Findings.

可替换变量: [projects]——例如 my-app-devmy-app-stagingmy-app-prod

15. Firebase 发现 → 迁移计划

最后跑——把发现转成部署序列。

Take all Firebase audit findings above. Group into deploy steps: (1) Rules changes (deploy first, test with emulator), (2) Index additions (deploy before queries that need them), (3) Function changes (deploy after rules), (4) Console changes (App Check, auth providers — note manual). Output: ordered checklist with rollback per step.

这套 Prompt 最常抓到的七种泄漏

按它们在真实 Firebase 仓库里出现的频率排:

  • allow read, write: if request.auth != null——任何登录用户全读到。最常见的一种 Firebase 泄漏,几乎一定错。
  • 测试模式规则上了生产。默认的 allow read, write: if request.time < ... 模板到期后会变成全开,不少应用还没等到那个日期就上线了。
  • 付费或耗配额功能的 callable 没接 App Check——刷接口的面就是整个功能。
  • custom claim 信了客户端。只有 Admin SDK 该设它,而且 claim 体积要控制在 1000 字节以内。
  • 查询先上、复合索引后上。第一个需要该索引的生产请求直接挂。
  • Firestore 触发器递归无深度保护——一个写触发一个写再触发一个写,账单跟着爆。
  • Service Account JSON 提交进 repo——一个泄漏的文件就能接管整个项目。

优化技巧

  • 别的都靠后,先跑规则审计(模板 1-3)。这里漏了,其他检查全失效。
  • 部署前用 Firebase Emulator Suite 和 Rules Unit Testing SDK 拿 fixture 数据 dry-run 规则改动。
  • 强制 Firestore rule 用 request.resource.data.keys() 约束——便宜,又能挡住客户端想偷写的意外字段。
  • 每个 callable 函数 review 都配一次 App Check 检查;这两个故障模式总是一起出现。
  • firestore.indexes.json*.rules 快照进 /firebase/baseline/,每个 PR 前 diff。
  • 成本 review 配一份到 BigQuery 的 billing export——静态审永远看不到真实金额。
  • 每次 Firebase 产品或 SDK 升级后把整套重跑一遍。默认值和代际会变(1st-gen → 2nd-gen 这一跳就动了这套里一半以上的检查)。

FAQ

  • 该用哪个模型跑? 三个 1M 上下文模型都行——Claude Opus 4.7、GPT-5.5、Gemini 3.1 Pro(截至 2026 年 6 月)——都能装下一整套 Firebase 配置。论安全规则推理,Opus 4.7(SWE-bench Verified 87.6%)给的 findings 通常最紧;如果要审一棵很大的 functions/ 树,Gemini 3.1 Pro 最便宜,每 1M token 进/出 $2/$12。
  • 客户端 Firebase apiKey 在源码里算泄漏吗? 不算。它只标识项目,不是密钥;安全靠安全规则和 App Check。当公开处理,只在代码把它当密钥用时才标出来。
  • 每个 PR 都跑吗? 只在 PR 动了 *.rulesfirestore.indexes.jsonfunctions/ 或 Auth 配置时跑。其他 PR 不用这一遍。
  • AI 能直接帮我写 rules 吗? 初稿可以——但凡是它生成的,一定跑模板 1、2、11。模型非常稳定地会吐 request.auth != null,太松了。
  • 不部署怎么测 rules? 用 Firebase Emulator Suite 加 Rules Unit Testing SDK。这套 Prompt 覆盖结构审计;emulator 覆盖针对 fixture 的真实行为。
  • functions.config() 还能用吗? 不能了。背后的 Cloud Runtime Configuration API 于 2025 年 12 月 31 日关停,firebase functions:config:get 取不到任何值。迁到 .env 文件、参数化配置(defineString / defineSecret)或 Cloud Secret Manager——模板 13 专门审这个迁移。
  • Firebase Extensions 呢? 审每个 extension 的 service-account 权限——往往要得很大。给每个装上的 extension 在模板 5 加一行。

相关阅读

标签: #Prompt #编程 #Firebase #安全