Why this matters
Security failures rarely arrive as movie-style password cracking; they arrive as an ordinary route that forgets a tenant filter, a crawler tricked into calling cloud metadata, or a single regex that stalls the whole server on 20 kilobytes of input. During Wave 46, our very first GitHub Actions run proved how easily a test suite can lull a team into false confidence: 150 tests checked ReDoS defences with fixed < 250 ms wall-clock budgets, and all of them passed on fast developer machines while hiding a genuinely quadratic e-mail regex that slowed down fifty-fold when input grew eight-fold. Good defence starts by writing down what is worth stealing, mapping every place untrusted bytes enter the system, and testing invariants that hold on every machine instead of trusting happy-path checks. This lesson walks through the repository's threat model, the concrete attack classes built against it, the bugs we caught along the way, and the security gaps that remain open before any real customer touches production.
The ideas
Threat modelling: assets, trust zones, and STRIDE
Instead of bolting security features on at random, a threat model answers four plain questions before code ships: what are we protecting, where does trust change, how could an attacker break it, and what automated gate proves the control works?
Every place where data moves from a less-trusted caller to a more-trusted component is a trust boundary. At each boundary, engineers run through the six STRIDE failure modes:
| Letter | Threat | Plain-English question | Primary defence in this repository |
|---|---|---|---|
| S | Spoofing | Can someone pretend to be another user or webhook sender? | Passkeys, sessions (L04), raw-body HMAC (L05) |
| T | Tampering | Can someone alter requests, database rows, or audit logs? | AES-256-GCM tags, AAD, hash-chained audit_log |
| R | Repudiation | Can someone deny approving an ad spend change? | Append-only audit chain and offline bundle proofs |
| I | Information Disclosure | Can secrets, tenant data, or internals leak in responses or logs? | RLS, vault isolation, problem+json, zero-echo, Gitleaks |
| D | Denial of Service | Can small hostile inputs stall CPU or exhaust RAM? | Linear-time parsing, depth caps, bounded rate limiters |
| E | Elevation of Privilege | Can a viewer act as an admin or read another workspace? | Route scope checks, PostgreSQL RLS, step-up MFA, least privilege |
Three engineering principles tie every defence below together:
- Defence in depth: put multiple independent barriers around high-value assets so one coding slip never causes a breach.
- Least privilege and blast radius: give every process and database role only the minimum credentials it needs so a compromise stays small.
- Fail closed: whenever a check errors, parses as
NaN, lacks configuration, or receives conflicting headers, refuse the request instead of letting it pass.
Cross-tenant access and IDOR
In a multi-tenant SaaS, every customer workspace shares one API and one PostgreSQL database. An IDOR (Insecure Direct Object Reference) happens when a logged-in user in Workspace A edits an ID in the URL or JSON body to point at Workspace B's campaign, order, or OAuth connection and the handler only checked whether the caller was logged in.
Stopping IDOR requires two independent locks: the API handler must confirm the caller holds a valid membership for the target workspace and never trust a workspace_id supplied in a request body, and PostgreSQL FORCE ROW LEVEL SECURITY must filter every query strictly to the session's active workspace even if a route query forgets a WHERE clause.
Injection: SQL, CSV formulas, prototype pollution, and search-path shadowing
Injection happens whenever untrusted input escapes data and gets executed as syntax by a downstream parser. Four distinct forms matter in this stack:
- SQL injection: gluing user input into a SQL string lets
' OR '1'='1rewrite query logic. Always passing inputs through parameterised placeholders ($1,$2) forces PostgreSQL to treat every input byte strictly as inert data. - Search-path shadowing (
CVE-2018-1058): even without SQL injection, a PostgreSQL function that omits schema prefixes resolves names along the caller'ssearch_path. PinningSET search_pathexplicitly on database functions prevents a rogue object in another schema from hijacking triggers or helper functions. - CSV formula injection: a hostile campaign title or customer note starting with
=,+,-, or@(even disguised behind leading tabs or invisible zero-width spaces) executes as a formula when a merchant opens an exported CSV in Excel or Google Sheets. Neutralizing dangerous leading characters turns formulas back into plain text. - Prototype pollution: in JavaScript, merging untrusted JSON objects carelessly lets a payload containing
__proto__,constructor, orprototypemodifyObject.prototypeacross the entire server process. Rejecting those keys explicitly and checking membership withObject.hasOwn,Map, orSetshuts the door permanently.
Browser attacks: XSS, clickjacking, and CSRF
Even a spotless API can be abused through a signed-in user's browser:
- XSS (Cross-Site Scripting): if untrusted text or a
javascript:link renders unescaped in the web app, attacker script executes inside the victim's session. React escapes JSX text automatically, link checks refuse unsafe URI schemes,HttpOnlykeeps session cookies away from JavaScript, and a strict Content-Security-Policy (CSP) constrains what scripts can run at all. - Clickjacking and MIME sniffing: attaching security headers (
X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: no-referrer,Content-Security-Policy: default-src 'none'; frame-ancestors 'none',Cache-Control: no-store, and HSTS over HTTPS) activates built-in browser shields on every single reply, including 404 and 500 errors. - CSRF (Cross-Site Request Forgery): because browsers attach cookies automatically to cross-site form submissions, an attacker's page could trigger state-changing POSTs while a merchant stays logged in. An origin guard pairs an exact
Origincheck with a required custom header (X-GD-Request) that plain HTML forms cannot send and untrusted origins fail CORS preflight on.
SSRF, DNS rebinding, and crawler isolation
Any feature that fetches a URL supplied by a merchant — here, the SEO page auditor — risks SSRF (Server-Side Request Forgery). Instead of submitting https://myshop.com.tr, an attacker submits http://127.0.0.1:5432/ or the cloud metadata address (169.254.169.254 or metadata.google.internal) to steal cloud IAM tokens or scan internal services.
Simple URL string checks fail against four classic bypasses: short or hexadecimal IPv4 forms (127.1, 0x7f000001), IPv4-mapped IPv6 addresses (::ffff:169.254.169.254), HTTP 302 redirects from a public page to an internal IP, and DNS rebinding (where an attacker's DNS server returns a safe public IP during validation with TTL 0, then swaps in 169.254.169.254 milliseconds later when fetch opens the socket).
A real SSRF guard stops all four together:
- Allow only HTTP/HTTPS on ports
80and443, and refuse HTTPS-to-HTTP protocol downgrades. - Canonicalise resolved IPs and block every private address range (RFC 1918 LANs, loopback, link-local, CGNAT
100.64.0.0/10, multicast, IPv6 unique-local/link-local, and::ffff:mapped ranges). - Use connect-time IP pinning: resolve DNS once, verify the IP is public, connect directly to that exact pinned IP, and repeat the whole check on every redirect hop (capped at 5 hops).
- Enforce an environment guard and network egress isolation so even a hypothetical crawler bug finds zero database, vault, payment, or OAuth secrets in
process.env.
ReDoS, backtracking, and growth-ratio testing
Because Node.js runs JavaScript on a single event loop, one slow regular expression freezes the API for every customer at once — ReDoS (Regular-Expression Denial of Service). Most JavaScript regexes rely on backtracking: when a pattern with overlapping quantifiers fails at the end of a long string, the engine rewinds and tries alternative splits over and over.
An unanchored pattern like /[A-Z0-9._%+-]+@/ on 50,000 a characters with no @ tries starting at index 0 (scanning 50,000 characters), fails, restarts at index 1 (49,999 characters), then index 2, and so on — quadratic time (O(n^2)). Doubling the string quadruples the CPU cost; multiplying input by 8 multiplies work by roughly 64.
In plain words
Fixing ReDoS keeps scanners in linear time (O(n)) by adding a negative lookbehind ((?<![A-Z0-9._%+-]) so the engine refuses to restart mid-word), bounding wildcard gaps ({0,200} instead of .*), or writing a single-pass character loop. Testing it reliably uses a growth-ratio check: warm up V8, time the function on N/8 bytes and N bytes across repeated medians, and fail if runtime grows by more than 3 * 8 = 24x, separating linear ~8x scaling cleanly from quadratic ~64x on any hardware.
Rate limiting, replay attacks, and error or timing leaks
Four quieter risks round out everyday API hardening:
- Replay attack and brute force: raw-body HMAC signatures include a 300-second freshness window, step-up MFA proofs are consumed atomically once, and a rate limiter caps request bursts per client (
429 Too Many Requests) using a monotonic clock, a 50,000-key LRU memory ceiling, single-hop client IP extraction, and IPv6/64prefix collapse. - Leaky errors and schema oracles: default framework 404 and 500 responses routinely echo raw URLs, field names, or stack traces. Returning RFC 9457 application/problem+json with fixed codes, enforcing zero-echo (never echoing caller input or secrets), and checking auth before body validation (pre-validation, returning
401before400) deny strangers both stack traces and schema maps. - Timing side channel: comparing secrets or hashes with
crypto.timingSafeEqualand answering sign-in requests uniformly prevent attackers from measuring microsecond differences to guess HMAC bytes or enumerate customer e-mails. - Supply-chain hygiene: enforcing a supply-chain policy (SHA-512 lockfile integrity hashes, zero npm install scripts, pinned Node/pnpm engines, and release cooling-off), scanning dependencies with osv-scanner, and blocking leaked literals with gitleaks prevent third-party packages or accidental commits from undermining your own code.
How this repository does it
divides the system into five trust zones (docs/THREAT-MODEL.mdZ0 browser and public internet, Z1 web/API tier, Z2 database and background workers, Z3 isolated token vault, Z4 untrusted third-party sites and webhooks), names seven crown-jewel assets (A1–A7), maps eight core threats (T1–T8), and pairs them with six automated verification gates (G1–G6):
[Z0 Browser / Public] --HTTPS + Headers + Rate Limit + Origin Guard--> [Z1 Web & API]
|
+-----------------------------------------------------------------+
| app_role + FORCE RLS | vault_executor + KEK | isolated (0 creds)
v v v
[Z2 PostgreSQL Business Tables] [Z3 Vault Schema] [Z4 SEO Worker -> Public Web]
(SSRF pin + env-guard + egress)Every major defence maps to live, automated code and verification scripts in this repository:
| Threat / Attack Class | Live repository files | Verified detail | Status |
|---|---|---|---|
| Threat model & review ledger | , | Assets A1–A7, zones Z0–Z4, STRIDE T1–T8, gates G1–G6, open findings ledger | Designed & tracked |
Security headers, problem+json & zero-echo | , | PLATFORM_SECURITY_HEADERS, Cache-Control: no-store, mapErrorToProblem (never returns error.message), cross-route canary fuzzing | Verified |
| CSRF & pre-validation | , | Exact Origin + X-GD-Request on cookie mutations; 401 before 400 across routes | Verified |
| Rate limiting | , | FixedWindowRateLimiter, monotonic performance.now(), 50,000 LRU cap, IPv6 /64 collapse, auth 60/min, audit_preview 30/min, marketer_apply 10/hr | Verified (per-process) |
| SSRF, DNS pinning & env guard | , | Blocks private IPv4/IPv6/::ffff: CIDRs and IMDS, pins IP per hop (max 5), ports 80/443, 5 MiB cap, 10s timeout, refuses DB/vault/payment env vars | Verified |
| ReDoS & linear-time harness | , | 8x input scaling, 5 median runs, 24x ceiling vs 64x quadratic, automatic confirmation re-run | Verified |
Database search_path & RLS | , | Parameterised queries, FORCE ROW LEVEL SECURITY, pinned search_path on DB functions | Verified (see P-7 below) |
| Supply chain, CVE & secret scans | , , , | Lockfile v9.0, 316/316 SHA-512 SRI hashes, 0 install hooks, Node 24 / pnpm@12.21.0, minimumReleaseAge, osv-scanner, Gitleaks | Verified |
Not built yet
What went wrong once
Every one of these four real incidents from Waves 45–48 came from code that already had passing tests — and each taught a lasting lesson about how defences fail in practice.
1. Framework defaults that leaked internals and paths (Wave 45, finding P-5)
Before Wave 45 hardening, the API left Fastify's built-in 404 and 500 handlers untouched. Requesting an unknown path echoed the HTTP method and raw URL right back in the response body, an unhandled 500 returned error.message verbatim (in the reproduction test, "pg: secret detail at /srv/app/internal.ts"), and responses carried zero browser security headers and zero rate limits. Eleven reproduction tests were written first and all eleven failed on the unmodified code.
Fix: replaced both handlers at the root Fastify instance so every error returns apps/api/src/platform/hardening.tsapplication/problem+json with static codes, PLATFORM_SECURITY_HEADERS, Cache-Control: no-store, and correlation IDs, paired with . Framework defaults optimise for local debugging, never for hostile callers.apps/api/src/platform/rate-limit.ts
2. Two quadratic regexes hiding behind 150 wall-clock tests (Wave 46, finding V-5)
Across 45 test files, 214 call sites asserted fixed millisecond caps like < 250 ms as ReDoS tests. On fast developer laptops those tests passed while hiding real bugs; on slower shared GitHub Actions runners (PR 95), three tests failed, exposing POST /v1/w/:workspaceId/seo/structured-data-preflight slowing down roughly 50x when json_ld.name grew 8x. The culprit was an unanchored e-mail regex /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i copied into four places (124–182 ms on 20,000 characters).
Converting wall-clock checks into growth-ratio checks immediately uncovered a second ReDoS flaw in tools/lib/linear-time.mjspackages/ai: detectPromptInjection joined trigger words with unbounded .*, taking 1,115 ms on 250 KB.
Fix: Adding a negative lookbehind (?<![A-Z0-9._%+-]) to EMAIL_RE and bounding prompt-injection keyword gaps to 200 characters dropped runtime to 18 ms and linear O(n) scaling across all 127 AI tests. A security guard that reads untrusted text is itself an attack surface and must have bounded linear cost.
3. Build-output false positives and committed test secrets (Waves 46–47)
The first local run of gitleaks dir flagged 65 generic-api-key hits — all inside Next.js's generated apps/web/.next/ build folder (fresh preview keys Next.js creates on every build). Separately, across three waves, test authors committed realistic-looking synthetic tokens (EAA..., ya29...., an MFA signing string, and a hex app secret) as string constants. Because Git history keeps committed literals forever, every one required a follow-up commit replacing the literal with a runtime-built low-entropy value plus a dated exact fingerprint in ..gitleaksignore
Fix: Root ignores only generated folders (.gitleaks.tomlnode_modules/, .pnpm-store/, .next/, .turbo/), proven narrow with a planted canary test, while test fixtures now build obviously synthetic low-entropy strings at runtime and Gitleaks runs before commits, not after.
4. Chrome's version number looked like an IPv4 address (Wave 48)
Meta's website events API requires sending client_user_agent unhashed. When a probe test ran with a real Chrome user agent containing Chrome/120.0.0.0, the raw-PII scanner saw four dot-separated octets and rejected the event as raw_ip.
Fix: Rather than weakening the global IPv4 detector, the team carved out only the IP shape strictly under the client_user_agent field while keeping every other guard active on that field (maximum 512 characters, zero control characters, and zero e-mail, phone, or IBAN shapes). Good security fixes stay narrow instead of disabling the rule.
Try it yourself
All four steps below are strictly read-only from the repository root in PowerShell or Git Bash. None touch ports 3000, 4000, or 5432, require PostgreSQL, or call any external server.
Step 1: Run the automated supply-chain and lockfile integrity gate
Check all six supply-chain invariants on pnpm-lock.yaml, workspace manifests, and Node/pnpm engine pins:
node tools/check-supply-chain.mjsVerify that all six checks print [PASS], including 316/316 SHA-512 SRI hashes and zero preinstall/postinstall/prepare lifecycle hooks.
Step 2: Run the SSRF guard and crawler isolation unit tests
Execute the SEO crawler security suite to see private CIDR blocking, 169.254.169.254 IMDS rejection, ::ffff: IPv4-mapped IPv6 blocking, DNS-rebinding pinning, and redirect-hop caps tested live:
node --test apps/seo-worker/test/ssrf-and-auditor.test.mjsAll tests run locally with mocked sockets and DNS resolvers, making zero real outbound network calls.
Step 3: Watch the linear-time growth-ratio harness measure 8x scaling
Run the Markdown parser's complexity test backed by to see tools/lib/linear-time.mjsassertLinearTime warm up V8 and verify that 8x larger hostile inputs scale linearly instead of quadratically:
node --test tools/learning/test/parser-linear-time.test.mjsNotice why this test passes consistently on both fast laptops and busy CI runners where fixed millisecond budgets flaked.
Step 4: Inspect the threat model, hardening hooks, and crawler env guard
Open , docs/THREAT-MODEL.md, and apps/api/src/platform/hardening.ts. Trace how apps/seo-worker/src/env-guard.tsmapErrorToProblem strips error.message completely and how assertSeoWorkerEnvIsolated refuses to boot if any DATABASE_*, VAULT_*, POSTGRES_*, or IYZICO_* variable leaks into the crawler environment.
Check yourself
0 / 7Why can a < 250 ms wall-clock test fail to catch a real quadratic O(n^2) ReDoS vulnerability?
Why is validating a URL's IP address before calling fetch(url) still vulnerable to DNS rebinding?
Why must authenticated API routes enforce pre-validation (401 before 400) and zero-echo error bodies?
Why does apps/api/src/auth/sign-in/origin-guard.ts require both an exact Origin header and the custom X-GD-Request header on cookie-authenticated mutations?
Why does apps/api/src/platform/rate-limit.ts collapse IPv6 client addresses to /64 prefixes and cap its map at 50,000 LRU keys?
Why does the SEO crawler run assertSeoWorkerEnvIsolated at startup even though ssrf-guard.ts already blocks internal IP ranges?
Why was the Wave 48 Chrome user-agent false positive (Chrome/120.0.0.0) fixed narrowly instead of disabling the raw-IP PII check?
Words to know
38Go deeper
Threat model— full inventory of assets A1–A7, trust zones Z0–Z4, STRIDE threats T1–T8, and gates G1–G6.Independent review (2026-12-02)— full findings log including fixed issues (P-2, P-5, P-10, V-5) and open pre-launch items (P-7, issue 97).Archived lesson 06: Security engineering, ReDoS, SSRF and chaos— earlier wave notes replaced by this lesson.Archived lesson 18: Incident postmortems and security audit playbook— earlier security audit and postmortem notes.Archived lesson 22: Cross-route fuzzing and guardrails— earlier notes on adversarial cross-route fuzzing.Archived lesson 24: Zero-echo API security— earlier notes on zero-echo API error hygiene.- OWASP Top 10 (2021) — consensus catalog of web application risks including A01 Broken Access Control, A03 Injection, and A10 SSRF.
- RFC 9457: Problem Details for HTTP APIs — standard specification behind
application/problem+json. - MDN Content Security Policy (CSP) — authoritative reference for browser script and framing controls.
- OWASP Regular Expression Denial of Service (ReDoS) — deep dive into catastrophic and polynomial backtracking.
- PostgreSQL Security Advisory: CVE-2018-1058 (
search_path) — why functions must pinsearch_path. - Gitleaks and OSV-Scanner — secret and lockfile vulnerability scanners wired into our gates.