Skip to content

Security Foundations: Why Systems Get Hacked, CIA Triad, Defense in Depth, STRIDE ​

"Every access to every object must be checked for authority." — Jerome H. Saltzer and Michael D. Schroeder, The Protection of Information in Computer Systems, Proceedings of the IEEE (1975), principle c) Complete mediation

Summary: Security in system design is the discipline of deciding, before the code exists, what must stay secret, correct and available, who might try to break that, where they can reach in, and which layered controls stop, detect and repair each attempt. Focus: Why systems really get hacked (attacker economics, attack surface, misconfiguration, stolen credentials, unpatched and zero-day vulnerabilities, supply chain, social engineering, with Verizon DBIR numbers), the CIA triad plus authenticity, non-repudiation and accountability (and the Parkerian hexad), threat modelling (assets, trust boundaries, data flow diagrams, STRIDE per element with a worked web app + API + queue + database table, DREAD, CVSS v4, attack trees, abuse cases, MITRE ATT&CK), defense in depth, the Saltzer and Schroeder principles with zero trust, secure by default and shift left, preventive/detective/corrective controls, secrets and supply chain hygiene (SBOM, pinning, Sigstore, SLSA), the security design review, and compliance frameworks (SOC 2, ISO 27001, PCI DSS, GDPR) as design constraints. Learning goal: Draw a data flow diagram of any system with its trust boundaries, generate and triage its STRIDE checklist, place layered controls with a reason for each, apply the design principles to a concrete API, and run a security design review that ends with owners, residual risk and tests instead of a feeling.

This chapter is the map of the SD 07 Security group. It owns the vocabulary, the threat model and the layering; each sibling owns one mechanism in depth: Authentication (passwords, MFA, sessions), JWT, OAuth 2.0 and OIDC, Authorization models and zero trust, Cryptography, TLS, PKI and secrets, OWASP Top 10, DDoS and network segmentation, mTLS between services and Secure SDLC and incident response. Primitives (AES-GCM, signatures, KDFs) live in Cryptography Fundamentals; database hardening (roles, RLS, pgAudit) lives in Database Security; code-level secure design lives in Security by Design.

Page map ​

If you are looking forGo to
The whole page in four tablesEverything in one minute
Why attackers succeed, with numbersWhy it exists, How systems really get hacked
Saltzer and Schroeder, STRIDE, ATT&CK, CVSS historyWhere it comes from
Attack surface and threat actorsAttack surface
Confidentiality, integrity, availabilityCIA triad
Authenticity, non-repudiation, accountability, Parkerian hexadBeyond CIA
Assets, trust boundaries, DFDs, the four questionsThreat modelling
Spoofing, Tampering, Repudiation, Information disclosure, DoS, ElevationSTRIDE per element
The worked table for web app + API + queue + DBWorked STRIDE table
DREAD, CVSS v4, likelihood times impactScoring risk
Attack trees, abuse casesAttack trees and abuse cases
Tactics and techniquesMITRE ATT&CK
Layers from edge to dataDefense in depth
Least privilege, fail-safe defaults, complete mediation and friendsDesign principles
Zero trust in one blockZero trust
Secure by default, shift leftSecure by default and shift left
Preventive, detective, correctiveControls catalogue
Secrets in code and configSecrets hygiene
SBOM, pinning, Sigstore, SLSASupply chain
SOC 2, ISO 27001, PCI DSS, GDPRCompliance as constraints
The design review checklistSecurity design review
What to do when it happens anywayIncident basics
Exact knobs, status codes, vector stringsMechanics
CodeGo, Laravel
Classic holes and their fixesSolving the classic problems
Which control for which situationChoosing
Monolith to distributed systemIn architecture
Run the threat-model tool and the serverLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The properties you protect, and the STRIDE threat that attacks each.

PropertyPlain wordsSTRIDE threat against itTypical control
ConfidentialityOnly the right people can read itInformation disclosureAuthorization, encryption, minimisation
IntegrityNobody can change it unnoticedTamperingValidation, MACs and signatures, least privilege
AvailabilityIt works when it is neededDenial of serviceLimits, timeouts, redundancy, backups
AuthenticityIt is really who or what it claims to beSpoofingMFA, mTLS, signed tokens
Non-repudiation / accountabilityAn actor cannot deny an action, and every action traces to an actorRepudiationAudit logs, signatures, synchronised clocks
AuthorizationEach actor does only what it is allowed toElevation of privilegePolicy check on every request, least privilege

How breaches start (Verizon DBIR 2025, 12,195 confirmed breaches).

Initial vector or factorWhat the DBIR 2025 press release saysDesign answer on this page
Credential abuseLeading vector, 22%MFA, rate limits against credential stuffing, short-lived tokens
Exploitation of vulnerabilities20%, up 34%, "zero-day exploits targeting perimeter devices and VPNs"Patch cadence, small attack surface, zero trust instead of VPN-equals-trusted
Third-party involvement"doubled to 30%"Supply chain controls, vendor least privilege
RansomwarePresent in 44% of breachesTested offline backups, segmentation, detective controls
Human element"significant overlap between social engineering and credential abuse"Phishing-resistant MFA (passkeys), least privilege

The threat-modelling loop (Threat Modeling Manifesto via OWASP).

QuestionOutputTool on this page
What are we working on?Data flow diagram with trust boundaries and assetsDFD, model.json
What can go wrong?Threat listSTRIDE per element, attack trees, ATT&CK
What are we going to do about it?Mitigate, eliminate, transfer or accept each threatControls catalogue, principles
Did we do a good enough job?Reviewed model, tests for each mitigationDesign review, CI gate in Go

Layers and principles worth reciting.

Layer (outside in)Example controlsPrinciple it leans on
EdgeCDN, WAF, DDoS protection, TLSEconomy of mechanism (one hardened entry)
NetworkVPC segmentation, security groups, mTLSLeast privilege for packets
IdentityMFA, SSO, workload identitySeparation of privilege
ApplicationAuthorization per request, validation, limitsComplete mediation, fail-safe defaults
DataLeast-privilege roles, encryption at rest, backupsLeast privilege, defense in depth
MonitoringAudit logs, alerts, incident responseCompromise recording, accountability
1 EdgeCDN, WAF (Cloudflare, AWS WAF), DDoS protection, TLS termination, bot rules2 NetworkVPC subnets, security groups, Kubernetes NetworkPolicy, no public DB, mTLS (Istio)3 IdentityMFA, SSO (OIDC), short-lived tokens, workload identity, no shared accounts4 Applicationauthorization on every request, validation, CSRF, rate limits, safe headers, timeouts5 Dataleast-privilege DB roles, encryption at rest (KMS), tokenisation, tested backups6 Monitoringaudit logsWAF and auth alertsSIEM correlationanomaly detectionincident responserunbooks, restoredetective andcorrective controlsthat see everylayerAttackerphishedpasswordpasses 1-3stoppedat 4Why layersEach layer assumes the one above it has already failed. A stolen password defeats the edge, the network and a password-only login,but the per-object authorization check still refuses another tenant's invoice, the DB role cannot dump other tables,and the audit log plus an alert on unusual access tells responders within minutes instead of months.

The picture is the shape of the whole chapter: the attacker is assumed to get through some layers, so every layer is designed as if the one above it has already failed.

Why it exists ​

A system is attacked because someone gains more from breaking it than it costs them. That is the whole economics: an attacker with a list of a billion leaked passwords pays almost nothing per login attempt, a ransomware crew pays nothing for a misconfigured backup server it finds by scanning, and a nation-state pays a lot for a zero-day because the prize justifies it. Defenders do not need to be unbreakable; they need to make every path more expensive than its prize, and to notice quickly when someone pays the price anyway.

Security is a design property, not a feature you add later, because the expensive mistakes are architectural: a database reachable from the internet, a single shared admin account, an API that trusts a tenant_id from the request body, a network where everything inside the VPN trusts everything else. None of these is a bug a scanner finds in a line of code; each is a decision on a diagram.

Security as an afterthoughtSecurity as a design input
Pen test finds the IDOR two weeks before launchThe DFD shows the trust boundary and the per-object check is a requirement
One perimeter (VPN, firewall), flat insideLayers; each assumes the outer one failed
Shared admin account, long-lived keysNamed identities, short-lived credentials, least privilege
Errors print stack tracesGeneric errors outside, details in an access-controlled log
"We will add logging later"Audit events are part of the API contract
Compliance is a yearly scrambleSOC 2 / PCI DSS / GDPR controls are traced to components

The analogy reused on this page: a bank branch. The vault holds the asset (confidentiality, integrity). The door, the guard, the teller window and the vault door are layers (defense in depth). The teller checks your ID for every withdrawal, not only the first one (complete mediation). The vault needs two keys held by two people (separation of privilege and duties). The cameras do not stop a robbery but make it provable and traceable (detective controls, non-repudiation). Insurance and the cash reserve let the branch reopen tomorrow (corrective controls, availability). A threat model is the walk-through the manager does with a floor plan, asking at every door "who could pretend to be someone else here, what could they change, what could they take, how could they stop us working?"

Three common misunderstandings, up front ​

  1. "Attackers mostly use clever zero-days." The DBIR 2025 press release puts credential abuse (22%) ahead of exploitation of vulnerabilities (20%) as initial vectors, and most exploited vulnerabilities are known ones. The 2026 DBIR landing page says software vulnerabilities now beat stolen passwords as the top way in, which is still mostly about patching speed and exposure, not genius.
  2. "We use HTTPS, so we are secure." TLS protects a data flow against tampering and disclosure in transit. It does nothing against a forged identity, a missing authorization check, a leaked database dump or a flood of requests. It is one control for three of eighteen cells in the STRIDE grid.
  3. "Threat modelling needs a security team and a week." The OWASP cheat sheet describes four questions; for one feature they take an hour around a whiteboard, and the model can live in the repository as data (the Go tool on this page does exactly that).

Where it comes from ​

Saltzer and Schroeder, 1975. The Protection of Information in Computer Systems placed potential violations in three categories: "Unauthorized information release", "Unauthorized information modification" and "Unauthorized denial of use". Those are confidentiality, integrity and availability under older names. The same paper lists eight design principles ("Economy of mechanism, fail-safe defaults, complete mediation, open design, separation of privilege, least privilege, least common mechanism, and psychological acceptability") plus two borrowed from physical security, work factor and compromise recording. Fifty years later they are still the vocabulary of every design review.

The CIA triad and the Parkerian hexad. The triad became the standard teaching frame; Donn B. Parker proposed in 1998 to add possession or control, authenticity and utility (secondary source: Wikipedia's Parkerian Hexad article). Regulation adopted the triad's words: GDPR Article 32 asks for "the ability to ensure the ongoing confidentiality, integrity, availability and resilience of processing systems and services".

STRIDE at Microsoft. OWASP's cheat sheet: "STRIDE is a mature and popular threat modeling technique and mnemonic originally developed by Microsoft employees." Microsoft's Security Development Lifecycle and the Microsoft Threat Modeling Tool built the per-element approach on data flow diagrams; Adam Shostack's Threat Modeling: Designing for Security (Wiley, 2014; a second edition, Designing for Security in an AI World, is announced by his site for February 2027) made it a teachable method. (The Microsoft Learn pages could not be fetched from this machine; the per-element chart below is the widely published SDL chart, reproduced from our knowledge and implemented in code, not quoted.)

DREAD, then CVSS. DREAD (Damage, Reproducibility, Exploitability, Affected users, Discoverability) rated each category 1 to 10 and summed them (secondary source: Wikipedia). It fell out of favour for being subjective; the OWASP threat modelling process page notes that qualitative values "help avoid the ranking becoming overly subjective". FIRST's CVSS became the industry score for vulnerabilities; version 4.0 "consists of four metric groups: Base, Threat, Environmental, and Supplemental".

Attack trees, ATT&CK, zero trust, supply chain. Bruce Schneier's Attack Trees (Dr. Dobb's Journal, December 1999) gave goal-rooted trees with AND and OR nodes. MITRE ATT&CK became "a globally-accessible knowledge base of adversary tactics and techniques based on real-world observations". NIST SP 800-207 (August 2020) defined zero trust architecture. After SolarWinds-style compromises, SBOMs (CISA), SLSA build levels and Sigstore keyless signing made the supply chain a first-class design topic, and OWASP Top 10:2025 lists "A03 Software Supply Chain Failures".

text
     Year   Idea                                        What changed in practice
1    1975   Saltzer & Schroeder                          Three violation categories (CIA) and eight design principles
2    1998   Parkerian hexad (Parker)                     Possession, authenticity, utility added to CIA
3    1999   Schneier, Attack Trees                       Goal-rooted AND/OR trees with priced leaves
4    -      STRIDE and DREAD at Microsoft (SDL)          Per-element threat checklists on DFDs
5    2014   Shostack, Threat Modeling (Wiley)            The method taught outside Microsoft
6    -      MITRE ATT&CK                                 Shared names for real adversary techniques
7    -      GDPR (Articles 25 and 32)                    "Data protection by design and by default" becomes law
8    2020   NIST SP 800-207 (August 2020)      No implicit trust from network location
9    2023   FIRST CVSS v4.0                              Base, Threat, Environmental, Supplemental groups
10   2024   NIST CSF 2.0 (26 Feb 2024)                   GOVERN added to Identify/Protect/Detect/Respond/Recover
11   2025   OWASP Top 10:2025                            Supply chain failures enter at A03

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline or request flow, real scenarios, how products provide it, and the fix.

Attack surface and threat actors Must-know ​

In plain words: the attack surface is every place an attacker can send input or reach in: every URL, port, queue, upload form, admin panel, CI token, third-party SDK and person with access. A threat actor is whoever might use it, with a motive and a budget.

Common misunderstanding: "Our attack surface is the public API." It also includes the staging environment with production data, the forgotten /debug endpoint, the S3 bucket with public ACLs, the CI runner that holds deploy keys, the support staff who can reset passwords, and every dependency you install.

Definition: attack surface = the set of entry points (and exit points) across trust boundaries, plus the assets reachable from each. Threat actor = an adversary class characterised by motive (money, espionage, activism, revenge, curiosity), capability (script, crew, nation-state) and access (outsider, customer, insider, partner).

text
     Attacker path through a typical web stack (attack surface enumerated)
1    scan: *.example.com -> finds staging.example.com (forgotten, no WAF)
2    staging /actuator/env -> leaks DB_PASSWORD (misconfiguration, information disclosure)
3    DB port 5432 open to 0.0.0.0/0 on the staging security group (misconfiguration)
4    staging DB is a nightly copy of production (asset outside its boundary)
5    exfiltrate customers table -> breach notification under GDPR Art. 33/34
     Every step used an entry point nobody listed in the design.

Real scenarios: a marketing subdomain on an old CMS; a mobile app that ships an API key; a partner SFTP drop that runs a parser on uploaded files; a support tool that impersonates users with no audit trail; a GitHub Actions workflow triggered by pull requests from forks that can read secrets.

Threat actorMotiveTypical capabilityWhat it usually goes for
Opportunistic criminalMoney at scaleAutomated scanning, leaked credential listsExposed services, credential stuffing, ransomware
Organised crewMoney, extortionCustom tooling, initial-access brokersVPN and edge-device exploits, backups, domain admin
Nation-stateEspionageZero-days, supply chain operationsLong-term access, source code, identity providers
Insider (malicious or careless)Money, revenge, mistakeLegitimate accessBulk exports, misconfigured sharing
Customer or partnerFraud, competitive dataValid accountsIDOR, business-logic abuse, scraping

