Skip to content

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 forGo to
The whole page in a few tablesEverything in one minute
Why security cannot be added at the endWhy it exists
Saltzer and Schroeder, STRIDE, SSDF, ASVS, the OWASP Top 10Where it comes from
Trust boundary, attack surface, threat model, STRIDE, attack tree, abuse caseThreat modeling
The eight design principles with Go and Laravel examplesSaltzer and Schroeder's principles
Input validation, output encoding, parameterized queriesTrust boundaries in code
Authentication, authorization, RBAC, ABAC, ReBAC, IDOR, mass assignmentWho may do what
Secure defaults, secrets, rate limiting, idempotency keys, audit loggingSecure design patterns
Defense in depth and zero trustDefense in depth
Cookies, JWT pitfalls, refresh rotation, OAuth 2.1, OIDC, Sanctum, PassportSessions and tokens
Tenant isolationMulti-tenancy isolation
Dependencies, SBOM, govulncheck, composer auditSupply chain
Data minimization, GDPR Article 25Privacy by design
OWASP Top 10 as design decisionsOWASP Top 10 mapped
A worked threat model of a checkoutMechanics: the checkout model
SAST, DAST, SCA, pentest, fuzzingSecurity testing
Go and Laravel codeGo, Laravel
Monolith, microservices, gateway auth, service identityIn architecture
The hands-on labLab: threat-model and fix
Wrong beliefs, cheat sheet, self-check, every termMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsTiny exampleWhat goes wrong without it
Trust boundaryA line where data or control passes between parts that trust each other differentlyBrowser to web app; web app to payment providerYou validate in the wrong place, or nowhere
Attack surfaceEverything an attacker can reach and feed input toRoutes, webhooks, file uploads, admin panelsA forgotten endpoint is the way in
Threat modelA written answer to "what can go wrong here and what do we do about it"A DFD plus a STRIDE tableControls are guesses
STRIDESix 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 youPassword plus second factorAnyone can claim to be anyone
Authorization (authz)What may you do to this objectOrderPolicy::viewLogged in means allowed (IDOR)
Least privilegeOnly the rights the job needsA DB role that cannot DROP TABLEOne bug owns everything
Deny by defaultNo rule, no accessA new route is closed until someone opens itNew code ships open
Defense in depthSeveral independent layersPolicy plus tenant scope plus RLSOne bug is a breach
Idempotency keyA client-chosen id that makes a retry safeIdempotency-Key: 7f3a... on POSTDouble charge, double refund
Audit logAppend-only record of who did whatactor=alice action=order:read outcome=denyNo evidence, no detection
SBOMBill of materials: every component and version you shipCycloneDX or SPDX fileYou cannot answer "are we affected"

Saltzer and Schroeder's eight principles in one line each (1975, quoted in full in the principles).

PrincipleOne lineViolated by
Economy of mechanismKeep it small and simple so it can be reviewedA 3,000-line custom auth framework
Fail-safe defaultsPermission, not exclusion; default is no accessA deny list of "bad" paths
Complete mediationCheck every access to every objectAuthorization only in the UI, or only on the first request
Open designSecrecy of design is not the protection; secrecy of keys is"Nobody knows our URL scheme"
Separation of privilegeTwo conditions, two keysOne admin can approve and pay their own invoice
Least privilegeMinimum rights for the jobThe app connects as the database owner
Least common mechanismShare as little as possible between usersOne shared cache key for all tenants
Psychological acceptabilityEasy to use correctlyA 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").

RankCategoryThe design question it asks
A01Broken Access ControlWho may touch this object, and where is that decided?
A02Security MisconfigurationWhat are the defaults, and who can change them?
A03Software Supply Chain FailuresWhat code do we run that we did not write?
A04Cryptographic FailuresWhat do we protect, with which keys, where kept?
A05InjectionWhere does data become code?
A06Insecure DesignDid anyone ask what can go wrong before coding?
A07Authentication FailuresHow do we know who is calling, and for how long?
A08Software or Data Integrity FailuresDo we verify what we load and deploy?
A09Security Logging and Alerting FailuresWould we notice, and could we prove it?
A10Mishandling of Exceptional ConditionsWhat do we do on error: open or closed?

