GetClaps
Ücretsiz DenetimFiyatlandırmaSözlükAkademi
  1. Ana sayfa
  2. /Akademi
  3. /L06 · Attacks and defences: the threat model and the bugs we caught

Ana sayfa / Akademi / L06 · Attacks and defences: the threat model and the bugs we caught

L06Bölüm B · GüvenlikOrtaKod doğrulama tarihi: 2026-12-04

Attacks and defences: the threat model and the bugs we caught

How this repository maps threats with STRIDE, blocks tenant leaks, injection, XSS, SSRF, ReDoS, replay, and supply-chain risks, and what remains open.

21 dk·4017 kelime·7 soru·38 terim·docs/lessons/06-attacks-and-defences.md
Ön koşul:L04 · Identity and access: sign-in, sessions, passkeys, step-up, OAuth, rolesL05 · Cryptography and secrets: hashing, HMAC, encryption and the vault
Tüm derslere dön
●

Ders içerikleri İngilizce yayınlanır (OD-23)

Sayfa çerçevesi Türkçe ve İngilizce olarak sunulur. Teknik ders metinleri, kod örnekleri ve kendini sına soruları doğrudan ortak kaynak dosyalarından İngilizce okunur; hukuk ve ürün terimlerinde Türkçe karşılıklar yer alır.

0%
▲Yanıtlanan sorular
0 / 7
—
○Doğruluk oranı
Henüz yanıt yok

Bu dersteki bölümler

  1. 1.Why this matters
  2. 2.The ideas
  3. 3.How this repository does it
  4. 4.What went wrong once
  5. 5.Try it yourself
  6. 6.Check yourself
  7. 7.Words to know
  8. 8.Go deeper

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:

LetterThreatPlain-English questionPrimary defence in this repository
SSpoofingCan someone pretend to be another user or webhook sender?Passkeys, sessions (L04), raw-body HMAC (L05)
TTamperingCan someone alter requests, database rows, or audit logs?AES-256-GCM tags, AAD, hash-chained audit_log
RRepudiationCan someone deny approving an ad spend change?Append-only audit chain and offline bundle proofs
IInformation DisclosureCan secrets, tenant data, or internals leak in responses or logs?RLS, vault isolation, problem+json, zero-echo, Gitleaks
DDenial of ServiceCan small hostile inputs stall CPU or exhaust RAM?Linear-time parsing, depth caps, bounded rate limiters
EElevation of PrivilegeCan 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:

  1. SQL injection: gluing user input into a SQL string lets ' OR '1'='1 rewrite query logic. Always passing inputs through parameterised placeholders ($1, $2) forces PostgreSQL to treat every input byte strictly as inert data.
  2. Search-path shadowing (CVE-2018-1058): even without SQL injection, a PostgreSQL function that omits schema prefixes resolves names along the caller's search_path. Pinning SET search_path explicitly on database functions prevents a rogue object in another schema from hijacking triggers or helper functions.
  3. 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.
  4. Prototype pollution: in JavaScript, merging untrusted JSON objects carelessly lets a payload containing __proto__, constructor, or prototype modify Object.prototype across the entire server process. Rejecting those keys explicitly and checking membership with Object.hasOwn, Map, or Set shuts 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, HttpOnly keeps 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 Origin check 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 80 and 443, 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

A < 250 ms speed test measures how fast your laptop is, not whether your regex is safe. An O(n^2) bug that takes 15 ms on 2 KB takes 38 seconds on 100 KB.

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 /64 prefix 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 401 before 400) deny strangers both stack traces and schema maps.
  • Timing side channel: comparing secrets or hashes with crypto.timingSafeEqual and 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

docs/THREAT-MODEL.md divides the system into five trust zones (Z0 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):