Fix / how to use it: keep an inventory (DNS, cloud accounts, endpoints, queues, CI), delete what you do not need (Shostack's "eliminate"), put every remaining entry behind the same edge and identity layers, and list actors explicitly in the threat model so "who would bother?" becomes a written assumption.

How systems really get hacked: the initial access vectors Must-know ​

In plain words: most break-ins use one of five doors: a password someone else already has, a known hole nobody patched, a setting left open, a trusted supplier that was itself compromised, or a person who was tricked.

Common misunderstanding: "Phishing is a user-training problem, not an architecture problem." Phishing-resistant authentication (passkeys, FIDO2, mTLS for services), least privilege and short-lived sessions are architecture; they make the phished credential worth less.

Definition: an initial access vector is the first technique that gives an attacker a foothold. The ones every design must answer:

VectorWhat happensEvidenceDesign control
Credential stuffingLeaked username/password pairs tried against your loginATT&CK T1110.004: "Adversaries may use credentials obtained from breach dumps of unrelated accounts to gain access to target accounts through credential overlap."MFA, per-account and per-IP throttling, breached-password checks, bot detection
PhishingA message tricks a person into giving credentials or running codeATT&CK T1566: "All forms of phishing are electronically delivered social engineering."Passkeys/FIDO2, least privilege, attachment sandboxing, reporting button
MisconfigurationA setting exposes data or control (public bucket, default password, debug mode)OWASP Top 10:2025 "A02 Security Misconfiguration"Secure-by-default templates, policy as code, config scanning
Unpatched or zero-day vulnerabilityCode flaw exploited before or after a fix existsDBIR 2025: exploitation up 34%, focus on "perimeter devices and VPNs"Patch SLAs, small surface, WAF virtual patching, segmentation
Supply chain attackA dependency, build tool or vendor is compromisedATT&CK T1195: "Adversaries may manipulate products or product delivery mechanisms prior to receipt by a final consumer"Pinning, SBOM, signature verification, vendor least privilege
Social engineering beyond emailHelp-desk password resets, SIM swaps, fake vendorsDBIR 2025: overlap of social engineering and credential abuseOut-of-band verification, step-up auth for resets
text
     Credential stuffing against /login, no throttling (timeline)
1    t=0     attacker loads 1,000,000 leaked pairs from an unrelated breach
2    t=0-60m 280 req/s from a residential proxy pool, ~1 attempt per IP per minute
3    t=60m   0.1% reuse rate (illustrative) -> 1,000 valid accounts
4    t=61m   logins succeed; nothing alerts because no single IP looks noisy
5    t=2d    stored cards used, loyalty points drained, support flooded
     Controls that break it: MFA (step 4), per-account limit + breached-password check (step 3),
     anomaly alert on failed-login ratio across IPs (step 2).

Real scenarios: a loyalty programme drained by credential stuffing; a ransomware crew entering through an unpatched VPN appliance; a typosquatted npm package stealing CI secrets; a contractor's laptop with a saved production kubeconfig.

Fix / how to use it: in the design review, ask for each entry point which of the five doors it offers, and require one preventive and one detective control per door. Credential and session mechanics are in Authentication; vulnerability classes in OWASP Top 10.

The CIA triad Must-know ​

In plain words: confidentiality means only the right people can read it, integrity means nobody can change it without being noticed or authorised, availability means it is there when it is needed.

Common misunderstanding: "Integrity means the data is encrypted." Encryption alone (for example AES-CBC without a MAC) gives confidentiality; integrity needs a MAC, a signature, an authenticated cipher (AES-GCM) or access control on writes. Laravel's encrypter makes this explicit: values are encrypted with AES-256-CBC and "signed using a message authentication code (MAC)".

Definition: the three security objectives of information and systems. Saltzer and Schroeder defined their violations: unauthorized information release (confidentiality), unauthorized information modification (integrity, which "does not require that the intruder see the information he has changed"), and unauthorized denial of use (availability).

text
     One order, three properties (request flow)
1    Browser -> POST /orders {card, address}           C: TLS in transit, card tokenised at the PSP
2    API validates, writes orders row                  I: validation, DB role cannot UPDATE amount after capture
3    API -> queue "order.placed" -> worker             I: message signed or broker ACL; C: no card in the message
4    Worker -> PSP capture                             A: timeout + retry with idempotency key
5    Black Friday: 20x traffic                         A: rate limits, autoscaling, load shedding

Real scenarios: confidentiality, a leaked customer export; integrity, a price changed in transit or an attacker editing their own invoice amount; availability, ransomware encrypting the database or a regex that spins one CPU per request. The three conflict: more replicas and backups (availability) create more copies to protect (confidentiality); strict input rejection (integrity) can lock users out (availability).

PropertyMeasured asTypical design controlProduct example
ConfidentialityWho can read what; data classificationAuthorization, encryption at rest and in transit, minimisationAWS KMS, PostgreSQL RLS, Laravel encrypted cast
IntegrityUnauthorised changes detected or preventedValidation, MACs/signatures, write permissions, auditSigned URLs (Laravel), Sigstore signatures, PostgreSQL grants
AvailabilitySLO, RTO/RPORedundancy, limits, timeouts, backupsCloudflare/AWS Shield, Go http.Server timeouts, throttle middleware

Fix / how to use it: classify data (public, internal, confidential, restricted), write the three properties per asset in the threat model, and pick controls per property; one control rarely serves all three. The cryptographic tools are in Cryptography in Practice.

Beyond CIA: authenticity, non-repudiation, accountability, Parkerian hexad Important ​

In plain words: authenticity is "this really came from who it says"; non-repudiation is "they cannot later deny they did it"; accountability is "every action traces back to one actor".

Common misunderstanding: "Our logs give us non-repudiation." Ordinary application logs that admins can edit, with a shared service account as the actor, give neither accountability nor non-repudiation. You need a named identity per actor, tamper-evident storage, and synchronised clocks; for legal-grade non-repudiation, a signature only the actor could have produced.

Definition: authenticity: the property that an entity or data is genuine (verified by authentication and integrity checks). Non-repudiation: assurance that the sender or actor cannot deny the action (signatures, append-only signed logs). Accountability: actions of an entity can be traced uniquely to it. OWASP's STRIDE table lists "Accounting" as what Repudiation violates. The Parkerian hexad (Parker, 1998; secondary source) has six attributes: confidentiality, possession or control, integrity, authenticity, availability, utility. Possession covers "they have our encrypted backup tape even if they cannot read it"; utility covers "we have the data, but the key is lost so it is useless".

text
     Repudiation dispute (two actors)
1    10:02  support agent A uses shared account "support" to refund order 42
2    10:05  refund of 9,000 EUR lands on an attacker card
3    +3d    finance asks who did it; log says actor=support, ip=office NAT
4           A and B both deny it; no evidence distinguishes them
     With named accounts + audit row {actor: A, action: refund, order: 42, request_id}
     in an append-only table, step 4 has an answer (accountability), and a
     step-up confirmation signed with A's passkey gives non-repudiation.

Real scenarios: payment approvals (two-person rule plus signed approval), contract signing, admin impersonation tools, data exports, configuration changes in production, API calls between companies (signed webhooks).

NeedWeak versionStrong version
Authenticity of a userPassword onlyPhishing-resistant MFA, device binding
Authenticity of a serviceShared API keymTLS or workload identity with short-lived certificates
Authenticity of a messagePlain JSON over HTTPSHMAC or signature over the body plus timestamp (webhooks)
AccountabilityShared accounts, mutable logsNamed identities, append-only audit table, central log store
Non-repudiation"It is in our logs"Actor's private-key signature, transparency log (Rekor for artifacts)

Fix / how to use it: add an "actor" to every write path, write audit events to a store the application role cannot modify (the SQL in Mechanics), and use signatures where a third party must be convinced.

Threat modelling: assets, trust boundaries and data flow diagrams Must-know ​

In plain words: draw what you are building, mark where trust changes, list what is valuable, then ask what can go wrong at each place.

Common misunderstanding: "A threat model is a document you write once for the auditors." OWASP: "A threat model is something that should be maintained, updated and refined alongside the system." If it is not in the repository next to the code, it is out of date by the next sprint.

Definition: OWASP: threat modelling is "a structured, repeatable process used to gain actionable insights into the security characteristics of a particular system". Its four questions (Threat Modeling Manifesto) are "What are we working on?", "What can go wrong?", "What are we going to do about it?", "Did we do a good enough job?". The model has:

DFD elementShapeMeaningExamples
External entityRectangleOutside your control, interacts through an entry pointBrowser user, payment provider, partner API
ProcessCircleCode you run that transforms dataWeb app, API, worker, Lambda function
Data storeTwo parallel linesData at rest; OWASP: "Data stores do not modify the data, they only store data."PostgreSQL, S3 bucket, Redis, queue backlog
Data flowArrowData moving between elementsHTTPS request, SQL connection, AMQP message
Trust boundaryDashed lineOWASP: "Boundaries show any location where the level of trust changes."Internet/DMZ, app zone/data zone, tenant A/tenant B, CI/prod

An asset is anything worth protecting: data (PII, card data, credentials, audit logs), capabilities (issuing refunds, deploying code), and reputation or availability itself.

Internet (untrusted)DMZ / edgeApplication zoneData zoneCustomerbrowser (entity)Paymentprovider (entity)CDN + WAFWeb app(process)Orders API(process)Worker(process)Order queue (store)Orders DB: PII (store)Audit log (store)1 HTTPS2 mTLS3 AMQP4 SQL/TLS6 HTTPS out5 audit eventsRead it like a threat modellerEvery dashed box is a trust boundary. Arrows 1, 2, 4, 5 and 6 cross one: ask Spoofing, Tampering, Info disclosure, DoS there first.Circles are processes (all six STRIDE letters), two-line shapes are stores (T, I, D; R for the audit log), boxes are external entities (S, R).
text
     One-hour threat-modelling session for a new "share invoice by link" feature
1    0-10m   draw the DFD: user -> web -> API -> invoice store; new flow: anonymous -> download URL
2    10-15m  mark boundaries: the anonymous flow crosses internet -> app with NO session
3    15-40m  STRIDE the new elements: S (who is the downloader?), T (can the id be changed?),
             I (can links be guessed or leak via Referer?), D (bulk download?), R (who shared?)
4    40-55m  responses: signed + expiring URL (S, T), Referrer-Policy (I), throttle (D), audit row (R)
5    55-60m  owners and tests: each mitigation becomes a ticket with an acceptance test

Real scenarios: a new public endpoint; a new third-party integration; moving a component to another network zone; adding a queue between services (new store and two new flows); introducing an LLM tool that can call internal APIs.

Fix / how to use it: keep the DFD as data (the model.json in Go), re-run the checklist when the diagram changes, and record responses as Shostack's four options quoted by OWASP: mitigate, eliminate, transfer, accept. Other methods exist for other questions: LINDDUN for privacy, PASTA for business impact, OCTAVE for organisational risk, VAST for many teams (OWASP lists all of them); STRIDE is the default for a technical design.

STRIDE per element Must-know ​

In plain words: six questions, each the opposite of a property you want: can someone pretend (Spoofing), change (Tampering), deny (Repudiation), read (Information disclosure), stop (Denial of service), or gain powers (Elevation of privilege)?

Common misunderstanding: "Apply all six letters to every box." The per-element approach applies only the letters that make sense for the element type, which keeps the list honest and short. A data flow cannot repudiate anything; an external entity is outside your code so you do not ask whether its memory can be tampered with.

Definition: STRIDE groups threats into six categories, each "a violation of a desirable security attribute" (OWASP):

LetterThreatViolates (OWASP wording)OWASP exampleFirst controls
SSpoofingAuthentication"An attacker steals the authentication token of a legitimate user and uses it to impersonate the user."MFA, mTLS, token binding, short TTLs
TTamperingIntegrity"An attacker abuses the application to perform unintended updates to a database."Validation, MAC/signature, least privilege on writes
RRepudiationAccounting"An attacker manipulates logs to cover their actions."Append-only audit, central log store, signatures
IInformation disclosureConfidentiality"An attacker extracts data from a database containing user account info."Authorization, encryption, generic errors, minimisation
DDenial of serviceAvailability"An attacker locks a legitimate user out of their account by performing many failed authentication attempts."Rate limits, timeouts, body limits, quotas, autoscaling
EElevation of privilegesAuthorization"An attacker tampers with a JWT to change their role."Policy check per request, signed tokens validated, least privilege
DFD elementSauthenticityTintegrityRnon-repudiationIconfidentialityDavailabilityEauthorizationExternal entityProcessData storeData flowXXXXXXXXXif audit logXXXXX4 element types x applicable letters = the checklist. The cmd/stride tool in this chapter generates exactly this grid from a JSON DFD.Processes carry the most threats because they are where code runs and decisions are made.

The per-element chart (the convention from Microsoft's SDL and Shostack's book, implemented in threatmodel.Applicable): external entities get S and R; processes get all six; data stores get T, I, D, and R when they hold logs; data flows get T, I, D.

text
     STRIDE walk over one flow: "web app -> Orders API" crossing DMZ -> app zone
1    S  can a non-web caller reach the API and claim to be the web app?   -> mTLS / workload identity
2    T  can the body be changed between them?                            -> TLS (mTLS), signed internal tokens
3    I  can someone on the path read it?                                  -> TLS
4    D  can the web tier flood the API?                                   -> per-caller limit, timeouts
5    (R and E are asked on the two processes at each end, not on the flow)

Real scenarios: S, a forged X-User-Id header trusted behind a proxy; T, a client-side price field; R, a support refund with no actor; I, a stack trace with the DB DSN; D, a /search endpoint with an unbounded regex; E, a role field accepted by mass assignment.

Fix / how to use it: generate the checklist from the DFD (the Go tool prints it as a Markdown table), answer each row with a control id or an explicit acceptance, and fail CI on open high-severity rows.

The worked STRIDE table: web app + API + queue + database Must-know ​

In plain words: the same shop as the diagram, one row per element and letter that matters, each with a concrete threat and the control that answers it.

Common misunderstanding: "The queue is internal, so it needs nothing." A queue is a data store (backlog at rest) plus two flows. A worker that trusts any message on the queue turns "can publish to the queue" into "can ship orders for free".

Definition: the threat register for the system in the DFD figure. Element types follow the per-element chart; severity follows the triage rule in generate.go (sensitive asset and boundary crossing gives high).

Element (type)STRIDEConcrete threatControlControl type
Customer (entity)SCredential stuffing takes over accountsMFA, per-account throttle, breached-password checkPreventive
Customer (entity)R"I never placed that order"Audit row with session id, device, IP; email receiptDetective
Browser to web (flow)T, ISession cookie stolen on hostile Wi-FiTLS, HSTS, Secure + HttpOnly + SameSite cookiesPreventive
Browser to web (flow)DRequest flood, SlowlorisCDN/WAF rate rules, ReadHeaderTimeout, body limitsPreventive
Web app (process)TCSRF makes the browser post a changeLaravel PreventRequestForgery (Sec-Fetch-Site, then token)Preventive
Web app (process)IStack trace with secrets on errorAPP_DEBUG=false, generic error page, recover middlewarePreventive
Web app (process)EMass assignment sets role=admin$fillable, validated input onlyPreventive
Web to API (flow)SSomething else inside the VPC calls the APImTLS or signed service token (workload identity)Preventive
Orders API (process)EIDOR: GET /invoices/43 returns another tenant's invoicePolicy check per object (complete mediation), 404 for foreign idsPreventive
Orders API (process)DOne customer's export starves everyonePer-user quotas, separate limiter for exports, timeoutsPreventive
Orders API (process)RAdmin deletes an invoice silentlyAudit event with actor, append-only storeDetective
API to queue (flow)TForged "order.paid" message published by a compromised serviceBroker ACL per producer, signed message envelopePreventive
Order queue (store)IMessages carry full card data and sit for daysOnly token ids in messages, encryption at rest, retention limitPreventive
Order queue (store)DQueue filled by a poison loopMax length, DLQ, alert on depthDetective / corrective
Worker (process)EWorker's DB role can drop tablesLeast-privilege role: INSERT/UPDATE on two tables onlyPreventive
API to DB (flow)IPlaintext DB connection inside the VPCTLS with sslmode=verify-fullPreventive
Orders DB (store)ISnapshot shared publicly or stolen backupEncryption at rest (KMS), private snapshots, least privilegePreventive
Orders DB (store)T, DRansomware encrypts the databasePoint-in-time recovery, immutable off-account backups, restore drillsCorrective
Audit log (store)R, TAttacker deletes their trailAppend-only grants + trigger, hash chain, ship to separate accountPreventive / detective
Worker to PSP (flow)SWebhook from a fake "payment provider" marks orders paidVerify the provider's webhook signature and timestampPreventive

Real scenarios: this is the table you bring to the design review for any CRUD + async system; swap the PSP for a shipping partner or an email provider and most rows stay.

Fix / how to use it: run go run ./cmd/stride in the Lab and compare its output with this hand-written table; the tool finds the rows, humans write the concrete threat and decide.

Scoring risk: likelihood times impact, DREAD, CVSS v4 Important ​

In plain words: after listing threats you need an order to fix them; score how likely and how bad each one is.

Common misunderstanding: "A CVSS 9.8 in a library means we are at 9.8." CVSS Base describes the vulnerability in general; your risk depends on whether the vulnerable function is reachable, the asset behind it and existing controls. CVSS v4 has Threat and Environmental groups exactly for that, and Go's govulncheck reports only vulnerabilities in functions your code actually calls.

Definition: OWASP: "ranking should be based on the mathematical product of an identified threat's likelihood and its impact", while noting both are hard to estimate and ignore the cost of the fix. DREAD rates five factors 1 to 10 and sums them (Wikipedia). CVSS v4.0 (FIRST) scores vulnerabilities from metric groups Base, Threat, Environmental and Supplemental, and names scores by what was used: CVSS-B, CVSS-BT, CVSS-BE, CVSS-BTE.

CVSS v4 ratingScore range
None0.0
Low0.1 - 3.9
Medium4.0 - 6.9
High7.0 - 8.9
Critical9.0 - 10.0
text
     Reading a CVSS v4 vector from the spec (example vector, ours annotated)
1    CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N/E:A
2    AV:N  attack vector network        AC:L  low complexity      AT:N  no attack requirements
3    PR:H  high privileges required     UI:N  no user interaction
4    VC/VI/VA  impact on the vulnerable system (L, L, None); SC/SI/SA impact on subsequent systems (None)
5    E:A   Threat metric Exploit Maturity = Attacked (exploitation reported) -> CVSS-BT score
MethodGood forWeakness
Likelihood x impact (High/Medium/Low)Design-time threatsCoarse, but honest about uncertainty
DREADHistorical; quick team discussionSubjective; Discoverability rewards obscurity
CVSS v4 BaseComparing vulnerabilities across vendorsNot your risk until Threat and Environmental are applied
CVSS-BTE + reachabilityPatch prioritisationNeeds asset inventory and exploit intelligence
Attack-tree costWhich path is cheapest for the attackerOnly as good as the leaf estimates

Real scenarios: a Critical CVE in an XML parser that your service never invokes (low priority after reachability); a Medium IDOR on the invoices API that exposes every customer (high business impact); a Low-scored info leak that reveals internal hostnames used in a later attack chain.

Fix / how to use it: use High/Medium/Low at design time, CVSS-BTE plus reachability for patching, and write the residual risk and its owner next to every accepted threat.

Attack trees and abuse cases Important ​

In plain words: an attack tree starts from what the attacker wants and branches into every way to get it; an abuse case is a user story written by the attacker ("as a customer I want to see other customers' invoices").

Common misunderstanding: "STRIDE already covers business-logic abuse." STRIDE asks about properties of elements; it rarely finds "apply the same coupon 50 times in parallel" or "refund to a different card". OWASP's method table recommends "Misuse or abuse cases" to "Explore actions performed out of order, repeatedly, concurrently, or for an unintended outcome."

Definition: Schneier (1999): "you represent attacks against a system in a tree structure, with the goal as the root node and different ways of achieving that goal as leaf nodes", with OR nodes as alternatives and AND nodes as required steps; leaves can carry costs that propagate up. Abuse case: a negative requirement describing an interaction that must fail, with an acceptance test.

GOAL: read another customer's invoicesOR take over an accountOR abuse the APIOR reach the DB directlycredentialstuffingcut: MFA, throttlephish asessioncut: passkeyschange invoiceid (IDOR)cut: policy checkreplay a leakedshare linkcut: signed + expirypublic DBendpointcut: private subnet.env in publicrepo AND reachablecut: secrets managerANDHow to use itRoot = attacker goal. Children of an OR node are alternatives (cheapest one wins); children of an AND node are all required.Price each leaf (cost, skill, detectability). The cheapest path is where the next control goes; one control on an AND branch cuts the whole branch.Pattern from Schneier, Attack Trees (Dr. Dobb's Journal, 1999).
text
     Abuse case -> test (coupon race)