Where each control lives in Go and Laravel.

ControlGoLaravel 13
Input validationDecode into a typed struct, DisallowUnknownFields, http.MaxBytesReaderForm Request with rules() and validated()
Output encodinghtml/template (contextual escaping)Blade escaped output
Parameterized querydatabase/sql placeholders ($1)Eloquent and query builder bindings
AuthorizationPolicy interface, one call per handlerPolicies and Gate::authorize
Mass-assignment guardA request type with no privileged fields#[Fillable] attribute on the model
CSRFNot built in; token or Sec-Fetch-Site check in middlewarePreventRequestForgery middleware in the web group
Password hashinggolang.org/x/crypto/bcrypt or argon2Hash facade: bcrypt by default, Argon2 supported
Rate limitingToken bucket middlewareRateLimiter::for and throttle middleware
SecretsEnvironment or secret manager, slog redaction.env, config(), Crypt facade with APP_KEY
Dependency auditgovulncheck ./...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 endDesigned in from the start
A scanner finds 400 findings the week before releaseThe threat model lists 15 risks at design time
Fixes change the data model and the APIThe model already carries tenant, owner and state
Controls are scattered if statementsControls 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 changeSlightly slower start, cheap to change
Risk: you ship holes you did not know existedRisk: over-engineering controls for threats that do not apply
TB1 Untrusted: internetTB2 Edge (DMZ)TB3 Internal network (mTLS)TB4 Third partyBrowsercustomer or attackerLaravel web/APIauthn, validation, authzGo pricing and orderserver-side price, policyRedissessions, limits, idempotencyOrders databasePostgreSQL, RLS, least-priv rolePaymentprovider (PSP)123456 signed webhook (untrusted until verified)1 HTTPS form/JSON 2 internal call + service identity 3 session, rate-limit counters 4 SQL 5 charge request 6 payment result

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 ​

  1. "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".
  2. "We use a framework, so we are secure." Laravel guards mass assignment and CSRF by default, but it cannot know that user_id in your URL must be compared with the caller. Go's net/http guards almost nothing by default. Frameworks remove classes of bugs; they do not design your authorization.
  3. "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.

text
     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".

text
     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 else

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

text
     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
S Spoofingviolates: authenticationattack: pretend to be someone elsedesign control:MFA, session design, mTLS, signed webhooksT Tamperingviolates: integrityattack: change data in flight or at restdesign control:server-side price, TLS, HMAC, constraintsR Repudiationviolates: non-repudiationattack: deny having done somethingdesign control:audit log, request id, signed receiptsI Information disclosureviolates: confidentialityattack: read what you must notdesign control:policy objects, tenant scope, encryptionD Denial of serviceviolates: availabilityattack: make the service unusabledesign control:rate limits, timeouts, quotas, backpressureE Elevation of privilegeviolates: authorizationattack: gain more rights than granteddesign control:deny by default, least privilege, no mass assign
STRIDE letterThreatProperty violatedTypical design control
SSpoofingAuthenticationMFA, signed tokens, mTLS, webhook signatures
TTamperingIntegrityServer-side pricing, TLS, HMAC, DB constraints
RRepudiationNon-repudiationAudit log, request id, signed receipts
IInformation disclosureConfidentialityPolicy objects, tenant scope, encryption, generic errors
DDenial of serviceAvailabilityRate limits, timeouts, quotas, backpressure
EElevation of privilegeAuthorizationDeny 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.

Goal: get goods without paying(OR: any branch is enough)1 Change the priceedit totalin requestprice fromcatalogue onserverstackcouponsone coupon perorder, rule indomain2 Fake the paymentforge PSPwebhookverifysignature withHMACreplay realwebhookidempotency key+ timestamp3 Take over accountcredentialstuffingrate limit peraccount+IP, MFAstealsessionHttpOnly,Secure,rotation4 Abuse refundsrefundtwiceidempotency +state machinerefund toown cardrefund only tooriginal method

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.

