firestore-guard-mcp
# firestore-guard-mcp
[](./LICENSE)
[](https://nodejs.org/)
[](https://www.typescriptlang.org/)
[](https://modelcontextprotocol.io/)
**Zero-bloat static security analyzer and Model Context Protocol (MCP) server for `firestore.rules` and `firestore.indexes.json`.**
Catch privilege escalations, create/update validation bypasses, PII exposure, and redundant composite indexes in milliseconds — offline, with zero Firebase Emulator setup, in your terminal, CI pipeline, or AI coding assistant.
---
## Why `firestore-guard-mcp`?
A single overlooked line in `firestore.rules` can expose an entire database or let any signed-in user promote themselves to admin. A redundant composite index in `firestore.indexes.json` silently inflates write latency and storage bills.
`firestore-guard-mcp` gives you:
- **Instant offline static analysis** — no Java runtime, no Firebase Emulator, no network calls.
- **Helper function expansion** — resolves custom `function isSignedIn()` / `isOwner()` helpers inside `firestore.rules` instead of doing naive regex matching.
- **Native MCP Server (stdio)** — plug directly into **Claude Desktop**, **Claude Code**, **Cursor**, or any MCP host so your AI assistant can audit and harden rules automatically.
- **CI-ready CLI** — deterministic `0–100` security score (`A`–`F`), `--json` output, and `--fail-on <severity>` exit codes.
- **Zero bloat** — only 2 runtime dependencies (`@modelcontextprotocol/sdk` and `zod`).
---
## What It Looks Like
```text
firestore-guard-mcp Audit — Project (/app/my-firebase-project)
Score: 34/100 (Grade F) | Total: 5 (critical: 1, high: 2, medium: 2, low: 0, info: 0)
[CRITICAL] FS-RULE-001: Unrestricted public access (line 22, match /databases/{database}/documents/posts/{postId})
Issue: Rule allows read unconditionally (if true) on /databases/{database}/documents/posts/{postId}.
Code: allow read: if true;
Fix: Restrict access with explicit authentication, ownership, or role checks instead of allowing unconditional access.
[HIGH] FS-RULE-006: Create vs. update validation bypass (line 16, match /databases/{database}/documents/users/{userId})
Issue: On /databases/{database}/documents/users/{userId}, `create` validates incoming document fields, but `update` omits validation/diff checks.
Code: allow update: if request.auth.uid == userId;
Fix: Enforce the same schema/type/size checks on `update` and lock immutable fields using `request.resource.data.diff(resource.data).affectedKeys()`.
[HIGH] FS-RULE-005: Email authorization without email_verified check (line 29, match /databases/{database}/documents/admin/{docId})
Issue: Rule checks `request.auth.token.email` without verifying `request.auth.token.email_verified == true`.
Code: allow read, write: if request.auth.token.email == 'admin@example.com';
Fix: Require `request.auth.token.email_verified == true` alongside any `request.auth.token.email` comparison.
[MEDIUM] FS-IDX-004: Redundant prefix composite index (match orders)
Issue: indexes[0] (orders) is a strict prefix of indexes[1] with identical sort/array modes.
Fix: Remove indexes[0] because queries it serves are already covered by indexes[1].
```
---
## Quick Start Guide
### 1. Clone & Build (from source)
```bash
git clone https://github.com/Adjureee/firestore-guard-mcp.git
cd firestore-guard-mcp
npm install
npm run build
```
### 2. Run Your First Audit (CLI)
**Audit an entire Firebase project** (auto-discovers `firebase.json` or default `firestore.rules` & `firestore.indexes.json`):
```bash
node ./dist/cli/index.js audit /path/to/your-firebase-project
```
**Audit a single file:**
```bash
# Audit security rules
node ./dist/cli/index.js rules ./firestore.rules
# Audit composite indexes & field overrides
node ./dist/cli/index.js indexes ./firestore.indexes.json
```
**Use in CI pipelines** (returns exit code `1` if any finding meets or exceeds `--fail-on`):
```bash
# Fail the build on any high or critical issue, output JSON for tooling
node ./dist/cli/index.js audit . --fail-on high --json
```
#### CLI Reference
| Command / Flag | Description |
| :--- | :--- |
| `audit [dir]` | Auto-discover and audit `firestore.rules` + `firestore.indexes.json` in `dir` (default `.`) |
| `rules <file>` | Audit a specific `firestore.rules` file |
| `indexes <file>` | Audit a specific `firestore.indexes.json` file |
| `serve` / `--mcp` | Start the MCP server on stdio (also the default when run with no arguments) |
| `--json` | Emit structured JSON report instead of formatted text |
| `--fail-on <level>` | Exit with code `1` if findings reach `critical`, `high`, `medium`, `low`, or `info` |
| `--rules <file>` | Override rules file path when running `audit` |
| `--indexes <file>` | Override indexes file path when running `audit` |
| `-v, --version` | Print package version |
| `-h, --help` | Show CLI usage |
---
### 3. Connect as an MCP Server
`firestore-guard-mcp` speaks standard MCP over `stdio` and exposes three tools:
| MCP Tool | Arguments | Purpose |
| :--- | :--- | :--- |
| `audit_firestore_rules` | `rulesContent?`, `filePath?` | Audit raw rules text or a local `firestore.rules` file |
| `audit_firestore_indexes` | `indexesContent?`, `filePath?` | Audit raw JSON or a local `firestore.indexes.json` file |
| `audit_firestore_project` | `projectDir?`, `rulesPath?`, `indexesPath?` | Auto-discover via `firebase.json` and audit the full project |
#### Claude Code
```bash
claude mcp add firestore-guard -- node /absolute/path/to/firestore-guard-mcp/dist/cli/index.js serve
```
#### Claude Desktop / Cursor / Windsurf / Antigravity
Add to your MCP configuration file (e.g., `claude_desktop_config.json` or `.cursor/mcp.json`):
```json
{
"mcpServers": {
"firestore-guard": {
"command": "node",
"args": ["/absolute/path/to/firestore-guard-mcp/dist/cli/index.js", "serve"]
}
}
}
```
Once connected, ask your AI assistant:
> *"Run `audit_firestore_project` on this repo, explain every critical/high finding, and patch `firestore.rules` until the score is 100/100."*
---
### 4. Programmatic TypeScript / Node.js API
```ts
import {
auditFirestoreRules,
auditFirestoreIndexes,
auditFirestoreProject,
formatReport,
} from 'firestore-guard-mcp';
const rulesReport = auditFirestoreRules(rulesSource, 'firestore.rules');
console.log(formatReport(rulesReport));
const indexesReport = auditFirestoreIndexes(indexesJson, 'firestore.indexes.json');
const projectReport = auditFirestoreProject({ projectDir: './my-firebase-app' });
```
---
## Audit Rules Reference
### Firestore Security Rules (`firestore.rules`)
| Rule ID | Severity | What It Catches |
| :--- | :--- | :--- |
| `FS-RULE-001` | **Critical** | Unrestricted public access (`if true` or missing `if` condition) |
| `FS-RULE-002` | **Critical** | Overly permissive recursive wildcard (`match /{document=**}`) |
| `FS-RULE-003` | **High** | Missing or legacy `rules_version` (not `'2'`) |
| `FS-RULE-004` | **High** | Broad authenticated write (`request.auth != null` without ownership/role check) |
| `FS-RULE-005` | **High** | `request.auth.token.email` checked without `request.auth.token.email_verified` |
| `FS-RULE-006` | **High** | `create` vs. `update` validation bypass (validated on create, unvalidated on update) |
| `FS-RULE-007` | **High** | Privilege escalation via user-supplied `request.resource.data` or unprotected sensitive fields (`role`, `isAdmin`, `permissions`, etc.) |
| `FS-RULE-008` | **Medium** | `hasOnly()` / `diff()` field restrictions without an identity/ownership check |
| `FS-RULE-009` | **Medium** | Broad read/list access on sensitive collections (`users`, `orders`, `payments`, `admin`, `private`, etc.) |
| `FS-RULE-010` | **Medium** | Missing data type (`is string`, `is int`, etc.) or `.size()` bounds on writes |
| `FS-RULE-011` | **Medium** | Temporary or expired test-mode time-bomb rules (`request.time < timestamp.date(...)`) |
| `FS-RULE-012` | **Low** | High `get()`/`exists()` lookup count (>2 per rule) or lookups inside `read`/`list` rules |
| `FS-RULE-013` | **Low** | Coarse-grained `allow write` instead of explicit `create`, `update`, `delete` |
| `FS-RULE-014` | **Info** | Empty rules file or missing `service cloud.firestore` match blocks |
### Firestore Indexes (`firestore.indexes.json`)
| Rule ID | Severity | What It Catches |
| :--- | :--- | :--- |
| `FS-IDX-001` | **Critical** | Invalid JSON syntax or malformed top-level structure |
| `FS-IDX-002` | **High** | Malformed composite index (missing `collectionGroup`, invalid `queryScope`, invalid `order`/`arrayConfig`, duplicate field path) |
| `FS-IDX-003` | **High** | Exact duplicate composite index definitions |
| `FS-IDX-004` | **Medium** | Redundant prefix composite index already covered by a wider index |
| `FS-IDX-005` | **Medium** | Unnecessary single-field composite index (Firestore auto-indexes single fields) |
| `FS-IDX-006` | **High** | Multiple `arrayConfig: "CONTAINS"` fields in a single composite index |
| `FS-IDX-007` | **Low** | Wide composite index (>4 fields) causing write amplification |
| `FS-IDX-008` | **Low** | Broad `COLLECTION_GROUP` override on generic fields (`id`, `createdAt`, `status`, etc.) |
| `FS-IDX-009` | **High** | Malformed or duplicate `fieldOverrides` entries |
---
## Scoring
Every audit starts at **100** and deducts per finding:
- **Critical**: `-30`
- **High**: `-15`
- **Medium**: `-8`
- **Low**: `-3`
- **Info**: `0`
Grades: **A** (`90–100`), **B** (`80–89`), **C** (`70–79`), **D** (`50–69`), **F** (`0–49`).
---
## Development
```bash
npm run typecheck # TypeScript strict typecheck (tsc --noEmit)
npm test # Vitest unit, CLI, and MCP InMemoryTransport tests
npm run build # Bundle ESM library, .d.ts types, and CLI via tsup
```
## License
[MIT](./LICENSE)
TDQS
Scored across 3 tools
The two file-level auditors are clearly distinct from each other, but audit_firestore_project overlaps heavily by auto-discovering and auditing both files, so an agent must guess whether to call the project-level tool alone or the two granular tools as well. The descriptions help somewhat but do not clarify the relationship or recommended call order.
All three names follow the same audit_firestore_<target> pattern with a consistent verb and resource scope. The project tool's broader target is still readable within the same convention.
Three tools is thin but defensible for a narrowly scoped audit-only server. However, one tool (audit_firestore_project) largely composites the other two, meaning the surface only really offers two distinct capabilities.
The server covers auditing of rules, indexes, and project discovery, which is coherent lifecycle coverage for a read-only audit role. It is a dead end for remediation though: there is no tool to suggest or apply fixes, regenerate indexes, or validate a corrected rules file after an audit.