1    Story:   as a customer I apply coupon SAVE50 in 20 parallel requests
2    Expect:  exactly one order gets the discount; 19 get 409 Conflict
3    Control: unique (coupon_id, customer_id) constraint + transaction (see /database/isolation-levels)
4    Test:    integration test fires 20 goroutines / Laravel parallel HTTP calls and counts 201s

Real scenarios: gift-card balance races, refund to a different instrument, account recovery via email takeover, scraping through pagination, invite-link reuse, quantity set to a negative number.

TechniqueStarts fromFinds best
STRIDE per elementThe diagramMissing technical controls at elements and flows
Attack treeAn attacker goalCheapest multi-step path; where one control cuts a branch
Abuse caseA user storyBusiness-logic flaws, races, workflow order
ATT&CK mappingKnown adversary behaviourDetection gaps after initial access

Fix / how to use it: one attack tree per top asset ("read another tenant's data", "move money", "deploy code"), and one abuse case per money- or permission-changing endpoint, each turned into an automated test.

MITRE ATT&CK mapping Good to know ​

In plain words: a shared dictionary of what real attackers do after they get in, organised by goal (tactic) and method (technique), so you can ask "would we notice this?".

Common misunderstanding: "ATT&CK is a checklist to make us secure." It describes adversary behaviour; it is most useful for detection engineering and red/blue exercises, after the design-time threat model.

Definition: "a globally-accessible knowledge base of adversary tactics and techniques based on real-world observations". The Enterprise matrix, as shown on the ATT&CK site when we fetched it, lists the tactics Reconnaissance, Resource Development, Initial Access, Execution, Persistence, Privilege Escalation, Stealth, Defense Impairment, Credential Access, Discovery, Lateral Movement, Collection, Command and Control, Exfiltration and Impact. Techniques have ids such as T1110.004 (Credential Stuffing), T1566 (Phishing), T1195 (Supply Chain Compromise).

text
     Mapping one breach story to ATT&CK and to our layers
1    Initial Access     T1566 Phishing -> developer laptop        layer: identity (passkeys), endpoint
2    Credential Access  steals cloud CLI token                    layer: short-lived creds, device-bound
3    Discovery          lists S3 buckets                          detect: unusual API calls alert
4    Collection/Exfil   downloads backups                         layer: data (KMS key policy), egress limits
5    Impact             deletes snapshots, ransom note            corrective: immutable cross-account backups
STRIDE (design time)ATT&CK tactic it relates to (operations)
SpoofingInitial Access, Credential Access
TamperingPersistence, Impact
RepudiationStealth, Defense Impairment
Information disclosureCollection, Exfiltration
Denial of serviceImpact
Elevation of privilegePrivilege Escalation, Lateral Movement

Real scenarios: writing detection rules for the SIEM; choosing which logs to keep; planning a tabletop exercise; reading a vendor's incident report.

Fix / how to use it: for each high-severity threat, name the ATT&CK technique and the log line that would show it; if no log would, that is a detective-control gap. Operations detail is in Secure SDLC and incident response.

Defense in depth Must-know ​

In plain words: several independent locks, so one broken lock is not a breach.

Common misunderstanding: "Defense in depth means buying more products." Two WAFs in a row are one layer. Layers must fail independently: different mechanism, different credentials, different team or account.

Definition: OWASP's Secure Product Design cheat sheet: a strategy "that involves multiple layers of security controls to protect an organization’s assets", based on the idea "that if one layer of security fails, the other layers will still be able to protect the asset."

LayerPreventiveDetectiveCorrectiveSibling chapter
EdgeWAF (Cloudflare, AWS WAF), DDoS protection, TLS, bot rulesWAF logs, rate anomaliesUnder-attack mode, block listsDDoS & network security, CDN
NetworkVPC private subnets, security groups, Kubernetes NetworkPolicy, mTLS (Istio, Linkerd)Flow logsIsolate a subnetmTLS, Firewalls
IdentityMFA, SSO (OIDC), workload identity, short-lived tokensFailed-login and impossible-travel alertsRevoke sessions, rotate keysOAuth/OIDC, Authentication
ApplicationAuthorization per request, validation, CSRF, rate limits, headers, timeoutsAudit events, error-rate alertsFeature flags, kill switchesOWASP Top 10, Rate limiting
DataLeast-privilege roles, RLS, encryption at rest (KMS), tokenisationpgAudit, access anomaly alertsPITR, immutable backupsDatabase Security, Encryption
Monitoring(none on its own)Central logs, SIEM, alertingIncident response, runbooksObservability
text
     Stolen password, with and without depth
1    attacker logs in with a phished password                    edge: passes; network: passes
2    without MFA: logged in                    with MFA (passkey): stopped here (identity)
3    GET /invoices/43 (another tenant)          policy check -> 404 (application)
4    tries SQL injection on /search             parameterised query; DB role read-only on 2 tables (data)
5    every step emits an audit event            alert "403/404 burst for one account" fires (monitoring)

Real scenarios: an SSRF that reaches the cloud metadata service is stopped by IMDSv2 and a role without S3 access; an SQL injection in a reporting page limited by a read-only replica role; a leaked API key blunted by IP allow-listing and per-key quotas.

Fix / how to use it: for each top threat, require controls in at least two different layers, one of them detective, and write down which layer you rely on if the first fails.

Design principles: Saltzer and Schroeder, applied Must-know ​

In plain words: a short list of habits that make whole classes of bugs impossible or cheap: give the least power, deny by default, check every time, keep it simple, assume the design is public, split critical powers.

Common misunderstanding: "Open design means open source." It means the protection must not depend on the attacker not knowing how it works: "The design should not be secret". Security rests on keys and credentials, which are easy to change, not on obscure endpoints, which are not.

Definition: the eight principles of the 1975 paper, with the modern names and practices:

PrincipleSaltzer and Schroeder wordingModern practiceExample in this chapter's code
Economy of mechanism"Keep the design as simple and small as possible."One auth library, one policy engine, small trusted baseOne middleware chain in secureserver.New
Fail-safe defaults"Base access decisions on permission rather than exclusion."Deny by default; zero config means safe configConfig.withDefaults never leaves a timeout at zero; policies deny unless allowed
Complete mediation"Every access to every object must be checked for authority."Authorization per request and per object; no cached "is admin"Gate::authorize('view', $invoice) on every call
Open design"The design should not be secret"Kerckhoffs; public algorithms; secrets only in keysSigned URLs rely on APP_KEY, not on hidden paths
Separation of privilege"a protection mechanism that requires two keys to unlock it is more robust"MFA, two-person approval, split KMS key policiespassword.confirm step-up before delete
Least privilege"Every program and every user of the system should operate using the least set of privileges necessary to complete the job."Scoped IAM roles, DB roles per service, short-lived tokensapp_writer role has INSERT/SELECT on audit only
Least common mechanism"Minimize the amount of mechanism common to more than one user"Tenant isolation, per-tenant keys, no shared admin accountsPer-user rate-limit keys
Psychological acceptability"the human interface be designed for ease of use"Passkeys over complex password rules; safe path is the easy pathSecure defaults instead of a hardening guide

Separation of duties is the organisational form of separation of privilege: the person who creates a payment cannot approve it, the developer who writes the code cannot deploy it alone. The InvoicePolicy::delete rule (the issuer cannot delete their own invoice) is a tiny example.

text
     Fail-safe defaults vs fail-open (authorization service timeout)
1    T0  request arrives, API asks the policy service "may user 7 view invoice 43?"
2    T1  policy service times out after 200 ms
3    fail-open code:  catch (Timeout) { allow }   -> every invoice readable during the outage
4    fail-safe code:  catch (Timeout) { deny 503 } -> users see an error, no data leaks
5    availability vs confidentiality trade-off decided in the design, not in a catch block

Real scenarios: an IAM policy with "Action": "*" for a Lambda that reads one bucket; a feature flag that defaults to "enabled" when the flag service is down; an admin panel protected only by an unlisted URL; a single person able to change bank details and approve the payment run.

Fix / how to use it: in review, ask for each new permission "what is the smallest set?", for each error path "does it fail closed?", and for each critical action "how many people or factors are needed?". Code-level application of the principles is in Security by Design.

Zero trust, in one block Important ​

In plain words: being inside the network proves nothing; every request is authenticated and authorised as if it came from the internet.

Common misunderstanding: "Zero trust is a product you buy." NIST SP 800-207 calls it "an evolving set of cybersecurity paradigms"; products implement parts (identity-aware proxies, mTLS meshes, device posture), but the decision is architectural.

Definition: NIST SP 800-207: "Zero trust assumes there is no implicit trust granted to assets or user accounts based solely on their physical or network location (i.e., local area networks versus the internet) or based on asset ownership (enterprise or personally owned)." Authentication and authorization "are discrete functions performed before a session to an enterprise resource is established."

text
     Perimeter model vs zero trust for an internal admin tool
1    perimeter: VPN login -> 10.0.0.0/8 reachable -> admin tool trusts source IP
2    attacker phishes one VPN credential -> every internal tool is open (lateral movement)
3    zero trust: identity-aware proxy -> SSO + MFA + device check -> per-app authorization
4    the same phished password fails at MFA; even with a session, only one app is reachable

Real scenarios: replacing a VPN with an identity-aware proxy; service-to-service mTLS with per-service authorization policies (Istio AuthorizationPolicy); short-lived database credentials issued per workload.

Perimeter assumptionZero trust replacement
Inside the VPC means trustedEvery call carries a verified identity
VPN grants network accessProxy grants access per application
Static service passwordsShort-lived certificates or tokens per workload
Check once at loginContinuous evaluation (device, risk, session age)

Fix / how to use it: start with the highest-value internal paths (admin tools, service-to-service calls to the payment service). The models and policy engines are in Authorization Models: RBAC, ABAC, ReBAC & Zero Trust.

Secure by default and shift left Must-know ​

In plain words: secure by default means the out-of-the-box configuration is the safe one; shift left means finding security problems earlier (design, code review, CI) where they are cheap.

Common misunderstanding: "Shift left means developers now do the security team's job." It means the security team builds paved roads (templates, libraries, CI checks) so the safe path is the default path; it does not remove the review or the operations side.

Definition: CISA's Secure by Design page: products should prioritise "the security of customers as a core business requirement", and "Out-of-the-box, products should be secure". GDPR Article 25 makes "Data protection by design and by default" a legal duty for personal data. Shift left: move threat modelling to design, SAST/SCA/secret scanning to the pull request, and policy as code to CI; OWASP: threat modelling "is ideally performed early in the SDLC, such as during the design phase."

text
     Cost of the same flaw found at different stages (qualitative)
1    design review   "tenant_id comes from the body" -> change one line in the spec
2    pull request    reviewer spots it -> change one handler, add a test
3    staging pen test -> fix handler, audit every similar endpoint
4    production      -> fix, investigate access logs, notify customers, regulators (GDPR Art. 33)

Real scenarios: a service template where new HTTP servers already have timeouts and headers (the secureserver package); a Terraform module where buckets are private and encrypted unless a reviewed exception says otherwise; a Laravel app where CSRF, hashing, encrypted cookies and APP_DEBUG=false in production are defaults.

DefaultInsecure defaultSecure default
Go HTTP serverhttp.ListenAndServe (zero-value Server, no timeouts)secureserver.New with all timeouts set
Laravel web routes(none; CSRF is on in the web group)PreventRequestForgery in the web group by default
PasswordsFast hashesLaravel Hash uses bcrypt by default; Argon2 available
Storage bucketsPublic ACLs allowedBlock public access on, encryption on
Debug outputDetailed errors everywhereGeneric errors in production

Fix / how to use it: make the secure configuration the only one the template offers, and require a reviewed, expiring exception to deviate. The pipeline side is in Secure SDLC.

Security controls catalogue: preventive, detective, corrective Must-know ​

In plain words: some controls stop the attack (lock), some notice it (alarm), some repair the damage (insurance and spare key).

Common misunderstanding: "If our preventive controls are good, we do not need detection." Every preventive control has gaps (zero-days, insiders, phished MFA). The DBIR's ransomware share (44% of breaches in the 2025 release) is largely a story of attacks that were not noticed until the impact.

Definition: a preventive control reduces the likelihood of a threat succeeding; a detective control identifies an attempt or a compromise; a corrective control limits damage and restores the system. Deterrent, compensating and recovery controls are sometimes added as separate types. NIST SP 800-53 Rev. 5 groups controls by family (Access Control, Audit and Accountability, Contingency Planning, Identification and Authentication, Incident Response, and others) rather than by type.

ControlTypeSTRIDE it answersProduct example
MFA / passkeysPreventiveSOkta, Entra ID, WebAuthn
Authorization policy per objectPreventiveE, ILaravel policies, OPA, Cedar
Input validation, parameterised queriesPreventiveT, ELaravel validation, database/sql placeholders
TLS / mTLSPreventiveT, I, SLet's Encrypt, Istio
Rate limits, timeouts, body limitsPreventiveDLaravel throttle, Go http.Server, Cloudflare rules
Encryption at restPreventiveIAWS KMS, PostgreSQL TDE (products vary), Laravel encrypted cast
Audit logDetectiveRpgAudit, CloudTrail, Laravel log channel
Alerting and SIEMDetectiveallDatadog, Elastic, Splunk
File integrity / signature verificationDetective (or preventive at admission)TSigstore cosign verify, Kubernetes admission policies
Backups and PITRCorrectiveD, TPostgreSQL PITR, AWS Backup
Key and credential rotationCorrectiveS, ILaravel APP_PREVIOUS_KEYS, Vault
Incident response runbookCorrectiveallPagerDuty, runbooks
text
     One threat, three control types (ransomware on the orders DB)