PrincipleThe paper saysViolation in a web systemGo exampleLaravel 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 possibleA homemade token format and a 500-line permission matrixOne 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 accessA blocklist of forbidden paths; new routes open by defaultDecide returns false unless a rule matchesA 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 checksAuthorization in the UI only; checking only on show, not on update or the export endpointRequire is called in every handler before the object is usedGate::authorize in each action, or can: middleware on the route group
Open design"The design should not be secret." Protection rests on keys, not ignoranceSecurity through obscurity: secret URL, home-grown cipherUse crypto/rand, crypto/subtle, standard TLSCrypt (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 payoutRefund needs the finance role and an order in state paidPolicy 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 scopeDB role orders_app with SELECT, INSERT, UPDATE on two tablesSanctum 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 tenantsTenant id in every cache key and in the contextGlobal 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 routinelyA 20-field permission form nobody understands; password rules that force sticky notesSecure defaults mean the easy path is the safe pathStarter kits give login, throttling, hashing with no setup
text
     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.

text
     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
DefenceProtects againstWhereGoLaravel
Allow-list validationMalformed and unexpected dataAt the boundaryTyped struct, regexp, slices.ContainsForm Request rules (in, regex, between)
Size and time limitsResource exhaustionServer and handlerhttp.MaxBytesReader, ReadHeaderTimeoutpost_max_size, upload max: rule, throttle
Reject unknown fieldsMass assignmentDecoderDisallowUnknownFieldsprohibited rule or validated() only
Output encodingXSSWhen writing to HTML, JS, URLhtml/template contextual escapingBlade escaped output; avoid raw output
Parameterized querySQL injectionData accessdb.QueryContext(ctx, "... $1", v)Query builder, Eloquent bindings; never DB::raw with user data
Canonicalize then validatePath traversal, Unicode tricksBefore usefilepath.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):

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

ModelDecides byExample ruleStrengthWeaknessFits
RBAC (role-based)The subject's rolefinance may refundSimple, auditableRole explosion; ignores which objectBack-office staff, coarse gates
ABAC (attribute-based)Attributes of subject, resource, contextowner equals caller, status is pending, time is business hoursExpressiveRules scatter and get hard to reviewBusiness 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 storeDocuments, orgs, teams
ACLA list on each objectAlice and Bob may edit this documentFine-grainedHard to audit at scaleFiles, 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."

text
     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=deny

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

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

text
     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
<?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".

text
     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 place

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

text
     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 seconds

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

text
     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 reuse

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

go
// 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.

text
     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 tokens

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

go
// 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.

1 Network and edge: TLS, WAF, rate limit, DDoS protection2 Gateway: authentication, token validation, coarse authz3 Application: input validation, policy objects, CSRF4 Domain: invariants, idempotency, state machine5 Data: RLS, least-priv role, encryptionCrown jewelsorders, PII, keys6 Detect and respond: audit log, alerts, anomaly detection, runbooksEach layer assumesthe one outside it failed.Example: an IDOR slips pastlayer 3. RLS in layer 5 stillreturns zero foreign rows,and layer 6 logs the attempt.Layers must be independent:same bug, same secret or thesame team in two layers isone layer, not two.
text
     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 paged

Real 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 attributeWhat it doesSettingNote
SecureSent only over HTTPSAlwaysWithout it, a downgrade to HTTP leaks the id
HttpOnlyNot readable by JavaScriptAlways for session idsStops cookie theft via XSS, not XSS itself
SameSiteWhether cross-site requests carry itLax (or Strict)OWASP: "defense in depth against CSRF, not a replacement for a CSRF token"; never None without Secure
__Host- prefixBrowser enforces Secure, Path=/, no DomainUse for the session cookieBlocks subdomain overwrite
LifetimeIdle and absolute timeoutsIdle 15-120 min, absolute hoursShort for sensitive apps
RotationNew id at login and privilege changesession()->regenerate()Defeats session fixation
JWT pitfallWhy it hurtsRFC 8725 / practice
Trusting the alg headernone 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, nbfToken from another service or an old token acceptedValidate every claim you rely on
Long-lived access tokenA stolen token works for daysMinutes, plus refresh
Sensitive data in the payloadPayload is only base64url, not encryptedPut ids, not secrets
Storing in localStorageAny XSS reads itPrefer HttpOnly cookie, or in-memory with short life
No revocationLogout and password reset do not kill itShort life, denylist or token version in the user row
Same key everywhere / weak HMAC keyOne leak forges for allPer-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.