text
[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 ClassLive repository filesVerified detailStatus
Threat model & review ledgerdocs/THREAT-MODEL.md, docs/INDEPENDENT-REVIEW-2026-12-02.mdAssets A1–A7, zones Z0–Z4, STRIDE T1–T8, gates G1–G6, open findings ledgerDesigned & tracked
Security headers, problem+json & zero-echoapps/api/src/platform/hardening.ts, apps/api/test/all-routes-zero-echo-and-header-fuzz.test.tsPLATFORM_SECURITY_HEADERS, Cache-Control: no-store, mapErrorToProblem (never returns error.message), cross-route canary fuzzingVerified
CSRF & pre-validationapps/api/src/auth/sign-in/origin-guard.ts, apps/api/test/all-routes-zero-echo-and-header-fuzz.test.tsExact Origin + X-GD-Request on cookie mutations; 401 before 400 across routesVerified
Rate limitingapps/api/src/platform/rate-limit.ts, apps/collector/src/rate-limit.tsFixedWindowRateLimiter, monotonic performance.now(), 50,000 LRU cap, IPv6 /64 collapse, auth 60/min, audit_preview 30/min, marketer_apply 10/hrVerified (per-process)
SSRF, DNS pinning & env guardapps/seo-worker/src/ssrf-guard.ts, apps/seo-worker/src/env-guard.tsBlocks 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 varsVerified
ReDoS & linear-time harnesstools/lib/linear-time.mjs, tools/learning/test/parser-linear-time.test.mjs8x input scaling, 5 median runs, 24x ceiling vs 64x quadratic, automatic confirmation re-runVerified
Database search_path & RLSdocs/schema.sql, packages/db/migrations/0001_baseline_r1.sqlParameterised queries, FORCE ROW LEVEL SECURITY, pinned search_path on DB functionsVerified (see P-7 below)
Supply chain, CVE & secret scanstools/check-supply-chain.mjs, .gitleaks.toml, .gitleaksignore, tools/gates.manifest.jsonLockfile v9.0, 316/316 SHA-512 SRI hashes, 0 install hooks, Node 24 / pnpm@12.21.0, minimumReleaseAge, osv-scanner, GitleaksVerified
◆

Not built yet

Honesty about remaining risk is part of real security engineering. Nothing in this repository is deployed to production, and no external users are on the system yet. Five open risks are explicitly tracked before public launch: (1) an external security review of the hand-written sign-in, passkey, and step-up code (issue 97) has not been conducted yet; (2) FixedWindowRateLimiter keeps counters in per-process memory, so scaling beyond one API instance requires moving buckets to a shared store such as Redis; (3) finding P-7 in docs/INDEPENDENT-REVIEW-2026-12-02.md notes that non-approval tables still rely on tenant-scoped rather than role-aware RLS policies; (4) master key custody (external KMS/HSM) and lost-MFA account recovery are not yet wired; and (5) there is no live production WAF, edge DDoS protection, or third-party penetration test against deployed infrastructure 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: apps/api/src/platform/hardening.ts replaced both handlers at the root Fastify instance so every error returns application/problem+json with static codes, PLATFORM_SECURITY_HEADERS, Cache-Control: no-store, and correlation IDs, paired with apps/api/src/platform/rate-limit.ts. Framework defaults optimise for local debugging, never for hostile callers.

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 tools/lib/linear-time.mjs growth-ratio checks immediately uncovered a second ReDoS flaw in packages/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 .gitleaks.toml ignores only generated folders (node_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:

bash
node tools/check-supply-chain.mjs

Verify 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:

bash
node --test apps/seo-worker/test/ssrf-and-auditor.test.mjs

All 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 tools/lib/linear-time.mjs to see assertLinearTime warm up V8 and verify that 8x larger hostile inputs scale linearly instead of quadratically:

bash
node --test tools/learning/test/parser-linear-time.test.mjs

Notice 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, apps/api/src/platform/hardening.ts, and apps/seo-worker/src/env-guard.ts. Trace how mapErrorToProblem 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 / 7

Q1.Why can a < 250 ms wall-clock test fail to catch a real quadratic O(n^2) ReDoS vulnerability?

Q2.Why is validating a URL's IP address before calling fetch(url) still vulnerable to DNS rebinding?

Q3.Why must authenticated API routes enforce pre-validation (401 before 400) and zero-echo error bodies?

Q4.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?

Q5.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?

Q6.Why does the SEO crawler run assertSeoWorkerEnvIsolated at startup even though ssrf-guard.ts already blocks internal IP ranges?

Q7.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

38
application/problem+json

The standard HTTP error JSON media type (RFC 9457) returning structured status, code, and safe message fields without internal stack traces.

Saldırı ve savunmalarSözlükte incele
backtrackingTR: geri izleme

How a regular-expression engine rewinds and retries alternative matches on failure, which can blow up into quadratic or exponential work.

Saldırı ve savunmalarSözlükte incele
blast radius

The maximum damage a single bug, compromised process, or leaked credential can cause before another security boundary stops it.

Saldırı ve savunmalarSözlükte incele
cloud metadata addressIMDS

The internal link-local endpoint (169.254.169.254 or metadata.google.internal) where cloud VMs fetch temporary IAM credentials.

Saldırı ve savunmalarSözlükte incele
connect-time IP pinning

Resolving a hostname once, verifying the IP is public, and connecting directly to that exact pinned IP to block DNS rebinding.

Saldırı ve savunmalarSözlükte incele
Content-Security-PolicyCSP

An HTTP response header that restricts which origins may load scripts, styles, or frame a document, limiting XSS and clickjacking.

Saldırı ve savunmalarSözlükte incele
CSRFCSRF

Tricking a signed-in user's browser into sending an unwanted state-changing request carrying their session cookie from another site.

Saldırı ve savunmalarSözlükte incele
CSV formula injection

Exporting untrusted cells starting with =, +, -, or @ that Excel or Sheets executes as spreadsheet formulas when opened.

Saldırı ve savunmalarSözlükte incele
defence in depthTR: derinlemesine savunma

Layering multiple independent security controls around the same asset so one mistake or bypassed check does not cause a breach.

Saldırı ve savunmalarSözlükte incele
DNS rebinding

An SSRF bypass where an attacker's DNS server returns a safe public IP during validation and an internal IP moments later when connecting.

Saldırı ve savunmalarSözlükte incele
environment guard

A startup assertion that aborts an untrusted worker immediately if any database, vault, payment, or OAuth secret appears in its environment.

Saldırı ve savunmalarSözlükte incele
external security review

An independent audit of hand-written authentication, session, and cryptographic code by outside security specialists before public launch.

Saldırı ve savunmalarSözlükte incele
fail closed

Defaulting to denial whenever a security check errors, receives ambiguous input, or lacks required configuration.

Saldırı ve savunmalarSözlükte incele
gitleaks

An automated secret scanner that inspects working trees (gitleaks dir) and full Git commit history (gitleaks git) for leaked credentials.

Saldırı ve savunmalarSözlükte incele
growth-ratio check

Measuring how much runtime increases when input size scales 8x, failing if growth looks quadratic (~64x) instead of linear (~8x).

Saldırı ve savunmalarSözlükte incele
IDORIDOR

Accessing or modifying another customer's record simply by changing an ID in a URL or JSON body when the server forgets to verify ownership.

Saldırı ve savunmalarSözlükte incele
least privilegeTR: en az yetki ilkesi

Granting every user, process, and database role the minimum permissions required for its job and nothing more.

Saldırı ve savunmalarSözlükte incele
linear timeTR: doğrusal zaman

Execution time that grows directly in proportion to input length (O(n)), ensuring an 8x bigger input takes roughly 8x the time.

Saldırı ve savunmalarSözlükte incele
origin guard

The API CSRF guard requiring every cookie-authenticated mutation to carry both an exact allowed Origin and the custom X-GD-Request header.

Saldırı ve savunmalarSözlükte incele
osv-scanner

Google's open-source vulnerability scanner that checks exact lockfile dependency versions against the OSV/CVE advisory database.

Saldırı ve savunmalarSözlükte incele
pre-validation

Enforcing authentication (401) and authorization (403) before validating request payloads (400) so strangers cannot probe route schemas.

Saldırı ve savunmalarSözlükte incele
private address range

Non-routable IP blocks reserved for internal LANs, loopback, link-local metadata, CGNAT, and multicast that public fetchers must refuse.

Saldırı ve savunmalarSözlükte incele
prototype pollutionTR: prototip kirliliği

A JavaScript attack sending keys like __proto__, constructor, or prototype in JSON to corrupt properties inherited by all objects.

Saldırı ve savunmalarSözlükte incele
quadratic timeTR: karesel

Runtime that scales with the square of input length (O(n^2)), meaning an 8x bigger input costs 64x as much CPU time.

Saldırı ve savunmalarSözlükte incele
rate limiter

A per-client request counter over a bounded time window that answers HTTP 429 once traffic exceeds its quota.

Saldırı ve savunmalarSözlükte incele
ReDoSReDoS

Regular-Expression Denial of Service: freezing a server's CPU by feeding crafted input into a backtracking regex.

Saldırı ve savunmalarSözlükte incele
replay attack

Capturing a genuine signed webhook, MFA step-up token, or payment callback and sending it again to repeat a privileged action.

Saldırı ve savunmalarSözlükte incele
search-path shadowing

A PostgreSQL attack (CVE-2018-1058) where a hostile object in an earlier schema on search_path hijacks calls inside a privileged function.

Saldırı ve savunmalarSözlükte incele
security headersTR: güvenlik başlıkları

Standard HTTP response headers (nosniff, DENY, no-referrer, CSP, HSTS, no-store) activating built-in browser defences on every reply.

Saldırı ve savunmalarSözlükte incele
SQL injection

Concatenating untrusted input into a SQL string so an attacker alters the query to read, modify, or delete arbitrary database rows.

Saldırı ve savunmalarSözlükte incele
SSRFSSRF

Server-Side Request Forgery: abusing a server that fetches user-supplied URLs to reach internal services, loopback, or cloud metadata.

Saldırı ve savunmalarSözlükte incele
STRIDESTRIDE

A structured threat-modelling mnemonic covering Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege.

Saldırı ve savunmalarSözlükte incele
supply-chain policy

The repository's automated dependency rules enforcing lockfile SHA-512 SRI hashes, zero install lifecycle scripts, engine parity, and release cooling-off.

Saldırı ve savunmalarSözlükte incele
threat modelTR: tehdit modeli

A living security blueprint mapping high-value assets, trust zones, concrete attacks, mitigating controls, and automated proof gates.

Saldırı ve savunmalarSözlükte incele
timing side channelTR: zamanlama yan-kanalı

Leaking secret bytes or account existence through tiny differences in how long a server takes to reject different inputs.

Saldırı ve savunmalarSözlükte incele
trust boundary

The dividing line between two security zones where privilege changes, requiring strict re-validation of every request and value that crosses it.

Saldırı ve savunmalarSözlükte incele
XSSXSS

Cross-Site Scripting: injecting attacker-controlled JavaScript into a trusted web page so it executes inside a victim's browser session.

Saldırı ve savunmalarSözlükte incele
zero-echoTR: sıfır yankı

The discipline that API error responses never reflect back caller-supplied input, unknown field names, URL paths, or secret fragments.

Saldırı ve savunmalarSözlükte incele

Go 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 pin search_path.
  • Gitleaks and OSV-Scanner — secret and lockfile vulnerability scanners wired into our gates.
◆

NOT LEGAL OR TAX ADVICE · Açık karar kapıları dürüstlüğü

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

Önceki ders: L05Sonraki ders: L07

L06 · Part B · intermediate · Verified 2026-12-04 · 21 min

Attacks and defences: the threat model and the bugs we caught

How this repository maps threats with STRIDE, blocks tenant leaks, injection, XSS, SSRF, ReDoS, replay, and supply-chain risks, and what remains open.

Bu müfredat öğrenme amaçlıdır; hukuk veya vergi danışmanlığı değildir. #3 hukuk ve mali müşavir onayı, #21 keşif görüşmeleri, OD-01 marka tescil kontrolü ve canlı dağıtım henüz tamamlanmamıştır. ISO-27001 / SOC 2: UNOBTAINED. Sıfır canlı müşteri veya canlı reklam harcaması iddia edilmez.

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:

LetterThreatPlain-English questionPrimary defence in this repository
SSpoofingCan someone pretend to be another user or webhook sender?Passkeys, sessions (L04), raw-body HMAC (L05)
TTamperingCan someone alter requests, database rows, or audit logs?AES-256-GCM tags, AAD, hash-chained audit_log
RRepudiationCan someone deny approving an ad spend change?Append-only audit chain and offline bundle proofs
IInformation DisclosureCan secrets, tenant data, or internals leak in responses or logs?RLS, vault isolation, problem+json, zero-echo, Gitleaks
DDenial of ServiceCan small hostile inputs stall CPU or exhaust RAM?Linear-time parsing, depth caps, bounded rate limiters
EElevation of PrivilegeCan 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:

  1. SQL injection: gluing user input into a SQL string lets ' OR '1'='1 rewrite query logic. Always passing inputs through parameterised placeholders ($1, $2) forces PostgreSQL to treat every input byte strictly as inert data.
  2. Search-path shadowing (CVE-2018-1058): even without SQL injection, a PostgreSQL function that omits schema prefixes resolves names along the caller's search_path. Pinning SET search_path explicitly on database functions prevents a rogue object in another schema from hijacking triggers or helper functions.
  3. 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.
  4. Prototype pollution: in JavaScript, merging untrusted JSON objects carelessly lets a payload containing __proto__, constructor, or prototype modify Object.prototype across the entire server process. Rejecting those keys explicitly and checking membership with Object.hasOwn, Map, or Set shuts 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, HttpOnly keeps 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 Origin check 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 80 and 443, 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

A < 250 ms speed test measures how fast your laptop is, not whether your regex is safe. An O(n^2) bug that takes 15 ms on 2 KB takes 38 seconds on 100 KB.

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 /64 prefix 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 401 before 400) deny strangers both stack traces and schema maps.
  • Timing side channel: comparing secrets or hashes with crypto.timingSafeEqual and 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

docs/THREAT-MODEL.md divides the system into five trust zones (Z0 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 ClassLive repository filesVerified detailStatus
Threat model & review ledgerdocs/THREAT-MODEL.md, docs/INDEPENDENT-REVIEW-2026-12-02.mdAssets A1–A7, zones Z0–Z4, STRIDE T1–T8, gates G1–G6, open findings ledgerDesigned & tracked
Security headers, problem+json & zero-echoapps/api/src/platform/hardening.ts, apps/api/test/all-routes-zero-echo-and-header-fuzz.test.tsPLATFORM_SECURITY_HEADERS, Cache-Control: no-store, mapErrorToProblem (never returns error.message), cross-route canary fuzzingVerified
CSRF & pre-validationapps/api/src/auth/sign-in/origin-guard.ts, apps/api/test/all-routes-zero-echo-and-header-fuzz.test.tsExact Origin + X-GD-Request on cookie mutations; 401 before 400 across routesVerified
Rate limitingapps/api/src/platform/rate-limit.ts, apps/collector/src/rate-limit.tsFixedWindowRateLimiter, monotonic performance.now(), 50,000 LRU cap, IPv6 /64 collapse, auth 60/min, audit_preview 30/min, marketer_apply 10/hrVerified (per-process)
SSRF, DNS pinning & env guardapps/seo-worker/src/ssrf-guard.ts, apps/seo-worker/src/env-guard.tsBlocks 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 varsVerified
ReDoS & linear-time harnesstools/lib/linear-time.mjs, tools/learning/test/parser-linear-time.test.mjs8x input scaling, 5 median runs, 24x ceiling vs 64x quadratic, automatic confirmation re-runVerified
Database search_path & RLSdocs/schema.sql, packages/db/migrations/0001_baseline_r1.sqlParameterised queries, FORCE ROW LEVEL SECURITY, pinned search_path on DB functionsVerified (see P-7 below)
Supply chain, CVE & secret scanstools/check-supply-chain.mjs, .gitleaks.toml, .gitleaksignore, tools/gates.manifest.jsonLockfile v9.0, 316/316 SHA-512 SRI hashes, 0 install hooks, Node 24 / pnpm@12.21.0, minimumReleaseAge, osv-scanner, GitleaksVerified
◆

Not built yet

Honesty about remaining risk is part of real security engineering. Nothing in this repository is deployed to production, and no external users are on the system yet. Five open risks are explicitly tracked before public launch: (1) an external security review of the hand-written sign-in, passkey, and step-up code (issue 97) has not been conducted yet; (2) FixedWindowRateLimiter keeps counters in per-process memory, so scaling beyond one API instance requires moving buckets to a shared store such as Redis; (3) finding P-7 in docs/INDEPENDENT-REVIEW-2026-12-02.md notes that non-approval tables still rely on tenant-scoped rather than role-aware RLS policies; (4) master key custody (external KMS/HSM) and lost-MFA account recovery are not yet wired; and (5) there is no live production WAF, edge DDoS protection, or third-party penetration test against deployed infrastructure 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: apps/api/src/platform/hardening.ts replaced both handlers at the root Fastify instance so every error returns application/problem+json with static codes, PLATFORM_SECURITY_HEADERS, Cache-Control: no-store, and correlation IDs, paired with apps/api/src/platform/rate-limit.ts. Framework defaults optimise for local debugging, never for hostile callers.

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 tools/lib/linear-time.mjs growth-ratio checks immediately uncovered a second ReDoS flaw in packages/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 .gitleaks.toml ignores only generated folders (node_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.mjs

Verify 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.mjs

All 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 tools/lib/linear-time.mjs to see assertLinearTime warm up V8 and verify that 8x larger hostile inputs scale linearly instead of quadratically:

node --test tools/learning/test/parser-linear-time.test.mjs

Notice 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, apps/api/src/platform/hardening.ts, and apps/seo-worker/src/env-guard.ts. Trace how mapErrorToProblem strips error.message completely and how assertSeoWorkerEnvIsolated refuses to boot if any DATABASE_*, VAULT_*, POSTGRES_*, or IYZICO_* variable leaks into the crawler environment.

Words to know

  • application/problem+json
  • Backtracking
  • Blast radius
  • Cloud metadata address
  • Connect-time IP pinning
  • Content-Security-Policy
  • CSRF
  • CSV formula injection
  • Defence in depth
  • DNS rebinding
  • Environment guard
  • External security review
  • Fail closed
  • Gitleaks
  • Growth-ratio check
  • IDOR
  • Least privilege
  • Linear time
  • Origin guard
  • OSV-Scanner
  • Pre-validation
  • Private address range
  • Prototype pollution
  • Quadratic time
  • Rate limiter
  • ReDoS
  • Replay attack
  • Search-path shadowing
  • Security headers
  • SQL injection
  • SSRF
  • STRIDE
  • Supply-chain policy
  • Threat model
  • Timing side channel
  • Trust boundary
  • XSS
  • Zero-echo

Go 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 pin search_path.
  • Gitleaks and OSV-Scanner — secret and lockfile vulnerability scanners wired into our gates.

Kendini sına soru özeti ve yanıt anahtarı

Q1. Why can a < 250 ms wall-clock test fail to catch a real quadratic O(n^2) ReDoS vulnerability?

Answer: B

Wall-clock budgets measure CPU speed as much as algorithmic scaling. Comparing runtime at N/8 versus N with a growth-ratio ceiling (tools/lib/linear-time.mjs) distinguishes ~8x linear scaling from ~64x quadratic backtracking reliably on any machine.

Q2. Why is validating a URL's IP address before calling fetch(url) still vulnerable to DNS rebinding?

Answer: B

Connect-time IP pinning (apps/seo-worker/src/ssrf-guard.ts) resolves DNS once, checks the IP against all blocked CIDRs, connects directly to that exact pinned IP, and repeats the whole check on every redirect hop.

Q3. Why must authenticated API routes enforce pre-validation (401 before 400) and zero-echo error bodies?

Answer: B

Checking identity first prevents unauthenticated attackers from probing route fields, and returning static application/problem+json codes without echoing input eliminates secret reflection and internal stack-trace leaks.

Q4. 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?

Answer: B

Requiring an exact allowed Origin plus a custom non-simple header defeats cross-site request forgery even across subtle cookie edge cases.

Q5. 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?

Answer: B

Collapsing IPv6 addresses to /64 blocks trivial rate-limit evasion, and bounding the map with LRU eviction stops memory-exhaustion DoS attacks.

Q6. Why does the SEO crawler run assertSeoWorkerEnvIsolated at startup even though ssrf-guard.ts already blocks internal IP ranges?

Answer: B

Layering SSRF pinning, egress network isolation, and zero-credential startup checks means no single bug gives an attacker access to PostgreSQL or the vault.

Q7. 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?

Answer: A

Narrowly scoping false-positive fixes preserves the underlying guard across all other fields while keeping real browser traffic working cleanly.

GetClaps Kurucu Akademisi · Tarayıcı açılışında ağ çağrısı yapılmaz; ilerleme yalnızca cihazındaki yerel depolamada tutulur.