1    preventive   no public DB, least-privilege roles, MFA for admins, patched hosts
2    detective    alert on mass UPDATE/DELETE rate, snapshot deletion events, new admin user
3    corrective   immutable backups in a separate account, restore drill RTO 2 h, runbook
4    if 1 fails and 2 is missing, 3 is the only thing between you and paying

Real scenarios: a payment API with fraud scoring (preventive), chargeback monitoring (detective) and refunds plus card reissue (corrective); a CI system with signed commits (preventive), audit of workflow changes (detective) and secret rotation (corrective).

Fix / how to use it: in the threat register, every high-severity threat gets at least one preventive and one detective control, and the asset gets a corrective plan. The Go tool tags each missing control with its type.

Secrets hygiene, overview Important ​

In plain words: passwords, API keys, signing keys and tokens must never be in code, never be shared between environments, live as short as possible, and be rotatable without a deploy.

Common misunderstanding: "The repository is private, so a key in .env committed once is fine." Git history keeps it, forks and CI caches copy it, and laptops get stolen. Treat any committed secret as leaked and rotate it.

Definition: secrets management is the lifecycle of credentials: generation, storage (a secrets manager or KMS), distribution to workloads (environment injection, workload identity), use, rotation, revocation and audit.

text
     Leaked key, the usual timeline
1    commit adds config with AWS key "for testing"
2    pushed to a public fork / package by mistake
3    automated scanners find the key (minutes, per public reports; not measured here)
4    crypto-mining instances launched in every region
5    fix: revoke key, rotate, purge history, add secret scanning + pre-commit hook, use workload identity

Real scenarios: Laravel APP_KEY (encrypts cookies, signs URLs; rotate with APP_PREVIOUS_KEYS so old values still decrypt); database passwords in Kubernetes Secrets; webhook signing secrets; CI deploy keys.

PracticeWeakStrong
Storage.env in the repoSecrets manager (Vault, AWS Secrets Manager), KMS
LifetimeYearsShort-lived (minutes to hours) via workload identity
ScopeOne key for everythingOne key per service and environment
RotationManual, needs downtimeOverlap window (APP_PREVIOUS_KEYS, dual keys)
DetectionNoneSecret scanning in CI and on the git host

Fix / how to use it: the full design (envelope encryption, PKI, rotation) is in Cryptography in Practice.

Supply chain: SBOM, dependency pinning, signing with Sigstore, SLSA Must-know ​

In plain words: most of your production code was written by someone else; know what it is (SBOM), make sure you get exactly the version you reviewed (pinning and checksums), and that it was built by who you think (signatures and provenance).

Common misunderstanding: "Pinning versions in composer.json is enough." A version range resolves differently tomorrow; a lockfile (composer.lock, go.sum) pins exact versions and hashes, and Go's checksum database makes the hash for a module version the same for everyone. Pinning stops silent drift; it does not stop a malicious version you deliberately upgrade to.

Definition: CISA: "An SBOM is a nested inventory, a list of ingredients that make up software components." Dependency pinning: resolving every direct and transitive dependency to an exact version and content hash. Code signing: a signature binding an artifact to an identity. Sigstore: "Signatures are generated with ephemeral signing keys so there’s no need to manage keys. Signing events are recorded in a tamper-resistant public log". Its client Cosign gets a short-lived certificate from Fulcio bound to an OIDC identity, and records the signature in "an immutable, append-only ledger known as Rekor". SLSA defines build levels: "Build L0: No guarantees", "Build L1: Provenance exists", "Build L2: Hosted build platform", "Build L3: Hardened builds".

text
     A dependency attack and where each control cuts it
1    attacker publishes "left-padx" (typosquat) or hijacks a maintainer account
2    developer runs composer require / go get                  cut: allow-list, review new deps
3    CI resolves a range to the new malicious version           cut: lockfile + go.sum, no floating ranges
4    build embeds it; image pushed                              cut: SBOM shows the new component in the diff
5    cluster pulls the image                                    cut: admission policy requires cosign signature from our CI identity
6    runtime calls home                                         cut: egress allow-list, alert on new destinations

Real scenarios: an npm/PyPI typosquat; a compromised GitHub Action tag; a build server that injects code (SolarWinds-style; we cite only the category here); a base image with a known CVE.

ControlGoPHP / LaravelContainers
Pin exact versions and hashesgo.mod + go.sum, checksum databasecomposer.lockImage digest @sha256:
Known vulnerabilitiesgovulncheck (call-graph aware)composer auditImage scanners
SBOMcyclonedx-gomod, SyftCycloneDX Composer plugin, SyftSyft, BuildKit SBOM attestations
Signing and verificationCosign for binaries (sign-blob)Cosign for release archivescosign sign / cosign verify, Kubernetes admission policy
ProvenanceSLSA generator in CISLSA generator in CIBuild attestations

Fix / how to use it: lockfiles committed and verified in CI, SBOM generated per build and stored with the artifact, images signed by the CI identity and verified at deploy, and a short list of who may add dependencies. OWASP Top 10:2025 now ranks this risk third.

Compliance frameworks as design constraints Important ​

In plain words: some customers, card networks and laws require specific controls; treat them as non-functional requirements on the design, not as paperwork after it.

Common misunderstanding: "Being compliant means being secure." Compliance is a minimum baseline audited at a point in time; attackers do not check certificates. The reverse also holds: a secure design with no evidence (logs, tickets, reviews) fails an audit.

Definition: the four frameworks a system designer meets most:

FrameworkWhat it is (from the source)What it forces on the designEvidence an auditor asks for
SOC 2 (AICPA)Reports on controls "Relevant to Security, Availability, Processing Integrity, Confidentiality, or Privacy"Access reviews, change management, logging, incident processTickets, approvals, log retention, access review records
ISO/IEC 27001:2022Information security management system standard (NIST publishes an SP 800-53 crosswalk to it)Risk register, asset inventory, policies, Annex A controlsStatement of Applicability, risk treatment plan
PCI DSS v4.x"a baseline of technical and operational requirements designed to protect payment account data"Shrink the cardholder data environment: tokenise, segment, never log PANsNetwork diagrams, scans, segmentation tests
GDPREU regulation; Art. 25 "Data protection by design and by default", Art. 32 security of processing including "the pseudonymisation and encryption of personal data"Data minimisation, purpose limits, erasure, breach notificationRecords of processing, DPIAs, breach logs
text
     PCI DSS scope reduction by design (request flow)
1    browser loads the PSP's hosted card field (iframe/JS from the PSP)
2    card number goes browser -> PSP directly; our servers never see the PAN
3    PSP returns a token; our API stores token + last4 only
4    our cardholder data environment shrinks to the page that embeds the field
     A design decision removed most of the PCI scope; no control had to be bought.

Real scenarios: an enterprise customer requiring a SOC 2 Type II report before signing; a payments feature that would put the whole Kubernetes cluster in PCI scope; GDPR erasure requests against an append-only event log (see Messaging Security for erasure in immutable logs).

Fix / how to use it: map each framework control to a component and a test in the threat model; design to shrink scope (tokenisation, separate accounts). Audit evidence and breach handling are in Secure SDLC, Incident Response, Compliance & Breaches; payment-specific design in Payment Processing Architecture.

Security in the design review: the checklist Must-know ​

In plain words: a short list of questions every design document answers before it is approved, so security is a gate with criteria, not an opinion.

Common misunderstanding: "The security reviewer will find the problems." The reviewer checks the answers; the authors must bring the DFD, the threat list and the decisions. A review without a model reviews prose.

Definition: a security review checklist is a fixed set of questions with required artefacts, applied at design time and re-applied when the DFD changes.

#QuestionRequired artefactFails if
1What assets does this touch and how are they classified?Asset list with classificationPII or secrets not listed
2Where are the trust boundaries and new entry points?DFD with boundariesAny arrow crosses a boundary unlabelled
3How is every caller authenticated (people and services)?Auth method per flowAny "internal, so trusted" flow
4Where is authorization checked, per object?Policy names per endpointTenant or owner id taken from input
5What do the STRIDE rows say, and who owns each open one?Generated checklist with ownersOpen high rows without owner or acceptance
6What are the limits (rate, size, time) on each entry point?Numbers per endpointAny unbounded input
7What is logged for audit, and what is never logged?Audit event list, redaction rulesSecrets or full PANs in logs
8Which secrets are needed, where do they live, how are they rotated?Secret inventoryLong-lived keys in config
9Which new dependencies or vendors, and what can they reach?SBOM diff, vendor scopesUnpinned or unreviewed dependency
10What fails closed, what fails open, and why?Failure-mode tableAuthorization that fails open
11How would we detect abuse and recover?Alerts, runbook, backup/restore planNo detective control on a high threat
12Which compliance controls apply?Mapping to SOC 2 / PCI DSS / GDPR itemsIn-scope data with no mapped control
text
     Review flow
1    author: design doc + DFD (model.json) + generated STRIDE table
2    CI: go run ./cmd/stride -> exit 1 while an open high-severity threat exists
3    review meeting: walk the 12 questions, record decisions (mitigate/eliminate/transfer/accept)
4    accepted risks: owner + expiry date in the risk register
5    tickets: each mitigation with an acceptance test; review re-opens if the DFD changes

Real scenarios: adding SSO, adding a public webhook, moving files to object storage with presigned URLs, adding an LLM agent with tool access, opening an API to partners.

Fix / how to use it: copy the table into your design-doc template and make question 5 machine-checked. The four-step design method this plugs into is in The 4-Step Approach.

Incident basics Good to know ​

In plain words: assume something will get through; decide now who is called, what logs exist, how to contain it and how to tell customers.

Common misunderstanding: "Incident response is the security team's problem." The first responder is usually the on-call engineer who sees odd traffic; the design decides whether the logs, kill switches and restore paths they need exist.

Definition: NIST CSF 2.0 organises outcomes into six functions: GOVERN, IDENTIFY, PROTECT, DETECT, "RESPOND (RS) — Actions regarding a detected cybersecurity incident are taken" and "RECOVER (RC) — Assets and operations affected by a cybersecurity incident are restored." An incident runbook covers detection, triage, containment, eradication, recovery and lessons learned.

text
     First hour after "unusual export volume" alert
1    00m  alert: one API key exported 50,000 invoices in 10 minutes
2    05m  triage: audit log shows key belongs to partner X, IPs new
3    10m  contain: revoke key (corrective), block IPs at the WAF
4    30m  scope: which records? (audit rows by request_id) -> GDPR 72-hour clock starts on awareness
5    60m  eradicate/recover: rotate partner secrets, add per-key export quota, post-incident review
Design decisionWhy it matters in an incident
Audit events with request idsScope "what was taken" in minutes, not days
Per-key and per-tenant credentialsRevoke one without taking everyone down
Kill switches and feature flagsContain without a deploy
Immutable, separate-account backupsRecover after ransomware
Synchronised clocks (NTP)Correlate events across services

Real scenarios: a leaked partner key, a compromised developer laptop, ransomware on a file server, a vulnerable dependency announced on a Friday.

Fix / how to use it: write the runbook alongside the threat model and drill it. The full lifecycle (logging, SIEM, breach notification) is in Secure SDLC & Incident Response.

Mechanics ​

The threat-model-as-code loop ​

The model is a JSON list of DFD elements; each has a kind, a boundary (trust zone), the holds assets and the controls already in place. The generator applies the per-element chart, marks a row mitigated when all its required controls are present, and computes a triage severity.

Element kindLetters generatedRequired controls per letter (from rules in generate.go)
external_entityS, RS: authn; R: audit-log
processS, T, R, I, D, ES: authn; T: validation; R: audit-log; I: authz; D: rate-limit; E: authz + least-priv
data_storeT, I, D (+ R if it holds audit_log)T: least-priv; I: least-priv + enc-rest; D: backups; R: integrity + least-priv
data_flowT, I, DT: tls; I: tls; D: rate-limit

Severity rule (a triage hint, not a CVSS score): high when the element touches a sensitive asset (pii, card, secrets, credentials, audit_log) and a trust boundary is crossed; medium when only one holds; low otherwise. The command exits 1 while an open high row exists, so CI can block the merge.

HTTP server knobs and status codes ​

KnobGo net/httpZero value meansThis chapter's default
ReadHeaderTimeout"the amount of time allowed to read request headers"Falls back to ReadTimeout; if that is zero, no timeout5 s
ReadTimeout"the maximum duration for reading the entire request, including the body"No timeout15 s
WriteTimeout"the maximum duration before timing out writes of the response"No timeout30 s
IdleTimeoutWait for the next keep-alive requestFalls back to ReadTimeout60 s
MaxHeaderBytesHeader size limit, "does not limit the size of the request body"DefaultMaxHeaderBytes (1 MB)16 KiB
Body limithttp.MaxBytesReader returns *http.MaxBytesErrorUnlimited1 MiB
CSRF (Go 1.25+)http.CrossOriginProtection ("added in go1.25.0", uses Sec-Fetch-Site)Not appliedNot used here: the module targets go 1.24
StatusWho emits itMeaning in this chapter
401Laravel auth, hasValidSignature() example in the docs uses abort(401)Not authenticated
403Laravel signed middleware on an invalid signature; PreventRequestForgery in origin-only modeAuthenticated or not, not allowed
404Response::denyAsNotFound()Hide that a foreign object exists
413Our LimitBodyBody over the cap
419Laravel CSRF token mismatch"the 419 response typically associated with CSRF token mismatches"
429Laravel throttle, rate limitersToo many requests, with Retry-After

The audit table in SQL ​

The repudiation control in the database: the application role can insert and read but not change history, a trigger blocks updates even if a grant is added by mistake, and a hash chain lets a nightly job detect edits by a superuser.

sql
-- Repudiation control in the database: an append-only audit table.
-- The application role may INSERT and SELECT, never UPDATE or DELETE;
-- a hash chain makes silent edits by a superuser detectable.
CREATE TABLE audit_events (
    id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    occurred_at timestamptz NOT NULL DEFAULT now(),
    actor       text        NOT NULL,          -- user id or service identity
    action      text        NOT NULL,          -- 'invoice.deleted'
    object_ref  text        NOT NULL,          -- 'invoice:42'
    source_ip   inet,
    request_id  text,
    prev_hash   bytea,
    row_hash    bytea       NOT NULL
);

CREATE ROLE app_writer NOLOGIN;
GRANT INSERT, SELECT ON audit_events TO app_writer;
REVOKE UPDATE, DELETE, TRUNCATE ON audit_events FROM app_writer;

-- Defence in depth: even a role that was granted UPDATE by mistake is stopped.
CREATE FUNCTION audit_events_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
    RAISE EXCEPTION 'audit_events is append-only' USING ERRCODE = 'insufficient_privilege';
END $$;

CREATE TRIGGER audit_events_no_update
    BEFORE UPDATE OR DELETE ON audit_events
    FOR EACH ROW EXECUTE FUNCTION audit_events_immutable();

-- Insert with a hash chain (computed in the application or here with pgcrypto):
-- row_hash = sha256(prev_hash || occurred_at || actor || action || object_ref)
-- Verification job (detective control): recompute the chain nightly and alert on a break.
sql
-- Quick check that the control works (expected, not run)
SET ROLE app_writer;
UPDATE audit_events SET actor = 'someone-else' WHERE id = 1;
-- ERROR:  permission denied for table audit_events
RESET ROLE;

Go ​

Before ​

The tutorial server: a zero-value http.Server through http.ListenAndServe, no body limit, error details reflected to the caller, no authorization, the whole payload in the log. Every comment names the STRIDE letter it opens.

go
// Before: the server most tutorials start with. Nothing here is a syntax or
// logic bug; every line is an insecure default that an attacker can use.
package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type order struct {
	ID     string  `json:"id"`
	Amount float64 `json:"amount"`
	Role   string  `json:"role"` // mass assignment: the client can send "admin"
}

func main() {
	http.HandleFunc("/orders", func(w http.ResponseWriter, r *http.Request) {
		var o order
		// No body limit: a 10 GB body is read until memory runs out (D).
		if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
			// Internal detail reflected to the caller (I).
			http.Error(w, fmt.Sprintf("decode failed: %v", err), http.StatusBadRequest)
			return
		}
		// No authentication, no authorization check (S, E), no audit record (R).
		log.Printf("order %+v", o) // the whole payload, PII included, goes to logs (I)
		w.WriteHeader(http.StatusCreated)
	})
	// http.ListenAndServe uses a zero-value Server: no ReadHeaderTimeout,
	// no ReadTimeout, no WriteTimeout, no IdleTimeout. One slow client per
	// connection holds a goroutine and a socket forever (Slowloris, D).
	log.Fatal(http.ListenAndServe(":8080", nil))
}

After ​

Two packages. threatmodel is the threat-model-as-code tool: DFD types, validation (unique ids, known kinds, flows that point at existing nodes and never at another flow), the STRIDE-per-element generator with a small control catalogue tagged preventive/detective/corrective, a triage severity, Markdown output and a per-category summary.

go
// Package threatmodel turns a data flow diagram (DFD) written as data into a
// STRIDE-per-element checklist. It is threat modelling as code: the model
// lives in the repository, is reviewed like code and is re-run in CI.
package threatmodel

import (
	"errors"
	"fmt"
	"sort"
	"strings"
)

// Kind is one of the four DFD element types used by Microsoft's SDL and Shostack.
type Kind string

const (
	ExternalEntity Kind = "external_entity" // a user, a partner, a third-party API
	Process        Kind = "process"         // code you run: web app, API, worker
	DataStore      Kind = "data_store"      // database, bucket, cache, queue at rest
	DataFlow       Kind = "data_flow"       // a connection between two elements
)

// Category is one STRIDE letter.
type Category string

const (
	Spoofing              Category = "S"
	Tampering             Category = "T"
	Repudiation           Category = "R"
	InformationDisclosure Category = "I"
	DenialOfService       Category = "D"
	ElevationOfPrivilege  Category = "E"
)

// Property is the security property each STRIDE category violates.
var Property = map[Category]string{
	Spoofing:              "authenticity",
	Tampering:             "integrity",
	Repudiation:           "non-repudiation",
	InformationDisclosure: "confidentiality",
	DenialOfService:       "availability",
	ElevationOfPrivilege:  "authorization",
}

// Applicable is the STRIDE-per-element chart: which categories apply to which
// element type. Data stores get Repudiation only when they hold audit logs.
var Applicable = map[Kind][]Category{
	ExternalEntity: {Spoofing, Repudiation},
	Process:        {Spoofing, Tampering, Repudiation, InformationDisclosure, DenialOfService, ElevationOfPrivilege},
	DataStore:      {Tampering, InformationDisclosure, DenialOfService},
	DataFlow:       {Tampering, InformationDisclosure, DenialOfService},
}

// Element is one node or flow of the DFD.
type Element struct {
	ID       string   `json:"id"`
	Name     string   `json:"name"`
	Kind     Kind     `json:"kind"`
	Boundary string   `json:"boundary,omitempty"` // trust zone the node sits in
	From     string   `json:"from,omitempty"`     // data flows only
	To       string   `json:"to,omitempty"`       // data flows only
	Holds    []string `json:"holds,omitempty"`    // assets: "pii", "card", "secrets", "audit_log"
	Controls []string `json:"controls,omitempty"` // control ids already in place
}

// Model is a whole system.
type Model struct {
	Name     string    `json:"name"`
	Elements []Element `json:"elements"`
}

// Validate checks the model is a real graph: unique ids, known kinds, flows
// that point at existing nodes and never at another flow.
func (m Model) Validate() error {
	var errs []error
	byID := map[string]Element{}
	for _, e := range m.Elements {
		if e.ID == "" {
			errs = append(errs, fmt.Errorf("element %q has no id", e.Name))
			continue
		}
		if _, dup := byID[e.ID]; dup {
			errs = append(errs, fmt.Errorf("duplicate id %q", e.ID))
		}
		if _, ok := Applicable[e.Kind]; !ok {
			errs = append(errs, fmt.Errorf("%s: unknown kind %q", e.ID, e.Kind))
		}
		byID[e.ID] = e
	}
	for _, e := range m.Elements {
		if e.Kind != DataFlow {
			continue
		}
		for _, end := range []string{e.From, e.To} {
			n, ok := byID[end]
			switch {
			case !ok:
				errs = append(errs, fmt.Errorf("%s: endpoint %q does not exist", e.ID, end))
			case n.Kind == DataFlow:
				errs = append(errs, fmt.Errorf("%s: endpoint %q is a flow", e.ID, end))
			}
		}
	}
	return errors.Join(errs...)
}

// CrossesBoundary reports whether a flow connects two different trust zones.
func (m Model) CrossesBoundary(flow Element) bool {
	from, to := m.find(flow.From), m.find(flow.To)
	return from.Boundary != to.Boundary
}

func (m Model) find(id string) Element {
	for _, e := range m.Elements {
		if e.ID == id {
			return e
		}
	}
	return Element{}
}

func has(list []string, v string) bool {
	for _, x := range list {
		if strings.EqualFold(x, v) {
			return true
		}
	}
	return false
}

// sortedIDs is used to make output deterministic for golden tests and diffs.
func sortedIDs(m Model) []string {
	ids := make([]string, 0, len(m.Elements))
	for _, e := range m.Elements {
		ids = append(ids, e.ID)
	}
	sort.Strings(ids)
	return ids
}
go
package threatmodel

import (
	"fmt"
	"io"
	"sort"
	"strings"
)

// ControlType is the conventional preventive / detective / corrective split.
type ControlType string

const (
	Preventive ControlType = "preventive"
	Detective  ControlType = "detective"
	Corrective ControlType = "corrective"
)

// Control is one entry of the control catalogue.
type Control struct {
	ID   string
	Name string
	Type ControlType
}

// Catalogue is the small control catalogue the generator suggests from.
var Catalogue = map[string]Control{
	"authn":      {"authn", "Strong authentication (MFA for people, mTLS or signed tokens for services)", Preventive},
	"authz":      {"authz", "Authorization check on every request (complete mediation)", Preventive},
	"least-priv": {"least-priv", "Least-privilege identity for the process and its credentials", Preventive},
	"tls":        {"tls", "TLS 1.2+ on the connection", Preventive},
	"integrity":  {"integrity", "Integrity protection (HMAC, signatures, signed URLs, checksums)", Preventive},
	"validation": {"validation", "Input validation and output encoding", Preventive},
	"enc-rest":   {"enc-rest", "Encryption at rest with managed keys", Preventive},
	"rate-limit": {"rate-limit", "Rate limits, quotas, body and timeout limits", Preventive},
	"audit-log":  {"audit-log", "Append-only audit log with actor, action, time", Detective},
	"alerting":   {"alerting", "Alerting on anomalies and failed authentication", Detective},
	"backups":    {"backups", "Tested backups and restore (corrective)", Corrective},
	"redundancy": {"redundancy", "Redundancy, autoscaling and failover", Corrective},
}

type rule struct {
	question string
	required []string // controls that, all present, mark the threat mitigated
	suggest  []string // extra controls worth considering
}

// rules is the STRIDE question bank per element kind.
var rules = map[Kind]map[Category]rule{
	ExternalEntity: {
		Spoofing:    {"Can someone pretend to be this user or partner?", []string{"authn"}, []string{"alerting"}},
		Repudiation: {"Can this actor deny an action they performed?", []string{"audit-log"}, []string{"integrity"}},
	},
	Process: {
		Spoofing:              {"Can a caller or a fake instance impersonate this process?", []string{"authn"}, []string{"tls"}},
		Tampering:             {"Can inputs, code or memory of this process be modified?", []string{"validation"}, []string{"integrity"}},
		Repudiation:           {"Are security-relevant actions recorded so they cannot be denied?", []string{"audit-log"}, []string{"alerting"}},
		InformationDisclosure: {"Can it leak data through errors, logs or responses?", []string{"authz"}, []string{"validation"}},
		DenialOfService:       {"Can a caller exhaust its CPU, memory, connections or threads?", []string{"rate-limit"}, []string{"redundancy"}},
		ElevationOfPrivilege:  {"Can a caller make it do something the caller is not allowed to do?", []string{"authz", "least-priv"}, []string{"validation"}},
	},
	DataStore: {
		Tampering:             {"Can stored data be modified outside the intended path?", []string{"least-priv"}, []string{"integrity", "backups"}},
		Repudiation:           {"Can audit records be altered or deleted?", []string{"integrity", "least-priv"}, []string{"backups"}},
		InformationDisclosure: {"Can stored data be read by someone who should not?", []string{"least-priv", "enc-rest"}, []string{"audit-log"}},
		DenialOfService:       {"Can the store be filled, locked or deleted?", []string{"backups"}, []string{"redundancy", "rate-limit"}},
	},
	DataFlow: {
		Tampering:             {"Can data be modified in transit?", []string{"tls"}, []string{"integrity"}},
		InformationDisclosure: {"Can data be read in transit?", []string{"tls"}, nil},
		DenialOfService:       {"Can the channel be flooded or cut?", []string{"rate-limit"}, []string{"redundancy"}},
	},
}

// Threat is one generated checklist row.
type Threat struct {
	ElementID string
	Element   string
	Kind      Kind
	Category  Category
	Property  string
	Question  string
	Missing   []string // required controls not present
	Suggested []string
	Severity  string // high, medium, low (a triage hint, not a CVSS score)
	Mitigated bool
}

var sensitive = []string{"pii", "card", "secrets", "credentials", "audit_log"}

// Generate returns the STRIDE-per-element checklist for a valid model,
// ordered by severity, then element id, then STRIDE order.
func Generate(m Model) ([]Threat, error) {
	if err := m.Validate(); err != nil {
		return nil, err
	}
	var out []Threat
	for _, id := range sortedIDs(m) {
		e := m.find(id)
		cats := append([]Category(nil), Applicable[e.Kind]...)
		if e.Kind == DataStore && has(e.Holds, "audit_log") {
			cats = append(cats, Repudiation)
		}
		for _, c := range cats {
			r := rules[e.Kind][c]
			t := Threat{
				ElementID: e.ID, Element: e.Name, Kind: e.Kind, Category: c,
				Property: Property[c], Question: r.question, Suggested: r.suggest,
			}
			for _, need := range r.required {
				if !has(e.Controls, need) {
					t.Missing = append(t.Missing, need)
				}
			}
			t.Mitigated = len(t.Missing) == 0
			t.Severity = m.severity(e, c)
			out = append(out, t)
		}
	}
	rank := map[string]int{"high": 0, "medium": 1, "low": 2}
	order := "STRIDE"
	sort.SliceStable(out, func(i, j int) bool {
		a, b := out[i], out[j]
		if a.Mitigated != b.Mitigated {
			return !a.Mitigated
		}
		if rank[a.Severity] != rank[b.Severity] {
			return rank[a.Severity] < rank[b.Severity]
		}
		if a.ElementID != b.ElementID {
			return a.ElementID < b.ElementID
		}
		return strings.Index(order, string(a.Category)) < strings.Index(order, string(b.Category))
	})
	return out, nil
}

// severity is a deliberately simple triage rule: sensitive assets plus a
// trust-boundary crossing is high; one of the two is medium; neither is low.
// A node "crosses" when any flow touching it crosses a boundary; a process is
// "sensitive" when it reads or writes a node that holds a sensitive asset.
func (m Model) severity(e Element, c Category) string {
	assets := append([]string(nil), e.Holds...)
	crosses := e.Kind == ExternalEntity
	for _, f := range m.Elements {
		if f.Kind != DataFlow {
			continue
		}
		switch {
		case f.ID == e.ID:
			assets = append(assets, m.find(f.From).Holds...)
			assets = append(assets, m.find(f.To).Holds...)
			crosses = crosses || m.CrossesBoundary(f)
		case f.From == e.ID || f.To == e.ID:
			crosses = crosses || m.CrossesBoundary(f)
			if e.Kind == Process {
				assets = append(assets, m.find(f.From).Holds...)
				assets = append(assets, m.find(f.To).Holds...)
			}
		}
	}
	sens := false
	for _, a := range sensitive {
		if has(assets, a) {
			sens = true
		}
	}
	switch {
	case sens && crosses:
		return "high"
	case sens || crosses:
		return "medium"
	default:
		return "low"
	}
}

// WriteMarkdown prints the checklist as a Markdown table for the design review.
func WriteMarkdown(w io.Writer, threats []Threat) error {
	if _, err := fmt.Fprintln(w, "| Element | STRIDE | Violates | Question | Severity | Status | Missing controls |"); err != nil {
		return err
	}
	if _, err := fmt.Fprintln(w, "| --- | --- | --- | --- | --- | --- | --- |"); err != nil {
		return err
	}
	for _, t := range threats {
		status := "OPEN"
		if t.Mitigated {
			status = "mitigated"
		}
		missing := make([]string, 0, len(t.Missing))
		for _, id := range t.Missing {
			missing = append(missing, fmt.Sprintf("%s (%s)", id, Catalogue[id].Type))
		}
		if _, err := fmt.Fprintf(w, "| %s | %s | %s | %s | %s | %s | %s |\n",
			t.Element, t.Category, t.Property, t.Question, t.Severity, status, strings.Join(missing, ", ")); err != nil {
			return err
		}
	}
	return nil
}

// Summary counts open threats per STRIDE category.
func Summary(threats []Threat) map[Category]int {
	s := map[Category]int{}
	for _, t := range threats {
		if !t.Mitigated {
			s[t.Category]++
		}
	}
	return s
}

The tests check the per-element counts (1 entity x 2 + 2 processes x 6 + 3 stores x 3 + 1 + 4 flows x 3), that only the audit store gets Repudiation, that "mitigated" needs every required control, the severity rule and ordering, validation errors, and the Markdown output.

go
package threatmodel

import (
	"bytes"
	"strings"
	"testing"
)

func shop() Model {
	return Model{Name: "shop", Elements: []Element{
		{ID: "user", Name: "Customer browser", Kind: ExternalEntity, Boundary: "internet"},
		{ID: "web", Name: "Web app", Kind: Process, Boundary: "dmz", Controls: []string{"authn", "validation", "rate-limit"}},
		{ID: "api", Name: "Orders API", Kind: Process, Boundary: "app", Controls: []string{"authn", "authz", "least-priv"}},
		{ID: "queue", Name: "Order queue", Kind: DataStore, Boundary: "app"},
		{ID: "db", Name: "Orders DB", Kind: DataStore, Boundary: "data", Holds: []string{"pii", "card"}, Controls: []string{"least-priv", "enc-rest", "backups"}},
		{ID: "audit", Name: "Audit log", Kind: DataStore, Boundary: "data", Holds: []string{"audit_log"}},
		{ID: "f1", Name: "HTTPS browser to web", Kind: DataFlow, From: "user", To: "web", Controls: []string{"tls", "rate-limit"}},
		{ID: "f2", Name: "web to API", Kind: DataFlow, From: "web", To: "api", Controls: []string{"tls"}},
		{ID: "f3", Name: "API to queue", Kind: DataFlow, From: "api", To: "queue"},
		{ID: "f4", Name: "API to DB", Kind: DataFlow, From: "api", To: "db", Controls: []string{"tls"}},
	}}
}

func TestPerElementCounts(t *testing.T) {
	threats, err := Generate(shop())
	if err != nil {
		t.Fatal(err)
	}
	per := map[Kind]int{}
	for _, th := range threats {
		per[th.Kind]++
	}
	// 1 entity x 2, 2 processes x 6, 3 stores x 3 + 1 (audit store gets R), 4 flows x 3
	want := map[Kind]int{ExternalEntity: 2, Process: 12, DataStore: 10, DataFlow: 12}
	for k, n := range want {
		if per[k] != n {
			t.Errorf("%s: got %d threats, want %d", k, per[k], n)
		}
	}
}

func TestAuditStoreGetsRepudiation(t *testing.T) {
	threats, _ := Generate(shop())
	found := false
	for _, th := range threats {
		if th.ElementID == "audit" && th.Category == Repudiation {
			found = true
		}
		if th.ElementID == "queue" && th.Category == Repudiation {
			t.Fatal("queue holds no audit log, R should not apply")
		}
	}
	if !found {
		t.Fatal("audit store must get a repudiation threat")
	}
}

func TestMitigatedNeedsEveryRequiredControl(t *testing.T) {
	threats, _ := Generate(shop())
	for _, th := range threats {
		switch {
		case th.ElementID == "api" && th.Category == ElevationOfPrivilege && !th.Mitigated:
			t.Error("api has authz and least-priv: EoP should be mitigated")
		case th.ElementID == "web" && th.Category == ElevationOfPrivilege && th.Mitigated:
			t.Error("web has no authz: EoP must stay open")
		case th.ElementID == "f3" && th.Category == InformationDisclosure && !(len(th.Missing) == 1 && th.Missing[0] == "tls"):
			t.Errorf("f3 should miss tls, got %v", th.Missing)
		}
	}
}

func TestSeverityAndOrdering(t *testing.T) {
	m := shop()
	threats, _ := Generate(m)
	if !m.CrossesBoundary(m.find("f4")) || m.CrossesBoundary(m.find("f3")) {
		t.Fatal("f4 crosses app->data, f3 stays inside app")
	}
	for _, th := range threats {
		if th.ElementID == "f4" && th.Severity != "high" {
			t.Errorf("flow into card store across a boundary should be high, got %s", th.Severity)
		}
		if th.ElementID == "f3" && th.Severity != "low" {
			t.Errorf("internal flow without assets should be low, got %s", th.Severity)
		}
	}
	seenMitigated := false
	for _, th := range threats {
		if th.Mitigated {
			seenMitigated = true
		} else if seenMitigated {
			t.Fatal("open threats must come before mitigated ones")
		}
	}
}

func TestValidate(t *testing.T) {
	m := shop()
	m.Elements = append(m.Elements,
		Element{ID: "f9", Kind: DataFlow, From: "api", To: "ghost"},
		Element{ID: "f10", Kind: DataFlow, From: "f1", To: "api"},
		Element{ID: "web", Kind: Process},
		Element{ID: "x", Kind: "router"},
	)
	err := m.Validate()
	if err == nil {
		t.Fatal("expected validation errors")
	}
	for _, want := range []string{`"ghost" does not exist`, `"f1" is a flow`, `duplicate id "web"`, `unknown kind "router"`} {
		if !strings.Contains(err.Error(), want) {
			t.Errorf("missing %q in %v", want, err)
		}
	}
	if _, err := Generate(m); err == nil {
		t.Fatal("Generate must refuse an invalid model")
	}
}

func TestMarkdownAndSummary(t *testing.T) {
	threats, _ := Generate(shop())
	var buf bytes.Buffer
	if err := WriteMarkdown(&buf, threats); err != nil {
		t.Fatal(err)
	}
	out := buf.String()
	if !strings.HasPrefix(out, "| Element | STRIDE |") || !strings.Contains(out, "audit-log (detective)") {
		t.Fatalf("unexpected markdown:\n%s", out)
	}
	s := Summary(threats)
	if s[Repudiation] == 0 || s[DenialOfService] == 0 {
		t.Fatalf("summary should count open R and D threats: %v", s)
	}
	if lines := strings.Count(out, "\n"); lines != len(threats)+2 {
		t.Fatalf("got %d lines for %d threats", lines, len(threats))
	}
}

The command reads model.json (embedded by default) and exits 1 while an open high-severity threat exists.

go
// Command stride reads a DFD as JSON and prints the STRIDE-per-element
// checklist as Markdown. Usage: go run ./cmd/stride [model.json]
// Exit status 1 when an open high-severity threat exists, so CI can gate on it.
package main

import (
	_ "embed"
	"encoding/json"
	"fmt"
	"os"

	"academy/security-foundations-cia-stride/threatmodel"
)

//go:embed model.json
var sample []byte

func main() {
	data := sample
	if len(os.Args) > 1 {
		b, err := os.ReadFile(os.Args[1])
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(2)
		}
		data = b
	}
	var m threatmodel.Model
	if err := json.Unmarshal(data, &m); err != nil {
		fmt.Fprintln(os.Stderr, "parse model:", err)
		os.Exit(2)
	}
	threats, err := threatmodel.Generate(m)
	if err != nil {
		fmt.Fprintln(os.Stderr, "invalid model:\n", err)
		os.Exit(2)
	}
	fmt.Printf("# Threat checklist: %s\n\n", m.Name)
	if err := threatmodel.WriteMarkdown(os.Stdout, threats); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(2)
	}
	s := threatmodel.Summary(threats)
	fmt.Printf("\nOpen per category: S=%d T=%d R=%d I=%d D=%d E=%d (total threats %d)\n",
		s["S"], s["T"], s["R"], s["I"], s["D"], s["E"], len(threats))
	for _, t := range threats {
		if !t.Mitigated && t.Severity == "high" {
			os.Exit(1)
		}
	}
}
json
{
  "name": "shop: web app + API + queue + DB",
  "elements": [
    {"id": "user", "name": "Customer browser", "kind": "external_entity", "boundary": "internet"},
    {"id": "psp", "name": "Payment provider", "kind": "external_entity", "boundary": "partner", "controls": ["authn"]},
    {"id": "web", "name": "Web app (Laravel)", "kind": "process", "boundary": "dmz", "controls": ["authn", "validation", "rate-limit", "audit-log"]},
    {"id": "api", "name": "Orders API (Go)", "kind": "process", "boundary": "app", "controls": ["authn", "authz", "least-priv", "validation"]},
    {"id": "worker", "name": "Fulfilment worker", "kind": "process", "boundary": "app", "controls": ["least-priv"]},
    {"id": "queue", "name": "Order queue (RabbitMQ)", "kind": "data_store", "boundary": "app"},
    {"id": "db", "name": "Orders DB (PostgreSQL)", "kind": "data_store", "boundary": "data", "holds": ["pii"], "controls": ["least-priv", "enc-rest", "backups"]},
    {"id": "audit", "name": "Audit log", "kind": "data_store", "boundary": "data", "holds": ["audit_log"], "controls": ["least-priv"]},
    {"id": "f1", "name": "browser -> web (HTTPS)", "kind": "data_flow", "from": "user", "to": "web", "controls": ["tls", "rate-limit"]},
    {"id": "f2", "name": "web -> API", "kind": "data_flow", "from": "web", "to": "api", "controls": ["tls"]},
    {"id": "f3", "name": "API -> queue", "kind": "data_flow", "from": "api", "to": "queue"},
    {"id": "f4", "name": "queue -> worker", "kind": "data_flow", "from": "queue", "to": "worker"},
    {"id": "f5", "name": "API -> DB", "kind": "data_flow", "from": "api", "to": "db", "controls": ["tls"]},
    {"id": "f6", "name": "worker -> payment provider", "kind": "data_flow", "from": "worker", "to": "psp", "controls": ["tls"]},
    {"id": "f7", "name": "web -> audit log", "kind": "data_flow", "from": "web", "to": "audit"}
  ]
}

secureserver is the secure-by-default HTTP server: timeouts that can never be zero, a 16 KiB header cap, a 1 MiB body cap with a 413, OWASP-recommended headers, a panic handler that keeps details out of the response, and one structured audit line per request that drops any client-supplied identity header and never logs bodies or credentials.

go
// Package secureserver builds an *http.Server whose defaults are safe:
// bounded time, bounded size, safe headers, no internal detail in errors,
// and one audit line per request. It is "secure by default" in code form.
package secureserver

import (
	"crypto/rand"
	"encoding/hex"
	"errors"
	"log/slog"
	"net/http"
	"time"
)

// Config holds the limits. Zero values are replaced by the defaults below,
// so forgetting a field never turns a limit off (fail-safe default).
type Config struct {
	Addr              string
	ReadHeaderTimeout time.Duration // Slowloris: time to send the headers
	ReadTimeout       time.Duration // whole request including body
	WriteTimeout      time.Duration // whole response
	IdleTimeout       time.Duration // keep-alive connections
	MaxHeaderBytes    int
	MaxBodyBytes      int64
	CSP               string
	Logger            *slog.Logger
}

func (c Config) withDefaults() Config {
	def := func(d *time.Duration, v time.Duration) {
		if *d <= 0 {
			*d = v
		}
	}
	def(&c.ReadHeaderTimeout, 5*time.Second)
	def(&c.ReadTimeout, 15*time.Second)
	def(&c.WriteTimeout, 30*time.Second)
	def(&c.IdleTimeout, 60*time.Second)
	if c.MaxHeaderBytes <= 0 {
		c.MaxHeaderBytes = 16 << 10 // 16 KiB instead of the 1 MiB DefaultMaxHeaderBytes
	}
	if c.MaxBodyBytes <= 0 {
		c.MaxBodyBytes = 1 << 20 // 1 MiB
	}
	if c.CSP == "" {
		c.CSP = "default-src 'none'; frame-ancestors 'none'"
	}
	if c.Logger == nil {
		c.Logger = slog.Default()
	}
	if c.Addr == "" {
		c.Addr = ":8443"
	}
	return c
}

// New wraps h with the middleware chain and returns a configured server.
// Order, outside to inside: audit log, panic recovery, headers, body limit.
func New(h http.Handler, cfg Config) *http.Server {
	cfg = cfg.withDefaults()
	chain := Audit(cfg.Logger, Recover(cfg.Logger, Headers(cfg.CSP, LimitBody(cfg.MaxBodyBytes, h))))
	return &http.Server{
		Addr:              cfg.Addr,
		Handler:           chain,
		ReadHeaderTimeout: cfg.ReadHeaderTimeout,
		ReadTimeout:       cfg.ReadTimeout,
		WriteTimeout:      cfg.WriteTimeout,
		IdleTimeout:       cfg.IdleTimeout,
		MaxHeaderBytes:    cfg.MaxHeaderBytes,
		ErrorLog:          slog.NewLogLogger(cfg.Logger.Handler(), slog.LevelWarn),
	}
}

// Headers sets the response headers recommended by the OWASP HTTP Headers
// Cheat Sheet for an API. HSTS is only meaningful over HTTPS; it is set
// unconditionally because this server is meant to sit behind TLS.
func Headers(csp string, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		h := w.Header()
		h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
		h.Set("Content-Security-Policy", csp)
		h.Set("X-Content-Type-Options", "nosniff")
		h.Set("X-Frame-Options", "DENY")
		h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
		h.Set("Cross-Origin-Opener-Policy", "same-origin")
		h.Set("Permissions-Policy", "geolocation=(), camera=(), microphone=()")
		h.Set("Cache-Control", "no-store")
		h.Del("Server")
		next.ServeHTTP(w, r)
	})
}

// LimitBody caps every request body. A handler that reads past the cap
// gets an *http.MaxBytesError; IsTooLarge lets it answer 413.
func LimitBody(n int64, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.ContentLength > n {
			http.Error(w, http.StatusText(http.StatusRequestEntityTooLarge), http.StatusRequestEntityTooLarge)
			return
		}
		r.Body = http.MaxBytesReader(w, r.Body, n)
		next.ServeHTTP(w, r)
	})
}

// IsTooLarge reports whether err came from the body limit.
func IsTooLarge(err error) bool {
	var mbe *http.MaxBytesError
	return errors.As(err, &mbe)
}

// Recover turns a panic into a generic 500. The detail goes to the log with
// the request id, never to the client (information disclosure).
func Recover(log *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if v := recover(); v != nil {
				if v == http.ErrAbortHandler {
					panic(v)
				}
				log.Error("panic", "request_id", r.Header.Get("X-Request-Id"), "panic", v)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
			}
		}()
		next.ServeHTTP(w, r)
	})
}

type statusWriter struct {
	http.ResponseWriter
	status int
}

func (s *statusWriter) WriteHeader(code int) {
	s.status = code
	s.ResponseWriter.WriteHeader(code)
}

// Audit assigns a request id and writes one structured line per request:
// who (remote address and, when present, the authenticated subject), what,
// when, outcome. It never logs bodies, cookies or Authorization headers.
func Audit(log *slog.Logger, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		id := newID()
		// Never trust identity headers from the client: an inner authn
		// layer sets the subject after verifying a credential (spoofing).
		r.Header.Del("X-Authenticated-Subject")
		r.Header.Set("X-Request-Id", id)
		w.Header().Set("X-Request-Id", id)
		sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
		start := time.Now()
		next.ServeHTTP(sw, r)
		log.Info("request",
			"request_id", id,
			"remote", r.RemoteAddr,
			"subject", r.Header.Get("X-Authenticated-Subject"),
			"method", r.Method,
			"path", r.URL.Path,
			"status", sw.status,
			"duration_ms", time.Since(start).Milliseconds(),
		)
	})
}

func newID() string {
	var b [8]byte
	_, _ = rand.Read(b[:])
	return hex.EncodeToString(b[:])
}
go
package secureserver

import (
	"bytes"
	"encoding/json"
	"io"
	"log/slog"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
	"time"
)

func echo() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if _, err := io.ReadAll(r.Body); err != nil {
			if IsTooLarge(err) {
				http.Error(w, "too large", http.StatusRequestEntityTooLarge)
				return
			}
			http.Error(w, "bad request", http.StatusBadRequest)
			return
		}
		if r.URL.Path == "/panic" {
			panic("db password is hunter2")
		}
		w.WriteHeader(http.StatusNoContent)
	})
}

func TestDefaultsAreNeverZero(t *testing.T) {
	srv := New(echo(), Config{})
	if srv.ReadHeaderTimeout != 5*time.Second || srv.ReadTimeout == 0 || srv.WriteTimeout == 0 || srv.IdleTimeout == 0 {
		t.Fatalf("timeouts must default to non-zero: %+v", srv)
	}
	if srv.MaxHeaderBytes != 16<<10 {
		t.Fatalf("MaxHeaderBytes = %d", srv.MaxHeaderBytes)
	}
}