text
     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 login

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

go
// 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)
}
go
// 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
<?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
<?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".

text
     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
sql
-- 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 BYPASSRLS

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

go
// 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
<?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.

ToolEcosystemWhat it doesCommand
govulncheckGoReports 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 auditPHPChecks installed packages against security advisoriescomposer audit (run in CI, fail on findings)
go mod verify, go.sumGoVerifies module hashes against the checksum databasego mod verify
composer.lockPHPPins exact versions; commit it for applicationscomposer install (not update) in CI
Dependabot / RenovateBothOpens update pull requestsConfig in repo
SBOM generators (Syft, cyclonedx-gomod, cyclonedx-php-composer)BothProduce CycloneDX or SPDXRun at build, store with the release
Signed builds and provenance (Sigstore cosign, SLSA)BothProve an artifact came from your pipelineSign 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).

text
     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 itWhere in this pageTypical Go controlTypical Laravel control
A01 Broken Access ControlDeny by default; one policy object; scope queries by owner and tenant; enforce server-sideAuthz, Tenancyauthz.Require per handlerPolicies, Gate::authorize, global scope
A02 Security MisconfigurationSecure defaults; same hardened config in every environment; no debug in productionSecure defaultsExplicit http.Server timeouts and headersAPP_DEBUG=false, SecurityHeaders, strict models
A03 Software Supply Chain FailuresLockfiles, SCA, SBOM, provenance, few dependenciesSupply chaingovulncheck, go mod verifycomposer audit, composer.lock
A04 Cryptographic FailuresStandard algorithms, managed keys, TLS everywhere, no home-grown cryptoOpen design, Encryptioncrypto/rand, crypto/tls, AEADCrypt, Hash, APP_KEY rotation
A05 InjectionData never becomes code: parameterize, encode output, allow-listInput$1 placeholders, html/templateBindings, Blade escaping
A06 Insecure DesignThreat model, secure design patterns, abuse cases, paved roadsThreat modelingShared authz, validate, ratelimit packagesShared policies, Form Requests, base classes
A07 Authentication FailuresStrong hashing, MFA, session rotation, rate limiting, no weak recoverySessions, Rate limitingsession package, bcrypt or argon2Starter kits, Hash, throttle
A08 Software or Data Integrity FailuresVerify signatures of webhooks, updates and artifacts; no unsafe deserialisationCheckout modelhmac.Equal on webhook bodiesSigned URLs, verified webhook middleware
A09 Security Logging and Alerting FailuresAudit events on decisions; alert on denies; redact secretsAuditslog with ReplaceAttrGate::after, an audit log channel
A10 Mishandling of Exceptional ConditionsFail closed; generic errors outward, detail inward; handle every error pathFail-safe defaultsRecover middleware, checked errorsException 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.

ConcernLaravel 13 (PHP 8.4)Go net/httpSpring Security (Java)Django (Python)Express (Node.js)ASP.NET Core
CSRFOn in the web group: Sec-Fetch-Site check, then session tokenNothing built in; add middlewareOn by default for browser sessionsCsrfViewMiddleware in the default stackNot built in; csurf-style packagesAntiforgery services for forms
Mass assignmentGuarded by default; #[Fillable] or #[Guarded] required for createNo ORM; your struct decidesBinder allow-lists are your jobModelForm fields listNo ORM; your code decides[Bind] / view models
Output encodingBlade escapes by defaulthtml/template escapes by context; text/template does notTemplate engine dependentTemplates auto-escapeDepends on the view engineRazor encodes by default
Password hashingHash: bcrypt (default) or Argon2x/crypto/bcrypt, x/crypto/argon2PasswordEncoderPBKDF2 default, Argon2 optionalbcrypt, argon2 packagesPasswordHasher
AuthorizationGates and PoliciesWrite your own (like our authz)Method and URL securityPermissions, decoratorsWrite your own or CASLPolicies and requirements
Rate limitingRateLimiter, throttle middlewaregolang.org/x/time/rate or customNot built inThird-partyexpress-rate-limitBuilt-in rate limiter middleware
Security headersAdd middlewareAdd middlewareDefault headers onSecurityMiddlewarehelmetAdd middleware
Dependency auditcomposer auditgovulncheckOWASP Dependency-Check, Dependabotpip-auditnpm auditdotnet 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.

