A condensed reference across the series — principles, headers, auth, injection classes, rate limiting, secrets, supply chain, LLM security, testing, and incident response. One section per surface, tables over prose, snippets over explanation.
Quick How-To Guides & Fast FixesNeed a quick fix or step-by-step solution? Browse our fast answers on HowTo.KandZ.me:
// ❌ Interpolated
db.query(`SELECT * FROM u WHERE email = '${email}'`);
// ✅ Parameterised
db.query("SELECT * FROM u WHERE email = $1", [email]);
// ✅ Identifier allowlist (names cannot be parameters)
const col = ["name", "created_at"].includes(sort) ? sort : "name";
db.query(`SELECT * FROM u ORDER BY ${col}`);
XSS
Type
Vector
Fix
Reflected
Query param echoed
Contextual encoding
Stored
DB content rendered
Encode on output
DOM
innerHTML, document.write
textContent, sanitise
Template
{{ x }} unescaped
Framework auto-escape on
Mutation
onerror=, javascript:
Allowlist schemes
el.textContent = input; // ✅ text
el.innerHTML = DOMPurify.sanitize(input, { // ✅ html
ALLOWED_TAGS: ["p","strong","em","ul","li"],
ALLOWED_ATTR: [],
});
CSRF
Defence
Coverage
SameSite=Lax
Blocks most POST CSRF
Synchronizer token
Per-session, server-compared
Double-submit cookie
Stateless, needs signed cookie
Origin / Sec-Fetch-Site
Rejects foreign origins
Custom header requirement
Browsers cannot forge preflight
// ✅ Check origin on state-changing requests
if (!TRUSTED_ORIGINS.has(req.headers.origin)) return res.sendStatus(403);
if (req.headers["sec-fetch-site"] === "cross-site") return res.sendStatus(403);
SSRF
// ❌ Model- or user-supplied URL fetched blindly
await fetch(req.query.url);
// ✅ Scheme + host allowlist, resolve then check IP
const u = new URL(raw);
if (!["https:"].includes(u.protocol)) throw new Error("scheme");
if (!ALLOWED_HOSTS.has(u.hostname)) throw new Error("host");
const { address } = await dns.lookup(u.hostname);
if (isPrivateIp(address)) throw new Error("private"); // block 10/8, 172.16/12, 192.168/16, 127/8, 169.254/16, ::1
Deny list to block:127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 (metadata!), ::1, fc00::/7, 0.0.0.0/8.
Command / Template Injection
// ❌ Shell string
exec(`convert ${file} out.png`);
// ✅ argv array, no shell
execFile("convert", [file, "out.png"]);
// ❌ Template rendered from user input
template.render(userInput);
// ✅ Fixed template, escaping engine, no logic in templates
nunjucks.render("greeting.njk", { name, autoescape: true });
// ✅ Object check in the query, not after the fetch
const inv = await db.invoice.findFirst({
where: { id: req.params.id, customerId: req.user.sub },
});
if (!inv) return res.status(404).json({ error: "not_found" }); // 404 not 403
-- Atomic token bucket: read, refill, decide, write in one round trip
local s = redis.call("HMGET", KEYS[1], "tokens", "ts")
local tokens = tonumber(s[1]) or cap
local ts = tonumber(s[2]) or now
tokens = math.min(cap, tokens + math.max(0, now - ts) * refill)
local ok = tokens >= cost
if ok then tokens = tokens - cost end
redis.call("HMSET", KEYS[1], "tokens", tokens, "ts", now)
redis.call("PEXPIRE", KEYS[1], math.ceil(cap / refill))
return { ok and 1 or 0, math.floor(tokens) }
Key
Survives Proxy Rotation
ip
No — collides on NAT
user
Yes
api_key
Yes — hash at rest
session
Partially
route
n/a (coarse)
Header
Meaning
429 Too Many Requests
RFC 6585
Retry-After
Seconds to wait
RateLimit-Limit / -Remaining / -Reset
IETF draft
X-RateLimit-*
Legacy de facto
GraphQL Hardening
Control
Limit
Bypass
Depth
7–10
Aliases, fragments
Complexity
Arg-scaled budget
Naive field count
Aliases
≤ 10 per field
—
Batching
Count operations
HTTP-layer limiter
Introspection
Off in prod
Suggestion errors
maxTokens
Parser-level
—
// ✅ Count operations, not requests
const ops = Array.isArray(body) ? body.length : 1;
await limiter.consume(`user:${userId}`, ops);
// Batched mutations are a stuffing vector
if (Array.isArray(body) && body.some(o => /^\s*mutation/.test(o.query))) return 400;
Secrets Management
Rule
Implementation
Never in git
.gitignore + push protection
Never in the prompt
Move to code
Runtime injection
Vault, AWS Secrets Manager, Doppler
CI → cloud
OIDC federation, no long-lived key
Rotation
90 days or on any suspicion
Scope
Per-service, per-environment
Logging
Reference, never print; mask transforms are not masked
Leak Remediation Order
1. revoke the credential ← minutes matter
2. issue a replacement
3. audit provider logs for use
4. git filter-repo + force push
5. enable push protection
# Remove a file from all history (rotation comes first)
git filter-repo --path config/secrets.yml --invert-paths --force
git push --force --all && git push --force --tags
# Scan full history, redacted output
gitleaks detect --log-opts="--all" --redact --report-format sarif
trufflehog git file://. --only-verified
Supply Chain
Control
Command
Protects
Reproducible install
npm ci
Lockfile drift
Block lifecycle scripts
npm ci --ignore-scripts
postinstall RCE
Build allowlist
pnpm.onlyBuiltDependencies
Script RCE
Runtime audit
npm audit --omit=dev --audit-level=high
Known CVE
Signature check
npm audit signatures
Tarball substitution
Force transitive
overrides
Unpatched deep dep
Provenance
npm publish --provenance
Source↔tarball
SBOM
@cyclonedx/cyclonedx-npm
Inventory
Image sign
cosign sign
Substitution
SRI
integrity="sha384-…"
CDN compromise
Standard
Identifier
SBOM format
SPDX (ISO/IEC 5962:2021)
SBOM format
CycloneDX (ECMA-424)
Provenance
SLSA Build L1 / L2 / L3
Signing
Sigstore: Fulcio + Rekor
SRI coverage
script, stylesheet, preload only — notfetch, XHR, import()
CI/CD Hardening
# Default deny; every grant deliberate
permissions:
contents: read
jobs:
test:
steps:
# SHA-pinned; a tag can be moved, a SHA cannot
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with: { persist-credentials: false }
# Untrusted context through env, never interpolated into the script
- env: { PR_TITLE: "${{ github.event.pull_request.title }}" }
run: echo "PR title is $PR_TITLE"
deploy:
environment: production # human approval gate
permissions: { contents: read, id-token: write }
Risk
Rule
Script injection
${{ }} never inside run; pass via env
pull_request_target
Never check out fork head
Tag mutation
Pin full commit SHA
Token in .git/config
persist-credentials: false
Cache poisoning
Key includes ref
Artifact theft
Scope run-id
Long-lived cloud key
OIDC with constrained sub
AI / LLM Security
Layer
Control
Injection
Tool-free read phase; separate act phase
Output → HTML
DOMPurify allowlist
Output → markdown
skipHtml, drop images
Output → URL
Host allowlist
Output → shell/SQL
argv array, parameterise
Exfiltration
CSP img-src / connect-src
Tools
Per-user OAuth, per-tool scope
Irreversible action
Confirm over raw JSON args
Consumption
max_tokens, loop ceiling, call cap
Prompt
No secrets — assume extraction
THE LETHAL TRIFECTA
[1] private data + [2] untrusted content + [3] egress
─────────────────────────────────────────────────────────────
remove any one of the three and the injection has
nowhere to go. Two are survivable; all three are not.
Defence
Robustness
Instruction hierarchy
Probabilistic
Prompt delimiters
Weak
Output sanitisation
Strong
CSP / egress allowlist
Strong
Least-privilege scope
Strong
Human confirmation
Strong
Monitoring
Detective
Threat Modeling — STRIDE
Letter
Threat
Property
Control
S
Spoofing
Authentication
MFA, mTLS
T
Tampering
Integrity
Signatures, TLS
R
Repudiation
Non-repudiation
Audit log, hash chain
I
Info disclosure
Confidentiality
Authz, encryption
D
DoS
Availability
Rate limits, quotas
E
Elevation
Authorization
Scope checks
STRIDE PER DFD ELEMENT
element S T R I D E
─────────────────────────────────────────────
external entity ✓ · ✓ · · ·
process ✓ ✓ ✓ ✓ ✓ ✓
data store · ✓ ✓ ✓ ✓ ·
data flow · ✓ · ✓ ✓ ·
Shostack's four questions: building / wrong / doing / good job
Security Testing
Technique
Runs On
Finds
Tool
Unit / types
Every commit
Logic errors
jest, tsc
SAST
PR diff
Tainted flows
Semgrep, CodeQL
SCA
PR
Known CVEs
Dependabot, Trivy
DAST baseline
Preview
Runtime misconfig
ZAP passive
DAST full
Staging only
Injections
ZAP active
Fuzzing
Continuous
Parser/memory
libFuzzer, Atheris
Pen test
Quarterly
Business logic
Manual
# Passive only — safe against preview
zap-baseline.py -t "$PREVIEW_URL" -J report.json -w report.md
# Active — disposable environments only
zap-full-scan.py -t "$STAGING_URL"
# SAST with SARIF so findings annotate the diff
semgrep ci --sarif --output=semgrep.sarif
// ✅ Fuzz target: any parse success must not panic
f.Add("filter=status:open")
f.Fuzz(func(t *testing.T, raw string) {
q, err := ParseQuery(raw)
if err != nil { return }
_ = q.String()
})
Audit Logging
Field
Required
Purpose
ts
✅
Timeline
event
✅
Classification
outcome
✅
Attempt vs success
actor.id
✅
Attribution
actor.ip
✅
Source
target.id
✅
Impact scope
request.id / trace_id
✅
Join to app logs
Never Log
Why
Passwords
Any hash is crackable
Session tokens / API keys
Replay
Full PAN
PCI DSS 3.3; truncate to last 4
CVV
PCI DSS — never stored at all
PII beyond purpose
GDPR minimisation
// ✅ Hash-chain append: removal is detectable
const body = JSON.stringify({ ...record, prev_hash: prev });
const hash = createHash("sha256").update(body).digest("hex");
await auditSink.append({ ...record, prev_hash: prev, hash });
// ✅ Enumeration detection
// SELECT actor->>'id', count(*) FROM audit_events
// WHERE event='invoice.read' AND outcome='denied'
// AND ts > now() - interval '15 minutes'
// GROUP BY 1 HAVING count(*) > 20;