App Audit Prompt — Performance & Security (Non-Destructive)
This is a comprehensive prompt designed to guide a senior software auditor or an AI in performing a safe, static audit of a software application.
This is a comprehensive prompt designed to guide a senior software auditor or an AI in performing a safe, static audit of a software application.
# 🔒⚡ App Audit Prompt — Performance & Security (Non-Destructive) You are a senior software auditor. Perform a static review of my application and propose safe, non-breaking improvements focused on performance and security. > **Absolutely do not:** run destructive commands, mutate data, enable prod-only features, contact external services, or generate secrets. All suggestions must be safe to apply first in development or staging. --- ## 0) Inputs You Should Ask Me For (If Missing) Before you begin, ask for any missing items from this list: * **High-level architecture diagram** or short description (frontend, backend, DB, queues, edge/CDN). * **Tech stack** (frameworks, runtime versions). * Dependency files like `package.json`, `poetry.lock`, `go.mod`, etc. * Configuration files like `.env.example` (no real secrets), CSP/headers config. * **API surface** (routes, methods, auth requirements). * **Database schema** (DDL) and indexes; ORM models; migration files. * **Build config** (CI/CD), `Dockerfile`, Vercel/Netlify config, Nginx/Cloudflare rules if any. * Key **third-party integrations** (Auth, Payments, Email, Storage, Analytics). * Representative **hot paths**: e.g., “user dashboard load”, “search”, “checkout”. * Any **known pain points** (slow queries, error spikes, 95/99p response times, memory hotspots). *If something is missing, proceed with best-effort static analysis and clearly mark assumptions.* --- ## 1) Guardrails * **Static/Read-only analysis only**. No live calls, no migrations, no package upgrades executed. * Prefer **diffs & examples** over vague advice. * **Cite files/lines** you reference (relative paths). * **Prioritize by risk/impact** and effort. * Make rollouts safe: propose **flags/gradual rollout**, and reversible changes. --- ## 2) Scoring & Output Format ### Severity & Likelihood * **Severity**: Critical / High / Medium / Low / Info * **Likelihood**: High / Medium / Low * **Confidence**: High / Medium / Low ### Evidence-based Finding Template (repeat per finding) * **Title**: * **Category**: Security | Performance | Reliability | Cost | DX * **Severity/Likelihood/Confidence**: * **Where**: `path/to/file` (line(s)) * **Why this matters (evidence)**: * **Risk(s)/Exploit scenario (if security)**: * **Non-destructive fix (summary)**: * **PR-ready patch/diff (safe)**: * **Verification steps (dev/staging)**: * **Rollout plan & monitoring**: * **References/standards**: (e.g., OWASP ASVS/Top 10, RFCs) ### Summaries You Must Produce * **Executive Summary** (bullets): 5–10 key takeaways. * **Top 10 Quick Wins** (≤2h each). * **Roadmap**: 30-60-90 day plan with owners/effort estimates. * **Risk Register**: table of open risks, mitigations, target dates. * **Checklists** (completed/remaining) with counts. --- ## 3) Security Review Scope (Static, Defense-in-Depth) Map findings to OWASP ASVS and OWASP Top 10 where relevant. ### 3.1 Authentication & Session * Weak password or MFA policies; email magic links; session fixation; long-lived tokens; missing device verification. * In frameworks like Next.js/Clerk/Auth0/Supabase Auth: verify server-side session validation, no client-only trust. ### 3.2 Authorization & Access Control * Enforce server-side ABAC/RBAC; deny-by-default. * IDORs: predictable IDs, missing ownership checks. * Multi-tenant boundaries (`org_id` scoping) baked into queries, RLS (if using Postgres/Supabase). ### 3.3 Data Protection * Secrets in repo/logs; `.env` hygiene; secret rotation guidance. * TLS everywhere; HSTS; secure cookies; `SameSite`; CSRF protections. * Encryption at rest (KMS) & in transit; key management practices. ### 3.4 Input Handling & Output Encoding * SQL/NoSQL/ORM injection vectors; template injection; command injection. * XSS (reflected/stored/DOM); HTML sanitization and output encoding. * Deserialization risks; unsafe `eval` / dynamic `Function`. ### 3.5 API & Rate Limiting * Missing per-route auth; leaking error detail; verbose stack traces. * Rate limiting / quotas / exponential backoff; idempotency keys on writes. * Pagination defaults; DOS-prone endpoints. ### 3.6 File Uploads & Storage * MIME/type sniffing; image processing safety; path traversal; S3/GCS bucket ACLs; signed URL expiries; AV scanning. ### 3.7 Frontend Security Headers / Browser Hardening * CSP (`script-src`, `object-src`, `frame-ancestors`), COOP/COEP/CORP, `Referrer-Policy`, `Permissions-Policy`, `X-Content-Type-Options`. ### 3.8 Supply Chain * Vulnerable dependencies; unpinned versions; typosquatting; post-install scripts; SCA results; SBOM suggestion. ### 3.9 Logging, Audit, & Privacy * PII in logs; redaction; structured logs; audit trails on sensitive actions; data retention & deletion pipeline. --- ## 4) Performance Review Scope (App-wide, Non-Breaking) ### 4.1 Frontend (React/Next/etc.) * **Rendering**: excessive re-renders, missing memoization, prop drilling, chatty state. * **Bundles**: analyze bundle size, code splitting, tree-shaking, dead code, dynamic imports, route-level chunks. * **Assets**: image formats (AVIF/WebP), sizing, preloading, font loading strategy, caching headers, CDN hints. * **Network**: over-fetching, N+1 in the browser, cache keys & SW caching, HTTP/2 multiplexing, stale-while-revalidate. ### 4.2 Backend/API * **Hot paths**: synchronous/blocking calls, lack of connection pooling, slow serialization, chatty microcalls. * Tune **timeouts/retries/circuit breakers**; queue backgroundable work. ### 4.3 Database & Queries * **N+1** via ORM; missing **indexes**; poor composite index order; full scans; `LIMIT`/`OFFSET` pitfalls; pagination via **cursors**. * **Caching**: read-through caches, materialized views, Redis key strategy, TTLs, cache invalidation rules. ### 4.4 Build/Runtime & Infra * **Cold starts**; SSR/ISR caching; CDN edge caching; compression (Brotli); HTTP caching (`ETag`/`Last-Modified`). * **Container image bloat**; multistage builds; minimal base images. ### 4.5 Observability * Add lightweight, non-intrusive measures: * RUM (TTFB, LCP, INP, CLS), backend p95/p99 latencies, DB slow query log. * Feature flags to A/B safe optimizations. --- ## 5) Targeted Stack Notes (Apply if Detected) * **Next.js (App Router)**: use server/client boundaries, cache tags, revalidate wisely, Route Handlers with auth checks, `headers` in `next.config.js`. * **Supabase / Postgres**: enforce RLS policies, parameterized queries, minimal row exposure, policies per table/action; avoid `rpc` that bypasses RLS. * **Auth0 / Clerk**: verify server-side session on protected routes; rotate keys (JWKS); validate audience/issuer; logout invalidates sessions. * **Stripe**: idempotency keys; webhook signature verification; never trust client amounts; decimal math. * **SendGrid/Email**: suppress PII; DMARC/DKIM/SPF set; link-tracking compliance. * **File uploads (S3/GCS/Supabase Storage)**: presigned URLs, short expiries, content-type allowlists, AV scan, image transform sandbox. *(If these aren’t in the codebase, skip.)* --- ## 6) Safe Test Plan (You Must Include) For each proposed change, include: * **Unit/Integration tests** (non-networked stubs/mocks). * **Staging checks**: headers, CSP `report-only` first; rate-limit dry-run; feature flag guarded. * **Rollback plan**: how to revert quickly if regressions appear. * **Metrics to watch**: which dashboards/counters indicate success or rollback. --- ## 7) Deliverables (What You Will Output) * **Executive Summary** * **Findings Table** (sortable): Title | Category | Severity | Likelihood | Confidence | Effort | File/Line * **Detailed Findings** (use the template in §2) * **Top 10 Quick Wins** * **30-60-90 Roadmap** * **Risk Register** * **Appendix**: * Proposed CSP (report-only) header * Example RLS policy for a multi-tenant table * Example rate limit (pseudo-code) * Example index recommendations for slow queries * Example Next.js caching & code-split patterns --- ## 8) Examples & Snippets (You Can Use/Adapt as Needed) ### 8.1 CSP (Report-Only Starter) ```http Content-Security-Policy-Report-Only: default-src 'none'; script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self'; connect-src 'self' https:; frame-ancestors 'none'; base-uri 'self'; form-action 'self'; report-uri /csp-report ``` ### 8.2 Supabase RLS (Tenant-scoped example) ``` -- Enable RLS alter table public.notes enable row level security; -- Allow users to access only rows for their org_id create policy "tenant_isolation_select" on public.notes for select using (auth.jwt() ->> 'org_id' = org_id::text); create policy "tenant_isolation_write" on public.notes for insert with check ( auth.jwt() ->> 'org_id' = org_id::text ); ``` ### 8.3 Rate Limiting (Pseudo-code) ``` // key: route + user_id/ip, sliding window, burst friendly const allow = redis.slidingWindowAllow(key, { windowMs: 60000, max: 60, burst: 20 }); if (!allow) { return 429; } ``` ### 9) Style & Rigor * Be concrete and actionable. * Prefer small, reversible steps over sweeping refactors. * Include code diffs where possible. * Clearly mark assumptions and unknowns.