#WhereSTRIDEThreatDesign controlTest or evidence
1Flow 1SCredential stuffing on /loginRate limit per account plus IP; MFA; breached-password checkFeature test: 6th attempt returns 429
2Flow 1SSession theft or fixation__Host- cookie, HttpOnly, Secure, regenerate on loginCookie-flag test
3Flow 1TClient sets price or statusServer-side pricing; prohibited fields; typed decodePOST with total_cents returns 422
4Flow 1TCSRF on "change address"PreventRequestForgery; SameSite=LaxCross-site POST rejected
5Flow 1IIDOR on /orders/{id}Policy plus tenant scope; 404 for foreignMallory reads Alice's order: 404
6Flow 1IVerbose errors reveal SQL or stackAPP_DEBUG=false; Recover returns a generic 500Error-path test
7Flow 1DCheckout flood; bot buys all stockPer-user and per-IP limits; hold stock with TTL; bot checksLoad test, limiter test
8Flow 1ECustomer calls an admin routeDeny by default; role check; route-list testTest: every route has an auth rule
9Flow 2SAnother internal service pretends to be LaravelmTLS or signed service token; allow-list of callersCall without a cert is refused
10Flow 2TLaravel forwards a tampered totalThe Go service recomputes the price itselfContract test
11Flow 3ICache key shared across tenantsTenant id in every key; TTLsTwo-tenant cache test
12Flow 4TSQL injectionPlaceholders; role without DDL rightsInjection payload test
13Flow 4IA bug reads another tenant's rowsRLS; per-transaction tenant settingpsql test as app role
14Flow 5R"I never paid" or "you never charged"Idempotency key; store PSP reference; audit eventReconciliation job
15Flow 6SFake "payment succeeded" webhookVerify the provider's HMAC signature; check timestampWebhook with a bad signature returns 401
16Flow 6TReplayed webhook marks order paid twiceIdempotency on event id; state machineReplay test: second call is a no-op
17StoreIDatabase dump leaks PIIEncrypt sensitive columns; mask outside production; least-privilege backupsBackup access review
18WholeRNo trace of who refunded whatAudit log with actor, action, object, outcomeLog 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 ​

FrameworkWhat it isUse it for
OWASP ASVS 5.0.0A numbered checklist of verifiable requirements (identifiers like v5.0.0-1.2.5)Requirements for a story; a test checklist; a pentest scope
OWASP SAMMA maturity model for an AppSec programmePlanning what to improve next
NIST SSDF (SP 800-218)High-level practices for producers and a common vocabulary for buyersProcurement and compliance conversations
Microsoft SDLA lifecycle with threat modeling, tooling and responseOrganising security activities per phase
Threat Modeling ManifestoValues and the four questionsCulture and facilitation

Security testing ​

Tests are how a threat-model row becomes true. Layer them; no tool finds design flaws on its own.

TechniqueWhat it checksFindsMissesWhen
Unit and feature tests of abuse casesPolicies, validation, limitsRegressions of known threatsUnknown threatsEvery commit
SAST (static analysis: gosec, staticcheck, go vet, Larastan, Psalm taint analysis, Semgrep, CodeQL)Source patternsInjection sinks, hard-coded secrets, weak cryptoBusiness-logic flaws, missing checksEvery pull request
SCA (govulncheck, composer audit)DependenciesKnown CVEsUnknown vulnerabilities; your own codeEvery pull request, nightly
DAST (OWASP ZAP, Burp Suite)A running app from outsideMisconfiguration, reflected XSS, missing headersAuthorization logic without credentialsStaging, nightly
IASTInstrumented runtimeTainted flows during testsUntested pathsCI with integration tests
Fuzzing (go test -fuzz)Parsers with random inputPanics, crashes, parser confusionLogic flawsParsers and decoders
Threat-model reviewThe designMissing controls, wrong boundariesImplementation bugsDesign, and on each flow change
Code review with a security checklistDiffsMissing authz call, new endpointSubtle bugs at scaleEvery pull request
Penetration testA human attacker with a time boxChained and logical flawsEverything outside scope or timeYearly and before major releases
Bug bountyMany external researchersReal-world surprisesNeeds triage capacityAfter basics are in place
text
     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-days

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

