Basinfy/Basinfy-SaaS-Studio / .agents/skills/saas-security-audit
saas-security-audit
UnverifiedAdversarial AppSec audit — RLS tenant isolation, auth/RBAC, OWASP, webhooks, and AI sinks.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 10.8 KB |
| references/ai-llm-security.md | markdown | 10.4 KB |
| references/attack-classes.md | markdown | 15.3 KB |
| references/data-isolation-lifecycle.md | markdown | 7.6 KB |
| references/resource-exhaustion.md | markdown | 7.3 KB |
| references/web-protocol-auth.md | markdown | 12.0 KB |
| scripts/report-schema.json | config | 14.2 KB |
| scripts/validate-coverage-ledger.cjs | script | 32.7 KB |
| scripts/validate-findings.cjs | script | 28.1 KB |
SKILL.md
View on GitHub---
name: saas-security-audit
description: "Adversarial AppSec audit — RLS tenant isolation, auth/RBAC, OWASP, webhooks, and AI sinks."
argument-hint: "[full | auth | tenant | api | quick]"
user-invocable: true
---
<!-- Generated from .claude/skills by scripts/sync-agent-skills.py. -->
## Running this workflow on this client
Run commands from the project root (use Git Bash on Windows if `bash` points to an unavailable WSL distro). Shared studio files live in `.claude/`; follow `.agents/PORTABLE-RUNTIME.md` and `.claude/docs/config-resolution.md` for client tools, delegation, and approval rules.
Run `bash .claude/hooks/yaml-helper.sh resolve_config --keys locale,automation,workflow` and use its output below.
**Automation mode**: Resolve `modes.automation` (`project.local.yaml` →
`project.yaml` → default `collaborative`). Every `AskUserQuestion` call and
every file write follows `.claude/docs/automation-modes.md`
(collaborative asks always · guided major-only · autonomous logs and proceeds;
`automation_always_ask` categories always prompt).
**`workflow`** (resolved above) decides only what Phase 7 tells you about the
release gate: at `standard` and `full` it requires this report; at `minimal` it
does not. The audit itself runs the same at every tier.
# Application Security (AppSec) Audit & Vulnerability Harness
> **Locale & User Profile**: Match `locale` (`pt-BR` → natural Brazilian Portuguese questions/options, overriding English examples; `en` → English) and `user_profile` (`founder` → plain business language with `(Recomendado)` first, zero tech jargon; `developer` → technical). Keep code/tests in English.
Security is mandatory for production SaaS platforms. Multi-tenant SaaS architectures face tenant data cross-contamination risks, broken object-level authorization (BOLA/IDOR), session fixation, webhook forgery, AI/LLM context injection, and resource exhaustion.
This skill implements an adversarial, evidence-grounded security audit workflow (derived from the Cloudflare Vulnerability Harness standard). It systematically maps attack surfaces, performs coverage-led hunting, executes independent verification to eliminate false positives, and generates structured, schema-validated remediation reports.
**Core Defensive Principles (Cloudflare Standard):**
1. **Concrete Boundary Violations Only**: A candidate without a concrete affected principal, resource, or security outcome is not a confirmed finding.
2. **Adversarial Validation**: The agent that checks a candidate finding is never the agent that identified it. Verifiers actively seek upstream defenses or framework protections.
3. **Severity Requires Real Impact**: Severity = Likelihood × Impact. Defense-in-depth gaps are hardening notes, not vulnerabilities, when an upstream layer reliably prevents exploitation.
4. **Three Strict Verdicts**:
- `confirmed`: Complete source-visible lineage and bounded reproducible verification.
- `needs_validation`: Viable vector where external deployment state, WAF rules, or third-party provider behavior is not observable locally.
- `rejected`: Hypothesis tested and disproved by existing deterministic safeguards.
---
## Phase 1: Parse Arguments and Scope
**Modes:**
- `full` — All attack domains with adversarial Hunter-Verifier loop (recommended before release; default if no argument given).
- `tenant` — Data isolation, RLS, cross-tenant leakage, and tombstone lifecycle (`references/data-isolation-lifecycle.md`).
- `auth` — Authentication, JWT/OAuth binding, session rotation, and API keys (`references/web-protocol-auth.md`).
- `api` — Input validation, OWASP Top 10, rate limiting, and resource exhaustion (`references/resource-exhaustion.md`).
- `quick` — CRITICAL checks only across all categories (15-minute smoke scan).
---
## Phase 2: Reconnaissance & Surface Mapping
Inspect the stack configuration and codebase entry points:
- **Framework Detection (`project.yaml`)**:
- *Next.js / Node.js*: API routes (`app/api/**/route.ts`), Server Actions (`"use server"`), middleware (`middleware.ts`).
- *FastAPI / Python*: Route handlers (`api/routes/**`), dependencies (`Depends(get_current_user)`), SQLAlchemy/SQLModel models.
- *Database & Storage*: Migration files (`supabase/migrations/**`, `prisma/schema.prisma`), RLS policies (`CREATE POLICY`), Redis key patterns.
- Consult the specialized attack manuals in `references/`:
- `references/data-isolation-lifecycle.md`: Multi-tenancy, soft-delete bypass, derived copies.
- `references/web-protocol-auth.md`: JWT/OAuth binding, session fixation, WebAuthn.
- `references/ai-llm-security.md`: RAG indirect injection, tool dispatch, MCP security.
- `references/resource-exhaustion.md`: ReDoS, unpaginated queries, worker starvation.
- `references/attack-classes.md`: Core and wildcard attack vectors.
---
## Phase 3: Coverage-Led Hunting (Hunter Agent)
Spawn the primary auditor subagent:
```yaml
subagent_type: appsec-engineer
role: Adversarial Security Hunter
focus: Source-to-sink vulnerability discovery and tenant boundary verification
```
The Hunter examines the target against the 6 core SaaS attack domains:
### 1. Multi-Tenancy & Tenant Isolation (IDOR / BOLA)
- **Row-Level Security (RLS)**: Is RLS enabled and strictly enforced on all tenant tables (`tenant_id = auth.tenant_id()`)?
- **Query Ownership Scoping**: Does every parameterized query filter by both entity ID AND active tenant ID?
- **Tombstone & Lifecycle Bypass**: Do direct lookups, nested relations, search endpoints, or background workers ever return soft-deleted (`deleted_at`) or consent-revoked records?
- **Derived Copies**: Do Redis caches, search indexes, analytics logs, or export packages leak tenant data across boundaries?
### 2. Authentication & Session Integrity
- **JWT Binding**: Are signature algorithms strictly pinned? Are `kid`, `jku`, and `alg: "none"` bypass vectors prevented? Are `iss`, `aud`, and `exp` validated?
- **Session Lifecycle**: Are session IDs rotated upon login, MFA step-up, organization switch, or impersonation? Does logout cascade across active tokens and WebSocket sessions?
- **Cookie Transport**: Are `HttpOnly`, `Secure`, and `SameSite=Lax/Strict` attributes enforced?
### 3. Authorization, RBAC & Webhooks
- **Server-Side RBAC**: Are sensitive mutations guarded by explicit role checks on the server rather than trusting client-supplied claims?
- **Webhook Signature Verification**: Are Stripe and third-party webhooks verified using raw request bodies against signature secrets?
- **API Key Scoping**: Are API keys stored as constant-time hashes and bound to specific tenant scopes?
### 4. Input Validation & Injection Sinks
- **Strict Schema Parsing**: Does every public endpoint validate payloads with Zod / Pydantic and strip unknown keys?
- **SQL / Command Injection**: Are all database queries parameterized? Are command execution sinks absent or strictly validated?
- **SSRF Prevention**: Are user-supplied URLs validated against private RFC 1918 ranges and cloud metadata IPs (`169.254.169.254`)?
### 5. AI, LLM & Agent Delegation (When Applicable)
- **Indirect Prompt Injection**: Can untrusted user content in RAG documents or issue bodies reach other users' model contexts?
- **Tool-Argument Authorization**: Do model-dispatched tools re-verify user authorization before executing side-effects?
- **MCP Trust Boundaries**: Are MCP tool schemas, descriptions, and servers treated as untrusted input?
### 6. Resource Exhaustion & Availability
- **Pagination Bounds**: Are all listing endpoints strictly capped (e.g. `limit` <= 100)?
- **Rate Limiting**: Are public authentication, password reset, and expensive AI endpoints throttled per IP/tenant?
- **ReDoS**: Are regular expressions on user input free of polynomial/exponential backtracking?
---
## Phase 4: Adversarial Candidate Validation (Verifier Agent)
In `full` audit mode, every candidate vulnerability identified by the Hunter is assigned to an independent Verifier:
```yaml
subagent_type: auth-security-specialist
role: Independent Security Verifier
focus: Adversarial disproval and verification of candidate vulnerabilities
```
The Verifier actively seeks:
1. Upstream sanitization or framework middleware that neutralizes the vector.
2. Type constraints or ORM guarantees that prevent the invalid state.
3. Defense-in-depth layers that prevent real-world exploitation.
Each candidate is resolved into:
- **`confirmed`**: The exploit trace is complete and unobstructed from source to sink.
- **`needs_validation`**: The code path appears vulnerable, but runtime verification depends on external infrastructure (e.g. WAF rules, Cloudflare edge config).
- **`rejected`**: Disproved by existing defenses (recorded to avoid re-hunting).
---
## Phase 5: Structured Output & Schema Validation
Validate the structured findings using the zero-dependency validator:
```bash
node .claude/skills/saas-security-audit/scripts/validate-findings.cjs <findings-file.json>
```
Ensure all records adhere to `scripts/report-schema.json`.
---
## Phase 6: Author Audit Report
Save the report to `production/security/saas-security-audit-[date]-[scope].md`:
```markdown
# Application Security Audit Report
> **Target**: [Project Name]
> **Date**: [YYYY-MM-DD]
> **Scope**: [full | tenant | auth | api | quick]
> **Auditors**: appsec-engineer (Hunter) / auth-security-specialist (Verifier)
> **Standard**: Cloudflare Vulnerability Harness Defensive Standard
> **Status**: [PASSED | REMEDIATION REQUIRED]
## Executive Summary
[High-level overview of security posture, verified findings count, and release recommendation]
| Verdict | Count | Blockers for Release |
|---|---|---|
| Confirmed (Critical / High) | [N] | Yes |
| Confirmed (Medium / Low) | [N] | No |
| Needs Validation | [N] | Manual review |
| Rejected (Disproved) | [N] | None (Hardened) |
## Confirmed Vulnerabilities
### SEC-001: [Title]
- **Severity**: CRITICAL | HIGH | MEDIUM | LOW
- **Domain**: [Data Isolation | Web Protocol & Auth | AI/LLM | Resource Exhaustion | Injection]
- **Affected Principal & Resource**: [Attacker role, Victim role, Affected entity]
- **Source Trace**: `src/path/to/file.ts:L45` -> `src/path/to/sink.ts:L112`
- **Observed Result**: [Concrete security failure]
- **Smallest Effective Fix**: [Code diff or targeted remediation]
## Items Needing External Validation
[List of leads requiring staging environment, WAF, or IdP configuration verification]
## Hardening Notes & Disproved Candidates
[Defense-in-depth observations that are not exploitable vulnerabilities]
## Remediation Priority Order
1. SEC-001: [Immediate fix]
```
---
## Phase 7: Gate Integration
- **CRITICAL / HIGH Confirmed Finding**:
- Verdict: **REMEDIATION REQUIRED** (Hard block for Polish → Release gate).
- **MEDIUM / LOW Confirmed Only**:
- Verdict: **CONCERNS** (Review with user; fix in current or next sprint).
- **Zero Confirmed Findings**:
- Verdict: **PASSED** (Ready for deployment).
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics. | Stars: 472k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |