Security by Design
"In a large system some objects will be inadequately considered, so a default of lack of permission is safer." — Jerome H. Saltzer and Michael D. Schroeder, The Protection of Information in Computer Systems, Proceedings of the IEEE, 1975 (Section I, "Fail-safe defaults")
Summary: Security is a quality attribute you design in, the way you design in latency or availability. You find the trust boundaries, ask what can go wrong at each one, and choose structures (policy objects, typed input, deny-by-default, tenant scoping, rate limits, audit trails) that make the wrong thing hard to write. Focus: Saltzer and Schroeder's eight principles, threat modeling with data flow diagrams and STRIDE, secure design patterns, the OWASP Top 10 as a list of design decisions, session and token design, multi-tenancy isolation, supply chain, security testing, privacy by design, and how all of it changes from a monolith to many services, in Go and Laravel. Learning goal: Take a feature (here, a checkout), draw its trust boundaries, list the threats per boundary, pick the design control for each, and prove with tests that an IDOR, a mass-assignment hole and a missing rate limit are closed.
This page is the design view of security. It tells you where to put controls and why, and it leaves the product-level detail to the pages that own it: roles, RLS, SQL injection and audit inside the database are in Database Security; keys, TDE and column encryption are in Encryption at Rest, in Transit & in Use; the tenant models and row-level security are in Multi-Tenancy Strategies; broker authentication and message-level controls are in Messaging Security. It builds on Quality Attributes (security is one of them), Design Quality Principles (information hiding and least coupling are security tools), Error Handling & Fault Tolerance (fail closed, no leaked stack traces), Data Persistence in Design (repositories are where tenant scoping lives), Distribution of Components (every network hop is a trust boundary) and the SOLID pages, especially Single Responsibility and Dependency Inversion.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in a few tables | Everything in one minute |
| Why security cannot be added at the end | Why it exists |
| Saltzer and Schroeder, STRIDE, SSDF, ASVS, the OWASP Top 10 | Where it comes from |
| Trust boundary, attack surface, threat model, STRIDE, attack tree, abuse case | Threat modeling |
| The eight design principles with Go and Laravel examples | Saltzer and Schroeder's principles |
| Input validation, output encoding, parameterized queries | Trust boundaries in code |
| Authentication, authorization, RBAC, ABAC, ReBAC, IDOR, mass assignment | Who may do what |
| Secure defaults, secrets, rate limiting, idempotency keys, audit logging | Secure design patterns |
| Defense in depth and zero trust | Defense in depth |
| Cookies, JWT pitfalls, refresh rotation, OAuth 2.1, OIDC, Sanctum, Passport | Sessions and tokens |
| Tenant isolation | Multi-tenancy isolation |
Dependencies, SBOM, govulncheck, composer audit | Supply chain |
| Data minimization, GDPR Article 25 | Privacy by design |
| OWASP Top 10 as design decisions | OWASP Top 10 mapped |
| A worked threat model of a checkout | Mechanics: the checkout model |
| SAST, DAST, SCA, pentest, fuzzing | Security testing |
| Go and Laravel code | Go, Laravel |
| Monolith, microservices, gateway auth, service identity | In architecture |
| The hands-on lab | Lab: threat-model and fix |
| Wrong beliefs, cheat sheet, self-check, every term | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The vocabulary. Every row is unpacked later.
| Term | In plain words | Tiny example | What goes wrong without it |
|---|---|---|---|
| Trust boundary | A line where data or control passes between parts that trust each other differently | Browser to web app; web app to payment provider | You validate in the wrong place, or nowhere |
| Attack surface | Everything an attacker can reach and feed input to | Routes, webhooks, file uploads, admin panels | A forgotten endpoint is the way in |
| Threat model | A written answer to "what can go wrong here and what do we do about it" | A DFD plus a STRIDE table | Controls are guesses |
| STRIDE | Six threat families: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege | "Can someone replay this webhook?" | You only think about the one attack you know |
| Authentication (authn) | Who are you | Password plus second factor | Anyone can claim to be anyone |
| Authorization (authz) | What may you do to this object | OrderPolicy::view | Logged in means allowed (IDOR) |
| Least privilege | Only the rights the job needs | A DB role that cannot DROP TABLE | One bug owns everything |
| Deny by default | No rule, no access | A new route is closed until someone opens it | New code ships open |
| Defense in depth | Several independent layers | Policy plus tenant scope plus RLS | One bug is a breach |
| Idempotency key | A client-chosen id that makes a retry safe | Idempotency-Key: 7f3a... on POST | Double charge, double refund |
| Audit log | Append-only record of who did what | actor=alice action=order:read outcome=deny | No evidence, no detection |
| SBOM | Bill of materials: every component and version you ship | CycloneDX or SPDX file | You cannot answer "are we affected" |
Saltzer and Schroeder's eight principles in one line each (1975, quoted in full in the principles).
| Principle | One line | Violated by |
|---|---|---|
| Economy of mechanism | Keep it small and simple so it can be reviewed | A 3,000-line custom auth framework |
| Fail-safe defaults | Permission, not exclusion; default is no access | A deny list of "bad" paths |
| Complete mediation | Check every access to every object | Authorization only in the UI, or only on the first request |
| Open design | Secrecy of design is not the protection; secrecy of keys is | "Nobody knows our URL scheme" |
| Separation of privilege | Two conditions, two keys | One admin can approve and pay their own invoice |
| Least privilege | Minimum rights for the job | The app connects as the database owner |
| Least common mechanism | Share as little as possible between users | One shared cache key for all tenants |
| Psychological acceptability | Easy to use correctly | A security setting nobody can explain |
The OWASP Top 10:2025 list (the 2021 list introduced Insecure Design; the 2025 page says it "slides two spots from #4 to #6").
| Rank | Category | The design question it asks |
|---|---|---|
| A01 | Broken Access Control | Who may touch this object, and where is that decided? |
| A02 | Security Misconfiguration | What are the defaults, and who can change them? |
| A03 | Software Supply Chain Failures | What code do we run that we did not write? |
| A04 | Cryptographic Failures | What do we protect, with which keys, where kept? |
| A05 | Injection | Where does data become code? |
| A06 | Insecure Design | Did anyone ask what can go wrong before coding? |
| A07 | Authentication Failures | How do we know who is calling, and for how long? |
| A08 | Software or Data Integrity Failures | Do we verify what we load and deploy? |
| A09 | Security Logging and Alerting Failures | Would we notice, and could we prove it? |
| A10 | Mishandling of Exceptional Conditions | What do we do on error: open or closed? |
Where each control lives in Go and Laravel.
| Control | Go | Laravel 13 |
|---|---|---|
| Input validation | Decode into a typed struct, DisallowUnknownFields, http.MaxBytesReader | Form Request with rules() and validated() |
| Output encoding | html/template (contextual escaping) | Blade escaped output |
| Parameterized query | database/sql placeholders ($1) | Eloquent and query builder bindings |
| Authorization | Policy interface, one call per handler | Policies and Gate::authorize |
| Mass-assignment guard | A request type with no privileged fields | #[Fillable] attribute on the model |
| CSRF | Not built in; token or Sec-Fetch-Site check in middleware | PreventRequestForgery middleware in the web group |
| Password hashing | golang.org/x/crypto/bcrypt or argon2 | Hash facade: bcrypt by default, Argon2 supported |
| Rate limiting | Token bucket middleware | RateLimiter::for and throttle middleware |
| Secrets | Environment or secret manager, slog redaction | .env, config(), Crypt facade with APP_KEY |
| Dependency audit | govulncheck ./... | composer audit |
Why it exists
Most breaches are not clever. They are a missing check, a default that was too open, a trust placed in a value the client controls. The OWASP Top 10:2025 page on Insecure Design says these are not coding slips: "We differentiate between design flaws and implementation defects for a reason, they have different root causes, take place at different times in the development process, and have different remediations." A perfect implementation of a flawed design is still flawed: if the checkout accepts the price from the browser, no amount of careful coding makes that safe.
Security is also a trade-off with usability, speed and cost, like every quality attribute in Quality Attributes. The skill is making the trade-off on purpose, early, where it is cheap.
| Bolted on at the end | Designed in from the start |
|---|---|
| A scanner finds 400 findings the week before release | The threat model lists 15 risks at design time |
| Fixes change the data model and the API | The model already carries tenant, owner and state |
Controls are scattered if statements | Controls are one policy object, one middleware, one scope |
| Security is "the security team's job" | Security is every story's acceptance criteria |
| Cheap to start, expensive to change | Slightly slower start, cheap to change |
| Risk: you ship holes you did not know existed | Risk: over-engineering controls for threats that do not apply |
The picture is the checkout we model in the worked example. Every dashed rectangle is a trust boundary; every arrow that crosses one is an attack surface and a place to ask the STRIDE questions.
The analogy we reuse on this page: a bank branch. The vault has a thick door, but the bank does not rely on the door alone. The street door is locked at night (network edge), the teller checks your identity (authentication), checks the account is yours (authorization), needs a second signature for large transfers (separation of privilege), logs everything on camera (audit), and gives each teller only the cash drawer they need (least privilege). Nobody designs a bank by building the building first and asking "where should we put the locks?" afterwards.
Three common misunderstandings, up front
- "Security is a feature we add before release." Features can be added; properties cannot. Whether a tenant can see another tenant's rows is decided by the schema, the query layer and the cache keys, long before any "security sprint".
- "We use a framework, so we are secure." Laravel guards mass assignment and CSRF by default, but it cannot know that
user_idin your URL must be compared with the caller. Go'snet/httpguards almost nothing by default. Frameworks remove classes of bugs; they do not design your authorization. - "Hiding the URL or the algorithm protects us." Saltzer and Schroeder, 1975: "The design should not be secret." Protection must rest on keys and checks, not on ignorance.
Where it comes from
Saltzer and Schroeder, 1975. The paper The Protection of Information in Computer Systems (Proceedings of the IEEE 63(9), 1975) gave the field its first lasting list of design principles. It starts from three kinds of violation: "Unauthorized information release", "Unauthorized information modification" and "Unauthorized denial of use". Then it admits there is no method to prove a design secure: "In the absence of such methodical techniques, experience has provided some useful principles that can guide the design and contribute to an implementation without security flaws. Here are eight examples of design principles that apply particularly to protection mechanisms." Those eight are the backbone of this page's principles section. The paper also lists two more ideas that "apply only imperfectly to computer systems": work factor and compromise recording.
Microsoft's STRIDE. Microsoft's threat-modeling guidance categorises threats as Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service and Elevation of Privilege, and says threat modeling "is ideally performed early in the SDLC, such as during the design phase. Moreover, it is not something that is performed once and never again."
OWASP. The Top 10 is an awareness list ("a broad consensus about the most critical security risks to web applications"). Insecure Design arrived as a category in 2021; in the 2025 edition it is A06 and "calls for more use of threat modeling, secure design patterns, and reference architectures", and asks the community to "move beyond 'shift-left' in the coding space, to pre-code activities such as requirements writing and application design". The Application Security Verification Standard (ASVS), currently 5.0.0, is the checklist behind it; the OWASP Cheat Sheet Series holds the per-topic advice we cite below.
NIST SSDF, 2022. NIST SP 800-218 (February 2022) describes "a core set of high-level secure software development practices that can be integrated into each SDLC implementation", with a stated aim to "reduce the number of vulnerabilities in released software, mitigate the potential impact of the exploitation of undetected or unaddressed vulnerabilities, and address the root causes of vulnerabilities to prevent future recurrences".
The Threat Modeling Manifesto's four questions (quoted by the OWASP Threat Modeling Cheat Sheet): What are we working on? What can go wrong? What are we going to do about it? Did we do a good enough job?
GDPR Article 25, 2016/2018. Data protection by design and by default became a legal obligation in the EU; see Privacy by design.
The concepts, one by one
Each block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, and the fix.
Security as a quality attribute Must-know
In plain words: security is a property of the whole system, like response time. You specify it ("a user can read only their own orders"), you design for it, and you test it.
Common misunderstanding: "Security means encryption." Encryption protects data in transit and at rest. Most real incidents are access-control and logic failures where every byte was properly encrypted and handed to the wrong person.
Definition: Saltzer and Schroeder define security as "techniques that control who may use or modify the computer or the information contained in it", and sort violations into release (confidentiality), modification (integrity) and denial of use (availability). Practitioners add authenticity and accountability. Each becomes a requirement with a measurable check.
Vague requirement Testable security requirement
1 "The app must be secure" "Mallory cannot read Alice's order by any URL" (test: GET /orders/{alice_order} as Mallory returns 404)
2 "Protect the payments" "A client cannot set total or status" (test: POST with total_cents returns 422)
3 "Prevent abuse" "More than 5 login attempts/min per account+IP returns 429"
4 "Be auditable" "Every deny writes actor, action, object, request id"Real scenario: a SaaS invoice app whose requirements doc has a section "Security" with one line, "use HTTPS"; the first customer to change an id in the URL reads a competitor's invoices.
Fix: write security requirements as acceptance criteria next to functional ones, and let ASVS chapters (authentication, session, access control, validation, logging) serve as the checklist. See Quality Attributes for scenario format.
Trust boundary and attack surface Must-know
In plain words: a trust boundary is a line where "data I control" meets "data somebody else controls". The attack surface is the set of all entry points across those lines.
Common misunderstanding: "Inside our network everything is trusted." A compromised laptop, a vulnerable dependency or a malicious tenant is already inside. Internal services are separate trust zones.
Definition: a trust boundary separates components with different privileges or different owners. The OWASP Threat Modeling Cheat Sheet asks for "a clear view of trust boundaries, data flows, data stores, processes, and the external entities", because these "often represent possible attack points".
Request path (checkout) Boundary crossed
1 Browser -> Laravel (HTTPS) TB1 -> TB2 : everything is untrusted input
2 Laravel -> Go pricing service (mTLS) TB2 -> TB3 : trust the caller identity, not its data
3 Go service -> PostgreSQL (role: orders_app) inside TB3 : least-privilege role, parameterized SQL
4 Go service -> payment provider TB3 -> TB4 : their response is untrusted until verified
5 Payment provider -> Laravel webhook TB4 -> TB2 : signature check before anything elseReal scenario: a webhook endpoint added for a payment provider that accepts any JSON, because "only the provider knows the URL"; anyone who finds it marks orders as paid.
Fix: at every boundary, authenticate the peer, validate the data, and decide what happens on failure (closed). Draw the boundaries first; the diagram above is the template.
Threat modeling Must-know
In plain words: threat modeling is a short structured conversation: draw the system, walk along each arrow asking "what could go wrong?", write down what you will do about it, and check later that you did.
Common misunderstanding: "Threat modeling is a big document written by the security team once." OWASP's A06 page says threat modeling "should be integrated into refinement sessions (or similar activities)", and Microsoft's guidance says a threat model "should be maintained, updated and refined alongside the system" and "treated as a standard and necessary step in the process, not an add-on". A whiteboard and 45 minutes per feature beat a 60-page report nobody updates.
Definition: a repeatable process answering the four questions above. Its inputs are a model of the system (a data flow diagram with processes, data stores, external entities, data flows and trust boundaries), its method is a prompt list (STRIDE for technical designs, attack trees for a high-value goal, misuse or abuse cases for business-rule abuse, LINDDUN for privacy), and its output is a ranked list of threats with an owner and a mitigation each.
Step Output
1 What are we working on? DFD with trust boundaries (see diagram)
2 What can go wrong? STRIDE per element and per crossing arrow
3 What are we going to do about it? Mitigate, accept, transfer or avoid; each with an owner and a test
4 Did we do a good enough job? Threat-driven tests; review when the data flow changes| STRIDE letter | Threat | Property violated | Typical design control |
|---|---|---|---|
| S | Spoofing | Authentication | MFA, signed tokens, mTLS, webhook signatures |
| T | Tampering | Integrity | Server-side pricing, TLS, HMAC, DB constraints |
| R | Repudiation | Non-repudiation | Audit log, request id, signed receipts |
| I | Information disclosure | Confidentiality | Policy objects, tenant scope, encryption, generic errors |
| D | Denial of service | Availability | Rate limits, timeouts, quotas, backpressure |
| E | Elevation of privilege | Authorization | Deny by default, least privilege, no mass assignment |
Attack trees start from the attacker's goal and split it into alternative (OR) or required (AND) paths. They suit a few high-value goals. Abuse cases (misuse cases) describe a valid workflow used wrongly: out of order, repeated, concurrent, or for an unintended outcome. OWASP's A06 gives two: a cinema that allows group bookings and caps them at fifteen can be hit with six hundred seats booked in a few requests; a retailer without anti-bot design lets scalpers buy every graphics card. Both are logic flaws that no scanner finds.
Ranking. The cheat sheet says ranking is "based on the mathematical product of an identified threat's likelihood and its impact", then admits both are hard to estimate. Use three levels (high, medium, low) and rank within a session; precision is false comfort.
Real scenario: a team threat-models "export my data". STRIDE on the export link finds Information disclosure (a guessable link), Spoofing (anyone with the link is the user) and Denial of service (huge exports). The fixes are a signed expiring URL, a re-authentication step and a queue with a per-user limit, all decided before coding.
Fix: put a 45-minute threat-model step in refinement for any story that adds a data flow, a role or a boundary; store the DFD in the repo next to the code. Tools: whiteboard, OWASP Threat Dragon (open-source diagrams with a rule engine), Microsoft Threat Modeling Tool.
Saltzer and Schroeder's eight principles Must-know
In plain words: eight rules of thumb from 1975 that still decide whether a protection mechanism will hold. Most of this page is these rules applied.
Common misunderstanding: "They are old and about operating systems." The vocabulary is dated; the logic is not. A Laravel policy, a Go middleware and a Kubernetes network policy are all protection mechanisms, and each fails in exactly the ways these principles predict.
Definition and examples. Each row quotes or paraphrases the paper (we read Section I.A.3 of the MIT copy) and ties it to code.
| Principle | The paper says | Violation in a web system | Go example | Laravel example |
|---|---|---|---|---|
| Economy of mechanism | "Keep the design as simple and small as possible." Errors in protection "will not be noticed during normal use" so review must be possible | A homemade token format and a 500-line permission matrix | One authz.Policy interface, 60 lines, table-tested (authz/authz.go) | Use framework Gate and Policies instead of ad hoc if ($user->is_admin) |
| Fail-safe defaults | "Base access decisions on permission rather than exclusion." The default is no access | A blocklist of forbidden paths; new routes open by default | Decide returns false unless a rule matches | A missing policy method denies; routes grouped under auth middleware |
| Complete mediation | "Every access to every object must be checked for authority." Be "skeptical" of cached checks | Authorization in the UI only; checking only on show, not on update or the export endpoint | Require is called in every handler before the object is used | Gate::authorize in each action, or can: middleware on the route group |
| Open design | "The design should not be secret." Protection rests on keys, not ignorance | Security through obscurity: secret URL, home-grown cipher | Use crypto/rand, crypto/subtle, standard TLS | Crypt (AES with MAC) and Hash (bcrypt, Argon2): public algorithms, secret APP_KEY |
| Separation of privilege | "A protection mechanism that requires two keys to unlock it is more robust" | One person creates and approves a payout | Refund needs the finance role and an order in state paid | Policy plus a second-approver rule; MFA for admin actions |
| Least privilege | "The least set of privileges necessary to complete the job" | App connects as DB owner; token with every scope | DB role orders_app with SELECT, INSERT, UPDATE on two tables | Sanctum abilities (['orders:read']), separate DB users for migrations and runtime |
| Least common mechanism | "Minimize the amount of mechanism common to more than one user" | One cache key or one global singleton shared by all tenants | Tenant id in every cache key and in the context | Global scope and tenant-prefixed cache keys; queue per tenant tier |
| Psychological acceptability | "The human interface [must be] designed for ease of use" so protection is applied routinely | A 20-field permission form nobody understands; password rules that force sticky notes | Secure defaults mean the easy path is the safe path | Starter kits give login, throttling, hashing with no setup |
Principle in action: fail-safe defaults + complete mediation on a new endpoint
1 Developer adds GET /orders/{id}/invoice
2 Without a policy method -> Gate denies -> 403/404 (fix: add the rule, a visible decision)
3 With a blocklist design -> no rule matches -> endpoint is open (bug found by a customer)Real scenario: the pattern "authorize in the controller show, forget the download action" is a complete-mediation failure; the pattern "admin routes are protected by a list of path prefixes" is a fail-safe-defaults failure (a new /internal/ prefix is open).
Fix: put the decision in one object (policy), call it from every entry point (middleware or first line of each action), make the default deny, and test that an unauthorised caller is refused for every route. Single Responsibility explains why the policy is its own module.
Input validation at trust boundaries Must-know
In plain words: check what comes in, once, at the door, and turn it into a type the rest of the code can trust.
Common misunderstanding: "Client-side validation is enough" or "blocklist the bad characters". The browser is the attacker's tool; and the OWASP Input Validation Cheat Sheet says "Do not try to recognize every malicious string. Blocking apostrophes, for example, rejects legitimate names without making a database query safe."
Definition: validation means syntax (shape, type, range, length, allow-list) and semantics ("whether the value makes sense for the operation": the end date is after the start). Output encoding and parameterized queries are separate, later defences, not substitutes for it.
Request Result
1 {"items":[{"sku":"BOOK-1","qty":2}], "currency":"EUR"} accepted -> typed Checkout
2 same + "total_cents": 1 rejected: unknown field (mass assignment attempt)
3 qty = -5 rejected: range
4 sku = "X' OR 1=1" rejected: allow-list regexp (and still parameterized later)
5 body of 70 KiB rejected: size limit, before parsing| Defence | Protects against | Where | Go | Laravel |
|---|---|---|---|---|
| Allow-list validation | Malformed and unexpected data | At the boundary | Typed struct, regexp, slices.Contains | Form Request rules (in, regex, between) |
| Size and time limits | Resource exhaustion | Server and handler | http.MaxBytesReader, ReadHeaderTimeout | post_max_size, upload max: rule, throttle |
| Reject unknown fields | Mass assignment | Decoder | DisallowUnknownFields | prohibited rule or validated() only |
| Output encoding | XSS | When writing to HTML, JS, URL | html/template contextual escaping | Blade escaped output; avoid raw output |
| Parameterized query | SQL injection | Data access | db.QueryContext(ctx, "... $1", v) | Query builder, Eloquent bindings; never DB::raw with user data |
| Canonicalize then validate | Path traversal, Unicode tricks | Before use | filepath.Clean, os.Root (Go 1.24) | Storage disks with fixed roots |
The Go package docs state the point of html/template: it "implements data-driven templates for generating HTML output safe against code injection", and "The escaping is contextual, so actions can appear within JavaScript, CSS, and URI contexts". Use text/template for HTML and you lose that.
Real scenario: a CSV import trusts a role column; an upload endpoint trusts the file extension; a search box concatenates into SQL. Each is a boundary with no validator. For SQL specifically see Database Security: SQL injection.
Fix (Go):
// Package validate parses untrusted input once, at the trust boundary, into a typed value.
package validate
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"slices"
)
const maxBody = 64 << 10 // 64 KiB
var (
skuRe = regexp.MustCompile(`^[A-Z0-9-]{3,32}$`)
couponRe = regexp.MustCompile(`^[A-Z0-9]{4,16}$`)
currencies = []string{"EUR", "USD", "GBP"}
)
// wire is what the client may send. It has no price, status or owner fields at all.
type wire struct {
Items []struct {
SKU string `json:"sku"`
Qty int `json:"qty"`
} `json:"items"`
Coupon string `json:"coupon"`
Currency string `json:"currency"`
}
// Line is a validated line item.
type Line struct {
SKU string
Qty int
}
// Checkout is the only type the domain accepts; it can only be built by DecodeCheckout.
type Checkout struct {
Lines []Line
Coupon string
Currency string
}
// ErrInvalid wraps every validation failure so handlers can map it to 400 or 422.
var ErrInvalid = errors.New("invalid input")
// DecodeCheckout reads the body with a size limit, rejects unknown fields, then checks
// syntax (shape, ranges, allow-lists) and leaves semantics (price, stock) to the server.
func DecodeCheckout(w http.ResponseWriter, r *http.Request) (Checkout, error) {
if r.Header.Get("Content-Type") != "application/json" {
return Checkout{}, fmt.Errorf("%w: content type", ErrInvalid)
}
r.Body = http.MaxBytesReader(w, r.Body, maxBody)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
var in wire
if err := dec.Decode(&in); err != nil {
return Checkout{}, fmt.Errorf("%w: %v", ErrInvalid, err)
}
if dec.More() {
return Checkout{}, fmt.Errorf("%w: trailing data", ErrInvalid)
}
if n := len(in.Items); n < 1 || n > 50 {
return Checkout{}, fmt.Errorf("%w: items must be 1..50", ErrInvalid)
}
out := Checkout{Coupon: in.Coupon, Currency: in.Currency}
for _, it := range in.Items {
if !skuRe.MatchString(it.SKU) || it.Qty < 1 || it.Qty > 99 {
return Checkout{}, fmt.Errorf("%w: bad line item", ErrInvalid)
}
out.Lines = append(out.Lines, Line{SKU: it.SKU, Qty: it.Qty})
}
if !slices.Contains(currencies, in.Currency) {
return Checkout{}, fmt.Errorf("%w: currency", ErrInvalid)
}
if in.Coupon != "" && !couponRe.MatchString(in.Coupon) {
return Checkout{}, fmt.Errorf("%w: coupon", ErrInvalid)
}
return out, nil
}Fix (Laravel):
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
// Validation at the trust boundary: syntax here, business rules (stock, price) in the service.
final class CheckoutRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
public function rules(): array
{
return [
'items' => ['required', 'array', 'min:1', 'max:50'],
'items.*.sku' => ['required', 'string', 'regex:/^[A-Z0-9-]{3,32}$/'],
'items.*.qty' => ['required', 'integer', 'between:1,99'],
'currency' => ['required', Rule::in(['EUR', 'USD', 'GBP'])],
'coupon' => ['nullable', 'string', 'regex:/^[A-Z0-9]{4,16}$/'],
// Fields the server owns: sending them is an attack or a bug, either way it is refused.
'status' => ['prohibited'],
'total_cents' => ['prohibited'],
'user_id' => ['prohibited'],
'tenant_id' => ['prohibited'],
];
}
}Authentication and authorization are different Must-know
In plain words: authentication asks "who are you?"; authorization asks "may you do this to that object?". Passing the first says nothing about the second.
Common misunderstanding: "The route is behind the login middleware, so it is protected." That is authn only. Any logged-in user can still request another user's order by id. This is IDOR (Insecure Direct Object Reference), the commonest form of A01 Broken Access Control.
Definition: authorization is a function decide(subject, action, resource) -> allow or deny evaluated on the server for every request. Models differ in what they look at:
| Model | Decides by | Example rule | Strength | Weakness | Fits |
|---|---|---|---|---|---|
| RBAC (role-based) | The subject's role | finance may refund | Simple, auditable | Role explosion; ignores which object | Back-office staff, coarse gates |
| ABAC (attribute-based) | Attributes of subject, resource, context | owner equals caller, status is pending, time is business hours | Expressive | Rules scatter and get hard to review | Business rules on an object |
| ReBAC (relationship-based) | A relation graph | "member of the org that owns the project" | Models sharing and hierarchies (Google Zanzibar style) | Needs a relation store | Documents, orgs, teams |
| ACL | A list on each object | Alice and Bob may edit this document | Fine-grained | Hard to audit at scale | Files, sharing |
The OWASP Authorization Cheat Sheet says to "Prefer Attribute and Relationship Based Access Control over RBAC", to "Enforce Least Privileges", to adopt "deny-by-default", and to validate "permissions on every request, regardless of whether the request was initiated by an AJAX script, server-side, or any other source", with "global, application-wide configuration" rather than per-method opt-in: "Remember an attacker only needs to find one way in."
Mallory (user 7) Server
1 GET /orders/1001 (her own) policy: owner=7 -> allow, 200
2 GET /orders/1002 (Alice's, id changed) BEFORE: no owner check -> 200 with Alice's data
3 GET /orders/1002 AFTER: policy: owner=3 != 7 -> deny, respond 404 (same as missing)
4 audit: actor=7 action=order:read object=order/1002 outcome=denyReal scenario: a ticketing app exposes /tickets/{id}/messages; changing the id lists strangers' conversations. A mobile API trusts user_id in the JSON body. An admin export endpoint was written for staff and left without a role check.
Fix: one policy object per resource, called from every entry point, returning a decision with a reason; respond 404 rather than 403 when existence itself is sensitive; scope queries by owner or tenant so the wrong row is not even loaded. Opaque or random ids (UUIDv4 and ULID: see ID Generation) reduce guessing but do not replace the check.
Go:
// Package authz is a tiny policy object: deny by default, one place for every decision.
package authz
import (
"errors"
"slices"
)
// ErrForbidden is returned when a policy denies an action.
var ErrForbidden = errors.New("authz: forbidden")
// Action is a verb on a resource kind, for example "order:read".
type Action string
const (
OrderRead Action = "order:read"
OrderCancel Action = "order:cancel"
OrderRefund Action = "order:refund"
)
// Subject is the authenticated caller, built from a verified session, never from the request body.
type Subject struct {
UserID string
TenantID string
Roles []string
}
// Resource carries only the attributes a policy needs (ABAC style).
type Resource struct {
OwnerID string
TenantID string
Status string
}
// Decision records the answer and the reason, so it can be audited.
type Decision struct {
Allow bool
Reason string
}
// Policy decides; it never fetches data and never has side effects.
type Policy interface {
Decide(s Subject, a Action, r Resource) Decision
}
// OrderPolicy combines a tenant fence, ownership (ReBAC-like) and roles (RBAC).
type OrderPolicy struct{}
// Decide denies unless an explicit rule allows (fail-safe defaults).
func (OrderPolicy) Decide(s Subject, a Action, r Resource) Decision {
if s.UserID == "" || s.TenantID == "" {
return Decision{false, "anonymous"}
}
if s.TenantID != r.TenantID {
return Decision{false, "other tenant"}
}
switch a {
case OrderRead:
if r.OwnerID == s.UserID || slices.Contains(s.Roles, "support") {
return Decision{true, "owner or support"}
}
case OrderCancel:
if r.OwnerID == s.UserID && r.Status == "pending" {
return Decision{true, "owner, still pending"}
}
case OrderRefund:
if slices.Contains(s.Roles, "finance") {
return Decision{true, "finance role"}
}
}
return Decision{false, "no rule allows this"}
}
// Require turns a decision into an error; handlers call it before touching the object.
func Require(p Policy, s Subject, a Action, r Resource) error {
if d := p.Decide(s, a, r); !d.Allow {
return ErrForbidden
}
return nil
}Laravel:
<?php
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\Response;
// One policy object per resource: the single place that answers "may this user do this to that order?".
final class OrderPolicy
{
// A foreign order and a missing order both become 404, so ids cannot be probed.
public function view(User $user, Order $order): Response
{
return $order->user_id === $user->id || $user->hasRole('support')
? Response::allow()
: Response::denyAsNotFound();
}
public function cancel(User $user, Order $order): Response
{
return $order->user_id === $user->id && $order->status === 'pending'
? Response::allow()
: Response::denyAsNotFound();
}
// Anything not listed (delete, forceDelete, restore) has no method, so Laravel denies it.
public function refund(User $user, Order $order): bool
{
return $user->hasRole('finance');
}
}Mass assignment and over-posting Important
In plain words: the client sends more fields than you expected and your code saves them all.
Common misunderstanding: "The form does not have an is_admin field." Attackers use curl, not your form. The Laravel docs describe it: "a malicious user might send an is_admin parameter through an HTTP request, which is then passed to your model's create method, allowing the user to escalate themselves to an administrator."
Definition: a mass-assignment vulnerability occurs when a request field changes a column you did not intend, because the model is filled directly from request data. The same pattern appears in Go when a JSON body is decoded straight into the database struct.
Client Server
1 POST /orders {"items":[...]} creates order, status=pending, total=5000 (server-computed)
2 POST /orders {"items":[...],"status":"paid","total_cents":1}
BEFORE: row saved with status=paid, total=1
AFTER: 422 (Laravel prohibited rule) / 400 (Go DisallowUnknownFields)Real scenario: a profile update lets the user set role; a checkout lets the user set total_cents; a Go service decodes the request into the same struct it stores. Laravel also ships Model::preventSilentlyDiscardingAttributes() to make unfillable attributes throw in development.
Fix: use separate request and storage types (data transfer objects); a Laravel model declares #[Fillable([...])] with only what a user may influence and the server sets user_id, tenant_id, status and total_cents explicitly; return an explicit output allow-list rather than serialising the whole model (also prevents leaking password_hash and internal columns).
<?php
namespace App\Models;
use App\Models\Scopes\TenantScope;
use App\Policies\OrderPolicy;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Model;
// Only fields a customer may influence are fillable. user_id, tenant_id, status and
// total_cents are set by server code, so they are not here (fail-safe default).
#[Fillable(['shipping_address_id', 'coupon_code'])]
#[UsePolicy(OrderPolicy::class)]
class Order extends Model
{
protected static function booted(): void
{
// Every query on this model is tenant-scoped; forgetting a where() is no longer possible.
static::addGlobalScope(new TenantScope());
// New rows always get the tenant of the authenticated user, never one from the request.
static::creating(function (Order $order) {
$order->tenant_id ??= auth()->user()?->tenant_id;
});
}
}Secure defaults and secrets Important
In plain words: ship closed, make the safe choice the easy choice, and keep passwords and keys out of code.
Common misunderstanding: "We will tighten it in production." Defaults travel: the debug flag, the permissive CORS and the admin password from the demo environment all reach production because nobody flips them. The OWASP Authorization Cheat Sheet adds that "explicit configuration should be preferred over relying on framework or library defaults", because "the logic and defaults of third-party code may evolve over time".
Definition: a secure default means the unconfigured system is the safe one (deny, TLS, Secure cookie, no debug). A secret is any value that grants access: database password, API key, signing key, APP_KEY, OAuth client secret. The OWASP Secrets Management Cheat Sheet states "Never transmit secrets via plaintext" and, for CI/CD, "Limit blast radius: Avoid storing high-value, long-term, or widely scoped credentials in CI/CD variables".
Secret lifecycle Control
1 create (random, from a CSPRNG) crypto/rand, php artisan key:generate
2 store (not in git, not in the image) secret manager (Vault, AWS Secrets Manager), or orchestrator secret mounted at runtime
3 use (least scope, short TTL) dynamic DB credentials per service, 1-hour tokens
4 rotate (without downtime) two valid versions during the switch (APP_KEY previous keys)
5 revoke and detect leaks secret scanning in CI, alert on use from a new placeReal scenario: a .env committed to a public repository; a Docker ENV line that bakes a key into every image layer; one shared admin credential for all services.
Fix: keep secrets in a manager or runtime mount; separate credentials per service and per environment; scan repositories (pre-commit and CI); never log secrets (see redaction below). Details of database credentials are in Database Security and key hierarchy in Encryption.
Rate limiting and abuse resistance Important
In plain words: limit how fast one caller can do something, so brute force, scraping and expensive calls cannot run at full speed.
Common misunderstanding: "A WAF or the CDN already does that." Edge limits are coarse (per IP). Business-aware limits (per account, per card number, per coupon, per API key) live in the application, which knows what an identity and an expensive operation are.
Definition: an algorithm that admits or refuses requests per key: token bucket (burst plus steady rate; used in our snippet), leaky bucket (smooths output), fixed window (simple, allows a 2x burst at the boundary), sliding window (accurate, more state). Refusal is HTTP 429 with a Retry-After header. Limits apply per IP, per user, per API key, and per sensitive object.
Attacker script (PIN login) Server
1 attempts 1..5 within a minute each admitted, tokens 5 -> 0
2 attempt 6 429, Retry-After: 12
3 attempts every 12 s 1 token refills each time: 5 guesses/min cap
4 10,000 possible PINs needs about 33 hours instead of secondsReal scenario: credential stuffing against /login; promo-code guessing; an SMS-sending endpoint abused to run up costs (a financial denial of service); a report endpoint that runs a 30-second query per call.
Fix: key by the thing being attacked (account plus IP for login, not IP alone, or one shared office IP locks out everyone), fail closed, return Retry-After, count in a shared store (Redis) when you run several instances, and add MFA or a captcha as the second line. Note the trap: behind a proxy, never key by the first X-Forwarded-For value, which a client can forge.
Go: ratelimit.go (token bucket, injectable clock, test). Laravel:
<?php
// app/Providers/AppServiceProvider.php (boot) and routes/api.php.
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
final class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Login: five tries per minute per account and IP, and a coarser cap per IP alone.
RateLimiter::for('login', function (Request $request) {
$account = mb_strtolower((string) $request->input('email'));
return [
Limit::perMinute(5)->by($account.'|'.$request->ip()),
Limit::perMinute(30)->by($request->ip()),
];
});
// Checkout: per user when known, per IP otherwise; a 429 carries Retry-After automatically.
RateLimiter::for('checkout', fn (Request $request) => Limit::perMinute(20)
->by($request->user()?->id ?: $request->ip()));
}
}
// routes/api.php
// Route::post('/login', [AuthController::class, 'login'])->middleware('throttle:login');
// Route::post('/orders', [OrderController::class, 'store'])->middleware(['auth:sanctum', 'throttle:checkout']);Idempotency keys Important
In plain words: a unique id the client sends so that if it retries (timeout, double click) the server does the work once.
Common misunderstanding: "Retries are the network's problem." Retries are also an attack: replaying a captured "pay" or "refund" request. An idempotency key plus a payload fingerprint turns both accidental and malicious repeats into the same single effect.
Definition: the server stores (caller, key) -> fingerprint, result. Same key and same payload returns the saved result; same key and different payload is rejected (422 in our sketch); an in-flight duplicate waits or gets 409. The key is scoped by caller so one user cannot probe another's keys.
Client Server
1 POST /pay Key: k1 {99.00} not seen -> charge, save result
2 (timeout, client retries)
3 POST /pay Key: k1 {99.00} seen, same fingerprint -> replay saved result, no second charge
4 POST /pay Key: k1 {5.00} seen, different fingerprint -> 422 key reuseReal scenario: a mobile client on a bad network pays twice; an attacker replays a captured refund; a payment webhook delivered twice by the provider (at-least-once delivery).
Fix: Go: idempotency.Store.Do below; Laravel: the middleware in Error Handling & Fault Tolerance (EnsureIdempotency). Also see Delivery Guarantees for the consumer side.
// Package idempotency makes a retried POST safe: same key and same payload, same answer, one side effect.
package idempotency
import (
"crypto/sha256"
"encoding/hex"
"errors"
"sync"
)
// ErrKeyReuse means the key was used before with a different payload.
var ErrKeyReuse = errors.New("idempotency key reused with a different request")
type entry struct {
fingerprint string
done chan struct{}
result string
err error
}
// Store remembers results by (caller, key). A production store lives in Redis or the database
// with a TTL (for example 24 hours) and a unique index, so every instance sees it.
type Store struct {
mu sync.Mutex
entries map[string]*entry
}
// NewStore returns an empty in-memory store.
func NewStore() *Store { return &Store{entries: map[string]*entry{}} }
func fingerprint(payload []byte) string {
sum := sha256.Sum256(payload)
return hex.EncodeToString(sum[:])
}
// Do runs fn once per (caller, key). A concurrent duplicate waits for the first call and
// receives its result; a duplicate with another payload gets ErrKeyReuse.
func (s *Store) Do(caller, key string, payload []byte, fn func() (string, error)) (result string, replayed bool, err error) {
id := caller + "|" + key // scoped by caller so one user cannot probe another user's keys
fp := fingerprint(payload)
s.mu.Lock()
if e, ok := s.entries[id]; ok {
s.mu.Unlock()
if e.fingerprint != fp {
return "", false, ErrKeyReuse
}
<-e.done
return e.result, true, e.err
}
e := &entry{fingerprint: fp, done: make(chan struct{})}
s.entries[id] = e
s.mu.Unlock()
e.result, e.err = fn()
close(e.done)
return e.result, false, e.err
}Audit logging Important
In plain words: a trustworthy record of who did what to which object and what the system decided.
Common misunderstanding: "We have logs." Application debug logs are not an audit trail: they are mutable, unstructured, full of secrets, and missing the denials. A logging failure is itself a Top 10 item (A09 Security Logging and Alerting Failures).
Definition: an audit event has actor, action, object, outcome, time, source and a correlation (request) id; it is append-only and shipped off the host. The OWASP Logging Cheat Sheet asks to log security events (authentication, access-control failures, input validation failures) and never to log secrets or personal data beyond need.
Event Level Why
1 login success / failure INFO / WARN detect stuffing
2 authz deny: actor=7 order:read order/1002 WARN detect IDOR probing
3 refund approved: actor=fin-2 order/1001 INFO accountability, separation of privilege
4 request body {"password":"hunter2"} never redact secrets and tokensReal scenario: a customer claims "I never approved that payout": without an audit record you cannot refute or confirm it (Repudiation in STRIDE). A scraper walks ids for a week and nobody sees it because 404s are not logged.
Fix: log decisions at the policy, not at the controller; redact by key name in the logger; alert on a spike of denies per actor; protect the log from the people it audits. See Database Security: audit for database-side auditing.
// Package audit writes who-did-what-to-which-object as structured events and keeps secrets out of logs.
package audit
import (
"context"
"io"
"log/slog"
"strings"
)
var sensitive = []string{"password", "token", "authorization", "card", "secret", "cookie"}
// New returns a JSON logger that redacts any attribute whose key looks sensitive.
func New(w io.Writer) *slog.Logger {
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
k := strings.ToLower(a.Key)
for _, s := range sensitive {
if strings.Contains(k, s) {
return slog.String(a.Key, "[REDACTED]")
}
}
return a
},
}))
}
// Event is one audit record: actor, action, object, outcome and a correlation id.
type Event struct {
Actor string
Action string
Object string
Outcome string // "allow", "deny", "error"
RequestID string
}
// Record logs the event; denials are logged at WARN so alerts can key on them.
func Record(ctx context.Context, l *slog.Logger, e Event) {
level := slog.LevelInfo
if e.Outcome != "allow" {
level = slog.LevelWarn
}
l.LogAttrs(ctx, level, "audit",
slog.String("actor", e.Actor), slog.String("action", e.Action),
slog.String("object", e.Object), slog.String("outcome", e.Outcome),
slog.String("request_id", e.RequestID))
}Defense in depth and zero trust Must-know
In plain words: never rely on one control. Stack independent ones so that when one fails, another still stops the attack. Zero trust is the same idea applied to the network: do not trust a request because of where it came from.
Common misunderstanding: "More layers is more security." Layers that share a failure (the same secret, the same bug, the same team) count as one. And layers cost latency and complexity: each must stop something the others cannot.
Definition: defense in depth places controls at several levels (edge, gateway, application, domain, data) plus detection. NIST SP 800-207 describes zero trust as an evolving set of paradigms that "move defenses from static, network-based perimeters to focus on users, assets, and resources", and says it "assumes there is no implicit trust granted to assets or user accounts based solely on their physical or network location". For services: authenticate and authorise every call, not just the one at the gateway.
One IDOR bug, three layers
1 Request GET /orders/1002 as Mallory (tenant 1, order belongs to Alice)
2 L3 policy forgotten in this new action -> bug, would leak
3 L3 global tenant scope -> same tenant, still passes
4 L5 PostgreSQL RLS (user = current_user) -> 0 rows, returns not found
5 L6 audit/alert -> deny counter jumps, on-call is pagedReal scenario: a common cloud pattern is one over-permissive role plus a server-side request forgery that reaches the instance metadata service; a second layer (metadata hardening, a least-privilege role) limits the damage. In code: the policy bug in step 2 above is survivable because RLS exists.
Fix: list for each crown jewel the independent controls guarding it; ask "if this one fails, what stops the attacker?". RLS for the database layer is in Multi-Tenancy: RLS in depth.
Sessions and tokens Must-know
In plain words: after login, the browser or app carries something that proves "this is Alice". How you issue, store, expire and revoke it decides how bad a theft is.
Common misunderstanding: "A JWT is more secure than a session cookie." A JWT is a signed container. It cannot be revoked before expiry without extra state, its payload is readable by anyone who has it, and a wrong verification (accepting alg: none, not checking aud) is a classic breach. For a browser app with one backend, a server-side session in an HttpOnly cookie is usually simpler and safer.
Definition: a session is server-side state looked up by an unguessable id in a cookie. A token (opaque or JWT) is presented in a header. Both are bearer credentials: whoever holds them is the user, until they expire or are revoked.
| Cookie attribute | What it does | Setting | Note |
|---|---|---|---|
Secure | Sent only over HTTPS | Always | Without it, a downgrade to HTTP leaks the id |
HttpOnly | Not readable by JavaScript | Always for session ids | Stops cookie theft via XSS, not XSS itself |
SameSite | Whether cross-site requests carry it | Lax (or Strict) | OWASP: "defense in depth against CSRF, not a replacement for a CSRF token"; never None without Secure |
__Host- prefix | Browser enforces Secure, Path=/, no Domain | Use for the session cookie | Blocks subdomain overwrite |
| Lifetime | Idle and absolute timeouts | Idle 15-120 min, absolute hours | Short for sensitive apps |
| Rotation | New id at login and privilege change | session()->regenerate() | Defeats session fixation |
| JWT pitfall | Why it hurts | RFC 8725 / practice |
|---|---|---|
Trusting the alg header | none or an HMAC-versus-RSA key confusion lets attackers forge tokens | "Libraries MUST enable the caller to specify a supported set of algorithms and MUST NOT use any other algorithms"; pin the algorithm |
Not checking iss, aud, exp, nbf | Token from another service or an old token accepted | Validate every claim you rely on |
| Long-lived access token | A stolen token works for days | Minutes, plus refresh |
| Sensitive data in the payload | Payload is only base64url, not encrypted | Put ids, not secrets |
Storing in localStorage | Any XSS reads it | Prefer HttpOnly cookie, or in-memory with short life |
| No revocation | Logout and password reset do not kill it | Short life, denylist or token version in the user row |
| Same key everywhere / weak HMAC key | One leak forges for all | Per-service keys, asymmetric signing, kid rotation |
OAuth 2.1 and OIDC in one paragraph. OAuth 2.1 (an IETF draft at the time we read it, draft-ietf-oauth-v2-1-17) consolidates the safe parts of OAuth 2.0: the authorization code flow with PKCE is mandatory ("Clients MUST use code_challenge and code_verifier"), the implicit grant is removed, and refresh tokens "MUST be bound to the scope and resource servers as consented by the resource owner"; when the client cannot authenticate, the server "SHOULD issue sender-constrained refresh tokens or use refresh token rotation". OpenID Connect adds an identity layer (the ID token, sub, nonce) on top of OAuth for login. Use an established identity provider or library; do not write an authorization server by hand. In Laravel, Sanctum issues first-party session auth and simple API tokens (SHA-256 hashed in the database, abilities, expiry) and Passport is a full OAuth2 server; in Go, use a maintained OIDC client library and the golang.org/x/oauth2 package.
Refresh token rotation. Every refresh returns a new refresh token and invalidates the old. If an old token is ever presented again, someone has a copy: revoke the whole family.
Legitimate app Attacker (stole R1) Server
1 login issue A1 + R1 (family F)
2 refresh with R1 issue A2 + R2, R1 marked used
3 refresh with R1 (replay) R1 already used -> revoke family F
4 refresh with R2 rejected, force loginReal scenario: an SPA stores a 30-day JWT in localStorage; one XSS in a third-party widget and the attacker has 30 days of access. A mobile app's refresh token leaks from a backup; without rotation nothing detects it.
Fix: Go: session and jwtcheck snippets below; Laravel: config/session.php, Hash, Sanctum token abilities.
// Package session shows server-side session and refresh-token design: random opaque tokens,
// only hashes stored, safe cookie flags, and refresh rotation with reuse detection.
package session
import (
"crypto/rand"
"crypto/sha256"
"crypto/subtle"
"encoding/base64"
"encoding/hex"
"errors"
"net/http"
"sync"
"time"
)
// NewToken returns 256 bits from crypto/rand, base64url encoded. Never use math/rand for this.
func NewToken() (string, error) {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
return "", err
}
return base64.RawURLEncoding.EncodeToString(b), nil
}
// Hash is what the database stores; a leaked table does not leak usable tokens.
func Hash(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
// Equal compares two hashes in constant time.
func Equal(a, b string) bool { return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 }
// Cookie builds a session cookie with the flags OWASP asks for. The __Host- prefix makes the
// browser require Secure, Path=/ and no Domain attribute.
func Cookie(token string, ttl time.Duration) *http.Cookie {
return &http.Cookie{
Name: "__Host-sid",
Value: token,
Path: "/",
MaxAge: int(ttl.Seconds()),
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
}
}
// ErrReuse means a refresh token that was already rotated was presented again: assume theft.
var ErrReuse = errors.New("refresh token reuse detected, family revoked")
// ErrUnknown means the token is not known or its family was revoked.
var ErrUnknown = errors.New("unknown refresh token")
type record struct {
family string
used bool
}
// Refresher issues single-use refresh tokens grouped in families.
type Refresher struct {
mu sync.Mutex
byHash map[string]*record
revoked map[string]bool
}
// NewRefresher returns an empty in-memory refresher.
func NewRefresher() *Refresher {
return &Refresher{byHash: map[string]*record{}, revoked: map[string]bool{}}
}
// Start opens a new family at login.
func (r *Refresher) Start() (token string, err error) {
family, err := NewToken()
if err != nil {
return "", err
}
return r.issue(family)
}
func (r *Refresher) issue(family string) (string, error) {
t, err := NewToken()
if err != nil {
return "", err
}
r.byHash[Hash(t)] = &record{family: family}
return t, nil
}
// Rotate exchanges a refresh token for a new one. Presenting an old token twice revokes the whole
// family, so the thief and the real user are both forced to log in again.
func (r *Refresher) Rotate(presented string) (string, error) {
r.mu.Lock()
defer r.mu.Unlock()
rec, ok := r.byHash[Hash(presented)]
if !ok || r.revoked[rec.family] {
return "", ErrUnknown
}
if rec.used {
r.revoked[rec.family] = true
return "", ErrReuse
}
rec.used = true
return r.issue(rec.family)
}// Package jwtcheck verifies an HS256 JWT the way RFC 8725 asks: pin the algorithm, check issuer,
// audience and time claims. It is a teaching sketch; in production use a maintained library.
package jwtcheck
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"strings"
"time"
)
// Claims is the subset we rely on.
type Claims struct {
Issuer string `json:"iss"`
Subject string `json:"sub"`
Audience []string `json:"aud"`
Expires int64 `json:"exp"`
NotBefore int64 `json:"nbf"`
}
// Expect is what this service demands from every token.
type Expect struct {
Issuer string
Audience string
Leeway time.Duration
}
// ErrInvalid hides which check failed from the caller; log the reason server-side.
var ErrInvalid = errors.New("invalid token")
func b64(s string) ([]byte, error) { return base64.RawURLEncoding.DecodeString(s) }
// Verify checks the structure, the pinned algorithm, the signature and the claims.
func Verify(token string, key []byte, now time.Time, want Expect) (Claims, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return Claims{}, ErrInvalid
}
hb, err := b64(parts[0])
if err != nil {
return Claims{}, ErrInvalid
}
var h struct {
Alg string `json:"alg"`
}
if json.Unmarshal(hb, &h) != nil || h.Alg != "HS256" { // never trust the header to choose; "none" dies here
return Claims{}, ErrInvalid
}
sig, err := b64(parts[2])
if err != nil {
return Claims{}, ErrInvalid
}
mac := hmac.New(sha256.New, key)
mac.Write([]byte(parts[0] + "." + parts[1]))
if !hmac.Equal(sig, mac.Sum(nil)) { // constant-time comparison
return Claims{}, ErrInvalid
}
pb, err := b64(parts[1])
if err != nil {
return Claims{}, ErrInvalid
}
var c Claims
if json.Unmarshal(pb, &c) != nil {
return Claims{}, ErrInvalid
}
if c.Issuer != want.Issuer || !contains(c.Audience, want.Audience) {
return Claims{}, ErrInvalid
}
if c.Expires == 0 || now.After(time.Unix(c.Expires, 0).Add(want.Leeway)) {
return Claims{}, ErrInvalid
}
if c.NotBefore != 0 && now.Before(time.Unix(c.NotBefore, 0).Add(-want.Leeway)) {
return Claims{}, ErrInvalid
}
return c, nil
}
func contains(list []string, v string) bool {
for _, s := range list {
if s == v {
return true
}
}
return false
}<?php
// config/session.php (excerpt): the cookie flags from the OWASP Session Management cheat sheet.
return [
'driver' => env('SESSION_DRIVER', 'database'),
'lifetime' => 120, // idle timeout in minutes
'expire_on_close' => false,
'encrypt' => true, // session payload encrypted at rest
'cookie' => '__Host-laravel_session', // __Host- prefix: Secure, Path=/, no Domain
'path' => '/',
'domain' => null,
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true, // not readable from JavaScript
'same_site' => 'lax', // defence in depth next to the CSRF token
];
// After login: $request->session()->regenerate(); // new id, defeats session fixation
// On logout: $request->session()->invalidate(); $request->session()->regenerateToken();<?php
// Issuing narrow, short-lived API tokens with Sanctum.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
final class TokenController extends Controller
{
public function store(Request $request)
{
$request->validate(['name' => ['required', 'string', 'max:64']]);
// Abilities act like OAuth scopes; the expiry is the third argument. Sanctum stores only a SHA-256 hash.
$token = $request->user()->createToken(
$request->string('name')->toString(),
['orders:read'],
now()->addHours(8),
);
return ['token' => $token->plainTextToken]; // shown once, never retrievable again
}
public function show(Request $request)
{
abort_unless($request->user()->tokenCan('orders:read'), 403);
return $request->user()->orders()->latest()->limit(20)->get(['id', 'status', 'total_cents']);
}
}CSRF, XSS and the browser as an attacker's tool Important
In plain words: CSRF makes a logged-in browser send a request the user did not intend; XSS makes the browser run attacker script inside your site.
Common misunderstanding: "My API is JSON so CSRF cannot happen." If authentication is a cookie, a cross-site form post can still carry it; JSON does not save you unless you check content type and origin. And "we escape input" is wrong: you encode output, for the specific context it lands in.
Definition: Laravel 13's PreventRequestForgery middleware (in the web group by default) first checks the browser's Sec-Fetch-Site header, then falls back to a CSRF token tied to the session; for state-changing methods it inspects "every incoming POST, PUT, PATCH, DELETE, or QUERY request for a secret session value that the malicious application is unable to access". Go has no built-in equivalent: check Sec-Fetch-Site or Origin, or use a maintained CSRF library, for cookie-authenticated endpoints. XSS is prevented by contextual output encoding (html/template, Blade escaping) plus a Content-Security-Policy as defence in depth.
Real scenario: an "email change" form without a token; a comment field rendered as raw HTML; a javascript: URL accepted into an href.
Fix: keep the framework's CSRF middleware on; SameSite=Lax cookies; encode on output; set Content-Security-Policy and X-Content-Type-Options: nosniff (see the server snippet in Go and SecurityHeaders in Laravel).
Multi-tenancy isolation Must-know
In plain words: many customers share one system, and customer A must never see customer B's data, even when the code has a bug.
Common misunderstanding: "A where tenant_id = ? in each query is isolation." It is a convention, and one forgotten where, one raw query or one background job breaks it. Real isolation makes the wrong query impossible or returns nothing.
Definition: tenant isolation is enforced at several layers: tenant identity taken from the verified session (never a header or body field), a data layer that requires a tenant (scope, context), per-tenant cache keys, per-tenant limits, and, in the database, row-level security or separate schemas or databases. The OWASP Multi-Tenant Security Cheat Sheet lists "Tenant Identification & Context Management", "Do Not Use an RLS-Bypassing Role for Tenant-Scoped Request Paths", "Scope Tenant Context to the Transaction" and "Verify Tenant Isolation".
Layer Control Failure it survives
1 Session tenant id from the verified token client sending X-Tenant: 2
2 ORM / repository global scope / required context a forgotten where()
3 Cache key = tenant:{id}:order:{id} cache returning another tenant's row
4 Database RLS policy USING (tenant_id = current_setting) raw SQL, a buggy report, a job
5 Tests two tenants in every integration test regressions-- PostgreSQL: the database refuses foreign rows even if the application forgets the filter.
ALTER TABLE orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE orders FORCE ROW LEVEL SECURITY; -- applies to the table owner too
CREATE POLICY tenant_isolation ON orders
USING (tenant_id = current_setting('app.tenant_id')::bigint)
WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);
-- per transaction, from the verified session: SELECT set_config('app.tenant_id', '42', true);
-- the application role must not be a superuser or have BYPASSRLSReal scenario: a report endpoint uses DB::select raw SQL and forgets the tenant filter; a queue job runs with no tenant context and processes all tenants' rows; a Redis key order:1001 returns tenant A's order to tenant B.
Fix: Go tenant package (store refuses calls without a tenant; foreign row equals not found); Laravel TenantScope (fails closed). Pick the model (shared schema, schema per tenant, database per tenant) with Multi-Tenancy Strategies.
// Package tenant makes cross-tenant access impossible by construction: the store cannot be
// called without a tenant in the context, and a foreign row looks exactly like a missing one.
package tenant
import (
"context"
"errors"
"sync"
)
type ctxKey struct{}
// ErrNoTenant means the request path forgot to establish a tenant; the store fails closed.
var ErrNoTenant = errors.New("tenant: missing tenant in context")
// ErrNotFound is returned for absent rows and for rows of another tenant alike (no existence leak).
var ErrNotFound = errors.New("tenant: not found")
// With stores the tenant id taken from the verified session, never from a header the client controls.
func With(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, ctxKey{}, id)
}
// From extracts the tenant or fails.
func From(ctx context.Context) (string, error) {
id, ok := ctx.Value(ctxKey{}).(string)
if !ok || id == "" {
return "", ErrNoTenant
}
return id, nil
}
// Order is a tenant-owned row.
type Order struct {
ID string
TenantID string
Total int64
}
// Store is an in-memory stand-in for a table with a tenant_id column.
type Store struct {
mu sync.RWMutex
rows map[string]Order
}
// NewStore returns an empty store.
func NewStore() *Store { return &Store{rows: map[string]Order{}} }
// Put inserts a row for the tenant in ctx; the caller cannot choose another tenant.
func (s *Store) Put(ctx context.Context, o Order) error {
t, err := From(ctx)
if err != nil {
return err
}
o.TenantID = t
s.mu.Lock()
s.rows[o.ID] = o
s.mu.Unlock()
return nil
}
// Get always filters by tenant. The SQL equivalent is:
// SELECT ... FROM orders WHERE id = $1 AND tenant_id = $2
func (s *Store) Get(ctx context.Context, id string) (Order, error) {
t, err := From(ctx)
if err != nil {
return Order{}, err
}
s.mu.RLock()
defer s.mu.RUnlock()
o, ok := s.rows[id]
if !ok || o.TenantID != t {
return Order{}, ErrNotFound
}
return o, nil
}<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
// A scope that fails closed: with no authenticated user it matches nothing.
final class TenantScope implements Scope
{
public function apply(Builder $builder, Model $model): void
{
$tenantId = auth()->user()?->tenant_id;
if ($tenantId === null) {
$builder->whereRaw('1 = 0');
return;
}
$builder->where($model->qualifyColumn('tenant_id'), $tenantId);
}
}Supply chain security Important
In plain words: most of your running code is other people's. A bad or hijacked dependency is your breach.
Common misunderstanding: "We only use popular packages." Popularity is also the target. And "no known CVE" is not "safe"; known-vulnerable is a minimum bar, not a goal.
Definition: OWASP made it its own category in 2025 (A03 Software Supply Chain Failures). The practices: pin versions with a lockfile (go.sum, composer.lock), scan for known vulnerabilities (SCA), generate an SBOM (CycloneDX or SPDX) so you can answer "are we affected by CVE-X?" in minutes, verify provenance and signatures, review new dependencies and their maintainers, and minimise the number of dependencies. NIST SSDF (SP 800-218) frames these as practices a software producer builds into every SDLC model.
| Tool | Ecosystem | What it does | Command |
|---|---|---|---|
govulncheck | Go | Reports only vulnerabilities your code can actually reach: "analyzes your codebase and only surfaces vulnerabilities that actually affect you, based on which functions in your code are transitively calling vulnerable functions" | go install golang.org/x/vuln/cmd/govulncheck@latest then govulncheck ./... |
composer audit | PHP | Checks installed packages against security advisories | composer audit (run in CI, fail on findings) |
go mod verify, go.sum | Go | Verifies module hashes against the checksum database | go mod verify |
composer.lock | PHP | Pins exact versions; commit it for applications | composer install (not update) in CI |
| Dependabot / Renovate | Both | Opens update pull requests | Config in repo |
SBOM generators (Syft, cyclonedx-gomod, cyclonedx-php-composer) | Both | Produce CycloneDX or SPDX | Run at build, store with the release |
| Signed builds and provenance (Sigstore cosign, SLSA) | Both | Prove an artifact came from your pipeline | Sign in CI, verify at deploy |
Real scenario: a transitive package changes owner and ships a post-install script that reads environment variables; a build pulls latest of an image on Monday and a different one on Tuesday.
Fix: commit lockfiles, run govulncheck ./... and composer audit on every pull request and nightly, generate an SBOM per release, restrict CI secrets, disable install scripts where you can, and review diffs of dependency bumps. See Secrets for CI credential blast radius.
Privacy by design Important
In plain words: collect less, keep it shorter, show it to fewer people, and make that the default.
Common misunderstanding: "Privacy is a legal page." GDPR Article 25 makes it an engineering duty: the controller "shall implement appropriate technical and organisational measures, such as pseudonymisation, which are designed to implement data-protection principles, such as data minimisation" and, "by default, only personal data which are necessary for each specific purpose of the processing are processed", covering "the amount of personal data collected, the extent of their processing, the period of their storage and their accessibility".
Definition: privacy by design means data minimisation (do not collect what you do not need), purpose limitation, retention limits, pseudonymisation, access limited by default, and the ability to export and delete a person's data. LINDDUN is the threat-modeling companion to STRIDE for privacy harms (Linking, Identifying, Non-repudiation, Detecting, Data disclosure, Unawareness, Non-compliance).
Design question Design answer in the checkout
1 Do we need the full card number? No: the payment provider holds it; we store a token and last4
2 How long do we keep order addresses? Anonymise N months after delivery (scheduled job)
3 Who can see the phone number? Policy: owner and the courier on that delivery only
4 Can the user delete their account? Yes: deletion cascades through services via events (see data ownership)Real scenario: logs that include full email addresses and addresses for a year; an analytics export with raw PII; a support tool where every agent sees every customer.
Fix: minimise at the schema, mask in logs, retention jobs, field-level encryption for the most sensitive columns (Encryption), and per-service data ownership (Microservices Data Ownership). This page gives pointers only: legal analysis (lawful basis, DPIA, data subject rights) belongs to your counsel and the regulation's own text.
OWASP Top 10 mapped to design decisions
The Top 10 is easy to read as a list of bugs. Read it as a list of design questions. The ranks below are from the 2025 edition; the OWASP A01 page records that "100% of the applications tested were found to have some form of broken access control" and that it "has the highest number of occurrences in the contributed data".
| Category (2025) | Design decision that prevents it | Where in this page | Typical Go control | Typical Laravel control |
|---|---|---|---|---|
| A01 Broken Access Control | Deny by default; one policy object; scope queries by owner and tenant; enforce server-side | Authz, Tenancy | authz.Require per handler | Policies, Gate::authorize, global scope |
| A02 Security Misconfiguration | Secure defaults; same hardened config in every environment; no debug in production | Secure defaults | Explicit http.Server timeouts and headers | APP_DEBUG=false, SecurityHeaders, strict models |
| A03 Software Supply Chain Failures | Lockfiles, SCA, SBOM, provenance, few dependencies | Supply chain | govulncheck, go mod verify | composer audit, composer.lock |
| A04 Cryptographic Failures | Standard algorithms, managed keys, TLS everywhere, no home-grown crypto | Open design, Encryption | crypto/rand, crypto/tls, AEAD | Crypt, Hash, APP_KEY rotation |
| A05 Injection | Data never becomes code: parameterize, encode output, allow-list | Input | $1 placeholders, html/template | Bindings, Blade escaping |
| A06 Insecure Design | Threat model, secure design patterns, abuse cases, paved roads | Threat modeling | Shared authz, validate, ratelimit packages | Shared policies, Form Requests, base classes |
| A07 Authentication Failures | Strong hashing, MFA, session rotation, rate limiting, no weak recovery | Sessions, Rate limiting | session package, bcrypt or argon2 | Starter kits, Hash, throttle |
| A08 Software or Data Integrity Failures | Verify signatures of webhooks, updates and artifacts; no unsafe deserialisation | Checkout model | hmac.Equal on webhook bodies | Signed URLs, verified webhook middleware |
| A09 Security Logging and Alerting Failures | Audit events on decisions; alert on denies; redact secrets | Audit | slog with ReplaceAttr | Gate::after, an audit log channel |
| A10 Mishandling of Exceptional Conditions | Fail closed; generic errors outward, detail inward; handle every error path | Fail-safe defaults | Recover middleware, checked errors | Exception handler, abort_unless |
Reading A06 and A04 together. A06 says insecure design is "missing or ineffective control design" and "is not the source for all other Top Ten risk categories". The point is not that design causes everything; it is that a missing control (no rate limit, no policy, no tenant column) cannot be fixed by writing the existing code better.
Per-framework and per-product view
Never assume a framework default; look it up for your version. The first two rows were read from the Laravel 13 and Go documentation for this page; the rest are general knowledge and worth verifying against each product's current docs.
| Concern | Laravel 13 (PHP 8.4) | Go net/http | Spring Security (Java) | Django (Python) | Express (Node.js) | ASP.NET Core |
|---|---|---|---|---|---|---|
| CSRF | On in the web group: Sec-Fetch-Site check, then session token | Nothing built in; add middleware | On by default for browser sessions | CsrfViewMiddleware in the default stack | Not built in; csurf-style packages | Antiforgery services for forms |
| Mass assignment | Guarded by default; #[Fillable] or #[Guarded] required for create | No ORM; your struct decides | Binder allow-lists are your job | ModelForm fields list | No ORM; your code decides | [Bind] / view models |
| Output encoding | Blade escapes by default | html/template escapes by context; text/template does not | Template engine dependent | Templates auto-escape | Depends on the view engine | Razor encodes by default |
| Password hashing | Hash: bcrypt (default) or Argon2 | x/crypto/bcrypt, x/crypto/argon2 | PasswordEncoder | PBKDF2 default, Argon2 optional | bcrypt, argon2 packages | PasswordHasher |
| Authorization | Gates and Policies | Write your own (like our authz) | Method and URL security | Permissions, decorators | Write your own or CASL | Policies and requirements |
| Rate limiting | RateLimiter, throttle middleware | golang.org/x/time/rate or custom | Not built in | Third-party | express-rate-limit | Built-in rate limiter middleware |
| Security headers | Add middleware | Add middleware | Default headers on | SecurityMiddleware | helmet | Add middleware |
| Dependency audit | composer audit | govulncheck | OWASP Dependency-Check, Dependabot | pip-audit | npm audit | dotnet list package --vulnerable |
The pattern: Laravel gives many guards for free and still leaves authorization of your own objects to you; Go gives sharp standard-library building blocks (crypto/rand, crypto/subtle, html/template, database/sql) and expects you to assemble the guards. In both, the object-level authorization (the IDOR question) is always your design.
Mechanics
Worked threat model: the checkout
What we are working on. A customer adds items, pays and receives an order. The diagram in Why it exists shows the parts: browser, Laravel web/API, a Go pricing and order service, Redis, PostgreSQL, a payment provider. Flows: (1) browser to Laravel, (2) Laravel to the Go service, (3) Laravel to Redis (session, limits), (4) Go to the database, (5) Go to the payment provider, (6) the provider's webhook back to Laravel. Assets: money, order integrity, customer PII, sessions, secrets.
What can go wrong, per element. A STRIDE pass over every flow and store; each row ends in a decision and a test.
| # | Where | STRIDE | Threat | Design control | Test or evidence |
|---|---|---|---|---|---|
| 1 | Flow 1 | S | Credential stuffing on /login | Rate limit per account plus IP; MFA; breached-password check | Feature test: 6th attempt returns 429 |
| 2 | Flow 1 | S | Session theft or fixation | __Host- cookie, HttpOnly, Secure, regenerate on login | Cookie-flag test |
| 3 | Flow 1 | T | Client sets price or status | Server-side pricing; prohibited fields; typed decode | POST with total_cents returns 422 |
| 4 | Flow 1 | T | CSRF on "change address" | PreventRequestForgery; SameSite=Lax | Cross-site POST rejected |
| 5 | Flow 1 | I | IDOR on /orders/{id} | Policy plus tenant scope; 404 for foreign | Mallory reads Alice's order: 404 |
| 6 | Flow 1 | I | Verbose errors reveal SQL or stack | APP_DEBUG=false; Recover returns a generic 500 | Error-path test |
| 7 | Flow 1 | D | Checkout flood; bot buys all stock | Per-user and per-IP limits; hold stock with TTL; bot checks | Load test, limiter test |
| 8 | Flow 1 | E | Customer calls an admin route | Deny by default; role check; route-list test | Test: every route has an auth rule |
| 9 | Flow 2 | S | Another internal service pretends to be Laravel | mTLS or signed service token; allow-list of callers | Call without a cert is refused |
| 10 | Flow 2 | T | Laravel forwards a tampered total | The Go service recomputes the price itself | Contract test |
| 11 | Flow 3 | I | Cache key shared across tenants | Tenant id in every key; TTLs | Two-tenant cache test |
| 12 | Flow 4 | T | SQL injection | Placeholders; role without DDL rights | Injection payload test |
| 13 | Flow 4 | I | A bug reads another tenant's rows | RLS; per-transaction tenant setting | psql test as app role |
| 14 | Flow 5 | R | "I never paid" or "you never charged" | Idempotency key; store PSP reference; audit event | Reconciliation job |
| 15 | Flow 6 | S | Fake "payment succeeded" webhook | Verify the provider's HMAC signature; check timestamp | Webhook with a bad signature returns 401 |
| 16 | Flow 6 | T | Replayed webhook marks order paid twice | Idempotency on event id; state machine | Replay test: second call is a no-op |
| 17 | Store | I | Database dump leaks PII | Encrypt sensitive columns; mask outside production; least-privilege backups | Backup access review |
| 18 | Whole | R | No trace of who refunded what | Audit log with actor, action, object, outcome | Log assertion in tests |
What we do about it. Ranked by likelihood times impact: 3, 5, 15 and 16 are high (direct money or data loss); 1, 7 and 13 are medium; 6 and 17 are lower given the other controls. The first sprint closes the highs; the lab below closes 1, 3 and 5.
Did we do a good enough job? Every row has a test. A row with no test is a wish. Re-run the model when a flow, a role or a boundary changes; keep it in the repository as a DFD plus this table.
Separation of privilege and abuse cases in this model. Refunds need a second control: the finance role and an order in state paid (rows 8 and 14). Abuse case: a user places an order, cancels it after the courier is dispatched, and requests a refund (an out-of-order workflow). The fix is a state machine: cancel is allowed only from pending.
ASVS, SSDF and the SDL as the process around it
| Framework | What it is | Use it for |
|---|---|---|
| OWASP ASVS 5.0.0 | A numbered checklist of verifiable requirements (identifiers like v5.0.0-1.2.5) | Requirements for a story; a test checklist; a pentest scope |
| OWASP SAMM | A maturity model for an AppSec programme | Planning what to improve next |
| NIST SSDF (SP 800-218) | High-level practices for producers and a common vocabulary for buyers | Procurement and compliance conversations |
| Microsoft SDL | A lifecycle with threat modeling, tooling and response | Organising security activities per phase |
| Threat Modeling Manifesto | Values and the four questions | Culture and facilitation |
Security testing
Tests are how a threat-model row becomes true. Layer them; no tool finds design flaws on its own.
| Technique | What it checks | Finds | Misses | When |
|---|---|---|---|---|
| Unit and feature tests of abuse cases | Policies, validation, limits | Regressions of known threats | Unknown threats | Every commit |
SAST (static analysis: gosec, staticcheck, go vet, Larastan, Psalm taint analysis, Semgrep, CodeQL) | Source patterns | Injection sinks, hard-coded secrets, weak crypto | Business-logic flaws, missing checks | Every pull request |
SCA (govulncheck, composer audit) | Dependencies | Known CVEs | Unknown vulnerabilities; your own code | Every pull request, nightly |
| DAST (OWASP ZAP, Burp Suite) | A running app from outside | Misconfiguration, reflected XSS, missing headers | Authorization logic without credentials | Staging, nightly |
| IAST | Instrumented runtime | Tainted flows during tests | Untested paths | CI with integration tests |
Fuzzing (go test -fuzz) | Parsers with random input | Panics, crashes, parser confusion | Logic flaws | Parsers and decoders |
| Threat-model review | The design | Missing controls, wrong boundaries | Implementation bugs | Design, and on each flow change |
| Code review with a security checklist | Diffs | Missing authz call, new endpoint | Subtle bugs at scale | Every pull request |
| Penetration test | A human attacker with a time box | Chained and logical flaws | Everything outside scope or time | Yearly and before major releases |
| Bug bounty | Many external researchers | Real-world surprises | Needs triage capacity | After basics are in place |
Test pyramid for authorization
1 Unit policy table: 9 cases (subject x action x resource) ms, hundreds
2 Feature every route as anonymous, user, other tenant s, one per route
3 Contract gateway to service: missing or forged identity is refused s
4 E2E a pentest or ZAP run with two real accounts min-daysA useful trick is a route-coverage test: list every route and assert that each one is either on an explicit public allow-list or rejects an anonymous request. This enforces fail-safe defaults mechanically.
Go
Before
The "before" handler decodes straight into the stored type, never asks whose order it is, has no limits, no timeouts, and builds SQL by concatenation. It is not broken code; it is a design with four holes.
// Package main is the "before": a checkout handler with the classic design holes.
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"sync"
)
// Order trusts every field the client sends, including the ones it must never set.
type Order struct {
ID string `json:"id"`
OwnerID string `json:"owner_id"`
Status string `json:"status"`
TotalCents int64 `json:"total_cents"`
Coupon string `json:"coupon"`
}
var (
mu sync.Mutex
orders = map[string]Order{}
)
func main() {
mux := http.NewServeMux()
// Hole 1: authentication may exist, but nothing checks that the order belongs to the caller (IDOR).
mux.HandleFunc("GET /orders/{id}", func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
o, ok := orders[r.PathValue("id")]
mu.Unlock()
if !ok {
http.NotFound(w, r)
return
}
_ = json.NewEncoder(w).Encode(o)
})
// Hole 2: the whole JSON body is decoded into the domain type (mass assignment),
// so a client can send "status":"paid" and "total_cents":1. No size limit, no rate limit.
mux.HandleFunc("POST /orders", func(w http.ResponseWriter, r *http.Request) {
var o Order
if err := json.NewDecoder(r.Body).Decode(&o); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mu.Lock()
orders[o.ID] = o
mu.Unlock()
w.WriteHeader(http.StatusCreated)
})
// Hole 3: no timeouts on the server (slowloris), default mux, no security headers.
_ = http.ListenAndServe(":8080", mux)
}
// findByEmail shows hole 4: SQL built by string concatenation (injection).
func findByEmail(db *sql.DB, email string) (*sql.Rows, error) {
return db.Query(fmt.Sprintf("SELECT id FROM users WHERE email = '%s'", email))
}After
The "after" splits the concerns. validate is the single trust-boundary parser; authz is the one policy; tenant makes isolation structural; ratelimit and idempotency protect expensive operations; session and jwtcheck carry identity; audit records decisions; server hardens the transport. Each package is small enough to review (economy of mechanism) and has a table test.
// Package ratelimit is a per-key token bucket with an injectable clock.
package ratelimit
import (
"net"
"net/http"
"strconv"
"sync"
"time"
)
type bucket struct {
tokens float64
last time.Time
}
// Limiter allows Burst requests at once and refills Rate tokens per second per key.
type Limiter struct {
Rate float64
Burst float64
Now func() time.Time
mu sync.Mutex
buckets map[string]*bucket
}
// New returns a limiter using the real clock.
func New(rate, burst float64) *Limiter {
return &Limiter{Rate: rate, Burst: burst, Now: time.Now, buckets: map[string]*bucket{}}
}
// Allow spends one token for key. When it refuses, wait says when to retry.
func (l *Limiter) Allow(key string) (ok bool, wait time.Duration) {
l.mu.Lock()
defer l.mu.Unlock()
now := l.Now()
b, found := l.buckets[key]
if !found {
b = &bucket{tokens: l.Burst, last: now}
l.buckets[key] = b
}
b.tokens = min(l.Burst, b.tokens+now.Sub(b.last).Seconds()*l.Rate)
b.last = now
if b.tokens >= 1 {
b.tokens--
return true, 0
}
return false, time.Duration((1 - b.tokens) / l.Rate * float64(time.Second))
}
// Middleware limits by the key function (client IP, user id, API key). It fails closed with 429.
func (l *Limiter) Middleware(key func(*http.Request) string, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ok, wait := l.Allow(key(r)); !ok {
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
http.Error(w, "too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}
// ClientIP keys by the remote address. Behind a proxy, take the address the proxy
// appends, never the first X-Forwarded-For value a client can forge.
func ClientIP(r *http.Request) string {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}// Package main shows a hardened net/http server: timeouts, size limits, security headers, safe errors.
package main
import (
"log"
"net/http"
"time"
)
// Headers sets baseline response headers. Tune the CSP to your front end.
func Headers(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
h.Set("Content-Security-Policy", "default-src 'self'; frame-ancestors 'none'")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Cache-Control", "no-store")
next.ServeHTTP(w, r)
})
}
// Recover turns a panic into a generic 500; the details go to the log, never to the client.
func Recover(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rec := recover(); rec != nil {
log.Printf("panic: %v", rec)
http.Error(w, "internal error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func newServer(h http.Handler) *http.Server {
return &http.Server{
Addr: ":8443",
Handler: Recover(Headers(h)),
ReadHeaderTimeout: 5 * time.Second, // slowloris defence
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
MaxHeaderBytes: 16 << 10,
}
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("ok")) })
srv := newServer(mux)
log.Fatal(srv.ListenAndServeTLS("cert.pem", "key.pem"))
}The Go angle
- The standard library has the sharp tools, not the guards.
crypto/randfor tokens,crypto/subtle.ConstantTimeComparefor secrets (its doc: "The time taken is a function of the length of the slices and is independent of the contents"),hmac.Equal,html/template,database/sqlplaceholders. Nothing is on by default excepthtml/templateescaping and prepared-statement placeholders when you use them. http.Servertimeouts are a security setting. The docs sayReadTimeout"does not let Handlers make per-request decisions", so most users should preferReadHeaderTimeout; without any, a slow client holds a connection forever (slowloris).context.Contextcarries identity and tenant through the call chain so a lower layer cannot be called without one; ourtenant.Storefails closed withErrNoTenant.internal/packages hide mechanisms (information hiding) so only your own module can call the privileged function.- Run
govulncheck ./...in CI. It reads call graphs, so it is quiet when you only import the vulnerable package but never call the vulnerable function. - Do not roll your own crypto. Use
crypto/aeswith GCM (cipher.NewGCM),golang.org/x/crypto/argon2orbcrypt, andcrypto/tls.
Laravel
Before
<?php
// app/Http/Controllers/OrderController.php: the "before". Every line below has shipped to production somewhere.
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
class OrderController extends Controller
{
// Hole 1 (IDOR): any logged-in user can read any order by changing the number in the URL.
public function show(int $id)
{
return Order::findOrFail($id);
}
// Hole 2 (mass assignment): the model has $guarded = [], so "status" and "total_cents"
// from the request body are written straight to the database.
public function store(Request $request)
{
return Order::create($request->all() + ['user_id' => $request->user()->id]);
}
}
// routes/api.php: Hole 3: the login route has no throttle, so a PIN or password can be brute-forced.
// Route::post('/login', [AuthController::class, 'login']);
// app/Models/Order.php: protected $guarded = [];After
The model fills only what a user may influence; the policy answers every question about an order; the Form Request is the trust-boundary validator; pricing and status come from the server; the global scope fails closed.
<?php
namespace App\Http\Controllers;
use App\Http\Requests\CheckoutRequest;
use App\Models\Order;
use App\Services\Pricing;
use Illuminate\Support\Facades\Gate;
final class OrderController extends Controller
{
public function __construct(private readonly Pricing $pricing)
{
}
public function show(Order $order)
{
// Complete mediation: every read goes through the policy. Route model binding already
// applied the tenant scope, so a foreign tenant's order is a 404 before we get here.
Gate::authorize('view', $order);
return $order->only(['id', 'status', 'total_cents']); // explicit output allow-list
}
public function store(CheckoutRequest $request)
{
$items = $request->validated('items');
$order = new Order($request->safe()->only(['coupon_code']));
$order->user_id = $request->user()->id; // set by the server
$order->status = 'pending'; // set by the server
$order->total_cents = $this->pricing->total($items); // price comes from our catalogue
$order->save();
return response($order->only(['id', 'status', 'total_cents']), 201);
}
}<?php
// bootstrap/app.php (excerpt) and a small middleware: secure defaults you set once.
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
final class SecurityHeaders
{
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('Referrer-Policy', 'no-referrer');
$response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
$response->headers->set('Content-Security-Policy', "default-src 'self'; frame-ancestors 'none'");
return $response;
}
}
// bootstrap/app.php
// ->withMiddleware(function (Middleware $middleware) {
// $middleware->append(\App\Http\Middleware\SecurityHeaders::class);
// $middleware->trustProxies(at: ['10.0.0.0/8']); // only your load balancer, never '*'
// })
//
// app/Providers/AppServiceProvider.php, boot():
// Model::shouldBeStrict(! app()->isProduction()); // lazy loading and silent discards throw in dev
// Model::preventSilentlyDiscardingAttributes(); // an unfillable attribute is an error, not a no-op
//
// .env (production): APP_DEBUG=false SESSION_SECURE_COOKIE=true SESSION_SAME_SITE=lax<?php
// app/Providers/AuditServiceProvider.php (boot): log every denied authorization, with who/what/which.
namespace App\Providers;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
final class AuditServiceProvider extends ServiceProvider
{
public function boot(): void
{
Gate::after(function ($user, string $ability, ?bool $result, mixed $arguments) {
$subject = $arguments[0] ?? null;
Log::channel('audit')->log($result ? 'info' : 'warning', 'authz', [
'actor' => $user?->getAuthIdentifier(),
'ability' => $ability,
'object' => is_object($subject) ? $subject::class.'#'.($subject->getKey() ?? '') : null,
'outcome' => $result ? 'allow' : 'deny',
'request_id' => request()->header('X-Request-Id'),
]);
return null; // observe only: never change the decision
});
}
}The Laravel angle
- Authorization: register policies (the
UsePolicyattribute or auto-discovery); callGate::authorize('view', $order)or put->can('view', 'order')on the route. Policy responses can beResponse::denyAsNotFound()orResponse::denyWithStatus(404).Gate::beforeis powerful (a super-admin shortcut) and dangerous: it runs for every check, so keep it tiny and audited.Gate::afteris where we log. - Validation: Form Requests run before the controller; use
validated()orsafe()->only()and never$request->all()into a model. - Mass assignment: Eloquent refuses
createuntil the model declares#[Fillable]or#[Guarded];Model::preventSilentlyDiscardingAttributes()turns a silent drop into an exception during development;Model::shouldBeStrict()also forbids lazy loading. - CSRF and sessions: the
PreventRequestForgerymiddleware,session()->regenerate()after login,invalidate()at logout, encrypted cookies,SESSION_SECURE_COOKIE,same_site. - Hashing and encryption:
Hash::make(bcrypt,rounds12 by default; Argon2 available),Hash::needsRehash;Crypt::encryptStringuses AES with a MAC, key fromAPP_KEY(rotate with previous keys, see the docs). - Signed URLs:
URL::signedRoute('unsubscribe', ['user' => 1])and thesignedmiddleware protect a public link from tampering; usetemporarySignedRoutefor expiry. They prove the URL was issued by you, not that the visitor is allowed to act: add authorisation when the action is sensitive. - Rate limiting:
RateLimiter::forwith severalLimits per limiter; thethrottle:namemiddleware returns 429 withRetry-After. - Tokens: Sanctum for first-party SPA (cookie session) and simple API tokens with abilities; Passport when you need to be an OAuth2 server.
- Operational:
APP_DEBUG=false,php artisan key:generate,composer audit,trustProxieslimited to your load balancers.
Solving the classic problems
| Problem | Solution | How | Cost or limit |
|---|---|---|---|
| IDOR | Policy object plus owner/tenant scope | Check decide(subject, action, resource) in every action; scope the query; 404 on foreign | One call per handler; needs discipline and a route-coverage test |
| Mass assignment | Separate request type; allow-list; server-owned fields | #[Fillable], prohibited rules, DisallowUnknownFields | A second type to maintain |
| Missing rate limit | Per-key token bucket, 429 plus Retry-After | RateLimiter::for, ratelimit.Middleware; shared store when scaled out | Shared state; false positives behind NAT |
| SQL injection | Placeholders; least-privilege DB role | db.QueryContext(ctx, q, args...), query builder | Dynamic identifiers (order by) need an allow-list |
| XSS | Contextual output encoding plus CSP | html/template, Blade escaping, Content-Security-Policy | CSP tuning effort |
| CSRF | Origin check plus token; SameSite cookie | PreventRequestForgery; Go middleware on Sec-Fetch-Site | Cross-site embeds need exceptions |
| Broken JWT | Pin algorithm; validate claims; short life | jwtcheck.Verify or a maintained library | Revocation needs state |
| Replayed webhook | Signature plus timestamp plus idempotency on event id | hmac.Equal; store processed ids | A table of seen events |
| Secrets in git | Manager, runtime mount, scanning, rotation | Vault or cloud secret manager; pre-commit and CI scan | Operational setup |
| Cross-tenant leak | Required tenant context plus RLS | tenant.Store, TenantScope, CREATE POLICY | Pool and role design with RLS |
| Over-powerful app role | Separate roles: migration, runtime, read-only | GRANT only needed privileges | More roles to manage |
| SSRF (server-side request forgery) | Allow-list outbound hosts; block link-local and internal ranges; no redirects to internal | Resolve and validate before connecting; egress policy | Breaks legitimate webhooks to arbitrary URLs |
| Vulnerable dependency | SCA in CI; update policy; SBOM | govulncheck, composer audit, Dependabot | Update churn |
| Verbose errors | Generic message outward, detail in logs | Recover middleware, exception handler | Needs correlation ids to debug |
Webhook verification deserves its own sketch, since it is the most common service-to-service trust boundary: compute HMAC-SHA256(secret, timestamp + "." + body), compare with hmac.Equal (constant time), reject if the timestamp is more than five minutes old, then process under an idempotency key equal to the provider's event id.
Choosing: which control for which situation
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Browser app, one backend | Server-side session, HttpOnly __Host- cookie, CSRF protection | Rotate id at login; idle timeout | Simplest, revocable |
| SPA plus first-party API on the same site | Sanctum cookie session | SameSite=Lax, CSRF token | Avoids tokens in JavaScript |
| Mobile app or third-party API consumers | OAuth 2.1 code flow with PKCE, short access tokens, rotating refresh tokens | Sender-constrained tokens where available | Standard, revocable at the server |
| Service to service inside one trust zone | mTLS or signed service tokens with audience | Network policy | Identity per service, not per network |
| Few coarse roles | RBAC | Policy for ownership | Simple |
| Rules depend on the object | ABAC in a policy object | Table tests | Expressive |
| Sharing, orgs, teams | ReBAC (relation store or Zanzibar-style service) | Cache with short TTL | Graph of relations |
| Many tenants, shared schema | Required tenant context plus RLS | Per-tenant cache keys | Defence in depth |
| Few large tenants with strict needs | Schema or database per tenant | Per-tenant keys | Strong isolation, higher cost |
| Money movement | Idempotency key, state machine, separation of privilege, audit | Reconciliation | One error costs more than a check |
| Public endpoint | Rate limit, size limit, validation, no secrets in URLs | WAF as extra layer | Anyone can call it |
| Handling PII | Minimise, mask, encrypt columns, retention | Pseudonymise | GDPR Article 25 |
In architecture: from a single process to a distributed system
Monolith: one process, one database
All controls sit in one codebase: middleware for authentication and headers, policies for authorisation, a Form Request per input, a global tenant scope, one audit log channel. The trust boundaries are few: the internet and the database.
Everyday example: a Laravel shop with auth middleware, OrderPolicy, a CheckoutRequest, and throttle:checkout. The threat model is one DFD. Production example: the same app behind a load balancer: trustProxies limited to the balancer's range, APP_DEBUG=false, sessions in the database with encrypt on, composer audit in CI. Complete mediation is easy to see because there is one call path; economy of mechanism says keep it that way.
Modular monolith and multiple databases
Modules (orders, billing, catalogue) call each other in process. Treat module borders as trust boundaries by design even though no network separates them: a module exposes a facade, authorises requests it receives from other modules by caller identity (a Subject passed explicitly), and owns its tables (a separate database role per module so the billing module cannot SELECT from orders). Single Responsibility and Dependency Inversion keep the modules from reaching into each other; that is also what keeps a compromised module from reading everything.
Everyday example: the billing module needs an order total; it calls Orders::totalFor($subject, $orderId), which checks the policy, instead of reading the orders table. Production example: separate PostgreSQL schemas per module with GRANT USAGE only on its own schema, and RLS on the shared tenant_id column.
Microservices: perimeter versus per-service authorization
Once services talk over a network, every hop is a trust boundary and a perimeter is not enough.
| Design | Where authn happens | Where authz happens | Failure mode |
|---|---|---|---|
| Perimeter only | Gateway | Nowhere after it | One bypass or one compromised service exposes everything ("hard shell, soft centre") |
| Gateway authn plus per-service authz | Gateway validates the user token; passes identity on | Each service decides on the user's identity and the object | Needs a consistent identity and policy format |
| Zero trust | Every call is authenticated (user and service) | Every service decides; policy as code | More moving parts, mTLS and certificate rotation |
Service identity. A service proves who it is with an mTLS certificate (SPIFFE IDs are a common naming scheme) or a signed service token; the callee keeps an allow-list of callers. Propagating the user. Pass the end user's identity (a short-lived token or signed claims), not just the calling service's: otherwise the downstream service cannot enforce "Alice may read this order" and falls back to trusting the caller blindly (the confused deputy problem). Gateway auth. A gateway or BFF (API Gateway, BFF & Service Mesh) is the right place for coarse authentication, token validation, rate limiting and request size limits, but never the only place for object-level decisions. mTLS pointer. Mutual TLS gives each side a verified identity and an encrypted channel; a service mesh can supply it without code changes. Messaging: consumers must authenticate the broker and verify the producer (see Messaging Security).
Checkout across services
1 Browser -> Gateway validate user JWT (alg pinned, aud=orders-api), rate limit by user
2 Gateway -> Orders service mTLS (service identity "gateway") + signed claims: sub=alice, tenant=acme
3 Orders -> Pricing service mTLS (identity "orders") + claims forwarded; pricing recomputes the price
4 Orders -> DB role orders_app, RLS tenant setting from claims
5 Any hop fails verification fail closed: 401/403, audit event with request idEveryday example: two services, orders and invoices; invoices trusts any caller on the private network. A compromised unrelated pod calls it and reads every invoice. Fix: mTLS identity plus policy. Production example: a mesh issues certificates per workload and enforces an authorisation policy such as "only the orders identity may call POST /invoices"; each service still checks object ownership.
Distributed data: replicas, caches and token lag
- Caches and replicas widen the attack surface. A cache key without the tenant id returns another tenant's data; a read replica copies PII to a place with weaker access controls; a CDN may cache a personalised response (
Cache-Control: no-storeon authenticated responses). - Stale authorization. Saltzer and Schroeder warn that remembered authority checks "must be systematically updated" when authority changes. A cached permission or a JWT with a role lives until it expires: choose short lifetimes or a revocation signal, and accept the lag as a documented risk.
- Clocks.
expandnbfand webhook timestamps depend on synchronised clocks; allow small leeway and sync with NTP. - Multi-region. Keys and secrets replicate carefully; data residency is a privacy requirement; audit logs must survive a region loss.
- Events carry identity too. An event published by a service should say who caused it (the end user) so downstream consumers can authorise and audit.
Scaling path: 1x, 10x, 100x
| Load | What changes in security | Concrete step |
|---|---|---|
| 1x: one app, one database | Basics: policies, validation, hashing, headers, backups | The lab's fixes plus composer audit |
| 10x: several instances, Redis | Shared state for rate limits, sessions, idempotency; secrets management | Redis counters, secret manager, per-environment credentials |
| 100x: many services and teams | Service identity, policy as code, paved roads, central audit pipeline, tenant isolation tested continuously | mTLS, shared auth library or sidecar, SIEM alerts, threat-model per service, bug bounty |
| Org growth | Security becomes platform work | Secure design pattern library; "paved road" templates (A06 recommends this) |
Lab: threat-model a Laravel + Go system, then fix three holes
Goal. Threat-model the checkout, then close an IDOR, a mass-assignment hole and a missing rate limit, with a test for each. Everything runs offline with the Go standard library; the Laravel steps are reviewed code (PHP is not run in this repository).
Setup.
cd docs/snippets/design/security-by-design/go
go version # go 1.24 or newer
go test ./... # all green: the baseline, including the exploit testsExperiment 1: threat-model (30 minutes, paper). Draw the DFD (the diagram in Why it exists is a starting point), mark the trust boundaries, and fill this table for flows 1, 2 and 6 before reading the worked model:
| Flow | S | T | R | I | D | E |
|---|---|---|---|---|---|---|
| 1 Browser to Laravel | ||||||
| 2 Laravel to Go service | ||||||
| 6 Webhook to Laravel |
Compare with the checkout model. Expected: you found at least the price-tampering, IDOR and replayed-webhook rows.
Experiment 2: see the exploits work.
go test ./lab/vulnerable -run Exploits -v
# --- PASS: TestExploits (a PASS here means the exploit succeeded: IDOR read, status=paid written, PIN brute-forced)Experiment 3: fix the IDOR. Read lab/fixed/service.go: GET /orders/{id} builds an authz.Resource and calls authz.Require before responding; a foreign order and a missing order both return 404.
go test ./lab/fixed -run IDOR -v
# --- PASS: TestIDORFixed (owner 200; foreign order is 404 with the same body as a missing one)Experiment 4: fix the mass assignment. POST /orders decodes through validate.DecodeCheckout (unknown fields rejected), the server prices the cart from its own catalogue and sets status=pending.
go test ./lab/fixed -run MassAssignment -v
# --- PASS: TestMassAssignmentFixed (status and total_cents in the body: 400; valid cart: total_cents=5000, status=pending)Experiment 5: add the rate limit. POST /login is wrapped in the token bucket (burst 5, one refill per 12 seconds).
go test ./lab/fixed -run LoginRateLimit -v
# --- PASS: TestLoginRateLimit (8th attempt: 429 and a Retry-After header)
go test ./ratelimit -v
# --- PASS: TestTokenBucket (burst of 3, refusal with a wait, per-key buckets, refill with an injected clock)Experiment 6: the Laravel side. Apply Order.php, OrderPolicy.php, CheckoutRequest.php, OrderController.php and RateLimiting.php to a fresh Laravel 13 app, then run the Pest tests:
<?php
// tests/Feature/OrderSecurityTest.php (Pest): the lab's three regression tests.
use App\Models\Order;
use App\Models\User;
use function Pest\Laravel\actingAs;
beforeEach(function () {
$this->alice = User::factory()->create(['tenant_id' => 1]);
$this->mallory = User::factory()->create(['tenant_id' => 1]);
$this->order = Order::withoutGlobalScopes()->create(['shipping_address_id' => 1]);
$this->order->forceFill(['user_id' => $this->alice->id, 'tenant_id' => 1, 'status' => 'pending', 'total_cents' => 5000])->save();
});
it('hides someone else\'s order (IDOR)', function () {
actingAs($this->mallory)->getJson("/api/orders/{$this->order->id}")->assertNotFound();
actingAs($this->alice)->getJson("/api/orders/{$this->order->id}")->assertOk()->assertJsonPath('total_cents', 5000);
});
it('refuses client-supplied status and price (mass assignment)', function () {
$body = ['items' => [['sku' => 'BOOK-1', 'qty' => 1]], 'currency' => 'EUR'];
actingAs($this->mallory)->postJson('/api/orders', $body + ['status' => 'paid', 'total_cents' => 1])
->assertUnprocessable()->assertJsonValidationErrors(['status', 'total_cents']);
actingAs($this->mallory)->postJson('/api/orders', $body)
->assertCreated()->assertJsonPath('status', 'pending');
});
it('throttles login attempts (rate limit)', function () {
foreach (range(1, 5) as $i) {
$this->postJson('/api/login', ['email' => 'alice@example.com', 'password' => 'wrong'])->assertStatus(422);
}
$this->postJson('/api/login', ['email' => 'alice@example.com', 'password' => 'wrong'])
->assertStatus(429)->assertHeader('Retry-After');
});php artisan test --filter=OrderSecurityTest
# 3 passed: 404 on a foreign order, 422 on status and total_cents, 429 with Retry-After on the 6th loginExperiment 7: the database layer. Prove RLS holds even when the application forgets the filter (PostgreSQL, using the policy shown in Multi-tenancy isolation):
-- as the application role (not owner, not superuser, no BYPASSRLS)
BEGIN;
SELECT set_config('app.tenant_id', '1', true);
SELECT count(*) FROM orders; -- only tenant 1 rows, with no WHERE clause
SELECT set_config('app.tenant_id', '2', true);
SELECT count(*) FROM orders WHERE id = 1001; -- 0 if order 1001 belongs to tenant 1
ROLLBACK;Experiment 8: supply chain and hardening.
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./... # expected: "No vulnerabilities found." for this stdlib-only module
go vet ./... && gofmt -l . # clean
# Laravel: composer auditStretch. Add an idempotency key to POST /orders using idempotency.Store; add audit.Record calls on every deny and assert the log contains the actor and object but no token; write the route-coverage test that fails when a route has no auth rule.
Common misconceptions
| Belief | Reality |
|---|---|
| "Security is a feature we add before release" | It is a property decided by structure (schema, scopes, boundaries); late fixes change the model |
| "We are behind a login, so it is protected" | Authentication is not authorization; IDOR is the number-one risk class (A01) |
| "Hiding the URL or algorithm protects us" | Open design: protection rests on keys and checks, not secrecy of the mechanism |
| "Client-side validation is enough" | The client is the attacker's tool; validate on the server at every boundary |
| "We escape input, so no XSS or SQL injection" | You parameterize queries and encode output for its context; input validation alone is not that |
| "JWT is more secure than sessions" | It is a signed bearer token that cannot be revoked early; pitfalls are alg confusion and missing claim checks (RFC 8725) |
| "Internal network means trusted" | Compromised hosts and tenants are already inside; every hop needs identity (zero trust) |
| "Encryption at rest solves breaches" | It protects stolen disks; a logged-in attacker or a buggy query still reads plaintext |
| "A WAF covers the application" | A WAF sees patterns, not your business rules or object ownership |
| "No CVE in the scan, so we are safe" | Scanners find known issues in dependencies; design flaws and logic bugs are invisible to them |
| "Rate limiting is only for DoS" | It is also the brute-force, scraping and cost-abuse control for authentication and expensive endpoints |
| "Threat modeling needs experts and weeks" | A 45-minute whiteboard on a DFD with STRIDE, repeated per feature, finds most design holes |
Cheat sheet
| Topic | What to remember |
|---|---|
| Mindset | Design in: boundaries, threats, controls, tests; not a scanner at the end |
| Four questions | What are we working on? What can go wrong? What will we do? Did we do well? |
| STRIDE | Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege |
| Saltzer | Economy, fail-safe defaults, complete mediation, open design, separation of privilege, least privilege, least common mechanism, psychological acceptability |
| Authz | Server-side, every request, deny by default, policy object, 404 for foreign, test it |
| IDOR | Owner or tenant check plus scoped query; random ids do not replace it |
| Input | Parse once at the boundary into a type; allow-list; size limit; reject unknown fields |
| Output | Encode for the context (html/template, Blade); CSP as backup |
| SQL | Placeholders always; role without DDL; RLS as the second layer |
| Mass assignment | Separate request type; #[Fillable]; server sets owner, tenant, status, price |
| Sessions | __Host- cookie, Secure, HttpOnly, SameSite=Lax, rotate at login, idle and absolute timeouts |
| JWT | Pin alg; check iss, aud, exp; short life; rotate refresh tokens and detect reuse |
| Rate limit | Per account plus IP; 429 plus Retry-After; shared store when scaled out |
| Idempotency | Key plus payload fingerprint plus caller scope; same result, one effect |
| Secrets | Manager or runtime mount; never in git or image; rotate; scan |
| Supply chain | Lockfiles, govulncheck, composer audit, SBOM, review new dependencies |
| Logging | Log decisions and denials, redact secrets, alert on spikes |
| Microservices | Gateway for coarse checks; every service authenticates callers and authorises objects; mTLS |
| Privacy | Minimise, limit retention, pseudonymise, default to least access (GDPR Art. 25) |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A route sits behind auth middleware and returns Order::findOrFail($id). What is wrong and how do you fix it? Must-know
Answer
Answer: Authentication is present but there is no authorization: any logged-in user can read any order (IDOR, A01). Add a policy (Gate::authorize('view', $order)), scope the query by owner or tenant, return 404 for foreign orders, and add a test with a second user. See Authz.
2 — State Saltzer and Schroeder's "fail-safe defaults" and give a web example of violating it. Must-know
Answer
Answer: "Base access decisions on permission rather than exclusion": the default is no access and rules say when access is allowed. A blocklist of protected paths violates it, because a new path not on the list is open. See the principles.
3 — What are the four questions of threat modeling and which STRIDE letters does "someone replays a payment webhook" touch? Important
Answer
Answer: What are we working on, what can go wrong, what will we do about it, did we do a good enough job. Replay is Spoofing (fake event) and Tampering (state change); lack of a record is Repudiation. Fix: signature, timestamp, idempotency on event id. See Threat modeling.
4 — Why does the Go validate package use DisallowUnknownFields and no price field in the request type? Important
Answer
Answer: To stop mass assignment: a client cannot set what the type does not contain, and unknown fields are rejected instead of ignored. The server computes the price from its own catalogue. See Mass assignment.
5 — Name three JWT validation mistakes from RFC 8725 thinking. Must-know
Answer
Answer: Letting the token header choose the algorithm (none or key confusion), not checking issuer and audience, and not enforcing expiry. Pin the algorithm and validate iss, aud, exp, nbf. See Sessions.
6 — Why should the login limiter key on account plus IP rather than IP alone? Important
Answer
Answer: Many users share an IP (office, mobile carrier NAT), so IP-only locks out innocents, while an attacker with many IPs bypasses it. Account plus IP stops focused guessing on one account without punishing a whole network; add a looser per-IP cap too. See Rate limiting.
7 — What does refresh-token rotation with reuse detection buy you? Important
Answer
Answer: A stolen refresh token becomes detectable: when an already-used token is presented again, the server revokes the whole token family and forces re-login. See the timeline in Sessions and session.Refresher.
8 — How do three layers protect against one forgotten where tenant_id? Must-know
Answer
Answer: A global scope or required context filters in the ORM; RLS in PostgreSQL filters again in the database; tests with two tenants catch regressions; audit alerts show the attempt. Independent layers mean one bug is not a breach. See Multi-tenancy isolation and Defense in depth.
9 — In microservices, why is a gateway-only authorization design weak? Must-know
Answer
Answer: Anything that bypasses the gateway, or any compromised internal service, reaches everything behind it ("hard shell, soft centre"). Each service must authenticate the caller (mTLS or signed token) and authorise the object using the end user's identity. See Microservices.
10 — What does govulncheck do that a plain version scanner does not? Important
Answer
Answer: It analyses which functions your code transitively calls and reports only vulnerabilities that actually affect you, reducing noise. composer audit checks installed versions against advisories. See Supply chain.
11 — Give two GDPR Article 25 design obligations as code decisions. Important
Answer
Answer: Data minimisation (do not store the card number; keep a provider token and last four digits) and by-default restriction (retention jobs, access limited to owner and the delivery courier). See Privacy by design.
Glossary
| Term | Meaning |
|---|---|
| Security by design | Treating security as a requirement and a structural property from the first design step |
| Insecure design | OWASP A06: missing or ineffective control design, different from an implementation bug |
| Trust boundary | A line where data or control passes between components of different trust |
| Attack surface | The set of entry points an attacker can reach |
| Threat model | A structured analysis of what can go wrong and what is done about it |
| DFD (data flow diagram) | Processes, data stores, external entities, flows and trust boundaries |
| STRIDE | Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege |
| LINDDUN | Privacy threat categories: Linking, Identifying, Non-repudiation, Detecting, Data disclosure, Unawareness, Non-compliance |
| Attack tree | A goal decomposed into alternative (OR) and required (AND) attack steps |
| Abuse case (misuse case) | A valid workflow used wrongly: out of order, repeated, concurrent |
| Economy of mechanism | Keep protection mechanisms small and simple |
| Fail-safe defaults | Default to no access; grant by explicit permission |
| Complete mediation | Check every access to every object |
| Open design | Security must not depend on secrecy of the design |
| Separation of privilege | Require two conditions or two parties for sensitive actions |
| Least privilege | Grant the minimum rights needed for the job |
| Least common mechanism | Minimise shared mechanisms between users |
| Psychological acceptability | Make the secure way the easy way |
| Work factor | The cost to an attacker of defeating a mechanism |
| Authentication (authn) | Establishing who the caller is |
| Authorization (authz) | Deciding what an authenticated caller may do to an object |
| RBAC | Role-based access control |
| ABAC | Attribute-based access control |
| ReBAC | Relationship-based access control (Zanzibar style) |
| ACL | Access control list attached to an object |
| IDOR | Insecure direct object reference: access by changing an identifier |
| Mass assignment | A request field overwriting a column the developer did not intend |
| Policy object | One class that answers every authorization question about a resource |
| Deny by default | No matching rule means no access |
| Defense in depth | Several independent controls so one failure is not a breach |
| Zero trust | No implicit trust from network location; authenticate and authorise every request |
| mTLS | Mutual TLS: both sides present certificates |
| Service identity | A verifiable name for a workload (certificate or signed token) |
| Confused deputy | A service misused by a caller to act with the service's own privileges |
| Idempotency key | A client id that makes a retried operation take effect once |
| Token bucket | Rate limiting with burst capacity and a steady refill |
| 429 and Retry-After | The status and header that tell a client to slow down |
| CSRF | Cross-site request forgery: a browser tricked into sending a request |
| XSS | Cross-site scripting: attacker script running in your page |
| CSP | Content-Security-Policy header restricting what a page may load or run |
SameSite, HttpOnly, Secure, __Host- | Cookie attributes and prefix that limit where and how a cookie is sent or read |
| Session fixation | Forcing a known session id on a victim; defeated by regenerating at login |
| JWT | JSON Web Token: signed claims; validate alg, iss, aud, exp |
| RFC 8725 | JWT best current practices |
| OAuth 2.1 | Consolidated OAuth: code flow with PKCE, no implicit grant, rotating refresh tokens (IETF draft) |
| OIDC | OpenID Connect: identity layer on OAuth 2 |
| PKCE | Proof Key for Code Exchange: binds an authorization code to the client that asked |
| Refresh token rotation | A new refresh token on each use; reuse revokes the family |
| Sanctum, Passport | Laravel first-party SPA and token auth; full OAuth2 server |
| Row-level security (RLS) | Database policy filtering rows per role or setting |
| Tenant isolation | Guaranteeing one customer cannot access another's data |
| Supply chain attack | Compromise through a dependency, build or distribution step |
| SBOM | Software bill of materials: list of components and versions (CycloneDX, SPDX) |
| SCA | Software composition analysis: scanning dependencies for known vulnerabilities |
govulncheck, composer audit | Go reachability-based vulnerability scanner; PHP advisory check |
| SAST, DAST, IAST | Static, dynamic and instrumented application security testing |
| Pentest | A time-boxed attack by a human tester |
| ASVS | OWASP Application Security Verification Standard |
| SSDF | NIST Secure Software Development Framework (SP 800-218) |
| SDL | Microsoft Security Development Lifecycle |
| SSRF | Server-side request forgery: making the server fetch an attacker-chosen URL |
| Data minimisation | Collect and keep only what the purpose needs (GDPR Art. 5 and 25) |
| Pseudonymisation | Replacing identifiers so data cannot be attributed without extra information |
| Audit log | Append-only record of who did what to which object, with outcome |
References
- Jerome H. Saltzer and Michael D. Schroeder, "The Protection of Information in Computer Systems", Proceedings of the IEEE 63(9), 1975. MIT copy, Section I "Basic Principles of Information Protection"
- OWASP Top 10:2025: overview, A01 Broken Access Control, A03 Software Supply Chain Failures, A06 Insecure Design, A10 Mishandling of Exceptional Conditions; A04:2021 Insecure Design
- OWASP Application Security Verification Standard (ASVS) 5.0.0
- OWASP Cheat Sheet Series: Input Validation, Authorization, Session Management, Secrets Management, Logging, Threat Modeling, SQL Injection Prevention, CSRF Prevention, Mass Assignment, Multi-Tenant Security, IDOR Prevention, Software Supply Chain Security, Vulnerable Dependency Management, Denial of Service
- Microsoft Learn, Threat modeling tool: threats (STRIDE); OWASP Threat Dragon
- NIST, SP 800-218 Secure Software Development Framework (SSDF) Version 1.1, February 2022; SP 800-207 Zero Trust Architecture
- RFC 8725, JSON Web Token Best Current Practices; IETF draft OAuth 2.1 (draft-ietf-oauth-v2-1-17, a draft, not yet an RFC when read); OpenID Connect Core 1.0
- GDPR Article 25: Data protection by design and by default (unofficial text of the regulation)
- Go: Go Vulnerability Management, govulncheck tutorial; package docs read with
go doc:html/template,net/http(Server),crypto/rand,crypto/subtle - Laravel 13: Authentication, Authorization, CSRF Protection, Validation, Encryption, Hashing, Rate Limiting, Eloquent (mass assignment), URL generation (signed URLs), Sanctum, Passport, Session; Composer,
composer audit; CISA, SBOM - Secondary and general knowledge (not re-read for this page): the framework comparison row for Spring, Django, Express and ASP.NET Core; Zanzibar-style ReBAC; SLSA and Sigstore