go
// 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.

go
// 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
}
go
// 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/rand for tokens, crypto/subtle.ConstantTimeCompare for 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/sql placeholders. Nothing is on by default except html/template escaping and prepared-statement placeholders when you use them.
  • http.Server timeouts are a security setting. The docs say ReadTimeout "does not let Handlers make per-request decisions", so most users should prefer ReadHeaderTimeout; without any, a slow client holds a connection forever (slowloris).
  • context.Context carries identity and tenant through the call chain so a lower layer cannot be called without one; our tenant.Store fails closed with ErrNoTenant.
  • 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/aes with GCM (cipher.NewGCM), golang.org/x/crypto/argon2 or bcrypt, and crypto/tls.

Laravel ​

Before ​

php
<?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
<?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
<?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
<?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 UsePolicy attribute or auto-discovery); call Gate::authorize('view', $order) or put ->can('view', 'order') on the route. Policy responses can be Response::denyAsNotFound() or Response::denyWithStatus(404). Gate::before is powerful (a super-admin shortcut) and dangerous: it runs for every check, so keep it tiny and audited. Gate::after is where we log.
  • Validation: Form Requests run before the controller; use validated() or safe()->only() and never $request->all() into a model.
  • Mass assignment: Eloquent refuses create until 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 PreventRequestForgery middleware, session()->regenerate() after login, invalidate() at logout, encrypted cookies, SESSION_SECURE_COOKIE, same_site.
  • Hashing and encryption: Hash::make (bcrypt, rounds 12 by default; Argon2 available), Hash::needsRehash; Crypt::encryptString uses AES with a MAC, key from APP_KEY (rotate with previous keys, see the docs).
  • Signed URLs: URL::signedRoute('unsubscribe', ['user' => 1]) and the signed middleware protect a public link from tampering; use temporarySignedRoute for 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::for with several Limits per limiter; the throttle:name middleware returns 429 with Retry-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, trustProxies limited to your load balancers.

Solving the classic problems ​

ProblemSolutionHowCost or limit
IDORPolicy object plus owner/tenant scopeCheck decide(subject, action, resource) in every action; scope the query; 404 on foreignOne call per handler; needs discipline and a route-coverage test
Mass assignmentSeparate request type; allow-list; server-owned fields#[Fillable], prohibited rules, DisallowUnknownFieldsA second type to maintain
Missing rate limitPer-key token bucket, 429 plus Retry-AfterRateLimiter::for, ratelimit.Middleware; shared store when scaled outShared state; false positives behind NAT
SQL injectionPlaceholders; least-privilege DB roledb.QueryContext(ctx, q, args...), query builderDynamic identifiers (order by) need an allow-list
XSSContextual output encoding plus CSPhtml/template, Blade escaping, Content-Security-PolicyCSP tuning effort
CSRFOrigin check plus token; SameSite cookiePreventRequestForgery; Go middleware on Sec-Fetch-SiteCross-site embeds need exceptions
Broken JWTPin algorithm; validate claims; short lifejwtcheck.Verify or a maintained libraryRevocation needs state
Replayed webhookSignature plus timestamp plus idempotency on event idhmac.Equal; store processed idsA table of seen events
Secrets in gitManager, runtime mount, scanning, rotationVault or cloud secret manager; pre-commit and CI scanOperational setup
Cross-tenant leakRequired tenant context plus RLStenant.Store, TenantScope, CREATE POLICYPool and role design with RLS
Over-powerful app roleSeparate roles: migration, runtime, read-onlyGRANT only needed privilegesMore roles to manage
SSRF (server-side request forgery)Allow-list outbound hosts; block link-local and internal ranges; no redirects to internalResolve and validate before connecting; egress policyBreaks legitimate webhooks to arbitrary URLs
Vulnerable dependencySCA in CI; update policy; SBOMgovulncheck, composer audit, DependabotUpdate churn
Verbose errorsGeneric message outward, detail in logsRecover middleware, exception handlerNeeds 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 ​