func TestSecurityHeaders(t *testing.T) {
	srv := New(echo(), Config{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
	rec := httptest.NewRecorder()
	srv.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/", nil))
	for _, h := range []string{"Strict-Transport-Security", "Content-Security-Policy", "X-Content-Type-Options", "X-Frame-Options", "Referrer-Policy", "X-Request-Id"} {
		if rec.Header().Get(h) == "" {
			t.Errorf("missing header %s", h)
		}
	}
}

func TestBodyLimit(t *testing.T) {
	srv := New(echo(), Config{MaxBodyBytes: 10, Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
	// Declared length over the cap: rejected before the handler runs.
	rec := httptest.NewRecorder()
	srv.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/", strings.NewReader(strings.Repeat("a", 11))))
	if rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("declared length: got %d", rec.Code)
	}
	// Unknown length (chunked): stopped by MaxBytesReader while reading.
	req := httptest.NewRequest(http.MethodPost, "/", io.MultiReader(strings.NewReader(strings.Repeat("a", 64))))
	req.ContentLength = -1
	rec = httptest.NewRecorder()
	srv.Handler.ServeHTTP(rec, req)
	if rec.Code != http.StatusRequestEntityTooLarge {
		t.Fatalf("streamed body: got %d", rec.Code)
	}
}

func TestPanicDoesNotLeak(t *testing.T) {
	var logs bytes.Buffer
	srv := New(echo(), Config{Logger: slog.New(slog.NewJSONHandler(&logs, nil))})
	rec := httptest.NewRecorder()
	srv.Handler.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/panic", nil))
	if rec.Code != http.StatusInternalServerError {
		t.Fatalf("got %d", rec.Code)
	}
	if strings.Contains(rec.Body.String(), "hunter2") {
		t.Fatal("panic detail leaked to the client")
	}
	if !strings.Contains(logs.String(), "hunter2") {
		t.Fatal("panic detail should be in the server log for responders")
	}
}

func TestAuditLine(t *testing.T) {
	var logs bytes.Buffer
	srv := New(echo(), Config{Logger: slog.New(slog.NewJSONHandler(&logs, nil))})
	req := httptest.NewRequest(http.MethodPost, "/orders", strings.NewReader(`{"card":"4111111111111111"}`))
	req.Header.Set("Authorization", "Bearer secret-token")
	req.Header.Set("X-Authenticated-Subject", "admin") // forged by the client
	srv.Handler.ServeHTTP(httptest.NewRecorder(), req)
	var line map[string]any
	if err := json.Unmarshal(bytes.TrimSpace(logs.Bytes()), &line); err != nil {
		t.Fatalf("audit line is not one JSON object: %v\n%s", err, logs.String())
	}
	if line["path"] != "/orders" || line["status"].(float64) != 204 || line["request_id"] == "" {
		t.Fatalf("unexpected audit line: %v", line)
	}
	if line["subject"] != "" {
		t.Fatalf("client-supplied subject must be dropped, got %v", line["subject"])
	}
	if strings.Contains(logs.String(), "4111") || strings.Contains(logs.String(), "secret-token") {
		t.Fatal("audit log must not contain bodies or credentials")
	}
}
Threat (STRIDE)BeforeAfter
D: SlowlorisNo timeoutsReadHeaderTimeout 5 s and friends
D: huge bodyUnlimitedMaxBytesReader, 413
I: error detailsdecode failed: ... to the clientGeneric 500/400; details only in the log
I: PII in logsWhole payload loggedMethod, path, status, ids only
S: forged identity header(no identity at all)Client X-Authenticated-Subject deleted before handlers
R: no recordNothingOne audit line with request id per request
T/E: mass assignmentRole decoded from inputHandlers decode into request-specific types (not shown; see Laravel $fillable)

The Go angle ​

Go's standard library gives you most controls but few defaults: http.ListenAndServe builds a zero-value Server, and its documentation says a zero ReadTimeout means "there will be no timeout", so production code always constructs http.Server explicitly. http.MaxBytesReader and the typed *http.MaxBytesError make body limits testable. log/slog gives structured audit lines; keep a separate handler for audit events if they go to a different store. crypto/rand (not math/rand) for ids and tokens. Since Go 1.25, http.CrossOriginProtection offers Sec-Fetch-Site based CSRF protection for cookie-authenticated handlers; our module stays on go 1.24 and therefore does not use it. For the supply chain, go.sum plus the checksum database pins module content, and govulncheck reports only vulnerabilities reachable from your call graph. Embedding the model with //go:embed keeps the tool a single binary for CI.

Laravel ​

Before ​

A controller that works in a demo and fails the threat model: no authorization (IDOR), forceCreate($request->all()) (mass assignment), the full payload in the default log, a guessable "share" URL, and a silent delete.

php
<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

// Before: works in a demo, fails a threat model. Every method maps to a STRIDE letter.
class InvoiceController extends Controller
{
    // E: no authorization. Any logged-in user can read any invoice by changing the id (IDOR).
    public function show(Invoice $invoice)
    {
        return $invoice;
    }

    // T + E: mass assignment of the whole request, including "status" and "tenant_id".
    public function store(Request $request)
    {
        $invoice = Invoice::forceCreate($request->all());

        // I: the full payload (bank account included) is written to the default log.
        Log::info('invoice created', $request->all());

        return $invoice;
    }

    // S + T: a "secret" link that is only a guessable id; anyone can change it or share it forever.
    public function shareLink(Invoice $invoice)
    {
        return url('/invoices/'.$invoice->id.'/download');
    }

    // R: an admin deletes an invoice and nothing records who did it.
    public function destroy(Invoice $invoice)
    {
        $invoice->delete();

        return response()->noContent();
    }
}

After ​

The same features, each method naming the STRIDE letter its control answers. Laravel 13 provides every control as a framework default or a one-liner; the code below uses only APIs from the 13.x documentation.

The model limits mass assignment and encrypts the bank account with the encrypted cast; #[UsePolicy] binds the policy.

php
<?php

namespace App\Models;

use App\Policies\InvoicePolicy;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Model;

#[UsePolicy(InvoicePolicy::class)]
class Invoice extends Model
{
    // Tampering: only these fields can ever be mass assigned.
    protected $fillable = ['customer_id', 'amount_cents', 'currency', 'bank_account'];

    protected function casts(): array
    {
        return [
            // Information disclosure: encrypted with APP_KEY (AES-256-CBC + MAC) before it reaches the database.
            'bank_account' => 'encrypted',
            'amount_cents' => 'integer',
        ];
    }
}

The policy is deny-by-default, answers a foreign invoice with denyAsNotFound(), and enforces separation of duties on delete.

php
<?php

namespace App\Policies;

use App\Models\Invoice;
use App\Models\User;
use Illuminate\Auth\Access\Response;

// Elevation of privilege: one place answers "may this user do this to this invoice?".
// Fail-safe default: anything not explicitly allowed is denied.
class InvoicePolicy
{
    public function view(User $user, Invoice $invoice): Response
    {
        // Information disclosure: a foreign invoice is answered with 404, not 403,
        // so the caller cannot even learn that the id exists.
        return $user->tenant_id === $invoice->tenant_id
            ? Response::allow()
            : Response::denyAsNotFound();
    }

    public function create(User $user): bool
    {
        return $user->hasVerifiedEmail();
    }

    public function delete(User $user, Invoice $invoice): bool
    {
        // Separation of duties: the person who issued an invoice cannot also delete it.
        return $user->tenant_id === $invoice->tenant_id
            && $user->is_finance_admin
            && $user->id !== $invoice->created_by;
    }
}

The controller authorises every action (complete mediation), validates input, takes tenant and author from the session, writes audit events without payloads, and issues a temporary signed URL.

php
<?php

namespace App\Http\Controllers;

use App\Models\Invoice;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;

// After: each method names the STRIDE letter its control answers.
class InvoiceController extends Controller
{
    // E + I: complete mediation, the policy runs on every request.
    public function show(Invoice $invoice)
    {
        Gate::authorize('view', $invoice);

        return $invoice->only(['id', 'amount_cents', 'currency', 'status']);
    }

    // T: validated fields only; tenant and author come from the session, never from input.
    public function store(Request $request)
    {
        Gate::authorize('create', Invoice::class);

        $data = $request->validate([
            'customer_id' => ['required', 'integer'],
            'amount_cents' => ['required', 'integer', 'min:1', 'max:100000000'],
            'currency' => ['required', 'in:EUR,USD,GBP'],
            'bank_account' => ['required', 'string', 'max:34'],
        ]);

        $invoice = new Invoice($data);
        $invoice->tenant_id = $request->user()->tenant_id;
        $invoice->created_by = $request->user()->id;
        $invoice->save();

        // R: an audit record with actor, action, object; no payload, no secrets.
        Log::channel('audit')->info('invoice.created', [
            'actor' => $request->user()->id,
            'invoice' => $invoice->id,
            'ip' => $request->ip(),
        ]);

        return response()->json(['id' => $invoice->id], 201);
    }

    // S + T: an HMAC-signed link that expires; changing the id or the expiry breaks the signature.
    public function shareLink(Invoice $invoice)
    {
        Gate::authorize('view', $invoice);

        return ['url' => URL::temporarySignedRoute(
            'invoices.download', now()->plus(minutes: 30), ['invoice' => $invoice->id]
        )];
    }

    // R + separation of duties: the policy forbids self-deletion, the log records who did it.
    public function destroy(Request $request, Invoice $invoice)
    {
        Gate::authorize('delete', $invoice);

        $invoice->delete();

        Log::channel('audit')->warning('invoice.deleted', [
            'actor' => $request->user()->id,
            'invoice' => $invoice->id,
        ]);

        return response()->noContent();
    }
}

Login: Hash::check, Hash::needsRehash, a per-email-and-IP limiter against credential stuffing, one generic message (no user enumeration), session regeneration and audit events.

php
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

// Spoofing controls at the front door: slow password hashing, rehash on login,
// a per-account-and-IP limit against credential stuffing, one generic error.
class LoginController extends Controller
{
    public function store(Request $request)
    {
        $credentials = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $key = 'login:'.Str::lower($credentials['email']).'|'.$request->ip();

        if (RateLimiter::tooManyAttempts($key, 5)) {
            // D + S: the attacker's guess rate is capped; the account is not locked for its owner forever.
            throw ValidationException::withMessages([
                'email' => 'Too many attempts. Try again in '.RateLimiter::availableIn($key).' seconds.',
            ]);
        }

        $user = User::where('email', $credentials['email'])->first();

        if (! $user || ! Hash::check($credentials['password'], $user->password)) {
            RateLimiter::increment($key);
            // R + detective control: failed logins are evidence for credential-stuffing alerts.
            Log::channel('audit')->notice('auth.failed', ['email_hash' => hash('sha256', Str::lower($credentials['email'])), 'ip' => $request->ip()]);

            // I: the same message whether the email exists or not (no user enumeration).
            throw ValidationException::withMessages(['email' => 'These credentials do not match our records.']);
        }

        if (Hash::needsRehash($user->password)) {
            // Corrective: old hashes are upgraded to the current work factor on the next login.
            $user->forceFill(['password' => Hash::make($credentials['password'])])->save();
        }

        RateLimiter::clear($key);
        Auth::login($user);
        $request->session()->regenerate(); // session fixation

        Log::channel('audit')->info('auth.login', ['actor' => $user->id, 'ip' => $request->ip()]);

        return redirect()->intended('/dashboard');
    }
}

Named rate limiters (one for the API, a much smaller one for exports) and the routes that use them, with password.confirm as step-up and signed on the anonymous download.

php
<?php

namespace App\Providers;

use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // D: per-user (or per-IP for guests) API quota; 429 with Retry-After when exceeded.
        RateLimiter::for('api', function (Request $request) {
            return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
        });

        // D: expensive exports get their own, much smaller budget (bulkhead for a hot endpoint).
        RateLimiter::for('exports', function (Request $request) {
            return [
                Limit::perMinute(2)->by($request->user()?->id),
                Limit::perDay(20)->by($request->user()?->id),
            ];
        });
    }
}
php
<?php

use App\Http\Controllers\InvoiceController;
use App\Http\Controllers\LoginController;
use App\Models\Invoice;
use Illuminate\Support\Facades\Route;

// Every route states its controls: who may call it (auth), how often (throttle),
// what proves the link was ours (signed). CSRF comes from the web group itself.
Route::post('/login', [LoginController::class, 'store']);

Route::middleware(['auth', 'verified', 'throttle:api'])->group(function () {
    Route::get('/invoices/{invoice}', [InvoiceController::class, 'show']);
    Route::post('/invoices', [InvoiceController::class, 'store']);
    Route::post('/invoices/{invoice}/share', [InvoiceController::class, 'shareLink']);
    Route::delete('/invoices/{invoice}', [InvoiceController::class, 'destroy'])
        ->middleware('password.confirm'); // step-up for a destructive action
    Route::get('/exports/invoices', fn () => response()->streamDownload(fn () => print ('...'), 'invoices.csv'))
        ->middleware('throttle:exports');
});

// No session needed: the HMAC signature and the expiry are the authorization (403 if tampered).
Route::get('/invoices/{invoice}/download', function (Invoice $invoice) {
    return response()->download(storage_path('invoices/'.$invoice->id.'.pdf'));
})->name('invoices.download')->middleware('signed');

Application wiring: preventRequestForgery(except: [...]) for the one webhook that is authenticated by signature instead, trustProxies restricted to the load balancers (documentation range), and the security headers middleware.

php
<?php

use App\Http\Middleware\SecurityHeaders;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        // T + S: PreventRequestForgery checks Sec-Fetch-Site, then falls back to the CSRF token.
        // Only the payment webhook is exempt; it is authenticated by the provider's signature instead.
        $middleware->preventRequestForgery(except: [
            'webhooks/psp',
        ]);

        // S: only our load balancers may set X-Forwarded-For (documentation range used here).
        $middleware->trustProxies(at: [
            '192.0.2.0/24',
        ]);

        $middleware->append(SecurityHeaders::class);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        // I: with APP_DEBUG=false (production) users see a generic error page; details stay in the log.
    })
    ->create();
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

// Secure by default at the response layer: the same headers as the Go server.
class SecurityHeaders
{
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);

        $response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
        $response->headers->set('Content-Security-Policy', "default-src 'self'; frame-ancestors 'none'; object-src 'none'");
        $response->headers->set('X-Content-Type-Options', 'nosniff');
        $response->headers->set('X-Frame-Options', 'DENY');
        $response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
        $response->headers->set('Permissions-Policy', 'geolocation=(), camera=(), microphone=()');
        $response->headers->remove('X-Powered-By');

        return $response;
    }
}
STRIDELaravel 13 controlWhere
SHash (bcrypt default), RateLimiter::tooManyAttempts, session()->regenerate(), signed middlewareLoginController, routes
TPreventRequestForgery (Sec-Fetch-Site then CSRF token), $fillable, validation, signed URLsbootstrap/app.php, model, controller
RLog::channel('audit') with actor and object idsControllers
Iencrypted cast (AES-256-CBC + MAC), denyAsNotFound(), only([...]) responses, generic errors with APP_DEBUG=falseModel, policy, controller
DRateLimiter::for + throttle: middleware, separate export limiterProvider, routes
EPolicies via #[UsePolicy], Gate::authorize, password.confirm step-upPolicy, controller, routes

The Laravel angle ​

Laravel 13's defaults already cover a large part of the STRIDE grid: the web middleware group includes PreventRequestForgery, which "checks the browser's Sec-Fetch-Site header" and "falls back to traditional CSRF token validation" (419 on mismatch; 403 in originOnly mode); the Hash facade uses bcrypt by default with Argon2 available; Crypt and the encrypted cast use "the AES-256-CBC cipher" with a MAC, and APP_PREVIOUS_KEYS lets you rotate APP_KEY; URL::temporarySignedRoute plus the signed middleware turn a link into a capability that cannot be edited. What Laravel cannot decide for you: which policy method runs on which route (complete mediation is your job), what goes into the audit channel and where that channel ships (a store the app cannot edit), the numbers in your rate limiters, and whether trustProxies lists only your real proxies. PHP-FPM workers are per request, so rate limiter state must live in a shared cache (Redis), which is the default for production deployments.

Solving the classic problems ​

IDOR: changing an id returns someone else's data ​

SolutionHowAdvantageCost / limitation
Policy check per objectGate::authorize('view', $invoice) on every actionComplete mediation; one place to auditMust be applied to every route; test it
Scope queries by tenantGlobal scope or where tenant_id = ? from the sessionDefence in depth below the policyForgotten in raw queries and reports
Row-level security in PostgreSQLRLS policy on tenant_id with a per-request settingHolds even if the app forgetsConnection-pool and migration care (Database Security)
Unguessable ids (UUIDv4/ULID)Random identifiersSlows enumerationNot an access control; never alone (open design)

Credential stuffing on login ​

SolutionHowAdvantageCost / limitation
MFA / passkeysWebAuthn, TOTPStolen passwords stop workingEnrolment UX, recovery flows
Per-account + per-IP throttlingLaravel RateLimiter keyed on email plus IPCaps guesses per accountDistributed botnets rotate IPs; combine with account-level limits
Breached-password checkCompare hash prefixes against a breach corpus at sign-up and loginRemoves reused passwordsExternal dependency or local dataset
DetectionAlert on failed-login ratio across all IPsSees low-and-slow attacksNeeds a baseline

Secrets committed to git ​

SolutionHowAdvantageCost / limitation
Rotate immediatelyRevoke and reissue the keyOnly real fix once leakedRequires rotatable design
Secret scanningPre-commit hook and host-side scanningCatches before pushFalse positives
Workload identityIAM roles for service accounts, OIDC to cloud from CINo long-lived secret existsCloud-specific setup
Secrets managerVault, AWS Secrets Manager, Kubernetes External SecretsCentral rotation and auditAnother critical dependency

Slowloris and oversized requests ​

SolutionHowAdvantageCost / limitation
Server timeoutsReadHeaderTimeout, ReadTimeout, IdleTimeoutFrees goroutines and socketsLong uploads need a per-route design
Body and header limitsMaxBytesReader, MaxHeaderBytes, NGINX client_max_body_sizeBounded memoryUpload endpoints need their own limit
Reverse proxy bufferingNGINX/Envoy/CDN in frontSlow clients handled at the edgeAnother layer to configure
Rate limiting and sheddingPer-client limits, load sheddingProtects shared capacityTuning

A malicious or vulnerable dependency ​

SolutionHowAdvantageCost / limitation
Lockfiles and checksumsgo.sum, composer.lock, image digestsNo silent driftUpgrades become explicit work
Reachability-aware scanninggovulncheck, composer auditFewer false alarmsCoverage differs per ecosystem
SBOM per buildSyft / CycloneDX stored with the artifactAnswer "are we affected?" in minutesStorage and tooling
Signature verification at deployCosign + admission policyOnly CI-built artifacts runKey/identity policy to maintain

Attackers erasing their tracks ​

SolutionHowAdvantageCost / limitation
Append-only grants + triggerSQL in MechanicsApp role cannot rewrite historySuperuser still can, hence the next rows
Hash chainEach row hashes the previousEdits become detectableVerification job needed
Ship to a separate accountLog pipeline to a different cloud account / WORM bucketSurvives a full app compromiseCost, retention policy
Alert on gapsMissing sequence or silence alertsDetects disabled loggingNoise

Verbose errors leak internals ​

SolutionHowAdvantageCost / limitation
Generic errors outsideGo Recover middleware; Laravel APP_DEBUG=falseNo stack traces or DSNs to clientsSupport needs request ids to debug
Request idsX-Request-Id in response and logCorrelate a user report to the logNone worth mentioning
Redaction rulesNever log bodies, cookies, AuthorizationLogs safe to share with respondersDiscipline; test it (TestAuditLine)

Choosing ​

Which threat-modelling technique ​

SituationTechniqueExtraReason
New service or feature with a diagramSTRIDE per elementGenerated checklist in CISystematic, covers technical controls
One high-value goal (move money, read all tenants)Attack treeCost per leafFinds the cheapest path
Money- or permission-changing workflowsAbuse casesAutomated testsFinds business-logic and race flaws
Personal data processingLINDDUNDPIA under GDPRPrivacy harms STRIDE does not name
Detection and SOC planningMITRE ATT&CKLog-source mappingReal adversary behaviour after access
Prioritising vulnerability patchesCVSS v4 BTE + reachabilitygovulncheckBase score alone overstates or understates

Which control first, by situation ​