SituationRecommendationExtra techniqueReason
Browser app, one backendServer-side session, HttpOnly __Host- cookie, CSRF protectionRotate id at login; idle timeoutSimplest, revocable
SPA plus first-party API on the same siteSanctum cookie sessionSameSite=Lax, CSRF tokenAvoids tokens in JavaScript
Mobile app or third-party API consumersOAuth 2.1 code flow with PKCE, short access tokens, rotating refresh tokensSender-constrained tokens where availableStandard, revocable at the server
Service to service inside one trust zonemTLS or signed service tokens with audienceNetwork policyIdentity per service, not per network
Few coarse rolesRBACPolicy for ownershipSimple
Rules depend on the objectABAC in a policy objectTable testsExpressive
Sharing, orgs, teamsReBAC (relation store or Zanzibar-style service)Cache with short TTLGraph of relations
Many tenants, shared schemaRequired tenant context plus RLSPer-tenant cache keysDefence in depth
Few large tenants with strict needsSchema or database per tenantPer-tenant keysStrong isolation, higher cost
Money movementIdempotency key, state machine, separation of privilege, auditReconciliationOne error costs more than a check
Public endpointRate limit, size limit, validation, no secrets in URLsWAF as extra layerAnyone can call it
Handling PIIMinimise, mask, encrypt columns, retentionPseudonymiseGDPR 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.

DesignWhere authn happensWhere authz happensFailure mode
Perimeter onlyGatewayNowhere after itOne bypass or one compromised service exposes everything ("hard shell, soft centre")
Gateway authn plus per-service authzGateway validates the user token; passes identity onEach service decides on the user's identity and the objectNeeds a consistent identity and policy format
Zero trustEvery call is authenticated (user and service)Every service decides; policy as codeMore 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).

text
     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 id

Everyday 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-store on 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. exp and nbf and 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 ​

LoadWhat changes in securityConcrete step
1x: one app, one databaseBasics: policies, validation, hashing, headers, backupsThe lab's fixes plus composer audit
10x: several instances, RedisShared state for rate limits, sessions, idempotency; secrets managementRedis counters, secret manager, per-environment credentials
100x: many services and teamsService identity, policy as code, paved roads, central audit pipeline, tenant isolation tested continuouslymTLS, shared auth library or sidecar, SIEM alerts, threat-model per service, bug bounty
Org growthSecurity becomes platform workSecure 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.

bash
cd docs/snippets/design/security-by-design/go
go version        # go 1.24 or newer
go test ./...     # all green: the baseline, including the exploit tests

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

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

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

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

bash
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).

bash
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
<?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');
});
bash
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 login

Experiment 7: the database layer. Prove RLS holds even when the application forgets the filter (PostgreSQL, using the policy shown in Multi-tenancy isolation):

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

bash
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 audit

Stretch. 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 ​

BeliefReality
"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 ​

TopicWhat to remember
MindsetDesign in: boundaries, threats, controls, tests; not a scanner at the end
Four questionsWhat are we working on? What can go wrong? What will we do? Did we do well?
STRIDESpoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege
SaltzerEconomy, fail-safe defaults, complete mediation, open design, separation of privilege, least privilege, least common mechanism, psychological acceptability
AuthzServer-side, every request, deny by default, policy object, 404 for foreign, test it
IDOROwner or tenant check plus scoped query; random ids do not replace it
InputParse once at the boundary into a type; allow-list; size limit; reject unknown fields
OutputEncode for the context (html/template, Blade); CSP as backup
SQLPlaceholders always; role without DDL; RLS as the second layer
Mass assignmentSeparate request type; #[Fillable]; server sets owner, tenant, status, price
Sessions__Host- cookie, Secure, HttpOnly, SameSite=Lax, rotate at login, idle and absolute timeouts
JWTPin alg; check iss, aud, exp; short life; rotate refresh tokens and detect reuse
Rate limitPer account plus IP; 429 plus Retry-After; shared store when scaled out
IdempotencyKey plus payload fingerprint plus caller scope; same result, one effect
SecretsManager or runtime mount; never in git or image; rotate; scan
Supply chainLockfiles, govulncheck, composer audit, SBOM, review new dependencies
LoggingLog decisions and denials, redact secrets, alert on spikes
MicroservicesGateway for coarse checks; every service authenticates callers and authorises objects; mTLS
PrivacyMinimise, limit retention, pseudonymise, default to least access (GDPR Art. 25)

Self-check: questions & answers ​

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

1 — 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 ​

TermMeaning
Security by designTreating security as a requirement and a structural property from the first design step
Insecure designOWASP A06: missing or ineffective control design, different from an implementation bug
Trust boundaryA line where data or control passes between components of different trust
Attack surfaceThe set of entry points an attacker can reach
Threat modelA 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
STRIDESpoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege
LINDDUNPrivacy threat categories: Linking, Identifying, Non-repudiation, Detecting, Data disclosure, Unawareness, Non-compliance
Attack treeA 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 mechanismKeep protection mechanisms small and simple
Fail-safe defaultsDefault to no access; grant by explicit permission
Complete mediationCheck every access to every object
Open designSecurity must not depend on secrecy of the design
Separation of privilegeRequire two conditions or two parties for sensitive actions
Least privilegeGrant the minimum rights needed for the job
Least common mechanismMinimise shared mechanisms between users
Psychological acceptabilityMake the secure way the easy way
Work factorThe 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
RBACRole-based access control
ABACAttribute-based access control
ReBACRelationship-based access control (Zanzibar style)
ACLAccess control list attached to an object
IDORInsecure direct object reference: access by changing an identifier
Mass assignmentA request field overwriting a column the developer did not intend
Policy objectOne class that answers every authorization question about a resource
Deny by defaultNo matching rule means no access
Defense in depthSeveral independent controls so one failure is not a breach
Zero trustNo implicit trust from network location; authenticate and authorise every request
mTLSMutual TLS: both sides present certificates
Service identityA verifiable name for a workload (certificate or signed token)
Confused deputyA service misused by a caller to act with the service's own privileges
Idempotency keyA client id that makes a retried operation take effect once
Token bucketRate limiting with burst capacity and a steady refill
429 and Retry-AfterThe status and header that tell a client to slow down
CSRFCross-site request forgery: a browser tricked into sending a request
XSSCross-site scripting: attacker script running in your page
CSPContent-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 fixationForcing a known session id on a victim; defeated by regenerating at login
JWTJSON Web Token: signed claims; validate alg, iss, aud, exp
RFC 8725JWT best current practices
OAuth 2.1Consolidated OAuth: code flow with PKCE, no implicit grant, rotating refresh tokens (IETF draft)
OIDCOpenID Connect: identity layer on OAuth 2
PKCEProof Key for Code Exchange: binds an authorization code to the client that asked
Refresh token rotationA new refresh token on each use; reuse revokes the family
Sanctum, PassportLaravel first-party SPA and token auth; full OAuth2 server
Row-level security (RLS)Database policy filtering rows per role or setting
Tenant isolationGuaranteeing one customer cannot access another's data
Supply chain attackCompromise through a dependency, build or distribution step
SBOMSoftware bill of materials: list of components and versions (CycloneDX, SPDX)
SCASoftware composition analysis: scanning dependencies for known vulnerabilities
govulncheck, composer auditGo reachability-based vulnerability scanner; PHP advisory check
SAST, DAST, IASTStatic, dynamic and instrumented application security testing
PentestA time-boxed attack by a human tester
ASVSOWASP Application Security Verification Standard
SSDFNIST Secure Software Development Framework (SP 800-218)
SDLMicrosoft Security Development Lifecycle
SSRFServer-side request forgery: making the server fetch an attacker-chosen URL
Data minimisationCollect and keep only what the purpose needs (GDPR Art. 5 and 25)
PseudonymisationReplacing identifiers so data cannot be attributed without extra information
Audit logAppend-only record of who did what to which object, with outcome

References ​

Built by Morteza Negahi