SituationFirst controlSecond layerReason
Public loginMFA or passkeysPer-account throttle + breached-password checkCredential abuse is the leading vector
Multi-tenant APIPolicy per objectTenant-scoped queries or RLSIDOR is the most common access-control failure
Internal service callsmTLS / workload identityPer-service authorization policyNo implicit trust from network location
File downloads for anonymous usersTemporary signed URLShort expiry, throttleCapability without a session
Webhooks from providersSignature + timestamp checkIP allow-list, idempotencySpoofed callbacks mark orders paid
Card paymentsTokenise at the PSP (hosted fields)Segment what remainsRemoves most PCI DSS scope
Admin and support toolsSSO + MFA + named accountsAudit every action, step-up for destructive onesInsider and phishing risk, accountability
Build and deploy pipelineLockfiles + signature verificationSBOM + SLSA provenanceSupply chain failures

How much depth for how much risk ​

Asset sensitivityMinimum layersDetective requirementReview
Public contentEdge + application limitsError-rate alertsLightweight checklist
Internal business dataIdentity + application authz + data rolesAudit of writesFull checklist
PIIAbove + encryption at rest + minimisationAudit of reads and exportsChecklist + DPIA
Card data, credentials, signing keysAbove + isolation (separate account/cluster) + HSM/KMSReal-time alerts, separate log accountChecklist + external review

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

The trust boundaries are few: internet to app, app to database. The threat model fits on one page and most controls are framework defaults: Laravel's CSRF, hashing, encrypted cookies, policies and throttling. The dangerous simplicity is a single database role with full rights and an admin panel inside the same app; give the app a least-privilege role, put admin routes behind SSO with MFA, and keep the audit table append-only. Concrete example: a Laravel shop with one PostgreSQL; the worked STRIDE table collapses to about ten rows, the most important being per-object policies and the DB role.

Modular monolith: boundaries without the network ​

Modules introduce internal trust boundaries that are not network boundaries: the billing module should not read the identity module's password hashes even though they share a process and maybe a database. Enforce it with separate schemas and database roles per module, module-level authorization at the public module interface, and no shared "god" service that every module calls with elevated rights (least common mechanism). Example: billing gets SELECT on a view of customers, not the users table.

Microservices: every arrow is a decision ​

Each service adds a process, a store and several flows, and every flow crosses a trust boundary. Without zero trust, compromising one service means reaching all of them. The flow for "place order" shows what must survive:

text
     Order placement across services
1    browser -> API gateway: OIDC session, WAF, rate limit           (S, D at the edge)
2    gateway -> orders: JWT with user + tenant, validated by orders  (S, E; never trust a header set by the client)
3    orders -> payments: mTLS (service identity) + per-service authz  (S, T, I between services)
4    orders -> broker "order.placed": producer ACL, no card data      (T, I on the queue)
5    fulfilment consumes: verifies envelope, idempotent processing    (T, D)
6    each service: own DB role, own secrets, audit events with trace id (E, R)

Gateways and meshes carry part of this (see API Gateway, BFF & Service Mesh and mTLS), but authorization of business objects stays in each service. Broker-side controls (TLS, SASL, ACLs, payload encryption) are in Messaging Security.

Distributed data: replicas, caches, regions ​

Every copy of the data is another asset to protect: read replicas need the same access controls as the primary, caches (Redis) need authentication and must not hold data the requester could not read (cache keys per tenant), analytics copies and backups need encryption and their own access policies, and multi-region deployments raise data-residency questions under GDPR. Integrity across copies needs authenticated replication channels; availability gains from replicas also widen the confidentiality surface. Example: a Redis cache keyed only by invoice:43 served tenant A's invoice to tenant B after a policy check was skipped on cache hits; the fix is checking authorization before the cache lookup and including the tenant in the key.

Scaling path: 1x, 10x, 100x ​

ScaleWhat changes in security design
1x (one team, one app)Framework defaults, one threat model, least-privilege DB role, MFA for admins, backups tested
10x (several teams and services)Paved-road templates (secure server, CI checks), threat model per service in the repo, mTLS, central logging, SOC 2 evidence
100x (many teams, regions, regulated data)Zero trust access, policy as code (OPA, Cedar), signed artifacts with admission control, SBOM per build, dedicated detection engineering mapped to ATT&CK, per-region data controls, incident drills

Lab: threat-model a system and harden a server ​

Experiment 1: generate the STRIDE checklist (run) ​

bash
cd docs/snippets/system-design/security-foundations-cia-stride/go
go run ./cmd/stride | head -8
text
# Threat checklist: shop: web app + API + queue + DB

| Element | STRIDE | Violates | Question | Severity | Status | Missing controls |
| --- | --- | --- | --- | --- | --- | --- |
| Orders API (Go) | R | non-repudiation | Are security-relevant actions recorded so they cannot be denied? | high | OPEN | audit-log (detective) |
| Orders API (Go) | D | availability | Can a caller exhaust its CPU, memory, connections or threads? | high | OPEN | rate-limit (preventive) |
| Audit log | R | non-repudiation | Can audit records be altered or deleted? | high | OPEN | integrity (preventive) |
| Audit log | I | confidentiality | Can stored data be read by someone who should not? | high | OPEN | enc-rest (preventive) |

The last line (run on this machine) is Open per category: S=2 T=5 R=5 I=7 D=10 E=2 (total threats 53) and the exit status is 1 because open high rows exist.

Experiment 2: close a threat and watch the gate (run, then edit) ​

Add "audit-log", "rate-limit" to the api element's controls in a copy of model.json and run go run ./cmd/stride my-model.json. Expected: the two Orders API rows move to "mitigated" at the bottom of the table, and the R and D counts drop by one each. The exit status stays 1 until every high row is closed or the model records the control.

Experiment 3: break the model on purpose (expected, not run) ​

Add {"id": "f9", "kind": "data_flow", "from": "api", "to": "ghost"}. Expected output on stderr and exit status 2:

text
invalid model:
 f9: endpoint "ghost" does not exist

Experiment 4: the secure server tests (run) ​

bash
go test -race ./...
text
ok   academy/security-foundations-cia-stride/secureserver
ok   academy/security-foundations-cia-stride/threatmodel

The tests prove: timeouts default to non-zero, five security headers and the request id are present, a declared 11-byte body over a 10-byte cap and a streamed 64-byte body both get 413, a panic containing a password returns a generic 500 while the detail stays in the log, and the audit line contains neither the card number, the bearer token nor the forged subject header.

Experiment 5: Slowloris against Before and After (expected, not run) ​

Run before/main.go, open a TCP connection and send one header byte every 10 seconds (nc localhost 8080, type POST /orders HTTP/1.1 and wait). Expected: the Before server keeps the connection open indefinitely. Against a server built with secureserver.New the connection is closed after the 5-second ReadHeaderTimeout.

Experiment 6: Laravel controls (expected, not run) ​

RequestExpected response
GET /invoices/43 as a user of another tenant404 (policy denyAsNotFound)
POST /invoices without CSRF token from an old browser without Sec-Fetch-Site419
Download URL with the invoice parameter changed403 (signed middleware)
Download URL after 30 minutes403 (expired temporary signature)
6th failed login for the same email and IP within the windowValidation error "Too many attempts. Try again in N seconds."
61st API request in one minute429 with Retry-After
DELETE /invoices/42 by the invoice's creator403 (separation of duties in the policy)

Common misconceptions ​

BeliefReality
"Hackers mostly use zero-days"Credential abuse (22%) and exploitation of known vulnerabilities lead in the DBIR 2025 press release; zero-days are concentrated on edge devices and VPNs
"HTTPS makes us secure"TLS covers T and I on flows; it does nothing for S, R, D or E at processes
"Internal services can trust each other"NIST SP 800-207: no implicit trust from network location
"Encryption gives integrity"Only authenticated encryption or a MAC does; plain CBC does not
"Our logs give non-repudiation"Not with shared accounts and logs the app can edit
"Obscure URLs are access control"Open design: protection must rest on keys, not secrecy of the design
"A threat model is a one-time document"OWASP: it should be maintained alongside the system
"CVSS Base is our risk"Apply Threat and Environmental metrics and reachability
"Compliance equals security"Compliance is an audited baseline, not protection against a motivated attacker
"Defense in depth means more tools"Layers must fail independently; two of the same is one layer
"Pinning in composer.json is enough"Ranges drift; lockfiles and checksums pin content
"Detection can wait until we are bigger"Without detective controls, prevention failures are discovered by customers

Cheat sheet ​

TopicRemember
Why hackedCredentials, known vulns, misconfiguration, supply chain, people; cheapest path wins
CIAConfidentiality (read), integrity (change), availability (use); Saltzer & Schroeder 1975
Beyond CIAAuthenticity, non-repudiation, accountability; Parkerian hexad adds possession, authenticity, utility
Four questionsWhat are we working on, what can go wrong, what will we do, did we do enough
DFDEntities, processes, stores, flows, trust boundaries
STRIDE per elementEntity S,R; process all six; store T,I,D (+R for logs); flow T,I,D
ResponsesMitigate, eliminate, transfer, accept (with owner and expiry)
ScoringLikelihood x impact at design; CVSS v4 BTE + reachability for patching
Attack treesGoal at root, OR = alternatives, AND = all required, price the leaves
Defense in depthEdge, network, identity, application, data, monitoring; each assumes the previous failed
PrinciplesLeast privilege, fail-safe defaults, complete mediation, economy of mechanism, open design, separation of privilege
Zero trustNo implicit trust from network location; authenticate and authorise every request
ControlsEvery high threat: one preventive and one detective; every asset: a corrective plan
Supply chainLockfiles, SBOM, signature verification (Sigstore), SLSA provenance
ComplianceSOC 2, ISO 27001, PCI DSS, GDPR as non-functional requirements; design to shrink scope

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Which three violation categories did Saltzer and Schroeder name, and which CIA property is each? Good to know ​

Answer

Answer: Unauthorized information release (confidentiality), unauthorized information modification (integrity), unauthorized denial of use (availability).

2 — Which STRIDE letters apply to a data flow, and why not R or E? Good to know ​

Answer

Answer: T, I and D. A flow does not act, so it cannot deny an action or gain privileges; those are asked of the processes at each end.

3 — A queue sits between the API and a worker. What new DFD elements does it add and which threats matter most? Important ​

Answer

Answer: A data store (the backlog) and two data flows. Tampering (forged messages from a compromised producer), information disclosure (sensitive data at rest in messages) and denial of service (queue flooding or poison loops). Controls: producer ACLs, signed envelopes, no sensitive payloads, max length and DLQ.

4 — Why is a CVSS 9.8 in a dependency not automatically a 9.8 risk for you? Must-know ​

Answer

Answer: Base describes the vulnerability in general. Your risk depends on reachability (govulncheck), exploit maturity (Threat metrics) and your environment and controls (Environmental metrics).

5 — Give two principles violated by an admin panel protected only by an unlisted URL. Must-know ​

Answer

Answer: Open design (protection depends on secrecy of the design) and complete mediation (no authorization check on access); also fail-safe defaults.

6 — What separates defense in depth from simply buying more security products? Must-know ​

Answer

Answer: Independence: each layer uses a different mechanism and credentials so one failure does not defeat the others, and each is designed assuming the outer layer already failed.

7 — Name a preventive, a detective and a corrective control against ransomware on the database. Must-know ​

Answer

Answer: Preventive: no public endpoint, least-privilege roles, MFA for admins. Detective: alerts on mass writes and snapshot deletion. Corrective: immutable backups in a separate account with tested restores.

8 — Why does the Go audit middleware delete X-Authenticated-Subject from incoming requests? Important ​

Answer

Answer: To prevent spoofing: only the inner authentication layer may set the subject after verifying a credential; a client-supplied value would be logged as if it were a verified identity.

9 — What does Laravel's PreventRequestForgery check first, and what status do token and origin failures return? Important ​

Answer

Answer: It checks the Sec-Fetch-Site header first, then falls back to the CSRF token. A token mismatch returns 419; in originOnly mode a failed origin check returns 403.

10 — How does tokenising card numbers at the payment provider change PCI DSS? Important ​

Answer

Answer: Card numbers never reach your servers, so most of your systems leave the cardholder data environment and PCI DSS scope shrinks to the page that embeds the provider's field.

11 — What does Sigstore record in Rekor, and why does that remove key management? Good to know ​

Answer

Answer: The artifact digest, signature and short-lived certificate. Signing uses an ephemeral key bound by Fulcio to an OIDC identity; verifiers check the identity and the log inclusion instead of a long-lived public key.

12 — Which design decisions make the first hour of an incident shorter? Must-know ​

Answer

Answer: Audit events with request ids, per-key and per-tenant credentials that can be revoked individually, kill switches, immutable separate-account backups and synchronised clocks.

Glossary ​

TermMeaning
Attack surfaceAll entry and exit points an attacker can reach, plus the assets behind them
Threat actorAn adversary class defined by motive, capability and access
AssetAnything worth protecting: data, capabilities, availability
MisconfigurationAn unsafe setting (public bucket, default password, debug mode)
Credential stuffingTrying leaked username/password pairs from other breaches (ATT&CK T1110.004)
PhishingElectronically delivered social engineering (ATT&CK T1566)
Social engineeringManipulating people into giving access or information
Zero-dayA vulnerability exploited before a fix is available
Supply chain attackCompromise through a dependency, build system or vendor (ATT&CK T1195)
RansomwareMalware that encrypts or steals data for extortion
CIA triadConfidentiality, integrity, availability
ConfidentialityOnly authorised parties can read information
IntegrityInformation cannot be changed without authorisation or detection
AvailabilityInformation and services are usable when needed
AuthenticityAn entity or data is genuine
Non-repudiationAn actor cannot deny an action they performed
AccountabilityActions trace uniquely to an actor
Parkerian hexadCIA plus possession or control, authenticity, utility (Parker, 1998)
Threat modellingStructured analysis of what can go wrong and what to do about it
Data flow diagram (DFD)Model of entities, processes, stores and flows
Trust boundaryA line where the level of trust changes
STRIDESpoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege
SpoofingPretending to be another user or system
TamperingUnauthorised modification of data or code
RepudiationDenying an action with no evidence to the contrary
Information disclosureExposing data to unauthorised parties
Denial of serviceMaking a system unavailable to legitimate users
Elevation of privilegeGaining rights beyond those granted
STRIDE per elementApplying only the letters relevant to each DFD element type
DREADDamage, Reproducibility, Exploitability, Affected users, Discoverability scoring (historical)
CVSSFIRST's Common Vulnerability Scoring System; v4.0 has Base, Threat, Environmental, Supplemental groups
Attack treeGoal-rooted tree of attack paths with AND/OR nodes (Schneier 1999)
Abuse caseA story an attacker wants to succeed, turned into a test that must fail
LINDDUNPrivacy threat-modelling method
PASTARisk-centric threat-modelling method linking business impact
MITRE ATT&CKKnowledge base of adversary tactics and techniques
Defense in depthMultiple independent layers of controls
Least privilegeEvery program and user has only the privileges needed
Fail-safe defaultsDeny unless explicitly permitted
Separation of dutiesCritical tasks split between people or roles
Separation of privilegeRequiring two keys or factors to unlock
Complete mediationEvery access to every object checked for authority
Economy of mechanismKeep protection mechanisms small and simple
Open designSecurity must not depend on secrecy of the design
Least common mechanismMinimise mechanisms shared between users
Psychological acceptabilityThe secure path must be easy to use
Zero trustNo implicit trust based on network location or ownership (NIST SP 800-207)
Secure by defaultThe out-of-the-box configuration is the safe one
Shift leftMoving security activities earlier in the lifecycle
Preventive controlReduces the likelihood of a successful attack
Detective controlIdentifies an attempt or compromise
Corrective controlLimits damage and restores the system
Residual riskRisk remaining after controls, owned and accepted explicitly
Secrets managementLifecycle of credentials: store, distribute, rotate, revoke, audit
SBOMSoftware bill of materials: a nested inventory of components
Dependency pinningResolving dependencies to exact versions and hashes
Code signingBinding an artifact to the identity that produced it
SigstoreKeyless signing with Fulcio certificates and the Rekor transparency log; client Cosign
SLSASupply-chain Levels for Software Artifacts, build levels L0 to L3
Security review checklistFixed questions and artefacts required before a design is approved
SOC 2AICPA report on controls for security, availability, processing integrity, confidentiality, privacy
ISO 27001International standard for an information security management system
PCI DSSPayment card industry baseline for protecting account data
GDPREU data protection regulation; Art. 25 by design and default, Art. 32 security
Verizon DBIRVerizon's annual Data Breach Investigations Report
OWASPOpen Worldwide Application Security Project: Top 10, cheat sheets, threat modelling guidance
NIST CSFNIST Cybersecurity Framework 2.0: Govern, Identify, Protect, Detect, Respond, Recover
IDORInsecure direct object reference: access by changing an identifier
SlowlorisHolding connections open by sending headers very slowly

References ​

Built by Morteza Negahi