OWASP API Security Top 10 (2023): BOLA, BOPLA, BFLA, Business Flows, Inventory, Unsafe Consumption
"The OWASP API Security Top 10 2023 is a forward-looking awareness document for a fast pace industry. It does not replace other TOP 10's." — OWASP API Security Top 10 2023, Release Notes
Summary: An API hands its client a map of every object and function it has: /orders/{id}, /admin/users, PATCH /me, POST /checkout. Most API breaches are not clever exploits; they are a client walking that map with a valid token and the server forgetting to ask "may you touch this object, call this function, read or write this property, run this flow a thousand times?". The OWASP API Security Top 10 2023 names those failures. This chapter teaches the six that are specific to APIs in full (API1 BOLA, API3 BOPLA, API5 BFLA, API6 business flows, API9 inventory, API10 unsafe consumption) and the other four in one paragraph each with a link to the chapter that owns them, with a vulnerable and a fixed endpoint in Go and Laravel 13 for every risk and tests that watch the leak happen and then stop. Focus: API1 Broken Object Level Authorization (BOLA, IDOR, the object-level authorization check, UUID vs sequential ids, enumeration, scoped queries, row-level security), API2 Broken Authentication (re-authentication for sensitive changes), API3 Broken Object Property Level Authorization (BOPLA: excessive data exposure, mass assignment, the allow-list of properties, input and response DTOs, $fillable, $guarded, #[Fillable], #[Hidden], DisallowUnknownFields), API4 Unrestricted Resource Consumption (page caps, batch caps, spending limits), API5 Broken Function Level Authorization (BFLA, admin endpoints, method tampering, deny by default at route registration), API6 Unrestricted Access to Sensitive Business Flows (scalping, bot abuse, business logic abuse, device fingerprinting, non-human patterns, rate limits per user and per resource), API7 Server Side Request Forgery, API8 Security Misconfiguration (problem details, CORS), API9 Improper Inventory Management (API inventory, shadow API, zombie API, OpenAPI as inventory, versioning and deprecation with Deprecation/Sunset/410), API10 Unsafe Consumption of APIs (third-party API trust, redirects, timeouts, size caps, input validation of upstream responses); authorization middleware, policy objects, Laravel Policies, Gate, Form Request, API resources; logging and alerting for authorization failures (authz_fail); CWE references; the OWASP risk table (exploitability, prevalence, detectability, impact). Learning goal: Given any API endpoint, say which of the ten risks it can fall into, write the one request that proves it (swap an id, add a property, change the method, run the flow in a loop, call the old version, poison the upstream), and ship the fix in Go (context-based ownership check, a route table that refuses routes without a policy, input/response DTOs, a flow guard, an OpenAPI-driven mount with lifecycle headers, a hardened upstream client) and Laravel 13 (Policies with denyAsNotFound, Gate::authorize, can: middleware and #[Middleware], Form Requests with prohibited, JsonResource, RateLimiter::for with several limits, a lifecycle middleware, an Http client with allow_redirects => false), plus the two-user test that keeps it fixed.
This chapter owns the API-specific risks of the OWASP API Security Top 10. The web application list (injection, XSS, CSRF, headers, debug mode, SSRF with the connect-time IP check) is in OWASP Top 10; who may do what in general (RBAC, ABAC, ReBAC, policy engines, Zero Trust) is in Authorization models; passwords, MFA and sessions are in Authentication; token formats and flows are in JWT deep dive and OAuth 2.0, OIDC and SSO and are not re-taught here; algorithms for limits are in Rate limiting; resource and version design are in REST API design and API versioning; the full hardening list (headers, input, CI/CD) is in API security hardening checklist; API keys, HMAC request signing and webhook signatures are in API keys, request signing and webhooks. Go-side mechanics are in Authentication in Go and Middlewares; id formats are in ID generation; the gateway layer is in API gateway, BFF and service mesh.
Page map
| If you are looking for | Go to |
|---|---|
| The ten risks, their scores and the 2019 → 2023 changes in three tables | Everything in one minute |
| Why APIs fail differently from web pages | Why it exists |
| Editions, methodology, the risk rating, NIST SP 800-228 | Where it comes from |
GET /orders/1002 with Ana's token | API1 BOLA |
| Sequential ids, UUIDv4 vs UUIDv7, enumeration | UUID vs sequential ids |
| Weak login, token in URL, no re-auth | API2 Broken Authentication |
password_hash in the response, role in the request | API3 BOPLA |
?limit=10000000, GraphQL batching, SMS bills | API4 Resource consumption |
DELETE instead of GET, /api/admin/v1/users/all | API5 BFLA |
| Scalpers, fake sign-ups, seat hoarding | API6 Business flows |
picture_url=localhost:8080 | API7 SSRF |
| Stack traces, reflected CORS, missing TLS | API8 Misconfiguration |
| Beta hosts, old versions, undocumented routes | API9 Inventory |
| A partner that redirects your POST to an attacker | API10 Unsafe consumption |
| Middleware vs policy vs query scope | Authorization middleware and policy objects |
authz_fail events and alerts | Logging and alerting for authorization failures |
GraphQL node(id:), gRPC, webhooks | Beyond REST |
| Status codes, knobs, CWE references | Mechanics |
| Code | Go, Laravel |
| Pentest findings and how to close them | Solving the classic problems |
| Two-user tests, scanners, spec diffs | Testing |
| Which control for which endpoint | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on | Lab |
Everything in one minute
The 2023 list. Each row is unpacked in the catalogue; "here" means taught in full on this page, a link means one paragraph here and the full treatment in the owner chapter.
| Risk | In plain words | Tiny exploit | First fix | Depth |
|---|---|---|---|---|
| API1 Broken Object Level Authorization (BOLA) | The server checks who you are, not whether this object is yours | GET /api/orders/1002 with the token of the owner of 1001 | Object-level authorization check on every access; scope the query by owner and tenant | here |
| API2 Broken Authentication | The way in is weak | Change account e-mail with a stolen token, then "forgot password" | Re-authenticate for sensitive changes; standard auth | Authentication |
| API3 Broken Object Property Level Authorization (BOPLA) | You may see the object, not every field of it; you may edit some fields, not all | Response contains password_hash; PATCH /me with "role":"admin" | Response DTO and input DTO: an allow-list of properties each way | here |
| API4 Unrestricted Resource Consumption | One request can cost CPU, memory, money | ?limit=10000000; 999 mutations in one GraphQL batch | Caps on page size, body, batch, timeouts; spending limits | Rate limiting |
| API5 Broken Function Level Authorization (BFLA) | A regular user calls an admin function | DELETE /api/users/2; GET /api/admin/v1/users/all | Deny by default; a role policy on every route, including the method | here |
| API6 Unrestricted Access to Sensitive Business Flows | A correct feature, run by a script, hurts the business | Bot buys the whole drop of a console | Name the sensitive flows; limits per user, device and resource; bot signals | here |
| API7 Server Side Request Forgery | The API fetches a URL the attacker chose | {"picture_url":"localhost:8080"} | Allow-list hosts, schemes, ports; isolate the fetcher; connect-time IP check | OWASP Top 10 |
| API8 Security Misconfiguration | Defaults and verbose errors | Stack trace with SQL; CORS reflecting any origin | Hardened config as code; generic errors; exact CORS | OWASP Top 10 |
| API9 Improper Inventory Management | Nobody knows every host, version and route | Brute-force reset codes on beta.api… where the limiter is missing | API inventory (OpenAPI as inventory), retirement plan, same protection for every version | here |
| API10 Unsafe Consumption of APIs | You trust a partner's data more than a user's | Partner answers 308 to attacker.com; your POST follows | TLS, timeouts, no blind redirects, size caps, validate upstream responses | here |
The risk table (exploitability, prevalence, detectability, impact). OWASP scores each risk with the OWASP Risk Rating Methodology: Exploitability and Detectability Easy 3 / Average 2 / Difficult 1, Prevalence Widespread 3 / Common 2 / Difficult 1, Technical impact Severe 3 / Moderate 2 / Minor 1; threat agents are "API Specific" and business impact "Business Specific" for every row. Copied from each risk page:
| Risk | Exploitability | Prevalence | Detectability | Technical impact | Key CWE references (from the risk page) |
|---|---|---|---|---|---|
| API1 BOLA | Easy | Widespread | Easy | Moderate | CWE-285, CWE-639 |
| API2 Broken Authentication | Easy | Common | Easy | Severe | CWE-204, CWE-307 |
| API3 BOPLA | Easy | Common | Easy | Moderate | CWE-213, CWE-915 |
| API4 Resource Consumption | Average | Widespread | Easy | Severe | CWE-770, CWE-400, CWE-799 |
| API5 BFLA | Easy | Common | Easy | Severe | CWE-285 |
| API6 Business Flows | Easy | Widespread | Average | Moderate | none listed |
| API7 SSRF | Easy | Common | Easy | Moderate | CWE-918 |
| API8 Misconfiguration | Easy | Widespread | Easy | Severe | CWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942 |
| API9 Inventory | Easy | Widespread | Average | Moderate | CWE-1059 |
| API10 Unsafe Consumption | Easy | Common | Average | Severe | CWE-20, CWE-200, CWE-319 |
2019 → 2023. The release notes: "We've combined Excessive Data Exposure and Mass Assignment focusing on the common root cause: object property level authorization validation failures."
| 2023 | Came from 2019 | What changed |
|---|---|---|
| API1 BOLA | API1 | Unchanged name, still first |
| API2 Broken Authentication | API2 Broken User Authentication | Renamed; covers machine-to-machine auth between microservices too |
| API3 BOPLA | API3 Excessive Data Exposure + API6 Mass Assignment | Merged on the root cause: property-level authorization |
| API4 Unrestricted Resource Consumption | API4 Lack of Resources & Rate Limiting | Focus on cost and resources, not only request rate |
| API5 BFLA | API5 | Unchanged |
| API6 Sensitive Business Flows | new | "most of those that can be mitigated using rate limiting" |
| API7 SSRF | new | Webhooks, URL previews, cloud metadata |
| API8 Security Misconfiguration | API7 | Moved down one |
| API9 Improper Inventory Management | API9 Improper Assets Management | Renamed; adds data-flow blindspots |
| API10 Unsafe Consumption of APIs | new | Attackers go after your integrations |
| (dropped) | API8 Injection, API10 Insufficient Logging & Monitoring | No longer separate entries; injection lives on in the API10 scenarios, and the API6 page still lists "API10:2019 Insufficient Logging & Monitoring" among its references |
Why it exists
A server-rendered web page decides what the user sees: the HTML has only the buttons this user may press. An API gives the client the raw functions and the raw objects and lets the client decide what to show. That moves three decisions to the server that web frameworks used to hide: which objects this caller may touch, which functions this caller may call, and which properties of an object this caller may read or write. The API1 page puts the cause in one sentence: the server "usually does not fully track the client's state, and instead, relies more on parameters like object IDs, that are sent from the client to decide which objects to access." Add machine clients that never get tired (API4, API6), versions and hosts that multiply faster than documentation (API9), and integrations that feed you data you never validated (API10), and you get a list that overlaps the web Top 10 only partly.
| Choice | Gain | Cost |
|---|---|---|
Generic findOrFail($id) / store.Get(id) | One line per endpoint | Every id-taking endpoint is a BOLA candidate |
| Scoped query + policy object per resource | Holds when routes are guessed; testable | Every query carries tenant/owner; policy tests |
Serialise the model (toJson, json.Marshal(user)) | No DTO code | Every new column leaks by default (excessive data exposure) |
| Response and input DTOs | New columns are private until published; writes are explicit | One class per shape |
| Admin routes hidden in the UI only | Fast | Anyone who reads the JavaScript bundle finds them (BFLA) |
| Route table where each route names its policy | Deny by default, reviewable in one file | Boilerplate per route |
| Flows open to any authenticated client | Frictionless UX | Bots win every scarce resource (API6) |
| Per-flow limits, device signals, challenges | Fair access | Friction for some humans; tuning |
| Keep old versions running "for safety" | No client breaks | Zombie APIs with old weaknesses (API9) |
| Trust partner responses | Fast integration | Their breach is your injection or data leak (API10) |
An everyday picture. A hotel. The front desk checks your passport and gives you a key card: that is authentication (API2). The card opens room 412 and not room 413: object-level authorization (API1). It opens the gym but not the staff corridor: function-level authorization (API5). In your room you may use the minibar but not reprogram the door lock or read the previous guest's folio, even though they are "in your room": property-level authorization (API3). A guest who books every room for New Year's Eve with fake names and cancels on the 30th is not breaking any lock: business-flow abuse (API6). An unlisted side entrance from the hotel's renovation, still unlocked, is a shadow API; the old wing that "closed" but still has working doors is a zombie API (API9). The laundry company you outsource to returns bags with whatever is inside them, and you put them in guests' rooms unchecked: unsafe consumption (API10). We reuse the hotel throughout.
Three common misunderstandings, up front
- "We use JWTs, so authorization is handled." A token says who the caller is and maybe which roles it has; it says nothing about whether order 1002 belongs to them. The API1 page is explicit: "Comparing the user ID of the current session (e.g. by extracting it from the JWT token) with the vulnerable ID parameter isn't a sufficient solution to solve Broken Object Level Authorization (BOLA). This approach could address only a small subset of cases."
- "Our ids are UUIDs, so nobody can guess them." Ids leak in URLs, logs, shared links, e-mails and other API responses. OWASP recommends random ids as an extra layer, and RFC 9562 warns that implementations "SHOULD NOT assume that UUIDs are hard to guess" and "MUST NOT be used as security capabilities (identifiers whose mere possession grants access)."
- "Rate limiting solves bots." A per-IP limit stops one laptop; the API6 scenario runs "distributed across different IP addresses and locations" and each request is valid. Business-flow protection decides how much of a flow one person, device or account cluster may consume, which is a product decision before it is a technical one.
Where it comes from
- OWASP API Security Project. The first edition appeared in 2019 (API1:2019 Broken Object Level Authorization through API10:2019 Insufficient Logging & Monitoring). The 2023 release notes call 2023 "the second edition of the OWASP API Security Top 10 edition, exactly four years after its first release."
- Methodology. A public Call for Data "ran from September 1st and November 30th, 2022"; the release notes admit "no data was contributed", so the list was built from the team's experience, specialist review and community feedback. Incident data from bug bounty platforms and public reports between 2019 and 2022 steered the direction. The risk section says: "Since this edition is not data-driven, prevalence results from a consensus among the team members."
- Risk rating. "The OWASP Risk Rating Methodology was used to do the risk analysis." The scale (Easy 3, Average 2, Difficult 1; Widespread, Common, Difficult; Severe, Moderate, Minor) is the table in Everything in one minute. OWASP adds that the rating "does not take into account the actual impact on your business" and that the Top 10 is "not to do this risk analysis for you".
- What is new. The release notes list four moves: the BOPLA merger, more emphasis on resource consumption, a new category for sensitive business flows "to address new threats, including most of those that can be mitigated using rate limiting", and Unsafe Consumption of APIs because "attackers have started looking for a target's integrated services to compromise those, instead of hitting the APIs of their target directly."
- NIST SP 800-228, Guidelines for API Protection for Cloud-Native Systems (published June 2025, updated March 13, 2026), puts the inventory problem in government language: "The enterprise estate cannot be protected without an accurate API inventory". It defines "Rogue or shadow APIs" as APIs "defined for internal use (e.g., debugging, testing, ad hoc solutions to business problems)" that "often bypass standard security review practices", and "Zombie or deprecated APIs" as APIs that "have been replaced or superseded by newer systems but have not yet been entirely removed". Its REC-API-4.2 asks for an "Organizational API inventory of all internal (including shadow and Zombie APIs) and external APIs". (The CSRC page of the original June 2025 text says "Withdrawn on March 13, 2026. Superseded by SP 800-228"; cite the update.)
- Relationship to the web list. Several API risks have a web twin: API1 is the API form of IDOR (A01:2021), API7 is A10:2021 SSRF, API8 is A05:2021. The OWASP Top 10 chapter owns those mechanics; this page owns the API angle.
- Version note. This page quotes the 2023 pages at owasp.org/API-Security/editions/2023/en/ as read on 2026-11-29. A 2027 edition may reorder the list; the mechanisms do not change.
The concept catalogue
API1 Broken Object Level Authorization (BOLA): the object-level authorization check Must-know
In plain words: The API checks your key card at the front door and then opens any room number you type. You are logged in, the endpoint is one you may call, but the object behind the id is somebody else's.
Common misunderstanding: "BOLA is the same as a missing login check." No: in BOLA the caller should reach the endpoint. OWASP draws the line exactly: "In the case of BOLA, it's by design that the user will have access to the vulnerable API endpoint/function. The violation happens at the object level, by manipulating the ID. If an attacker manages to access an API endpoint/function they should not have access to - this is a case of Broken Function Level Authorization (BFLA) rather than BOLA." The second misunderstanding is that comparing sub from the JWT with a user_id in the path fixes it; it covers only the /users/{id} shape, not /orders/{id}, /shops/{shopName}/revenue_data.json or a VIN.
Definition: "Object level authorization is an access control mechanism that is usually implemented at the code level to validate that a user can only access the objects that they should have permissions to access." OWASP's rule: "Every API endpoint that receives an ID of an object, and performs any action on the object, should implement object-level authorization checks." IDOR (Insecure Direct Object Reference) is the older web name for the same failure; the OWASP IDOR cheat sheet lists its "three ingredients": an object, a reference to it ("an ID, UUID, account number, token or slug"), and "A missing object-level authorization check". CWE references: CWE-639 Authorization Bypass Through User-Controlled Key and CWE-285 Improper Authorization; CWE-862 Missing Authorization and CWE-863 Incorrect Authorization are the related weakness classes MITRE uses (not listed on the OWASP page).
Ana (user 41, tenant 7) API (authenticated, no object check)
1 GET /api/orders/1001 Bearer tok-ana -> 200 {"id":1001,"owner_id":41,...} hers
2 GET /api/orders/1002 Bearer tok-ana -> 200 {"id":1002,"owner_id":57,...} BOLA: Bob's order
3 for id in 1000..99999: GET /api/orders/$id -> every order of every customer enumeration
4 DELETE /api/orders/1003 (same handler pattern) -> 204 data loss
fix: SELECT ... WHERE id = $1 AND tenant_id = $2 AND owner_id = $3, then policy check
5 GET /api/orders/1002 Bearer tok-ana -> 404 (identical to /orders/999999) + authz_fail log lineReal scenarios (the first three are OWASP's own): an e-commerce host exposes /shops/{shopName}/revenue_data.json, and a script replaces the shop name with every name from another endpoint, reading "the sales data of thousands of e-commerce stores"; a car maker's mobile API starts engines and unlocks doors by VIN without checking that the VIN belongs to the caller; a document service deletes any report id passed to a GraphQL deleteReports mutation; a multi-tenant SaaS where tenant_id comes from the request body; a support tool that shows any user's tickets because "support can see everything" was implemented as "anyone with the support URL"; a presigned-URL endpoint that signs whatever object key the client names.
| Where the id hides | Example | Detection | Fix |
|---|---|---|---|
| Path | GET /orders/{id} | Two test users, swap ids | Scoped query + policy |
| Query string | ?account=123 | Replay with B's token | Same; prefer /me/... routes |
| Body | {"user_id": 12345} in an update | Diff body ids against token | Take the subject from the session, ignore body ids |
| Header | X-Tenant-Id: 8 | Change header | Tenant from the authenticated principal only |
| GraphQL | node(id: "T3JkZXI6MTAwMg=="), batched mutations | Decode global ids, replay | Authorize in every resolver, not in the gateway |
| File keys | /files/invoices/2026/1002.pdf | Guess names | Map public id → stored key after the check |
| Nested resources | /shops/7/orders/1002 where 1002 is in shop 8 | Mix parent and child ids | Scope the child by the parent (scopeBindings) |
What prevents it (OWASP's "How To Prevent", in order): "Implement a proper authorization mechanism that relies on the user policies and hierarchy"; use it "in every function that uses an input from the client to access a record in the database"; "Prefer the use of random and unpredictable values as GUIDs for records' IDs"; "Write tests to evaluate the vulnerability of the authorization mechanism. Do not deploy changes that make the tests fail."
| Layer | Go | Laravel 13 | Database |
|---|---|---|---|
| Who is calling | principal.From(r.Context()) set by auth middleware | $request->user() from auth:sanctum | SET LOCAL app.tenant_id per transaction |
| Load only what the caller may see | GetScoped(id, tenant, owner) | Order::where('tenant_id', …)->findOrFail($id), $user->orders()->findOrFail($id) | WHERE id = $1 AND tenant_id = $2 |
| Decide | CanView(u, o) policy function | OrderPolicy::view + Gate::authorize('view', $order) | Row-level security policy (PostgreSQL) |
| Respond | 404 for foreign and missing alike | Response::denyAsNotFound() | n/a |
| Record | slog authz_fail | Gate::after → Log::warning('authz_fail') | pgAudit (optional) |
Fix / how to use it: SQL first: put the owner and the tenant in the WHERE (see Solving: BOLA). Go: a context-based ownership check in the handler, with the caller from the context and never from the request (Go). Laravel: Laravel Policies plus a tenant-scoped query (Laravel). The general authorization models are in Authorization models.
UUID vs sequential ids, and enumeration Important
In plain words: Sequential ids turn a BOLA into a for loop. Random ids make the loop useless, but they do not make the door locked.
Common misunderstanding: "Switching to UUIDs fixes BOLA." It removes enumeration, the cheap way to find targets. It does nothing against an id that leaked: in an e-mail link, a shared screenshot, a referrer header, a log, another API response (the OWASP API3 scenario shows a "report user" mutation returning the reported user's id), or a partner integration. The OWASP IDOR cheat sheet: "even with complex identifiers, access control checks are essential."
Definition: Enumeration is discovering valid object ids by trying them in order or by pattern. UUID version 4 is 122 random bits; UUID version 7 (RFC 9562) puts a millisecond timestamp in the first 48 bits and random bits after it, so it sorts by time and indexes well while staying hard to guess, provided the random part comes from a CSPRNG (RFC 9562 §6.9: implementations "SHOULD utilize a cryptographically secure pseudorandom number generator"). RFC 9562 §8: "Implementations SHOULD NOT assume that UUIDs are hard to guess."
1 ids 1001, 1002, 1003 ... attacker: for i in 1..N -> N requests find every object
2 ids UUIDv4 / UUIDv7 attacker: cannot iterate; needs a leaked id
3 leaked UUID (email, log) attacker: GET /orders/0193f0f2-... -> still 200 without the object check
4 with the object check -> 404 for every id that is not the caller's, sequential or not| Id scheme | Enumeration | Index locality | Leaks | Use |
|---|---|---|---|---|
bigint identity / AUTO_INCREMENT | Trivial | Excellent | Volume (order 1002 → ~1000 orders) | Internal key; never the only defence |
| UUIDv4 | Infeasible | Poor (random inserts) | Nothing | Public id column |
| UUIDv7 | Infeasible for the random part | Good (time-ordered) | Creation time | Public id and primary key |
| ULID | Same as UUIDv7 | Good | Creation time | Same, non-RFC format |
| Hashids / encrypted ints | Reversible if the key leaks | n/a | Sequence after decode | OWASP: "Avoid encrypting identifiers" |
Id generation at scale (Snowflake, ULID, UUIDv7 internals) is in ID generation.
API2 Broken Authentication Important
In plain words: The lock on the front door is weak: guessable passwords, unlimited guesses, tokens in URLs, or a stolen token is enough to take the whole account.
Common misunderstanding: "OAuth is our authentication." The API2 page: "OAuth is not authentication, and neither are API keys." And "API keys should not be used for user authentication. They should only be used for API clients authentication."
Definition and the one paragraph this page owns: API2 covers credential stuffing and brute force without lockout or captcha (including GraphQL batching to bypass "three requests are allowed per minute"), weak passwords, tokens and passwords in URLs, unsigned or alg: none JWTs, unchecked expiry, weak hashing, and, for microservices, services reachable "without authentication". The API-specific lesson in OWASP's scenario 2 is re-authentication: an e-mail change accepted on a bearer token alone lets a token thief move the account to their mailbox and run "forgot password". "Require re-authentication for sensitive operations (e.g. changing the account owner email address/2FA phone number)", and treat "Credential recovery/forgot password endpoints" as login endpoints for rate limiting and lockout. The Go authn and Laravel ChangeEmailRequest snippets show that one fix; passwords, MFA, sessions and lockout are in Authentication, token validation in JWT deep dive, flows in OAuth 2.0, OIDC and SSO. CWE references: CWE-204 Observable Response Discrepancy, CWE-307 Improper Restriction of Excessive Authentication Attempts.
API3 Broken Object Property Level Authorization (BOPLA): excessive data exposure and mass assignment Must-know
In plain words: You may see the guest list, not the guests' passport numbers; you may change your own pillow preference, not your room rate. BOPLA is the server forgetting that authorization goes down to the field: on the way out (it sends fields you should not read) and on the way in (it accepts fields you should not write).
Common misunderstanding: "The client only shows name and avatar, so the rest of the JSON does not matter." The response is the data; anyone with a proxy reads all of it. The 2019 text was blunt: "Never rely on the client side to filter sensitive data." The write-side twin: "We validate the fields we expect." Validation of expected fields does not reject unexpected ones; a framework that binds the whole body still writes role.
Definition: "When allowing a user to access an object using an API endpoint, it is important to validate that the user has access to the specific object properties they are trying to access." An endpoint is vulnerable if it "exposes properties of an object that are considered sensitive and should not be read by the user. (previously named: "Excessive Data Exposure")" or "allows a user to change, add/or delete the value of a sensitive object's property which the user should not be able to access (previously named: "Mass Assignment")". The OWASP Mass Assignment cheat sheet lists the framework names: "Mass Assignment: Ruby on Rails, NodeJS", "Autobinding: Spring MVC, ASP NET MVC", "Object injection: PHP". CWE references: CWE-213 Exposure of Sensitive Information Due to Incompatible Policies and CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes; CWE-1321 (prototype pollution) is the JavaScript cousin of CWE-915, related but not on the OWASP page.
Read side (excessive data exposure) Write side (mass assignment)
1 GET /api/users/313 (Ana looks at Sam) PATCH /api/me {"name":"Sam"} normal
2 -> {"id":313,"name":"Sam","password_hash":"$argon2id..", PATCH /api/me {"name":"Sam","role":"admin","blocked":false}
"mfa_secret":"JBSW..","recent_location":"52.37,4.89"} -> 200, role=admin, blocked=false escalation + unblock
3 app shows "Sam" only; the proxy shows everything host replays approve_booking + "total_stay_price":"$1,000,000"
fix: response DTO = allow-list of properties fix: input DTO / $fillable / prohibited rules
4 -> {"id":313,"name":"Sam"} -> 422 role prohibited (or 400 unknown field)Real scenarios (OWASP's three, then common ones): a dating app's reportUser mutation returns the reported user's fullName and recentLocation; a rental marketplace's host adds "total_stay_price": "$1,000,000" to an approve-booking call; a video platform user sends "blocked": false with a description update and unblocks their own censored video; a user list for an autocomplete returns e-mail, phone and last login; an orders response includes internal_margin and fraud_score; a PUT /me accepts email_verified_at, tenant_id or balance; GraphQL introspection plus a permissive schema let clients request any field.
| Side | Wrong tool | Right tool (Go) | Right tool (Laravel 13) |
|---|---|---|---|
| Read | json.Marshal(user), $user->toArray(), "to_json() and to_string()" (OWASP) | Response DTO struct per audience (PublicUser, SelfUser) | JsonResource (UserResource) with when(); #[Hidden] as a backstop |
| Write | json.Decode(&user), $model->update($request->all()), #[Unguarded] / $guarded = [] | Input DTO + DisallowUnknownFields + explicit copy | Form Request rules + validated() / safe()->only(), #[Fillable] (12.x and older: protected $fillable) |
| Both | Block-lists ($guarded = ['role'], json:"-" only) | Allow-list of properties | Allow-list; OWASP: "Do not rely on a block-list as the sole protection" |
| Extra layer | Trust the client to filter | Schema-based response validation in CI/tests | assertExactJson in feature tests |
OWASP's prevention list maps one-to-one: "cherry-pick specific object properties you specifically want to return"; "avoid using functions that automatically bind a client's input into code variables, internal objects, or object properties"; "Allow changes only to the object's properties that should be updated by the client"; "Implement a schema-based response validation mechanism as an extra layer of security"; "Keep returned data structures to the bare minimum". The cheat sheet adds the key sentence: "DTOs and field allowlists restrict writable properties; they do not replace authorization for the requested object and operation" (API3 does not replace API1).
$fillable vs $guarded: in Laravel 12 and older code the allow-list is protected $fillable = ['name', 'email']; and the block-list is protected $guarded = ['role']; ($guarded = [] unguards everything). Laravel 13 documents the same mechanism as class attributes, #[Fillable([...])], #[Guarded([...])] and #[Unguarded], and states that "all Eloquent models are protected against mass assignment vulnerabilities by default." Prefer $fillable/#[Fillable]; $guarded fails open when someone adds a column.
API4 Unrestricted Resource Consumption Important
In plain words: One request can be made to cost a lot: a page of ten million rows, a thousand mutations in one batch, an 18 GB download, or ten thousand SMS at your expense.
Common misunderstanding: "We have a rate limit, so we are covered." A limit on requests does not limit work per request; OWASP's GraphQL scenario bypasses "traditional rate limiting" by sending 999 uploadPic mutations in one request.
Definition and the one paragraph this page owns: An API is vulnerable "if at least one of the following limits is missing or set inappropriately": execution timeouts, maximum allocable memory, file descriptors, processes, upload size, "Number of operations to perform in a single API client request (e.g. GraphQL batching)", "Number of records per page", and "Third-party service providers' spending limit". The fixes in the Go resource and Laravel OrderController::index snippets are the per-request caps (page size clamped to 100, body ≤ 32 KiB, batch ≤ 25 operations) and the spending side: "Configure spending limits for all service providers/API integrations. When setting spending limits is not possible, billing alerts should be configured instead." Per-operation throttles ("validate an OTP, or request password recovery") are rate limits per user and per resource; algorithms (token bucket, sliding window, distributed limits) are in Rate limiting. CWE references: CWE-770, CWE-400, CWE-799.
API5 Broken Function Level Authorization (BFLA): admin endpoints and method tampering Must-know
In plain words: A guest's key card opens the staff corridor because nobody programmed the corridor door; the guest only had to find it. In APIs the corridor is /api/admin/..., POST /api/invites/new, or simply DELETE on a URL where you were allowed GET.
Common misunderstanding: "Admin endpoints live under /admin, and the gateway protects /admin/*." OWASP: "Don't assume that an API endpoint is regular or administrative only based on the URL path", and "it's very common to find these administrative endpoints under other relative paths together with regular endpoints, like /api/users." Another: "The admin console is the only client that calls it." The JavaScript bundle and the mobile app binary list every URL.
Definition: BFLA is a missing or wrong check on which functions a caller may invoke, as opposed to which objects (API1). OWASP's questions: "Can a regular user access administrative endpoints?"; can a user act "by simply changing the HTTP method (e.g. from GET to DELETE)?"; can group X reach group Y's function "by simply guessing the endpoint URL and parameters (e.g. /api/v1/users/export_all)?". CWE reference: CWE-285 Improper Authorization.
Mallory (role=user) API (authenticated, no function check)
1 GET /api/invites/{guid} -> 200 {"email":..., "role":"user"} allowed
2 POST /api/invites/new {"email":"m@evil","role":"admin"} -> 201 BFLA: admin function
3 (accepts own invite, logs in as admin)
4 GET /api/admin/v1/users/all -> 200 every user BFLA: guessed URL
5 DELETE /api/users/2 -> 204 BFLA: method change
fix: route table where each route names roles; deny by default; 403 + authz_fail
6 POST /api/invites/new -> 403 GET /api/admin/v1/users/all -> 403Real scenarios: OWASP's invite flow (a user creates an admin invite) and the guessed GET /api/admin/v1/users/all; a mobile app's "export CSV" endpoint shipped for an internal tool; PUT /api/users/{id}/role registered by a generator next to the user's own PUT /api/users/{id}; a "support impersonation" endpoint protected only by not being linked; a feature flag that hides a button but not the route; a GraphQL schema exposing deleteUser to every authenticated client.
| Pattern | Why it fails | Fix |
|---|---|---|
| Check in the UI only | APIs are called directly | Server-side check on the function |
Path-prefix rule at the gateway (/admin/*) | Admin functions live elsewhere too | Policy per route, in the service |
Same handler for GET and DELETE, check in one branch | The other method is unchecked | Method in the route pattern (DELETE /api/users/{id}); one policy per method |
Opt-in checks ("add ->middleware('can:...') when needed") | The one forgotten route is the breach | Deny by default: router refuses a route without a policy |
| Roles from the token without re-checking server state | Revoked admin still admin until expiry | Short-lived tokens, server-side role lookup for admin functions |
OWASP's prevention: the enforcement mechanism "should deny all access by default, requiring explicit grants to specific roles for access to every function"; "all of your administrative controllers inherit from an administrative abstract controller that implements authorization checks"; and admin functions inside regular controllers check the role too. In Go that is the bfla.NewMux route table; in Laravel a can:admin route group plus #[Middleware('can:admin')] on the controller so the check moves with the class.
API6 Unrestricted Access to Sensitive Business Flows: bot abuse and business logic abuse Must-know
In plain words: Every request is valid, authenticated and correctly processed, and the business still loses: a script buys the whole stock, books every table, farms every referral bonus. Nothing is broken except the assumption that a human is clicking.
Common misunderstanding: "That is a fraud team's problem, not an API vulnerability." OWASP lists it as an API risk precisely because the API exposes the flow "without compensating for how the functionality could harm the business if used excessively in an automated manner. This doesn't necessarily come from implementation bugs." Second: "A per-IP rate limit handles it." The console scenario's bot runs "distributed across different IP addresses and locations".
Definition: "An API Endpoint is vulnerable if it exposes a sensitive business flow, without appropriately restricting the access to it." OWASP's examples: purchasing ("buy all the stock of a high-demand item at once and resell for a higher price (scalping)"), creating comments or posts (spam), making reservations ("reserve all the available time slots"). The risk is relative: "creation of posts by a script might be considered as a risk of spam by one social network, but encouraged by another". The page lists no CWE; the matching catalogue is OWASP's Automated Threats to Web Applications (OAT), whose entries include OAT-005 Scalping ("limited availability of sought-after or exclusive goods or services") and OAT-013 Sniping (the "last minute" variant).
Bot (one operator, 300 accounts, residential proxies) Shop API
1 09:00:00.000 POST /cart {"sku":"console-x"} x300 -> 201 valid
2 09:00:00.180 POST /checkout {"sku":"console-x"} x300 -> 204 x100, 409 sold out every unit gone in 180 ms
3 09:00:05 humans click "Buy" -> 409 sold out
4 09:10 listings appear on a resale site at 3x
fix: per user 2, per device 2, per SKU 300/min, cart->checkout >= 1 s, device id required, challenge on doubt
5 09:00:00.180 checkout x300 -> 428 challenge (too fast), 429 (device cap)Real scenarios (OWASP's three, then more): console scalping on launch day; an airline with free cancellation where one user books 90% of a flight, cancels days before departure and buys the discounted seat; a ride-sharing referral programme farmed by scripted sign-ups; ticket drops; restaurant or clinic slot hoarding; gift-card balance checking (card cracking); coupon and free-trial abuse; review and vote stuffing; inventory denial (add to cart and hold).
| Layer | Mechanism | Strength | Cost |
|---|---|---|---|
| Business | Name the sensitive flows and their acceptable use per person ("2 per customer per drop") | Turns a vague fear into a testable rule | Product decision, needs an owner |
| Identity | Rate limits per user and per resource (per account per SKU, per SKU overall) | Stops one account and protects the scarce resource | Account farms bypass per-user limits |
| Device | Device fingerprinting: "denying service to unexpected client devices (e.g headless browsers)" | Raises the attacker's cost | Privacy rules; spoofable |
| Human detection | CAPTCHA, "advanced biometric solutions (e.g. typing patterns)" | Strong against cheap bots | UX friction; solving farms |
| Behaviour | "Non-human patterns" such as add-to-cart to purchase "in less than one second" | Cheap, server-side | Needs server-side timestamps |
| Network | "Consider blocking IP addresses of Tor exit nodes and well-known proxies" | Cuts the cheapest traffic | Residential proxies remain |
| Machine APIs | "Secure and limit access to APIs that are consumed directly by machines (such as developer and B2B APIs)" | Closes the side door | Partner friction |
| Design | Queue or lottery for drops; deposit for reservations; cancellation fees | Removes the incentive | Business change |
Fix / how to use it: the Go flows.Guard and the Laravel CheckoutController + throttle:checkout limiter implement the identity, device and behaviour layers; the vulnerable versions are correct, race-free code with no business rule, which is the point. The caps themselves must be race-free too: "count the user's purchases, then insert" lets two parallel requests both read 1 and both buy (a plain SELECT takes no lock, and PostgreSQL refuses SELECT count(*) ... FOR UPDATE), so the Laravel controller keeps one counter row per (SKU, user) and per (SKU, device) and takes a unit with a single conditional UPDATE ... SET count = count + 1 WHERE count < cap; zero affected rows means the cap is reached, and the surrounding transaction rolls back whatever was already taken. Where counters must be shared across instances (Redis), see Rate limiting.
API7 Server Side Request Forgery Good to know
In plain words: The API fetches a URL for you (a profile picture, a webhook test) and you give it an address inside the hotel's staff network.
Common misunderstanding: "An allow-list of hostnames is enough." DNS rebinding and redirects defeat name checks; the IP check has to happen when the socket connects.
Definition and the one paragraph this page owns: "Server-Side Request Forgery (SSRF) flaws occur when an API is fetching a remote resource without validating the user-supplied URL." OWASP says APIs make it "More common" (webhooks, file fetching from URLs, custom SSO, URL previews) and "More dangerous" (cloud, Kubernetes and Docker management channels "over HTTP on predictable, well-known paths"), and that "The SSRF risk can not always be completely eliminated." Its scenarios: {"picture_url": "localhost:8080"} used for port scanning by response time, and a webhook "send test request" that returns the response of an internal URL. Prevention: "Isolate the resource fetching mechanism in your network" and allow-lists of remote origins, "URL schemes and ports", and media types. The Go ssrf.Check and the Laravel RemoteImageFetcher (behind POST /me/avatar/import) show the URL-level allow-list (https, port 443, no userinfo, no IP literals, allow-listed hosts, no redirects); the connect-time IP check (net.Dialer.Control), cloud metadata (IMDSv2) and egress design are in OWASP Top 10: SSRF. CWE reference: CWE-918.
API8 Security Misconfiguration Good to know
In plain words: The hotel left the fire door propped open and the master-key list on the reception desk: defaults, debug output, open CORS, plain HTTP inside the network.
Common misunderstanding: "Internal APIs do not need TLS." OWASP: all communications "from the client to the API server and any downstream/upstream components" over TLS, "regardless of whether it is an internal or public-facing API."
Definition and the one paragraph this page owns: API8 lists missing hardening "across any part of the API stack", missing patches, "Unnecessary features are enabled (e.g. HTTP verbs, logging features)", inconsistent request processing "in the HTTP server chain" (request smuggling), missing TLS, missing cache-control, a "Cross-Origin Resource Sharing (CORS) policy is missing or improperly set", and "Error messages include stack traces". The API-specific fixes in the Go misconfig package and the Laravel config/cors.php + bootstrap/app.php render closure: an exact CORS origin allow-list (with Vary: Origin in Go), an RFC 9457 application/problem+json error body carrying only a correlation id, route patterns with the method so other verbs get 405, and "define and enforce all API response payload schemas, including error responses". Headers, APP_DEBUG, XXE and hardening are in OWASP Top 10: A05 and the API security hardening checklist. CWE references: CWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942.
API9 Improper Inventory Management: API inventory, shadow API, zombie API Must-know
In plain words: You cannot lock doors you do not know exist. A beta host, a forgotten /v1, a debug route, a partner endpoint that shares more than it should: each is an entrance outside the security review.
Common misunderstanding: "Our gateway has the rate limiter, so every API has it." OWASP's first scenario is exactly this: the limiter lived "in a separate component between the client and the official API (api.socialnetwork.owasp.org)", and "beta.api.socialnetwork.owasp.org" ran the same API without it, so a researcher brute-forced "the 6 digit token" and reset any password. Second: "Inventory means a list of URLs." OWASP's inventory covers hosts, environments, audiences, versions and data flows to third parties.
Definition: OWASP describes two blindspots. A "documentation blindspot": the purpose of a host is unclear (which environment, who should have network access, "Which API version is running?"), documentation is missing or stale, "There is no retirement plan for each API version", or "The host's inventory is missing or outdated". A "data flow blindspot": a "sensitive data flow" to a third party without "a business justification or approval", without "inventory or visibility of the flow", or without knowing "which type of sensitive data is shared". NIST SP 800-228 names the two classic results: shadow API (undocumented, outside review) and zombie API (superseded, not removed). CWE reference: the OWASP page cites "CWE-1059: Incomplete Documentation"; MITRE's current title for CWE-1059 is Insufficient Technical Documentation.
Researcher Estate
1 dig api.socialnetwork.example / certificate transparency -> api., beta.api., v1.api., staging-api.
2 POST api./reset {"code":"000000".."999999"} -> 429 after 5 tries (gateway limiter)
3 POST beta.api./reset {"code":"000000".."999999"} -> no limiter; code found in minutes
4 GET v1.api./users/me -> old response shape with mfa_secret (zombie)
fix: inventory every host+version+owner; same protection on every exposed version; sunset v1; delete beta
5 GET v1.api./users/me (after sunset) -> 410 Gone, Deprecation/Sunset headers before thatReal scenarios: OWASP's beta host without the limiter; OWASP's second scenario, a social network whose data flow to third-party apps exposed friends' data, so that "consent of 270,000 users" yielded "the private information of 50,000,000 users"; a /v1 kept for one old mobile client that still returns password_reset_token; a Kubernetes Service of type LoadBalancer created for a demo; a GraphQL endpoint with introspection on in production; a partner-only endpoint that is also on the public gateway.
| Inventory field | Why | Where it lives |
|---|---|---|
| Host and environment | "production, staging, test, development" | Service catalogue, DNS, cloud tags |
| Audience | "public, internal, partners" | OpenAPI x-audience, gateway route config |
| Version and lifecycle | Deprecation date, sunset date, successor | OpenAPI deprecated: true + x-sunset; Deprecation/Sunset headers |
| Owner | Who answers the incident | x-owner, service catalogue |
| Operations | Every path, method, parameter, request and response | OpenAPI document generated in CI |
| Auth, errors, limits, CORS | OWASP: "authentication, errors, redirects, rate limiting, cross-origin resource sharing (CORS) policy" | OpenAPI securitySchemes + gateway policy |
| Integrated services and data flows | "their role in the system, what data is exchanged (data flow), and their sensitivity" | Data-flow register, DPA records |
| Runtime facts | NIST: "service instances, instance IP addresses, runtime service ID, traffic volume" | Gateway and mesh telemetry |
OpenAPI as inventory: OWASP asks to "Generate documentation automatically by adopting open standards. Include the documentation build in your CI/CD pipeline." The OpenAPI 3.1 Operation Object has a deprecated field that "Declares this operation to be deprecated. Consumers SHOULD refrain from usage of the declared operation." Make the OpenAPI document the source of truth, then make the build fail when code and document disagree (the Go inventory.Mount refuses a shadow route; in Laravel, CI diffs php artisan route:list --json against the spec).
Versioning and deprecation: announce with Deprecation: @<unix-time> (RFC 9745, which signals that a resource "will be or has been deprecated") and Sunset: <HTTP-date> (RFC 8594, a URI "is likely to become unresponsive at a specified point in the future"), link the successor, apply every new security fix to all exposed versions or retire the old one ("perform a risk analysis to inform the mitigation actions required for the older versions"), answer 410 Gone after the sunset, and then remove the route and the host. Version strategy (URI vs header, compatibility rules) is in API versioning. OWASP also says: "Avoid using production data with non-production API deployments" and "Make API documentation available only to those authorized to use the API."
API10 Unsafe Consumption of APIs: third-party API trust Must-know
In plain words: You check every guest's bag at the door but accept the laundry company's bags unopened. Data from a partner API is input from a stranger who happens to have a contract with you.
Common misunderstanding: "It is a well-known provider, so the data is clean." OWASP: "Developers tend to trust data received from third-party APIs more than user input. This is especially true for APIs offered by well-known companies." A provider can be breached, buggy, or simply store what its own users typed, which is how a SQL payload arrives through an address-enrichment service.
Definition: The API "might be vulnerable if" it "Interacts with other APIs over an unencrypted channel"; "Does not properly validate and sanitize data gathered from other APIs prior to processing it or passing it to downstream components"; "Blindly follows redirections"; "Does not limit the number of resources available to process third-party services responses"; "Does not implement timeouts for interactions with third-party services". CWE references: CWE-20 Improper Input Validation, CWE-200 Exposure of Sensitive Information to an Unauthorized Actor, CWE-319 Cleartext Transmission of Sensitive Information.
Your API Partner (compromised) attacker.com
1 POST https://partner/store_phr_record
{"genome":"ACTAGTAG..."} -> 308 Permanent Redirect
Location: https://attacker.com/
2 client follows 308, re-sends the body ------------------------------------------> receives the genome
3 GET https://geo-partner/lookup?q=... -> {"name":"x'); DROP TABLE businesses;--"}
4 INSERT ... VALUES ('x'); DROP TABLE businesses;--') SQL injection via partner
fix: TLS + host allow-list, redirects off, timeouts, body cap, validate fields, bind parameters
5 308 -> ErrRedirect (nothing sent on); payload -> bound as $1 (stored as text) or rejected by validationReal scenarios (OWASP's three, then more): an address-enrichment provider used to plant an SQLi payload that executes in your database; a medical-data partner that, once compromised, answers 308 so your client replays sensitive data to the attacker; a git repository named '; drop db;-- that an integration puts into SQL; a payment provider's webhook body trusted without signature checks (see API keys, request signing and webhooks); an LLM or search API returning HTML rendered unescaped; a partner that returns a 2 GB body or never closes the connection; a shipping API whose tracking_url you then fetch (SSRF via the partner).
| Check | Go | Laravel 13 | Why |
|---|---|---|---|
| TLS only + host allow-list | checkEndpoint on the first hop, CheckRedirect on later hops | Http::baseUrl('https://...') | "Ensure all API interactions happen over a secure communication channel (TLS)" |
| Redirect allow-list | CheckRedirect returns an error off the list | withOptions(['allow_redirects' => false]), Http::globalOptions | "do not blindly follow redirects" |
| Timeouts | http.Client.Timeout, request context | connectTimeout(2), timeout(5) | Laravel's default is 30 s; Go's zero Timeout means none |
| Size cap (before buffering) | io.LimitReader(body, max+1) | withOptions(['stream' => true]), refuse a Content-Length above the cap, read $response->resource() up to the cap (BoundedBody) | Memory exhaustion; a check after $response->body() is too late |
| Status and type | 200 + application/json | status(), header('Content-Type') | Error pages parsed as data |
| Field validation | Business.Validate() with regexes and lengths | Validator::make($response->json(), [...]) | "Always validate and properly sanitize data received from integrated APIs" |
| Use as data | bound parameters ($1) | DB::insert('... ?', [...]) | Injection |
| Provider posture | n/a | n/a | "When evaluating service providers, assess their API security posture" |
Authorization middleware and policy objects: where each check lives Must-know
In plain words: Three questions, three places. "Is there a logged-in caller?" belongs in middleware. "May this caller call this function?" belongs on the route. "May this caller touch this object, this field?" needs the object, so it belongs in a policy object called by the handler, backed by a scoped query.
Common misunderstanding: "Put all authorization in one middleware." Middleware runs before the handler has loaded the object; it can check roles and scopes (API5) but not ownership (API1) or fields (API3). The reverse mistake is scattering if ($order->user_id !== $user->id) through controllers, where one copy is always missing. OWASP's API5 advice is "a consistent and easy-to-analyze authorization module that is invoked from all your business functions", and the Authorization cheat sheet wants checks "on every request, regardless of whether the request was initiated by an AJAX script, server-side, or any other source", with technology that allows "global, application-wide configuration rather than needing to be applied individually to every method or class".
Definition: Authorization middleware is a request filter that rejects calls before the handler (authentication, roles, OAuth scopes, tenant header consistency). A policy object is a class or function with one method per action (view, update, delete) that receives the caller and the object and returns allow or deny; Laravel Policies and the Gate are the framework form, a CanView(user, order) bool function is the Go form, and OPA/Cedar/OpenFGA are the externalised form (see Authorization models). A query scope is the database half: the object cannot be loaded unless it is in the caller's tenant.
1 request -> auth middleware (401 if no valid principal; principal into context)
2 -> route policy (403 if role/scope missing: API5)
3 -> handler loads object (scoped by tenant: foreign tenant = not found)
4 -> policy.view(user, obj) (404/403 if not owner/allowed: API1)
5 -> input DTO / Form Request (422/400 for prohibited or unknown properties: API3)
6 -> response DTO (only allow-listed properties leave: API3)
7 any deny -> authz_fail event (logged with user, action, resource, object id)| Concern | Middleware | Route policy | Policy object | Query scope | DTO |
|---|---|---|---|---|---|
| Authenticated? | yes | ||||
| Role / scope for the function (API5) | possible | yes | |||
| Ownership / tenant of the object (API1) | no | no | yes | yes | |
| Which properties may be read or written (API3) | no | no | partly (when) | yes | |
| Business-flow limits (API6) | limiter | limiter | flow rule | counts | |
| Testable in isolation | yes | yes | yes (unit) | yes (SQL) | yes |
Go handler authorization: Go has no framework policy layer; the idiom is a middleware that puts the principal into context.Context (principal.Middleware), a route table that wraps every handler with its function policy (bfla.NewMux), and plain policy functions called in the handler (bola.CanView). The context-based ownership check is "read the principal from r.Context(), load by id, call the policy, 404 on deny"; the id in the path is only ever a lookup key. Middleware composition in Go is in Middlewares; token validation in Go is in Authentication in Go.
Laravel: auth:sanctum (authentication), can:admin / ->can('update', 'post') route middleware or the Laravel 13 #[Middleware] and #[Authorize] controller attributes (function level), Gate::authorize('view', $order) inside the action with a Policy found by policy discovery (object level), Form Request authorize() + rules() (input), JsonResource (output). Gate::before can grant super-admins everything; use it sparingly because it also skips the object rules.
Logging and alerting for authorization failures Important
In plain words: A BOLA probe looks like a burst of 404s and 403s from one account walking ids. If you log those denials as security events and alert on the rate, you see the attack while it is still a probe.
Common misunderstanding: "We return 404 so nobody knows; we do not need to log it." The 404 is for the attacker; the log is for you. Logging every 404 is noise; log the denials your policy made (the object exists, the caller was refused).
Definition: The OWASP Logging Vocabulary cheat sheet defines authz_fail[:userid,resource] ("An attempt was made to access a resource which was unauthorized", level CRITICAL in its example), authz_change and authz_admin. Record who (user id, tenant, client id), what (ability, route, method), which object (type, id), outcome, and a request id; never the token or the body. Alert on rates: one user with more than N authz_fail in M minutes, or many users hitting one admin route.
1 09:14:02 authz_fail user=41 ability=view resource=Order object=1002 path=/api/v2/orders/1002
2 09:14:02 authz_fail user=41 ability=view resource=Order object=1003 ...
3 ... 120 lines in 60 s, object ids increasing by 1
4 alert: authz_fail rate user=41 > 20/min -> revoke tokens, open incident, check other tenants| Event | Source | Alert rule (starting point) |
|---|---|---|
authz_fail object-level (API1) | Policy deny | > 20 per user per minute; ids sequential |
authz_fail function-level (API5) | Route policy deny | Any on /admin from a non-admin more than 3 per hour |
| 422 on prohibited properties (API3) | Form Request / unknown-field decoder | > 5 per user per hour (probing for role) |
| 429 on sensitive flows (API6) | Flow limiter | Spike per SKU or per device cluster |
| 410 on retired versions (API9) | Lifecycle middleware | Any: a client still uses the zombie |
| Upstream rejected (API10) | Consumption client | Any: provider changed or compromised |
The 2019 list had API10:2019 Insufficient Logging & Monitoring; 2023 has no logging entry, and the API6 page still points to the 2019 text, so logging is now your job inside each risk. Pipeline, SIEM and incident handling are in Secure SDLC and incident response.
Beyond REST: GraphQL, gRPC and webhooks Good to know
In plain words: The same ten risks, different shapes. GraphQL puts many objects and fields behind one URL; gRPC hides methods in protobuf; webhooks make you the client of someone else's events.
Common misunderstanding: "GraphQL has one endpoint, so one authorization check at the endpoint is enough." Every resolver loads objects and fields; authorization belongs per resolver (object level) and per field (property level), and a batch of 1,000 operations in one request is one "request" to a per-request rate limiter (OWASP API2 and API4 scenarios).
| Risk | GraphQL | gRPC | Webhooks (you receive) |
|---|---|---|---|
| API1 | node(id:) and global ids; authorize in each resolver | Check in each method handler or an interceptor with object lookup | The event's object id must belong to the sender's account |
| API3 | Field-level auth; introspection reveals hidden fields | Response messages with internal fields | Do not store the whole payload as your model |
| API4 | Depth, complexity and batch limits (OWASP GraphQL cheat sheet) | Max message size, deadlines | Body size cap, async processing |
| API5 | Mutations exposed to all roles | Admin RPCs in the same service | n/a |
| API9 | Introspection on in production; old schema fields | Old proto packages still served | Unknown webhook URLs still active |
| API10 | Federated subgraphs trusted blindly | Upstream services trusted blindly | Verify signatures (HMAC), timestamps, replay windows |
Schema and resolver design are in GraphQL and gRPC; webhook signatures are in API keys, request signing and webhooks.
Mechanics
The exact knobs
| Knob | Where | Value used in this chapter |
|---|---|---|
ServeMux method patterns (GET /orders/{id}) | Go 1.22+ net/http | Method in every pattern; other methods get 405 |
r.PathValue("id") | Go 1.22+ | Lookup key only, never authority |
context.WithValue principal | Go context | Set once by auth middleware, read by every handler |
json.Decoder.DisallowUnknownFields | Go encoding/json | On for every input DTO (API3) |
http.MaxBytesReader | Go net/http | 8 KiB profile, 32 KiB batch (API4) |
| Page size clamp | both | default 20, max 100 |
| Batch operations per request | both | max 25 |
http.Client.Timeout | Go | 5 s for partners; zero means none (API10) |
http.Client.CheckRedirect | Go | error unless https + allow-listed host, max 3 hops |
io.LimitReader | Go | 64 KiB upstream body |
#[Fillable([...])] / protected $fillable | Laravel model | name, email only |
#[Hidden([...])] | Laravel model | password, remember_token, mfa_secret |
prohibited rule | Laravel Form Request | role, blocked, tenant_id |
Response::denyAsNotFound() | Laravel policy | foreign objects look missing |
Gate::define('admin', ...) + can:admin | Laravel | every admin route group and controller |
RateLimiter::for('checkout', ...) | Laravel | 5/min per user, 300/min per SKU |
Model::preventSilentlyDiscardingAttributes | Laravel | $this->app->isLocal() |
Http::globalOptions(['allow_redirects' => false]) | Laravel | all outgoing calls |
connectTimeout / timeout | Laravel HTTP client | 2 s / 5 s (default timeout 30 s) |
Deprecation / Sunset | response headers | @1782863999 / Thu, 31 Dec 2026 23:59:59 GMT |
OpenAPI deprecated, x-owner, x-sunset | spec | every operation has an owner; deprecated ones a sunset |
| Flow policy | Go flows.Policy / Laravel constants | 2 per user, 2 per device, ≥ 1 s cart-to-checkout |
Status codes and messages
| Status | Meaning in this chapter | Risk | Notes |
|---|---|---|---|
| 401 Unauthorized | No or invalid credentials | API2 | Set by auth middleware before any handler |
| 403 Forbidden | Function not allowed for this role | API5 | Laravel AuthorizationException; Gate::authorize throws it |
| 404 Not Found | Object missing or not yours | API1 | Same body for both, so ids cannot be confirmed |
| 405 Method Not Allowed | Method not registered for the path | API5, API8 | Go ServeMux returns it with an Allow header; OWASP REST cheat sheet: "Reject all requests not matching the allowlist with HTTP response code 405" |
| 400 Bad Request | Unknown property (json: unknown field "role") | API3 | Go input DTO with DisallowUnknownFields |
| 422 Unprocessable Content | The role field is prohibited. | API3 | Laravel's English message 'prohibited' => 'The :attribute field is prohibited.' (framework lang/en/validation.php) |
| 428 Precondition Required | Challenge (CAPTCHA, step-up) required | API6 | Used here for "too fast to be human" |
| 429 Too Many Requests | Flow or rate limit hit | API4, API6 | Laravel: "a response with a 429 HTTP status code will automatically be returned" by the throttle middleware |
| 409 Conflict | Sold out | API6 | Not a security event |
| 410 Gone | Version past its sunset | API9 | After weeks of Deprecation/Sunset headers |
| 413 Content Too Large | Body over the cap | API4 | http.MaxBytesError in Go |
500 with application/problem+json | Generic error with instance: urn:error:<id> | API8 | Detail only in the server log |
Risk → CWE → detection
CWE references as printed on each OWASP risk page (MITRE titles, from cwe.mitre.org), with the way each is found:
| Risk | CWE (OWASP's list) | Finds it well | Misses it |
|---|---|---|---|
| API1 | CWE-285 Improper Authorization; CWE-639 Authorization Bypass Through User-Controlled Key | Two-account replay (Burp Suite Autorize-style), authz unit tests, authz_fail alerts | SAST (needs domain knowledge) |
| API2 | CWE-204 Observable Response Discrepancy; CWE-307 Improper Restriction of Excessive Authentication Attempts | Login fuzzing, JWT test suites | Business re-auth rules |
| API3 | CWE-213 Exposure of Sensitive Information Due to Incompatible Policies; CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes | Response schema diff, property fuzzing ("Fuzzing is usually used to identify additional (hidden) properties") | Fields that look harmless |
| API4 | CWE-770, CWE-400 Uncontrolled Resource Consumption, CWE-799 Improper Control of Interaction Frequency | Load tests with large limit, batch fuzzing, cost alerts | Spend on third parties |
| API5 | CWE-285 | Role matrix tests: every route × every role | Routes not in the matrix |
| API6 | none listed | Product review of flows, bot-management telemetry | Code review alone |
| API7 | CWE-918 Server-Side Request Forgery | Out-of-band callbacks | Blind SSRF without OAST |
| API8 | CWE-2, CWE-16, CWE-209, CWE-319, CWE-388, CWE-444, CWE-942 | Config scanners, DAST baseline | Inconsistent proxies |
| API9 | CWE-1059 (OWASP: "Incomplete Documentation"; MITRE: Insufficient Technical Documentation) | DNS and certificate-transparency enumeration, spec vs route diff, traffic discovery | Data-flow blindspots |
| API10 | CWE-20 Improper Input Validation; CWE-200; CWE-319 | Contract tests with hostile fixtures, egress logs | Partner compromise |
What a defence costs
| Control | Cost per request (estimate) |
|---|---|
Scoped query (AND tenant_id = $2 AND owner_id = $3) | Nothing measurable with an index on (tenant_id, id) |
| Policy function call | Nanoseconds; Laravel policy resolution microseconds |
| Response DTO mapping | One struct copy or array build |
DisallowUnknownFields | None; it is a flag on the decoder |
| Role check in route table | One slice lookup |
| Flow guard (in memory) | A mutex and two map lookups; with Redis one round trip |
| Lifecycle headers | Two Header().Set calls |
| Upstream validation | A few regex matches on short strings |
authz_fail log line | One structured log write, only on deny |
These are back-of-the-envelope estimates from the operations involved, not benchmarks. None of them is a performance trade-off; the cost is in engineering discipline (every query scoped, every route with a policy, every shape a DTO).
Go
Example: vulnerable and fixed endpoints with tests
One stdlib-only module (module academy/owasp-api-security-top-10, go 1.24; the method-and-wildcard ServeMux patterns and Request.PathValue arrived in Go 1.22). Every package has a test that passes by observing the leak in the "before" code and then shows the "after" code closing it.
The principal in the context (authentication stub, shared by the handlers) and its test:
// Package principal carries the authenticated caller through context.Context.
// Authentication (who are you?) happens once, at the edge; every handler then
// reads the caller from the context for authorization (may you do this?).
// Real token validation lives in the JWT and OAuth chapters; this is a stub.
package principal
import (
"context"
"net/http"
"slices"
"strings"
)
// User is the caller as the server knows it. It never comes from the request
// body or a path parameter.
type User struct {
ID int64
TenantID int64
Roles []string
}
// HasRole reports whether the caller holds role r.
func (u User) HasRole(r string) bool { return slices.Contains(u.Roles, r) }
type ctxKey struct{}
// With returns a context that carries u.
func With(ctx context.Context, u User) context.Context {
return context.WithValue(ctx, ctxKey{}, u)
}
// From returns the caller stored by With, if any.
func From(ctx context.Context) (User, bool) {
u, ok := ctx.Value(ctxKey{}).(User)
return u, ok
}
// Lookup maps a bearer token to a user. Production code verifies a session
// or a signed token here.
type Lookup func(token string) (User, bool)
// Middleware rejects requests without a known bearer token (401) and stores
// the caller in the request context for the handlers behind it.
func Middleware(lookup Lookup) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tok, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !ok {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
u, ok := lookup(tok)
if !ok {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r.WithContext(With(r.Context(), u)))
})
}
}
// Static is a Lookup over a fixed token table, for tests and examples.
func Static(users map[string]User) Lookup {
return func(tok string) (User, bool) {
u, ok := users[tok]
return u, ok
}
}package principal
import (
"context"
"net/http"
"net/http/httptest"
"testing"
)
func TestWithFromRoundTrip(t *testing.T) {
if _, ok := From(context.Background()); ok {
t.Fatal("empty context must carry no principal")
}
u, ok := From(With(context.Background(), User{ID: 41, TenantID: 7, Roles: []string{"support"}}))
if !ok || u.ID != 41 || !u.HasRole("support") || u.HasRole("admin") {
t.Fatalf("round trip lost data: %+v %v", u, ok)
}
}
func TestMiddleware(t *testing.T) {
var seen User
h := Middleware(Static(map[string]User{"tok": {ID: 41}}))(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
seen, _ = From(r.Context())
}))
for header, want := range map[string]int{"": 401, "Basic abc": 401, "Bearer nope": 401, "Bearer tok": 200} {
req := httptest.NewRequest("GET", "/", nil)
if header != "" {
req.Header.Set("Authorization", header)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != want {
t.Fatalf("%q: want %d, got %d", header, want, rec.Code)
}
}
if seen.ID != 41 {
t.Fatalf("handler did not see the principal: %+v", seen)
}
}API1 BOLA: the store with an unscoped and a scoped lookup, the vulnerable handler, the fixed handler with the policy function and authz_fail log, and the test (Ana reads Bob's order and enumerates 3 orders; after the fix: 404 identical to a missing id, one log line):
// Package bola shows API1:2023 Broken Object Level Authorization: the caller
// is authenticated and allowed to call GET /orders/{id}, but the handler
// never asks whether this order belongs to this caller.
package bola
import "sync"
// Order is one stored object. OwnerID and TenantID are what the
// object-level authorization check compares against the caller.
type Order struct {
ID int64 `json:"id"`
OwnerID int64 `json:"owner_id"`
TenantID int64 `json:"tenant_id"`
Total int64 `json:"total_cents"`
}
// Store is an in-memory stand-in for the orders table.
type Store struct {
mu sync.RWMutex
byID map[int64]Order
}
// NewStore returns a store holding orders.
func NewStore(orders ...Order) *Store {
s := &Store{byID: make(map[int64]Order, len(orders))}
for _, o := range orders {
s.byID[o.ID] = o
}
return s
}
// Get is "SELECT ... FROM orders WHERE id = $1": no owner in the WHERE clause.
func (s *Store) Get(id int64) (Order, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
o, ok := s.byID[id]
return o, ok
}
// GetScoped is "SELECT ... WHERE id = $1 AND tenant_id = $2 AND owner_id = $3":
// the database cannot return a foreign row, whatever the handler forgets.
func (s *Store) GetScoped(id, tenantID, ownerID int64) (Order, bool) {
o, ok := s.Get(id)
if !ok || o.TenantID != tenantID || o.OwnerID != ownerID {
return Order{}, false
}
return o, true
}package bola
import (
"encoding/json"
"net/http"
"strconv"
)
// GetOrderBefore is authenticated (it sits behind principal.Middleware) but
// trusts the id in the path: any logged-in user can read any order by
// changing /orders/1001 to /orders/1002.
func GetOrderBefore(s *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
o, ok := s.Get(id)
if !ok {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(o)
}
}package bola
import (
"encoding/json"
"log/slog"
"net/http"
"strconv"
"academy/owasp-api-security-top-10/principal"
)
// CanView is the policy object for orders: one place that answers
// "may this caller see this order?". Tenant first, then ownership, then
// an explicit support role scoped to the same tenant.
func CanView(u principal.User, o Order) bool {
if o.TenantID != u.TenantID {
return false
}
return o.OwnerID == u.ID || u.HasRole("support")
}
// GetOrder performs the object-level authorization check on every request.
// The caller comes from the context (set by the auth middleware), never from
// the request. Foreign and missing orders get the same 404 so the response
// is not an existence oracle; foreign ones are logged as authz_fail.
func GetOrder(s *Store, log *slog.Logger) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
u, ok := principal.From(r.Context())
if !ok {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
if err != nil {
http.Error(w, "bad id", http.StatusBadRequest)
return
}
o, found := s.Get(id)
if !found || !CanView(u, o) {
if found {
log.Warn("authz_fail",
slog.Int64("user_id", u.ID),
slog.String("resource", "order"),
slog.Int64("object_id", id),
slog.String("path", r.URL.Path))
}
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(o)
}
}package bola
import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/owasp-api-security-top-10/principal"
)
var users = principal.Static(map[string]principal.User{
"tok-ana": {ID: 41, TenantID: 7},
"tok-bob": {ID: 57, TenantID: 7},
})
func store() *Store {
return NewStore(
Order{ID: 1001, OwnerID: 41, TenantID: 7, Total: 1999},
Order{ID: 1002, OwnerID: 57, TenantID: 7, Total: 250000},
Order{ID: 1003, OwnerID: 57, TenantID: 7, Total: 1200},
)
}
func server(h http.HandlerFunc) http.Handler {
mux := http.NewServeMux()
mux.Handle("GET /orders/{id}", h)
return principal.Middleware(users)(mux)
}
func get(t *testing.T, h http.Handler, path, tok string) (int, string) {
t.Helper()
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Header.Set("Authorization", "Bearer "+tok)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
b, _ := io.ReadAll(rec.Body)
return rec.Code, string(b)
}
func TestBeforeLeaksForeignOrder(t *testing.T) {
h := server(GetOrderBefore(store()))
code, body := get(t, h, "/orders/1002", "tok-ana")
if code != http.StatusOK || !strings.Contains(body, `"owner_id":57`) {
t.Fatalf("expected the vulnerable handler to return Bob's order to Ana, got %d %s", code, body)
}
// Sequential ids make enumeration a loop.
leaked := 0
for _, p := range []string{"/orders/1001", "/orders/1002", "/orders/1003", "/orders/1004"} {
if c, _ := get(t, h, p, "tok-ana"); c == http.StatusOK {
leaked++
}
}
if leaked != 3 {
t.Fatalf("expected 3 readable orders by enumeration, got %d", leaked)
}
}
func TestAfterDeniesAndLogs(t *testing.T) {
var logs bytes.Buffer
h := server(GetOrder(store(), slog.New(slog.NewJSONHandler(&logs, nil))))
if code, _ := get(t, h, "/orders/1001", "tok-ana"); code != http.StatusOK {
t.Fatalf("owner must read own order, got %d", code)
}
codeForeign, bodyForeign := get(t, h, "/orders/1002", "tok-ana")
codeMissing, bodyMissing := get(t, h, "/orders/9999", "tok-ana")
if codeForeign != http.StatusNotFound || codeForeign != codeMissing || bodyForeign != bodyMissing {
t.Fatalf("foreign and missing must look identical: %d %q vs %d %q", codeForeign, bodyForeign, codeMissing, bodyMissing)
}
if !strings.Contains(logs.String(), `"msg":"authz_fail"`) || !strings.Contains(logs.String(), `"object_id":1002`) {
t.Fatalf("expected an authz_fail log line, got %s", logs.String())
}
if strings.Contains(logs.String(), `"object_id":9999`) {
t.Fatal("a missing object is not an authorization failure")
}
if code, _ := get(t, h, "/orders/1002", "no-such-token"); code != http.StatusUnauthorized {
t.Fatalf("unknown token must be 401, got %d", code)
}
}
func TestScopedQuery(t *testing.T) {
s := store()
if _, ok := s.GetScoped(1002, 7, 41); ok {
t.Fatal("scoped lookup returned a foreign row")
}
if _, ok := s.GetScoped(1002, 7, 57); !ok {
t.Fatal("scoped lookup must return the owner's row")
}
}API3 BOPLA: the model, the whole-model serialise and bind, then response DTOs per audience and an input DTO with DisallowUnknownFields:
// Package bopla shows API3:2023 Broken Object Property Level Authorization,
// the merger of two 2019 risks: excessive data exposure (reading properties
// the caller must not see) and mass assignment (writing properties the
// caller must not set).
package bopla
// User is the persistence model. Several properties are server-owned or
// secret and must never be bound from, or written to, an API payload.
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PasswordHash string `json:"password_hash"`
MFASecret string `json:"mfa_secret"`
Role string `json:"role"`
Blocked bool `json:"blocked"`
RecentLocation string `json:"recent_location"`
}package bopla
import (
"encoding/json"
"net/http"
)
// ShowBefore serialises the whole model and relies on the client to hide
// what it should not display: password_hash, mfa_secret and
// recent_location travel to every caller.
func ShowBefore(w http.ResponseWriter, u User) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(u)
}
// UpdateBefore binds the request body onto the model: a client that adds
// "role":"admin" or "blocked":false to a profile update gets it.
func UpdateBefore(u *User, r *http.Request) error {
return json.NewDecoder(r.Body).Decode(u)
}package bopla
import (
"encoding/json"
"errors"
"net/http"
"net/mail"
"strings"
)
// PublicUser is the response DTO other users get: an allow-list of
// properties, so a new column on User is private until someone adds it here.
type PublicUser struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
// SelfUser is what the owner sees about themselves.
type SelfUser struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Role string `json:"role"`
}
// View picks the DTO by the relationship between viewer and subject. It is
// a property-level authorization decision, made on the server.
func View(subject User, viewerID int64) any {
if subject.ID == viewerID {
return SelfUser{ID: subject.ID, Name: subject.Name, Email: subject.Email, Role: subject.Role}
}
return PublicUser{ID: subject.ID, Name: subject.Name}
}
// Show writes the DTO chosen by View.
func Show(w http.ResponseWriter, subject User, viewerID int64) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(View(subject, viewerID))
}
// UpdateInput is the input DTO: the only properties a user may change.
// Pointers distinguish "absent" from "empty".
type UpdateInput struct {
Name *string `json:"name"`
Email *string `json:"email"`
}
// ErrInvalid covers unknown properties, oversize bodies and bad values.
var ErrInvalid = errors.New("bopla: invalid input")
// Update decodes into the input DTO with DisallowUnknownFields (a probe for
// "role" is a 400, not a silent success), validates every field into local
// values, and only then copies them: a rejected request changes nothing.
func Update(u *User, w http.ResponseWriter, r *http.Request) error {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8<<10))
dec.DisallowUnknownFields()
var in UpdateInput
if err := dec.Decode(&in); err != nil {
return errors.Join(ErrInvalid, err)
}
name, email := u.Name, u.Email
if in.Name != nil {
name = strings.TrimSpace(*in.Name)
if name == "" || len(name) > 100 {
return ErrInvalid
}
}
if in.Email != nil {
a, err := mail.ParseAddress(*in.Email)
if err != nil || a.Address != *in.Email {
return ErrInvalid
}
// Changing the e-mail also needs re-authentication (API2); see authn.
email = a.Address
}
u.Name, u.Email = name, email
return nil
}package bopla
import (
"errors"
"net/http/httptest"
"strings"
"testing"
)
func victim() User {
return User{ID: 313, Name: "Sam", Email: "sam@example.com", PasswordHash: "$argon2id$v=19$...",
MFASecret: "JBSWY3DPEHPK3PXP", Role: "user", Blocked: true, RecentLocation: "52.37,4.89"}
}
func TestBeforeExposesSecrets(t *testing.T) {
rec := httptest.NewRecorder()
ShowBefore(rec, victim())
for _, leak := range []string{"password_hash", "mfa_secret", "recent_location"} {
if !strings.Contains(rec.Body.String(), leak) {
t.Fatalf("expected the vulnerable handler to expose %s, got %s", leak, rec.Body.String())
}
}
}
func TestBeforeMassAssignment(t *testing.T) {
u := victim()
body := `{"name":"Sam","role":"admin","blocked":false}`
if err := UpdateBefore(&u, httptest.NewRequest("PATCH", "/me", strings.NewReader(body))); err != nil {
t.Fatal(err)
}
if u.Role != "admin" || u.Blocked {
t.Fatalf("expected escalation and unblocking in the vulnerable version, got %+v", u)
}
}
func TestAfterResponseDTO(t *testing.T) {
rec := httptest.NewRecorder()
Show(rec, victim(), 41) // another user looks at Sam
got := strings.TrimSpace(rec.Body.String())
if got != `{"id":313,"name":"Sam"}` {
t.Fatalf("public view must be the allow-list only, got %s", got)
}
rec = httptest.NewRecorder()
Show(rec, victim(), 313) // Sam looks at Sam
if strings.Contains(rec.Body.String(), "password_hash") || !strings.Contains(rec.Body.String(), "sam@example.com") {
t.Fatalf("self view wrong: %s", rec.Body.String())
}
}
func TestAfterRejectsServerOwnedProperties(t *testing.T) {
u := victim()
err := Update(&u, httptest.NewRecorder(), httptest.NewRequest("PATCH", "/me", strings.NewReader(`{"name":"Sam","blocked":false}`)))
if !errors.Is(err, ErrInvalid) || !u.Blocked || u.Role != "user" {
t.Fatalf("blocked/role must not change: err=%v user=%+v", err, u)
}
err = Update(&u, httptest.NewRecorder(), httptest.NewRequest("PATCH", "/me", strings.NewReader(`{"name":" Samira "}`)))
if err != nil || u.Name != "Samira" {
t.Fatalf("allowed property not applied: err=%v user=%+v", err, u)
}
}
func TestAfterRejectedUpdateChangesNothing(t *testing.T) {
u := victim()
err := Update(&u, httptest.NewRecorder(), httptest.NewRequest("PATCH", "/me", strings.NewReader(`{"name":"Changed","email":"not an address"}`)))
if !errors.Is(err, ErrInvalid) || u.Name != "Sam" || u.Email != "sam@example.com" {
t.Fatalf("no partial update allowed: err=%v user=%+v", err, u)
}
}API5 BFLA: admin functions registered next to user functions, versus a route table that refuses a route without a policy:
// Package bfla shows API5:2023 Broken Function Level Authorization: a
// regular user calls a function meant for administrators, by guessing the
// URL or by changing the HTTP method.
package bfla
import "net/http"
// NewMuxBefore registers admin functions next to user functions and relies
// on the admin console not showing them. Every route is authenticated by the
// outer middleware; none checks the role.
func NewMuxBefore(h Handlers) *http.ServeMux {
mux := http.NewServeMux()
mux.Handle("GET /api/users/{id}", h.ShowUser)
mux.Handle("DELETE /api/users/{id}", h.DeleteUser) // only the method differs
mux.Handle("POST /api/invites/new", h.CreateInvite) // admin-only function
mux.Handle("GET /api/admin/v1/users/all", h.ExportUsers) // "hidden" admin URL
return mux
}package bfla
import (
"fmt"
"log/slog"
"net/http"
"academy/owasp-api-security-top-10/principal"
)
// Handlers are the business functions; they contain no authorization code.
type Handlers struct {
ShowUser, DeleteUser, CreateInvite, ExportUsers http.Handler
}
// Route is one function plus the policy that guards it. A route must either
// name the roles allowed to call it or say explicitly that any
// authenticated caller may (AnyUser); there is no third option.
type Route struct {
Pattern string
Handler http.Handler
Roles []string
AnyUser bool
}
// NewMux builds the router from a route table and refuses to start if a
// route has no policy: deny by default is enforced at build time, not by
// remembering to add a check.
func NewMux(routes []Route, log *slog.Logger) (*http.ServeMux, error) {
mux := http.NewServeMux()
for _, rt := range routes {
if !rt.AnyUser && len(rt.Roles) == 0 {
return nil, fmt.Errorf("bfla: route %q has no authorization policy", rt.Pattern)
}
mux.Handle(rt.Pattern, requireRoles(rt, log))
}
return mux, nil
}
func requireRoles(rt Route, log *slog.Logger) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, ok := principal.From(r.Context())
if !ok {
http.Error(w, "unauthenticated", http.StatusUnauthorized)
return
}
if !rt.AnyUser && !hasAny(u, rt.Roles) {
log.Warn("authz_fail",
slog.Int64("user_id", u.ID),
slog.String("function", rt.Pattern),
slog.String("method", r.Method),
slog.String("path", r.URL.Path))
http.Error(w, "forbidden", http.StatusForbidden)
return
}
rt.Handler.ServeHTTP(w, r)
})
}
func hasAny(u principal.User, roles []string) bool {
for _, r := range roles {
if u.HasRole(r) {
return true
}
}
return false
}
// Routes is the production table: the method is part of the pattern, so
// DELETE has its own policy, and admin functions say so wherever they live.
func Routes(h Handlers) []Route {
return []Route{
{Pattern: "GET /api/users/{id}", Handler: h.ShowUser, AnyUser: true}, // object check inside (API1)
{Pattern: "DELETE /api/users/{id}", Handler: h.DeleteUser, Roles: []string{"admin"}},
{Pattern: "POST /api/invites/new", Handler: h.CreateInvite, Roles: []string{"admin"}},
{Pattern: "GET /api/admin/v1/users/all", Handler: h.ExportUsers, Roles: []string{"admin"}},
}
}package bfla
import (
"bytes"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/owasp-api-security-top-10/principal"
)
var users = principal.Static(map[string]principal.User{
"tok-user": {ID: 41, TenantID: 7, Roles: []string{"user"}},
"tok-admin": {ID: 1, TenantID: 7, Roles: []string{"admin"}},
})
func ok(name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, name) })
}
var handlers = Handlers{ShowUser: ok("show"), DeleteUser: ok("deleted"), CreateInvite: ok("invited"), ExportUsers: ok("all users")}
func call(h http.Handler, method, path, tok string) int {
req := httptest.NewRequest(method, path, strings.NewReader(`{"email":"x@example.com","role":"admin"}`))
req.Header.Set("Authorization", "Bearer "+tok)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec.Code
}
var attacks = []struct{ method, path string }{
{http.MethodDelete, "/api/users/2"},
{http.MethodPost, "/api/invites/new"},
{http.MethodGet, "/api/admin/v1/users/all"},
}
func TestBeforeRegularUserReachesAdminFunctions(t *testing.T) {
h := principal.Middleware(users)(NewMuxBefore(handlers))
for _, a := range attacks {
if code := call(h, a.method, a.path, "tok-user"); code != http.StatusOK {
t.Fatalf("expected the vulnerable router to allow %s %s, got %d", a.method, a.path, code)
}
}
}
func TestAfterDenyByDefault(t *testing.T) {
var logs bytes.Buffer
mux, err := NewMux(Routes(handlers), slog.New(slog.NewJSONHandler(&logs, nil)))
if err != nil {
t.Fatal(err)
}
h := principal.Middleware(users)(mux)
for _, a := range attacks {
if code := call(h, a.method, a.path, "tok-user"); code != http.StatusForbidden {
t.Fatalf("%s %s by a user: want 403, got %d", a.method, a.path, code)
}
if code := call(h, a.method, a.path, "tok-admin"); code != http.StatusOK {
t.Fatalf("%s %s by an admin: want 200, got %d", a.method, a.path, code)
}
}
if code := call(h, http.MethodGet, "/api/users/2", "tok-user"); code != http.StatusOK {
t.Fatalf("regular function must stay open to users, got %d", code)
}
if code := call(h, http.MethodPut, "/api/users/2", "tok-user"); code != http.StatusMethodNotAllowed {
t.Fatalf("unregistered method must be 405, got %d", code)
}
if got := strings.Count(logs.String(), `"msg":"authz_fail"`); got != len(attacks) {
t.Fatalf("want %d authz_fail lines, got %d", len(attacks), got)
}
}
func TestRouteWithoutPolicyFailsAtStartup(t *testing.T) {
_, err := NewMux([]Route{{Pattern: "POST /api/users/{id}/promote", Handler: ok("x")}}, slog.Default())
if err == nil {
t.Fatal("a route without a policy must not be mounted")
}
}API6 business flows: a correct, race-free shop that a single script empties, and a guard with per-user, per-device and per-SKU limits plus non-human signals:
// Package flows shows API6:2023 Unrestricted Access to Sensitive Business
// Flows: a purchase endpoint with no bug in it, which a script can still use
// to buy the whole stock of a limited drop (scalping).
package flows
import (
"errors"
"sync"
)
// ErrSoldOut is returned when stock is exhausted.
var ErrSoldOut = errors.New("flows: sold out")
// Shop holds stock per SKU. It is correct under concurrency: the flaw in the
// "before" flow is a missing business rule, not a race.
type Shop struct {
mu sync.Mutex
stock map[string]int
}
// NewShop returns a shop with the given stock.
func NewShop(stock map[string]int) *Shop {
s := &Shop{stock: make(map[string]int, len(stock))}
for k, v := range stock {
s.stock[k] = v
}
return s
}
// take decrements stock atomically.
func (s *Shop) take(sku string, qty int) error {
s.mu.Lock()
defer s.mu.Unlock()
if s.stock[sku] < qty {
return ErrSoldOut
}
s.stock[sku] -= qty
return nil
}
// Stock returns the remaining units.
func (s *Shop) Stock(sku string) int {
s.mu.Lock()
defer s.mu.Unlock()
return s.stock[sku]
}package flows
// CheckoutBefore sells whatever is asked for while stock lasts. Valid input,
// authenticated user, correct arithmetic: and one script empties the drop.
func CheckoutBefore(s *Shop, userID int64, sku string, qty int) error {
_ = userID // nothing about the caller limits the flow
return s.take(sku, qty)
}package flows
import (
"errors"
"strconv"
"strings"
"sync"
"time"
)
// Errors a protected flow returns. The HTTP layer maps ErrLimit to 429 and
// ErrSuspicious to a challenge (CAPTCHA, step-up) rather than a hard 403.
var (
ErrLimit = errors.New("flows: limit reached for this flow")
ErrSuspicious = errors.New("flows: automated client suspected")
ErrQuantity = errors.New("flows: quantity must be between 1 and the per-user cap")
)
// Request is one checkout attempt with the signals the guard needs.
type Request struct {
UserID int64
DeviceID string // device fingerprint computed by the client SDK or the edge
UserAgent string // a weak signal, but free
CartAddedAt time.Time // when this item went into the cart (server-side record)
SKU string
Qty int
}
// Policy is the business decision about this flow, written down.
type Policy struct {
MaxPerUser int // units per user per SKU for this drop
MaxPerDevice int // units per device per SKU (many accounts, one phone)
MaxPerSKURate int // checkouts per SKU per Window across all users
Window time.Duration // window for MaxPerSKURate
MinHumanDelay time.Duration // add-to-cart -> checkout faster than this is not a human
BlockedAgents []string // substrings of user agents refused outright
RequireDevice bool
Now func() time.Time
}
// Guard enforces Policy: rate limits per user and per resource, a device
// cap, and two cheap non-human pattern checks. It keeps counters in memory;
// a cluster keeps them in Redis (see the rate-limiting chapter).
type Guard struct {
p Policy
shop *Shop
mu sync.Mutex
byUser map[string]int
byDevice map[string]int
skuHits map[string][]time.Time
}
// NewGuard wraps a shop with a flow policy.
func NewGuard(s *Shop, p Policy) *Guard {
if p.Now == nil {
p.Now = time.Now
}
return &Guard{p: p, shop: s, byUser: map[string]int{}, byDevice: map[string]int{}, skuHits: map[string][]time.Time{}}
}
// Checkout applies the policy, then the stock rule.
func (g *Guard) Checkout(r Request) error {
now := g.p.Now()
if r.Qty < 1 || r.Qty > g.p.MaxPerUser {
return ErrQuantity // a negative quantity would add stock and dodge the caps
}
if g.p.RequireDevice && r.DeviceID == "" {
return ErrSuspicious
}
for _, bad := range g.p.BlockedAgents {
if strings.Contains(r.UserAgent, bad) {
return ErrSuspicious
}
}
if now.Sub(r.CartAddedAt) < g.p.MinHumanDelay {
return ErrSuspicious
}
g.mu.Lock()
defer g.mu.Unlock()
uk := r.SKU + "|u|" + strconv.FormatInt(r.UserID, 10)
dk := r.SKU + "|d|" + r.DeviceID
if g.byUser[uk]+r.Qty > g.p.MaxPerUser || g.byDevice[dk]+r.Qty > g.p.MaxPerDevice {
return ErrLimit
}
hits := g.skuHits[r.SKU][:0]
for _, t := range g.skuHits[r.SKU] {
if now.Sub(t) < g.p.Window {
hits = append(hits, t)
}
}
if len(hits) >= g.p.MaxPerSKURate {
g.skuHits[r.SKU] = hits
return ErrLimit
}
if err := g.shop.take(r.SKU, r.Qty); err != nil {
return err
}
g.skuHits[r.SKU] = append(hits, now)
g.byUser[uk] += r.Qty
g.byDevice[dk] += r.Qty
return nil
}package flows
import (
"errors"
"strconv"
"sync"
"testing"
"time"
)
const sku = "console-x"
func TestBeforeOneScriptBuysTheDrop(t *testing.T) {
s := NewShop(map[string]int{sku: 100})
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() { defer wg.Done(); _ = CheckoutBefore(s, 666, sku, 1) }()
}
wg.Wait()
if s.Stock(sku) != 0 {
t.Fatalf("expected the bot to buy everything, %d left", s.Stock(sku))
}
}
func policy(now time.Time) Policy {
return Policy{MaxPerUser: 2, MaxPerDevice: 2, MaxPerSKURate: 50, Window: time.Second,
MinHumanDelay: time.Second, BlockedAgents: []string{"HeadlessChrome"}, RequireDevice: true,
Now: func() time.Time { return now }}
}
func TestAfterPerUserAndPerDeviceLimits(t *testing.T) {
now := time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC)
s := NewShop(map[string]int{sku: 100})
g := NewGuard(s, policy(now))
human := Request{UserID: 666, DeviceID: "dev-a", UserAgent: "Mozilla/5.0", CartAddedAt: now.Add(-20 * time.Second), SKU: sku, Qty: 1}
var ok, limited int
for i := 0; i < 100; i++ {
switch err := g.Checkout(human); {
case err == nil:
ok++
case errors.Is(err, ErrLimit):
limited++
default:
t.Fatal(err)
}
}
if ok != 2 || limited != 98 || s.Stock(sku) != 98 {
t.Fatalf("per-user cap: ok=%d limited=%d stock=%d", ok, limited, s.Stock(sku))
}
// A second account on the same device gets nothing more.
other := human
other.UserID = 667
if err := g.Checkout(other); !errors.Is(err, ErrLimit) {
t.Fatalf("per-device cap: want ErrLimit, got %v", err)
}
}
func TestAfterNonHumanSignals(t *testing.T) {
now := time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC)
g := NewGuard(NewShop(map[string]int{sku: 10}), policy(now))
base := Request{UserID: 1, DeviceID: "dev-b", UserAgent: "Mozilla/5.0", CartAddedAt: now.Add(-5 * time.Second), SKU: sku, Qty: 1}
fast := base
fast.CartAddedAt = now.Add(-300 * time.Millisecond)
headless := base
headless.UserAgent = "Mozilla/5.0 HeadlessChrome/120.0"
noDevice := base
noDevice.DeviceID = ""
for name, r := range map[string]Request{"fast": fast, "headless": headless, "no device": noDevice} {
if err := g.Checkout(r); !errors.Is(err, ErrSuspicious) {
t.Fatalf("%s: want ErrSuspicious, got %v", name, err)
}
}
for _, q := range []int{0, -5, 3} {
bad := base
bad.Qty = q
if err := g.Checkout(bad); !errors.Is(err, ErrQuantity) {
t.Fatalf("qty %d: want ErrQuantity, got %v", q, err)
}
}
if err := g.Checkout(base); err != nil {
t.Fatalf("a human-looking request must pass: %v", err)
}
}
func TestAfterPerResourceRate(t *testing.T) {
now := time.Date(2026, 11, 27, 9, 0, 0, 0, time.UTC)
p := policy(now)
p.MaxPerSKURate = 3
g := NewGuard(NewShop(map[string]int{sku: 100}), p)
var ok int
for u := int64(1); u <= 10; u++ {
r := Request{UserID: u, DeviceID: "dev-" + strconv.FormatInt(u, 10), UserAgent: "Mozilla/5.0", CartAddedAt: now.Add(-time.Minute), SKU: sku, Qty: 1}
if g.Checkout(r) == nil {
ok++
}
}
if ok != 3 {
t.Fatalf("per-SKU rate: want 3 checkouts in the window, got %d", ok)
}
}API9 inventory: mount whatever the code contains, versus mount what the OpenAPI document declares (shadow routes fail the start, deprecated versions get Deprecation, Sunset, a successor link, then 410):
{
"openapi": "3.1.0",
"info": { "title": "Shop API", "version": "2.3.0" },
"paths": {
"/v2/users/{id}": {
"parameters": [
{ "name": "id", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } }
],
"get": { "operationId": "getUserV2", "x-owner": "team-accounts", "x-audience": "public" }
},
"/v1/users/{id}": {
"parameters": [
{ "name": "id", "in": "path", "required": true, "schema": { "type": "integer", "format": "int64" } }
],
"get": {
"operationId": "getUserV1",
"deprecated": true,
"x-owner": "team-accounts",
"x-audience": "public",
"x-deprecated-at": "2026-06-30T23:59:59Z",
"x-sunset": "2026-12-31T23:59:59Z",
"x-successor": "/v2/users/{id}"
}
}
}
}// Package inventory shows API9:2023 Improper Inventory Management: routes
// that exist in the binary but in no inventory (shadow APIs), and old
// versions nobody retired (zombie APIs).
package inventory
import "net/http"
// MountBefore mounts whatever handlers the code base happens to contain.
// /v1 still runs (without the rate limit that v2 got), and a debug endpoint
// added for an incident never left.
func MountBefore(mux *http.ServeMux, handlers map[string]http.Handler) {
for pattern, h := range handlers {
mux.Handle(pattern, h)
}
}package inventory
import (
_ "embed"
"encoding/json"
"fmt"
"net/http"
"regexp"
"slices"
"sort"
"strings"
"time"
)
//go:embed openapi.json
var specJSON []byte
// Parameter is the part of an OpenAPI Parameter Object the loader checks.
type Parameter struct {
Name string `json:"name"`
In string `json:"in"`
Required bool `json:"required"`
}
// Operation is the part of an OpenAPI 3.1 Operation Object the inventory
// needs, plus x- extensions for ownership and lifecycle.
type Operation struct {
OperationID string `json:"operationId"`
Deprecated bool `json:"deprecated"`
Parameters []Parameter `json:"parameters"`
Owner string `json:"x-owner"`
Audience string `json:"x-audience"`
DeprecatedAt string `json:"x-deprecated-at"`
Sunset string `json:"x-sunset"`
Successor string `json:"x-successor"`
}
// Spec is a minimal OpenAPI document: paths -> method -> operation, plus the
// path-level parameters shared by every operation of a path.
type Spec struct {
Paths map[string]map[string]Operation
PathParams map[string][]Parameter
}
var methods = map[string]bool{"get": true, "put": true, "post": true, "delete": true, "options": true, "head": true, "patch": true, "trace": true}
var templateRe = regexp.MustCompile(`\{([^{}]+)\}`)
// Parse decodes an OpenAPI document and validates it: every template
// expression in a path must have a required "in: path" parameter, declared
// on the Path Item or on the operation (OpenAPI 3.1, Path Templating).
func Parse(doc []byte) (Spec, error) {
var raw struct {
Paths map[string]map[string]json.RawMessage `json:"paths"`
}
if err := json.Unmarshal(doc, &raw); err != nil {
return Spec{}, err
}
s := Spec{Paths: map[string]map[string]Operation{}, PathParams: map[string][]Parameter{}}
for path, item := range raw.Paths {
s.Paths[path] = map[string]Operation{}
for key, val := range item {
switch {
case key == "parameters":
var ps []Parameter
if err := json.Unmarshal(val, &ps); err != nil {
return Spec{}, fmt.Errorf("inventory: %s parameters: %w", path, err)
}
s.PathParams[path] = ps
case methods[key]:
var op Operation
if err := json.Unmarshal(val, &op); err != nil {
return Spec{}, fmt.Errorf("inventory: %s %s: %w", key, path, err)
}
s.Paths[path][key] = op
}
}
}
for path, ops := range s.Paths {
for method, op := range ops {
for _, m := range templateRe.FindAllStringSubmatch(path, -1) {
if !hasPathParam(effectiveParams(s.PathParams[path], op.Parameters), m[1]) {
return Spec{}, fmt.Errorf("inventory: %s %s: template {%s} has no required path parameter", strings.ToUpper(method), path, m[1])
}
}
}
}
return s, nil
}
// effectiveParams applies the OpenAPI rule: an operation-level parameter
// overrides a path-level one with the same name and location ("in").
func effectiveParams(pathLevel, opLevel []Parameter) []Parameter {
out := slices.Clone(opLevel)
for _, p := range pathLevel {
overridden := slices.ContainsFunc(opLevel, func(o Parameter) bool { return o.Name == p.Name && o.In == p.In })
if !overridden {
out = append(out, p)
}
}
return out
}
func hasPathParam(ps []Parameter, name string) bool {
for _, p := range ps {
if p.Name == name && p.In == "path" && p.Required {
return true
}
}
return false
}
// Load parses and validates the embedded OpenAPI document, the single source
// of truth.
func Load() (Spec, error) { return Parse(specJSON) }
// Patterns returns "METHOD /path" for every operation in the spec.
func (s Spec) Patterns() []string {
var out []string
for path, ops := range s.Paths {
for method := range ops {
out = append(out, strings.ToUpper(method)+" "+path)
}
}
sort.Strings(out)
return out
}
func (s Spec) op(pattern string) (Operation, bool) {
method, path, _ := strings.Cut(pattern, " ")
op, ok := s.Paths[path][strings.ToLower(method)]
return op, ok
}
// Diff compares the spec with the handlers in the binary. Shadow: code
// without an inventory entry. Missing: an entry without code.
func Diff(s Spec, handlers map[string]http.Handler) (shadow, missing []string) {
declared := s.Patterns()
for p := range handlers {
if !slices.Contains(declared, p) {
shadow = append(shadow, p)
}
}
for _, p := range declared {
if _, ok := handlers[p]; !ok {
missing = append(missing, p)
}
}
sort.Strings(shadow)
sort.Strings(missing)
return shadow, missing
}
// Mount refuses to start when code and inventory disagree, and wraps
// deprecated operations with lifecycle headers: Deprecation (RFC 9745),
// Sunset (RFC 8594), a successor Link, and 410 Gone after the sunset date.
func Mount(mux *http.ServeMux, s Spec, handlers map[string]http.Handler, now func() time.Time) error {
if shadow, missing := Diff(s, handlers); len(shadow)+len(missing) > 0 {
return fmt.Errorf("inventory: shadow=%v missing=%v", shadow, missing)
}
for pattern, h := range handlers {
op, _ := s.op(pattern)
if op.Owner == "" {
return fmt.Errorf("inventory: %s has no x-owner", pattern)
}
if op.Deprecated {
wrapped, err := lifecycle(op, h, now)
if err != nil {
return fmt.Errorf("inventory: %s: %w", pattern, err)
}
h = wrapped
}
mux.Handle(pattern, h)
}
return nil
}
func lifecycle(op Operation, next http.Handler, now func() time.Time) (http.Handler, error) {
dep, err := time.Parse(time.RFC3339, op.DeprecatedAt)
if err != nil {
return nil, fmt.Errorf("x-deprecated-at: %w", err)
}
sunset, err := time.Parse(time.RFC3339, op.Sunset)
if err != nil {
return nil, fmt.Errorf("x-sunset: %w", err)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("Deprecation", fmt.Sprintf("@%d", dep.Unix()))
h.Set("Sunset", sunset.UTC().Format(http.TimeFormat))
if op.Successor != "" {
h.Set("Link", fmt.Sprintf("<%s>; rel=\"successor-version\"", op.Successor))
}
if !now().Before(sunset) {
http.Error(w, "this API version has been retired", http.StatusGone)
return
}
next.ServeHTTP(w, r)
}), nil
}package inventory
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func h(name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, name) })
}
func codeAndHeaders(mux http.Handler, path string) (int, http.Header) {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
return rec.Code, rec.Header()
}
func TestBeforeShadowAndZombieAreLive(t *testing.T) {
mux := http.NewServeMux()
MountBefore(mux, map[string]http.Handler{
"GET /v2/users/{id}": h("v2"), "GET /v1/users/{id}": h("v1"), "GET /debug/vars": h("secrets"),
})
for _, p := range []string{"/v1/users/1", "/debug/vars"} {
if code, hdr := codeAndHeaders(mux, p); code != http.StatusOK || hdr.Get("Deprecation") != "" {
t.Fatalf("expected %s to be silently reachable in the vulnerable setup, got %d", p, code)
}
}
}
func TestAfterShadowRouteBlocksStartup(t *testing.T) {
spec, err := Load()
if err != nil {
t.Fatal(err)
}
err = Mount(http.NewServeMux(), spec, map[string]http.Handler{
"GET /v2/users/{id}": h("v2"), "GET /v1/users/{id}": h("v1"), "GET /debug/vars": h("secrets"),
}, time.Now)
if err == nil || !strings.Contains(err.Error(), "shadow=[GET /debug/vars]") {
t.Fatalf("want a shadow-route error, got %v", err)
}
}
func TestAfterDeprecationThenSunset(t *testing.T) {
spec, err := Load()
if err != nil {
t.Fatal(err)
}
clock := time.Date(2026, 11, 29, 12, 0, 0, 0, time.UTC)
mux := http.NewServeMux()
handlers := map[string]http.Handler{"GET /v2/users/{id}": h("v2"), "GET /v1/users/{id}": h("v1")}
if err := Mount(mux, spec, handlers, func() time.Time { return clock }); err != nil {
t.Fatal(err)
}
code, hdr := codeAndHeaders(mux, "/v1/users/1")
if code != http.StatusOK || hdr.Get("Deprecation") != "@1782863999" || hdr.Get("Sunset") != "Thu, 31 Dec 2026 23:59:59 GMT" {
t.Fatalf("deprecated version: %d %v", code, hdr)
}
if !strings.Contains(hdr.Get("Link"), `rel="successor-version"`) {
t.Fatalf("missing successor link: %v", hdr)
}
if code, hdr := codeAndHeaders(mux, "/v2/users/1"); code != http.StatusOK || hdr.Get("Deprecation") != "" {
t.Fatalf("current version must carry no lifecycle headers: %d %v", code, hdr)
}
clock = time.Date(2027, 1, 1, 0, 0, 0, 0, time.UTC)
if code, _ := codeAndHeaders(mux, "/v1/users/1"); code != http.StatusGone {
t.Fatalf("after sunset want 410, got %d", code)
}
}
func TestSpecRequiresPathParameters(t *testing.T) {
if _, err := Load(); err != nil {
t.Fatalf("embedded spec must validate: %v", err)
}
bad := []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{"get":{"x-owner":"team-orders"}}}}`)
if _, err := Parse(bad); err == nil || !strings.Contains(err.Error(), "template {id}") {
t.Fatalf("a template without a path parameter must be rejected, got %v", err)
}
ok := []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{"get":{"x-owner":"o","parameters":[{"name":"id","in":"path","required":true}]}}}}`)
if _, err := Parse(ok); err != nil {
t.Fatalf("an operation-level parameter must count: %v", err)
}
}
func TestOperationParameterOverridesPathLevel(t *testing.T) {
// Path level says required; the operation overrides id/path with
// required=false, so the template is not satisfied.
doc := []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{
"parameters":[{"name":"id","in":"path","required":true}],
"get":{"x-owner":"o","parameters":[{"name":"id","in":"path","required":false}]}}}}`)
if _, err := Parse(doc); err == nil || !strings.Contains(err.Error(), "template {id}") {
t.Fatalf("an operation-level override must win over the path level, got %v", err)
}
// A same-name parameter in another location does not override.
doc = []byte(`{"openapi":"3.1.0","paths":{"/v2/orders/{id}":{
"parameters":[{"name":"id","in":"path","required":true}],
"get":{"x-owner":"o","parameters":[{"name":"id","in":"query","required":false}]}}}}`)
if _, err := Parse(doc); err != nil {
t.Fatalf("a query parameter named id must not override the path one: %v", err)
}
}API10 unsafe consumption: the default client that replays a POST body to the attacker on 308 and splices upstream text into SQL, versus a client with TLS and a host allow-list on the first hop and on every redirect, timeouts, a body cap, field validation and bound parameters:
// Package consume shows API10:2023 Unsafe Consumption of APIs: the API
// treats a third-party response as trusted, so a compromised or malicious
// upstream can redirect sensitive data, inject into SQL, or exhaust memory.
package consume
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
// Business is what the enrichment provider returns for an address.
type Business struct {
Name string `json:"name"`
City string `json:"city"`
Country string `json:"country"`
}
// EnrichBefore uses http.DefaultClient (no timeout, follows up to 10
// redirects), reads the whole body, and builds SQL from the upstream value.
func EnrichBefore(url string) (query string, err error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) // unbounded
if err != nil {
return "", err
}
var b Business
if err := json.Unmarshal(body, &b); err != nil {
return "", err
}
// "It comes from our provider, so it is clean."
return fmt.Sprintf("INSERT INTO businesses (name, city) VALUES ('%s', '%s')", b.Name, b.City), nil
}
// StoreRecordBefore posts sensitive data to a partner. net/http replays the
// body on 307/308, so a compromised partner answering
// "308 Location: https://attacker.example/" receives the same payload.
func StoreRecordBefore(client *http.Client, url string, record []byte) error {
resp, err := client.Post(url, "application/json", bytes.NewReader(record))
if err != nil {
return err
}
return resp.Body.Close()
}package consume
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"time"
"unicode/utf8"
)
// Errors returned by the hardened client.
var (
ErrUpstream = errors.New("consume: upstream response rejected")
ErrRedirect = errors.New("consume: redirect to a host that is not allow-listed")
)
// Client wraps one integration with its own trust rules.
type Client struct {
HTTP *http.Client
MaxBytes int64
allowed map[string]bool
}
// ErrEndpoint is returned when the first hop itself is not https or not on
// the allow-list (CheckRedirect only sees the hops after it).
var ErrEndpoint = errors.New("consume: endpoint is not https on an allow-listed host")
func (c *Client) checkEndpoint(endpoint string) error {
u, err := url.Parse(endpoint)
if err != nil || u.Scheme != "https" || !c.allowed[u.Host] {
return fmt.Errorf("%w: %q", ErrEndpoint, endpoint)
}
return nil
}
// NewClient returns a client that only talks TLS to allow-listed hosts (first
// hop checked by checkEndpoint, later hops by CheckRedirect),
// gives up after timeout, and never follows a redirect off the allow-list.
// base is used for the transport (tests pass an httptest TLS client).
func NewClient(base *http.Client, allowedHosts []string, timeout time.Duration) *Client {
allowed := make(map[string]bool, len(allowedHosts))
for _, h := range allowedHosts {
allowed[h] = true
}
c := &http.Client{
Transport: base.Transport,
Timeout: timeout,
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 || req.URL.Scheme != "https" || !allowed[req.URL.Host] {
return fmt.Errorf("%w: %s", ErrRedirect, req.URL.Host)
}
return nil
},
}
return &Client{HTTP: c, MaxBytes: 64 << 10, allowed: allowed}
}
// StoreRecord posts to the partner; a redirect off the allow-list fails the
// call before the body is sent anywhere else.
func (c *Client) StoreRecord(ctx context.Context, endpoint string, record []byte) error {
if err := c.checkEndpoint(endpoint); err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(record))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.HTTP.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
return fmt.Errorf("%w: status %d", ErrUpstream, resp.StatusCode)
}
return nil
}
var cityRe = regexp.MustCompile(`^[\p{L} .'-]{1,80}$`)
var countryRe = regexp.MustCompile(`^[A-Z]{2}$`)
// Validate is input validation of upstream responses: the same rules as for
// user input, because the provider is just another untrusted source.
func (b Business) Validate() error {
switch {
case !utf8.ValidString(b.Name) || len(b.Name) == 0 || len(b.Name) > 200:
return fmt.Errorf("%w: name", ErrUpstream)
case !cityRe.MatchString(b.City):
return fmt.Errorf("%w: city", ErrUpstream)
case !countryRe.MatchString(b.Country):
return fmt.Errorf("%w: country", ErrUpstream)
}
return nil
}
// Enrich fetches, caps the body, checks status and content type, decodes,
// validates, and returns a parameterised statement: the upstream value is a
// bound argument, never SQL text.
func (c *Client) Enrich(ctx context.Context, endpoint string) (query string, args []any, err error) {
if err := c.checkEndpoint(endpoint); err != nil {
return "", nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return "", nil, err
}
resp, err := c.HTTP.Do(req)
if err != nil {
return "", nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK || resp.Header.Get("Content-Type") != "application/json" {
return "", nil, fmt.Errorf("%w: status %d, type %q", ErrUpstream, resp.StatusCode, resp.Header.Get("Content-Type"))
}
body, err := io.ReadAll(io.LimitReader(resp.Body, c.MaxBytes+1))
if err != nil {
return "", nil, err
}
if int64(len(body)) > c.MaxBytes {
return "", nil, fmt.Errorf("%w: body larger than %d bytes", ErrUpstream, c.MaxBytes)
}
var b Business
if err := json.Unmarshal(body, &b); err != nil {
return "", nil, fmt.Errorf("%w: %v", ErrUpstream, err)
}
if err := b.Validate(); err != nil {
return "", nil, err
}
return "INSERT INTO businesses (name, city, country) VALUES ($1, $2, $3)", []any{b.Name, b.City, b.Country}, nil
}package consume
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
)
const record = `{"genome":"ACTAGTAG"}`
// attacker counts how many bytes of sensitive data reached it.
func attacker(t *testing.T, tls bool) (*httptest.Server, *atomic.Int64) {
t.Helper()
var got atomic.Int64
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
got.Add(int64(len(b)))
})
var s *httptest.Server
if tls {
s = httptest.NewTLSServer(h)
} else {
s = httptest.NewServer(h)
}
t.Cleanup(s.Close)
return s, &got
}
// compromisedPartner answers every request with 308 to the attacker.
func compromisedPartner(t *testing.T, tls bool, to string) *httptest.Server {
t.Helper()
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = io.Copy(io.Discard, r.Body)
http.Redirect(w, r, to, http.StatusPermanentRedirect)
})
var s *httptest.Server
if tls {
s = httptest.NewTLSServer(h)
} else {
s = httptest.NewServer(h)
}
t.Cleanup(s.Close)
return s
}
func host(s *httptest.Server) string { u, _ := url.Parse(s.URL); return u.Host }
func TestBeforeFollowsRedirectWithBody(t *testing.T) {
evil, got := attacker(t, false)
partner := compromisedPartner(t, false, evil.URL+"/steal")
if err := StoreRecordBefore(http.DefaultClient, partner.URL+"/store_phr_record", []byte(record)); err != nil {
t.Fatal(err)
}
if got.Load() != int64(len(record)) {
t.Fatalf("expected the record to be replayed to the attacker, got %d bytes", got.Load())
}
}
func TestBeforeTrustsUpstreamIntoSQL(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, `{"name":"x'); DROP TABLE businesses;--","city":"Delft","country":"NL"}`)
}))
defer up.Close()
q, err := EnrichBefore(up.URL)
if err != nil || !strings.Contains(q, "DROP TABLE businesses") {
t.Fatalf("expected injected SQL text in the vulnerable query, got %q %v", q, err)
}
}
func TestAfterRefusesRedirectOffAllowList(t *testing.T) {
evil, got := attacker(t, true)
partner := compromisedPartner(t, true, evil.URL+"/steal")
c := NewClient(partner.Client(), []string{host(partner)}, 2*time.Second)
err := c.StoreRecord(context.Background(), partner.URL+"/store_phr_record", []byte(record))
if !errors.Is(err, ErrRedirect) || got.Load() != 0 {
t.Fatalf("want ErrRedirect and nothing at the attacker; err=%v bytes=%d", err, got.Load())
}
}
func TestAfterValidatesAndBinds(t *testing.T) {
var body atomic.Value
up := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = io.WriteString(w, body.Load().(string))
}))
defer up.Close()
c := NewClient(up.Client(), []string{host(up)}, 2*time.Second)
body.Store(`{"name":"x'); DROP TABLE businesses;--","city":"Delft","country":"NL"}`)
q, args, err := c.Enrich(context.Background(), up.URL)
if err != nil || strings.Contains(q, "DROP") || args[0] != "x'); DROP TABLE businesses;--" {
t.Fatalf("upstream text must travel as a bound argument: %q %v %v", q, args, err)
}
body.Store(`{"name":"Acme","city":"<script>","country":"NL"}`)
if _, _, err := c.Enrich(context.Background(), up.URL); !errors.Is(err, ErrUpstream) {
t.Fatalf("invalid city must be rejected, got %v", err)
}
body.Store(`{"name":"` + strings.Repeat("A", 70<<10) + `","city":"Delft","country":"NL"}`)
if _, _, err := c.Enrich(context.Background(), up.URL); !errors.Is(err, ErrUpstream) {
t.Fatalf("oversized body must be rejected, got %v", err)
}
}
func TestAfterRefusesFirstHopOffAllowList(t *testing.T) {
evil, got := attacker(t, true)
plain, gotPlain := attacker(t, false)
c := NewClient(evil.Client(), []string{"geo-partner.example"}, 2*time.Second)
for _, endpoint := range []string{evil.URL + "/store", "http://" + host(plain) + "/store"} {
if err := c.StoreRecord(context.Background(), endpoint, []byte(record)); !errors.Is(err, ErrEndpoint) {
t.Fatalf("%s: want ErrEndpoint, got %v", endpoint, err)
}
if _, _, err := c.Enrich(context.Background(), endpoint); !errors.Is(err, ErrEndpoint) {
t.Fatalf("%s: want ErrEndpoint from Enrich, got %v", endpoint, err)
}
}
if got.Load()+gotPlain.Load() != 0 {
t.Fatal("nothing may be sent to a host that is not allow-listed")
}
}
func TestAfterTimeout(t *testing.T) {
release := make(chan struct{})
slow := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-release:
case <-r.Context().Done():
}
}))
defer slow.Close()
defer close(release)
c := NewClient(slow.Client(), []string{host(slow)}, 100*time.Millisecond)
start := time.Now()
if _, _, err := c.Enrich(context.Background(), slow.URL); err == nil || time.Since(start) > 2*time.Second {
t.Fatalf("want a timeout error quickly, got %v after %v", err, time.Since(start))
}
}The four short pairs (one file plus test each): API2 re-authentication, API4 page and batch caps, API7 URL allow-list, API8 problem details and exact CORS:
// Package authn is the API2:2023 Broken Authentication pair kept short:
// a sensitive change (the account e-mail) accepted on a bearer token alone,
// versus one that demands a recent re-authentication. Password hashing, MFA
// and sessions are taught in the authentication chapter.
package authn
import (
"crypto/subtle"
"errors"
"time"
)
// Session is what the server knows about the current login.
type Session struct {
UserID int64
AuthAt time.Time // last time the user proved a credential
}
// Account is the stored user.
type Account struct {
ID int64
Email string
}
// ErrReauth means "ask for the password (or a passkey/MFA) again".
var ErrReauth = errors.New("authn: re-authentication required")
// ChangeEmailBefore trusts the token: whoever stole it can redirect the
// account's e-mail and then run "forgot password" to take the account.
func ChangeEmailBefore(a *Account, s Session, newEmail string) error {
a.Email = newEmail
return nil
}
// Verifier checks a credential; production code compares an Argon2id or
// bcrypt hash, here a constant-time compare stands in.
type Verifier func(userID int64, password string) bool
// StaticVerifier is a test double.
func StaticVerifier(want string) Verifier {
return func(_ int64, got string) bool { return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1 }
}
// ChangeEmail requires the current password, or a login within maxAge.
func ChangeEmail(a *Account, s Session, newEmail, currentPassword string, verify Verifier, now time.Time, maxAge time.Duration) error {
recent := now.Sub(s.AuthAt) <= maxAge
if !recent && (currentPassword == "" || !verify(s.UserID, currentPassword)) {
return ErrReauth
}
a.Email = newEmail
return nil
}// Package resource is the API4:2023 Unrestricted Resource Consumption pair
// kept short: a list endpoint that honours any page size and any body size,
// versus one with server-side caps. Rate-limit algorithms are taught in the
// rate-limiting chapter.
package resource
import (
"encoding/json"
"errors"
"net/http"
"strconv"
)
// Limits are the per-request ceilings.
const (
DefaultPage = 20
MaxPage = 100
MaxBody = 32 << 10 // 32 KiB
MaxBatch = 25 // items per batch request
)
// PageSizeBefore trusts ?limit=: limit=10000000 makes the database and the
// encoder do ten million rows of work for one request.
func PageSizeBefore(r *http.Request) int {
n, _ := strconv.Atoi(r.URL.Query().Get("limit"))
return n
}
// PageSize clamps the requested size to [1, MaxPage].
func PageSize(r *http.Request) int {
n, err := strconv.Atoi(r.URL.Query().Get("limit"))
switch {
case err != nil || n <= 0:
return DefaultPage
case n > MaxPage:
return MaxPage
}
return n
}
// ErrTooMany is returned when a batch exceeds MaxBatch.
var ErrTooMany = errors.New("resource: too many operations in one request")
// DecodeBatch caps the body bytes and the number of operations, the two
// knobs GraphQL batching and bulk endpoints abuse.
func DecodeBatch(w http.ResponseWriter, r *http.Request) ([]json.RawMessage, error) {
var ops []json.RawMessage
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, MaxBody)).Decode(&ops); err != nil {
return nil, err
}
if len(ops) > MaxBatch {
return nil, ErrTooMany
}
return ops, nil
}// Package ssrf is the API7:2023 Server Side Request Forgery pair kept short:
// the URL check only. The connect-time IP check that stops DNS rebinding
// (net.Dialer.Control) is in the OWASP Top 10 chapter's ssrf package.
package ssrf
import (
"errors"
"net/netip"
"net/url"
"strings"
)
// ErrNotAllowed is returned for any URL outside the allow-list.
var ErrNotAllowed = errors.New("ssrf: destination not allowed")
// CheckBefore accepts anything that parses: localhost:8080, file:///,
// http://169.254.169.254/ and internal service names all pass.
func CheckBefore(raw string) (*url.URL, error) {
return url.Parse(raw)
}
// Check allows https on port 443 to an allow-listed host only, and refuses
// IP literals and userinfo outright.
func Check(raw string, allowedHosts map[string]bool) (*url.URL, error) {
u, err := url.Parse(raw)
if err != nil || u.Scheme != "https" || u.User != nil || u.Opaque != "" {
return nil, ErrNotAllowed
}
host := strings.ToLower(u.Hostname())
if _, err := netip.ParseAddr(host); err == nil {
return nil, ErrNotAllowed
}
if p := u.Port(); p != "" && p != "443" {
return nil, ErrNotAllowed
}
if !allowedHosts[host] {
return nil, ErrNotAllowed
}
return u, nil
}// Package misconfig is the API8:2023 Security Misconfiguration pair kept
// short: verbose errors and a reflect-any-origin CORS policy, versus RFC 9457
// problem details with a correlation id and an exact origin allow-list.
// Headers, debug mode and hardening are taught in the OWASP Top 10 chapter.
package misconfig
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"log/slog"
"net/http"
)
// ErrorBefore sends the internal error to the client: SQL text, file paths
// and driver versions help the attacker map the stack.
func ErrorBefore(w http.ResponseWriter, err error) {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
// CORSBefore reflects any Origin and allows credentials: every web page can
// read the logged-in user's API responses.
func CORSBefore(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", r.Header.Get("Origin"))
w.Header().Set("Access-Control-Allow-Credentials", "true")
next.ServeHTTP(w, r)
})
}
// Problem is an RFC 9457 problem details body.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Instance string `json:"instance,omitempty"`
}
// Error logs the detail server-side under a correlation id and sends the
// client a generic problem document carrying only that id.
func Error(w http.ResponseWriter, r *http.Request, log *slog.Logger, err error) {
var b [8]byte
_, _ = rand.Read(b[:])
id := hex.EncodeToString(b[:])
log.Error("internal_error", slog.String("error_id", id), slog.String("path", r.URL.Path), slog.String("err", err.Error()))
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(http.StatusInternalServerError)
_ = json.NewEncoder(w).Encode(Problem{Type: "about:blank", Title: "Internal Server Error", Status: 500, Instance: "urn:error:" + id})
}
// CORS allows exactly the listed origins and says so in Vary.
func CORS(allowed map[string]bool, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Origin")
if o := r.Header.Get("Origin"); allowed[o] {
w.Header().Set("Access-Control-Allow-Origin", o)
w.Header().Set("Access-Control-Allow-Credentials", "true")
}
next.ServeHTTP(w, r)
})
}The Go angle
- Routing carries the method. Since Go 1.22 the release notes say "The patterns used by net/http.ServeMux have been enhanced to accept methods and wildcards", and "A pattern with a method takes precedence over a matching pattern without one." Registering
DELETE /api/users/{id}as its own pattern gives it its own policy in the route table and makes unregistered methods return 405 automatically, which closes the "change GET to DELETE" variant of BFLA by construction. - The principal travels in
context.Context. Authentication middleware stores a typed value under an unexported key; handlers read it withprincipal.From(ctx). Never put the caller's id into a path, header or body field the handler then trusts. Chi, Echo and Gin follow the same pattern with their own context types. - No policy framework; write functions.
CanView(u, o) boolis easy to unit-test with a table of users × objects. Larger systems call an external engine (OPA with Rego, Cedar, OpenFGA/SpiceDB for relationship-based checks) from the same place; the shape of the handler does not change. encoding/jsonis permissive by default.json.Unmarshalignores unknown fields and matches keys case-insensitively, so{"Role":"admin"}binds toRoleon the model. Decoding into an input DTO withDisallowUnknownFields, validating every field into local values and only then copying them (a rejected request changes nothing) is the Go form of$fillable. For output, a DTO per audience beatsjson:"-"tags on the model, which are a block-list.net/httpclient defaults are for browsers, not partners.http.DefaultClienthas no timeout ("A Timeout of zero means no timeout"), follows up to 10 redirects, and re-sends the body on 307/308 when it can. Partner clients get their ownhttp.ClientwithTimeout,CheckRedirectand a transport with TLS settings; bodies go throughio.LimitReader.database/sqlbinds. Upstream values and user values both travel as$1/?arguments; scoping (AND tenant_id = $2) is in the SQL text, which the code owns.- Logging.
log/slog(Go 1.21 release notes: "The new log/slog package provides structured logging with levels") with a JSON handler gives structuredauthz_failevents; add the request id from the context.
Laravel
Example: Policies, Gate, Form Requests, API resources, limiters, lifecycle, a guarded HTTP client
The vulnerable controller (bad design on purpose: one flaw per method, all behind auth:sanctum) and its routes file (API9 before: no versions, a zombie /v1 copy and a shadow debug route):
<?php
namespace App\Http\Controllers\Before;
use App\Models\Order;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
// Bad design on purpose: one controller, one flaw per method, all of them
// behind auth:sanctum. Authentication is fine; authorization is missing.
class ApiController
{
// API1 BOLA: any logged-in user reads any order by changing the id.
public function showOrder(string $id)
{
return Order::findOrFail($id);
}
// API3 BOPLA (excessive data exposure): the whole model goes out,
// including mfa_secret, role and recent_location; the mobile app
// "just doesn't show them".
public function showUser(User $user)
{
return response()->json($user->makeVisible(['mfa_secret'])->toArray());
}
// API3 BOPLA (mass assignment): forceFill() bypasses #[Fillable], which
// is exactly what an #[Unguarded] model (or protected $guarded = [])
// does to update(): {"role":"admin","blocked":false} is written.
public function updateProfile(Request $request)
{
$request->user()->forceFill($request->except(['id', 'password']))->save();
return response()->noContent();
}
// API5 BFLA: the admin export sits next to user routes, protected only by
// the fact that the admin console is the only screen that calls it.
public function exportUsers()
{
return User::all();
}
// API6: correct code, unprotected flow. A script buys the whole drop.
public function checkout(Request $request)
{
DB::table('products')->where('sku', $request->input('sku'))
->where('stock', '>=', 1)->decrement('stock');
return response()->noContent();
}
// API10: the provider's answer is trusted, redirects are followed,
// and the value is spliced into SQL.
public function enrich(Request $request)
{
$business = Http::get('http://geo-partner.example/lookup', [
'q' => $request->input('address'),
])->json();
DB::insert("INSERT INTO businesses (name) VALUES ('{$business['name']}')");
return response()->noContent();
}
// API2: a stolen token is enough to move the account to a new e-mail.
public function changeEmail(Request $request)
{
$request->user()->forceFill(['email' => $request->input('email')])->save();
return response()->noContent();
}
// API7: the server fetches whatever URL the client names:
// picture_url=http://169.254.169.254/latest/meta-data/ or localhost:8080.
public function importAvatar(Request $request)
{
$image = Http::get($request->input('picture_url'))->body();
$request->user()->forceFill(['avatar' => base64_encode($image)])->save();
return response()->noContent();
}
// API8: the exception travels to the client, and any Origin may read it
// with the user's credentials.
public function report(Request $request)
{
try {
return DB::select('SELECT * FROM report_v2 WHERE tenant_id = ?', [$request->user()->tenant_id]);
} catch (\Throwable $e) {
return response()->json([
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
], 500)->withHeaders([
'Access-Control-Allow-Origin' => $request->header('Origin'),
'Access-Control-Allow-Credentials' => 'true',
]);
}
}
// API4: ?per_page=10000000 is honoured.
public function listOrders(Request $request)
{
return $request->user()->orders()->paginate($request->integer('per_page', 20));
}
}<?php
use App\Http\Controllers\Before\ApiController;
use Illuminate\Support\Facades\Route;
// API9 before: no version prefix, no inventory, and two routes nobody
// remembers. The /v1 copy was "temporary" when v2 shipped; the debug route
// was added during an incident. In the lab app this file is
// routes/before.php, mounted under /api/before in local and testing only
// (bootstrap/app.php), so the feature tests can watch every flaw happen.
Route::middleware('auth:sanctum')->group(function () {
Route::get('/orders', [ApiController::class, 'listOrders']);
Route::get('/orders/{id}', [ApiController::class, 'showOrder']);
Route::get('/v1/users/{user}', [ApiController::class, 'showUser']); // zombie: old shape, no throttle
Route::patch('/me', [ApiController::class, 'updateProfile']);
Route::put('/me/email', [ApiController::class, 'changeEmail']);
Route::get('/admin/users', [ApiController::class, 'exportUsers']); // no can:admin
Route::post('/checkout', [ApiController::class, 'checkout']);
Route::post('/enrich', [ApiController::class, 'enrich']);
Route::post('/avatar/import', [ApiController::class, 'importAvatar']);
Route::get('/report', [ApiController::class, 'report']);
Route::get('/debug/env', fn () => ['app' => config('app')]); // shadow: never in the spec
});The tests that pass by observing each leak on those routes (mounted at /api/before in the testing environment only):
<?php
namespace Tests\Feature;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;
// Every test here PASSES BY OBSERVING THE LEAK on the vulnerable routes
// (Before/routes.php, mounted at /api/before in the testing environment).
// ApiSecurityTest runs the same attacks against the fixed routes.
class BeforeLeaksTest extends TestCase
{
use RefreshDatabase;
private function orderFor(User $owner): Order
{
$order = new Order;
$order->forceFill(['user_id' => $owner->id, 'tenant_id' => $owner->tenant_id, 'number' => 'B-1', 'status' => 'paid', 'total_cents' => 250000])->save();
return $order;
}
public function test_api1_ana_reads_bobs_order(): void
{
$bobsOrder = $this->orderFor(User::factory()->create());
Sanctum::actingAs(User::factory()->create());
$this->getJson("/api/before/orders/{$bobsOrder->id}")
->assertOk()->assertJsonPath('total_cents', 250000);
}
public function test_api3_whole_model_and_mass_assignment(): void
{
$sam = User::factory()->create();
$ana = User::factory()->create();
Sanctum::actingAs($ana);
$this->getJson("/api/before/v1/users/{$sam->id}")
->assertOk()->assertJsonPath('mfa_secret', 'JBSWY3DPEHPK3PXP')->assertJsonPath('role', 'user');
$this->patchJson('/api/before/me', ['name' => 'Ana', 'role' => 'admin', 'blocked' => false])->assertNoContent();
$this->assertSame('admin', $ana->fresh()->role);
}
public function test_api5_user_exports_every_account(): void
{
User::factory()->count(3)->create();
Sanctum::actingAs(User::factory()->create());
$this->getJson('/api/before/admin/users')->assertOk()->assertJsonCount(4);
}
public function test_api2_email_changes_on_token_alone(): void
{
$ana = User::factory()->create();
Sanctum::actingAs($ana);
$this->putJson('/api/before/me/email', ['email' => 'attacker@example.net'])->assertNoContent();
$this->assertSame('attacker@example.net', $ana->fresh()->email);
}
public function test_api4_one_request_returns_every_row(): void
{
$ana = User::factory()->create();
DB::table('orders')->insert(collect(range(1, 500))->map(fn ($i) => [
'tenant_id' => 7, 'user_id' => $ana->id, 'number' => "A-{$i}", 'status' => 'paid', 'total_cents' => 100,
])->all());
Sanctum::actingAs($ana);
// 500 rows in one response: the server did all the work the client asked for.
$this->getJson('/api/before/orders?per_page=100000')
->assertOk()->assertJsonCount(500, 'data');
}
public function test_api6_one_account_buys_without_limit(): void
{
Sanctum::actingAs(User::factory()->create());
DB::table('products')->insert(['sku' => 'console-x', 'stock' => 10]);
foreach (range(1, 10) as $i) {
$this->postJson('/api/before/checkout', ['sku' => 'console-x'])->assertNoContent();
}
$this->assertSame(0, DB::table('products')->where('sku', 'console-x')->value('stock'));
}
public function test_api7_server_fetches_the_metadata_endpoint(): void
{
$ana = User::factory()->create();
Sanctum::actingAs($ana);
Http::fake(['169.254.169.254/*' => Http::response('role-credentials')]);
$this->postJson('/api/before/avatar/import', ['picture_url' => 'http://169.254.169.254/latest/meta-data/'])->assertNoContent();
$this->assertSame(base64_encode('role-credentials'), $ana->fresh()->avatar);
}
public function test_api8_error_and_reflected_cors(): void
{
Sanctum::actingAs(User::factory()->create());
$this->withHeader('Origin', 'https://evil.example')->getJson('/api/before/report')
->assertStatus(500)
->assertSee('report_v2')
->assertHeader('Access-Control-Allow-Origin', 'https://evil.example');
}
public function test_api9_shadow_debug_route_is_live(): void
{
Sanctum::actingAs(User::factory()->create());
$this->getJson('/api/before/debug/env')->assertOk()->assertJsonStructure(['app' => ['key']]);
}
public function test_api10_partner_text_becomes_sql(): void
{
Sanctum::actingAs(User::factory()->create());
Http::fake(['geo-partner.example/*' => Http::response(['name' => "x'), ('injected"])]);
$this->postJson('/api/before/enrich', ['address' => '1 Main St'])->assertNoContent();
// One INSERT intended, two rows written: the partner wrote SQL.
$this->assertSame(2, DB::table('businesses')->count());
}
}API1: the model relations, a Policy that answers 404 for foreign objects, and a controller that scopes by tenant and calls Gate::authorize:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
// No Fillable attribute: orders are created by server code with explicit
// assignments, so every attribute stays guarded (the Eloquent default).
class Order extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}<?php
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
use Illuminate\Auth\Access\Response;
// Found by policy discovery (App\Models\Order -> App\Policies\OrderPolicy).
// One place answers "may this user act on this order?"; controllers call it,
// they do not re-implement it.
class OrderPolicy
{
public function view(User $user, Order $order): Response
{
if ($order->tenant_id !== $user->tenant_id) {
return Response::denyAsNotFound();
}
return $order->user_id === $user->id || $user->role === 'support'
? Response::allow()
: Response::denyAsNotFound();
}
public function update(User $user, Order $order): Response
{
// Support may read but not change orders.
return $order->tenant_id === $user->tenant_id && $order->user_id === $user->id
? Response::allow()
: Response::denyAsNotFound();
}
}<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
class OrderController
{
// API1: two layers. The query is scoped to the caller's tenant, so a
// foreign tenant's row cannot even load; the policy then decides owner
// vs support and answers 404 for both "missing" and "not yours".
public function show(Request $request, string $id)
{
$order = Order::query()
->where('tenant_id', $request->user()->tenant_id)
->findOrFail($id);
Gate::authorize('view', $order);
return $order->only(['id', 'number', 'status', 'total_cents', 'created_at']);
}
// API4: the page size is clamped on the server.
public function index(Request $request)
{
$perPage = min(max($request->integer('per_page', 20), 1), 100);
return $request->user()->orders()->select(['id', 'number', 'status', 'total_cents'])
->orderByDesc('id')->cursorPaginate($perPage);
}
}API3: the model's write allow-list (#[Fillable], with the $fillable/$guarded property form in the comment) and read backstop (#[Hidden]), a Form Request that prohibits server-owned keys, and a JsonResource as the response DTO:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
// Write side: the allow-list of properties a request may mass-assign.
// Laravel 12 and older code write the same thing as properties:
// protected $fillable = ['name', 'email'];
// protected $guarded = ['role', 'blocked', 'tenant_id']; // a block-list: avoid
// Read side: #[Hidden] keeps secrets out of toArray()/toJson(), but the
// response DTO (UserResource) is the real allow-list for output.
#[Fillable(['name', 'email'])]
#[Hidden(['password', 'remember_token', 'mfa_secret'])]
class User extends Authenticatable
{
use HasApiTokens, HasFactory;
public function orders(): HasMany
{
return $this->hasMany(Order::class);
}
public function isAdmin(): bool
{
return $this->role === 'admin';
}
}<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
// API3 write side: the Form Request is the input DTO. Only the keys in
// rules() survive $request->validated(); server-owned keys are rejected
// loudly with 422 instead of being silently dropped.
class UpdateProfileRequest extends FormRequest
{
public function authorize(): bool
{
// The route is /me: the subject is always the caller.
return $this->user() !== null;
}
public function rules(): array
{
return [
'name' => ['sometimes', 'string', 'max:100'],
'role' => ['prohibited'],
'blocked' => ['prohibited'],
'tenant_id' => ['prohibited'],
];
}
}<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
// API3 read side: the response DTO. Properties are listed one by one, so a
// new column is private until someone decides to publish it here.
class UserResource extends JsonResource
{
public function toArray(Request $request): array
{
$self = $request->user()?->id === $this->id;
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->when($self, $this->email),
'role' => $this->when($self || $request->user()?->isAdmin(), $this->role),
];
}
}<?php
namespace App\Http\Controllers;
use App\Http\Requests\ChangeEmailRequest;
use App\Http\Requests\UpdateProfileRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Services\RemoteImageFetcher;
use Illuminate\Http\Request;
class ProfileController
{
// Profiles are visible inside the caller's tenant only (API1), and the
// resource decides which properties (API3).
public function show(Request $request, string $id)
{
$user = User::query()
->where('tenant_id', $request->user()->tenant_id)
->findOrFail($id);
return new UserResource($user);
}
public function update(UpdateProfileRequest $request)
{
// validated() holds only the keys in rules(); #[Fillable] is the
// second fence if someone later passes the wrong array.
$request->user()->update($request->safe()->only(['name']));
return response()->noContent();
}
public function changeEmail(ChangeEmailRequest $request)
{
$user = $request->user();
$user->email = $request->validated('email');
$user->email_verified_at = null;
$user->save();
// Revoke other tokens so a thief's copy stops working.
$user->tokens()->where('id', '!=', $user->currentAccessToken()->id)->delete();
return response()->noContent();
}
// API7: the URL goes through the allow-list fetcher; a refused URL is 422.
public function importAvatar(Request $request, RemoteImageFetcher $fetcher)
{
$data = $request->validate(['picture_url' => ['required', 'url:https', 'max:2048']]);
try {
$image = $fetcher->fetch($data['picture_url']);
} catch (\InvalidArgumentException) {
return response()->json(['message' => 'This image URL is not allowed.'], 422);
}
$request->user()->forceFill(['avatar' => base64_encode($image)])->save();
return response()->noContent();
}
public function me(Request $request)
{
return new UserResource($request->user());
}
}API2: the e-mail change needs current_password:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
// API2: a sensitive change needs the current password, not just a token.
class ChangeEmailRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user() !== null;
}
public function rules(): array
{
return [
'email' => ['required', 'email', 'max:254', 'unique:users,email'],
'current_password' => ['required', 'current_password:sanctum'],
];
}
}API5: the admin controller checks again with the Laravel 13 #[Middleware] attribute:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Routing\Attributes\Controllers\Middleware;
// API5: the admin function carries its own check (Laravel 13 controller
// attribute), in addition to the can:admin group in routes/api.php. If the
// route is ever moved out of the admin group, the check moves with it.
#[Middleware('can:admin')]
class UserExportController
{
public function __invoke()
{
return UserResource::collection(User::query()->orderBy('id')->cursorPaginate(100));
}
}API6: per-user and per-device caps, a non-human timing check and an atomic decrement:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use RuntimeException;
// API6: the business rule written down. The throttle:checkout limiter
// (AppServiceProvider) caps attempts per user and per product; this
// controller caps units per user and per device for the drop, and refuses
// requests that look automated.
//
// Why not "count purchases, then insert"? Two concurrent requests both read
// count = 1 (below the cap of 2), both insert, and the user ends with 3:
// a plain SELECT takes no lock, and SELECT count(*) ... FOR UPDATE is
// rejected by PostgreSQL for aggregates. Instead each cap is a counter row
// changed by ONE conditional UPDATE ("... WHERE count < cap"): the database
// row-locks it, the second writer re-evaluates the condition after the
// first commits, and 0 affected rows means "cap reached". Stock uses the
// same pattern. All three run in one transaction, so a refusal rolls back
// the counters that were already taken.
class CheckoutController
{
private const MAX_PER_USER = 2;
private const MAX_PER_DEVICE = 2;
private const MIN_SECONDS_IN_CART = 1;
public function __invoke(Request $request)
{
$data = $request->validate([
'sku' => ['required', 'string', 'max:64'],
'device_id' => ['required', 'string', 'max:128'],
]);
$user = $request->user();
$cartItem = DB::table('cart_items')
->where('user_id', $user->id)->where('sku', $data['sku'])->first();
if ($cartItem === null || now()->diffInSeconds($cartItem->created_at, true) < self::MIN_SECONDS_IN_CART) {
// Non-human pattern: add-to-cart and checkout within a second.
return response()->json(['challenge' => 'captcha'], 428);
}
try {
DB::transaction(function () use ($data, $user) {
$this->takeOne($data['sku'], 'user', (string) $user->id, self::MAX_PER_USER, 'limit');
$this->takeOne($data['sku'], 'device', $data['device_id'], self::MAX_PER_DEVICE, 'limit');
$taken = DB::table('products')->where('sku', $data['sku'])
->where('stock', '>=', 1)->decrement('stock');
if ($taken === 0) {
throw new RuntimeException('sold_out');
}
DB::table('purchases')->insert([
'user_id' => $user->id,
'sku' => $data['sku'],
'device_id' => $data['device_id'],
'created_at' => now(),
]);
});
} catch (RuntimeException $e) {
return $e->getMessage() === 'sold_out'
? response()->json(['message' => 'Sold out.'], 409)
: response()->json(['message' => 'Limit reached for this item.'], 429);
}
return response()->noContent();
}
// Atomic "increment if below cap": the row exists after insertOrIgnore,
// and the conditional increment is a single UPDATE statement.
private function takeOne(string $sku, string $scope, string $key, int $cap, string $reason): void
{
DB::table('purchase_caps')->insertOrIgnore(['sku' => $sku, 'scope' => $scope, 'key' => $key, 'count' => 0]);
$affected = DB::table('purchase_caps')
->where(['sku' => $sku, 'scope' => $scope, 'key' => $key])
->where('count', '<', $cap)
->increment('count');
if ($affected === 0) {
throw new RuntimeException($reason);
}
}
}The service provider: the admin Gate, Gate::after turning every denial into an authz_fail log line, rate limits per user and per resource, preventSilentlyDiscardingAttributes, and no redirects for outgoing HTTP:
<?php
namespace App\Providers;
use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// API5: one named ability for every admin function.
Gate::define('admin', fn (User $user) => $user->isAdmin());
// Logging and alerting for authorization failures: every denied
// gate or policy check becomes an authz_fail event (OWASP logging
// vocabulary). Alert on the rate per user, not on single events.
Gate::after(function (User $user, string $ability, mixed $result, mixed $arguments) {
$denied = $result === false || ($result instanceof Response && $result->denied());
if ($denied) {
$subject = $arguments[0] ?? null;
Log::warning('authz_fail', [
'user_id' => $user->id,
'ability' => $ability,
'resource' => is_object($subject) ? $subject::class : $subject,
'object_id' => $subject instanceof Model ? $subject->getKey() : null,
]);
}
});
// API4 and API6: rate limits per user and per resource.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(120)->by($request->user()?->id ?: $request->ip());
});
RateLimiter::for('checkout', function (Request $request) {
return [
Limit::perMinute(5)->by('user:'.$request->user()?->id),
Limit::perMinute(300)->by('sku:'.$request->input('sku')),
];
});
// API3 in development: fail loudly when code mass-assigns a
// property that is not in #[Fillable].
Model::preventSilentlyDiscardingAttributes($this->app->isLocal());
// API10: no outgoing call follows redirects unless it opts in.
Http::globalOptions(['allow_redirects' => false]);
}
}API9 and API8: the lifecycle middleware (Deprecation, Sunset, successor Link, 410 after sunset), bootstrap/app.php with its alias and the problem-details render closure, and the versioned routes file:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Symfony\Component\HttpFoundation\Response;
// API9: versioning and deprecation as code. Routes of a deprecated version
// carry Deprecation (RFC 9745) and Sunset (RFC 8594) headers and a link to
// the successor; after the sunset date the version answers 410 Gone instead
// of living on as a zombie API.
class ApiLifecycle
{
public function handle(Request $request, Closure $next, string $deprecatedAt, string $sunset, string $successor = ''): Response
{
$sunsetAt = Carbon::parse($sunset);
$headers = [
'Deprecation' => '@'.Carbon::parse($deprecatedAt)->getTimestamp(),
'Sunset' => $sunsetAt->toRfc7231String(),
];
if ($successor !== '') {
$headers['Link'] = '<'.$successor.'>; rel="successor-version"';
}
if (now()->greaterThanOrEqualTo($sunsetAt)) {
return response()->json(['message' => 'This API version has been retired.'], 410, $headers);
}
$response = $next($request);
$response->headers->add($headers);
return $response;
}
}<?php
use App\Http\Middleware\ApiLifecycle;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
health: '/up',
then: function () {
// The chapter's vulnerable routes (Before/routes.php), for the
// feature tests and the lab only. Never mounted in production.
if (app()->environment(['local', 'testing'])) {
Route::middleware('api')->prefix('api/before')->group(base_path('routes/before.php'));
}
},
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->alias([
'api.lifecycle' => ApiLifecycle::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
// API8: unexpected errors on the API become an RFC 9457 problem
// document with a correlation id; the detail goes to the log only.
// Expected outcomes (401, 403, 404, 422, 429 ...) keep Laravel's own
// rendering, so the closure returns null for them.
$exceptions->render(function (Throwable $e, Request $request) {
if (! $request->is('api/*') || config('app.debug')
|| $e instanceof HttpExceptionInterface
|| $e instanceof ValidationException
|| $e instanceof AuthenticationException
|| $e instanceof AuthorizationException) {
return null;
}
$id = (string) Str::uuid();
Log::error('internal_error', ['error_id' => $id, 'path' => $request->path(), 'exception' => $e]);
return response()->json([
'type' => 'about:blank',
'title' => 'Internal Server Error',
'status' => 500,
'instance' => 'urn:error:'.$id,
], 500, ['Content-Type' => 'application/problem+json']);
});
})
->create();<?php
use App\Http\Controllers\Admin\UserExportController;
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\OrderController;
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
// Every route is in this file, versioned, and mirrored in openapi.yaml,
// which CI diffs against `php artisan route:list --json` (API9).
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
Route::prefix('v2')->group(function () {
Route::get('/me', [ProfileController::class, 'me']);
Route::patch('/me', [ProfileController::class, 'update']);
Route::put('/me/email', [ProfileController::class, 'changeEmail']);
Route::get('/users/{id}', [ProfileController::class, 'show']);
Route::post('/me/avatar/import', [ProfileController::class, 'importAvatar']);
Route::get('/orders', [OrderController::class, 'index']);
Route::get('/orders/{id}', [OrderController::class, 'show']);
Route::post('/checkout', CheckoutController::class)->middleware('throttle:checkout');
// API5: admin functions are grouped AND each controller checks again.
Route::prefix('admin')->middleware('can:admin')->group(function () {
Route::get('/users', UserExportController::class);
});
});
// API9: the old version keeps working until its sunset, loudly.
Route::prefix('v1')
->middleware('api.lifecycle:2026-06-30T23:59:59Z,2026-12-31T23:59:59Z,/api/v2/orders')
->group(function () {
Route::get('/orders/{id}', [OrderController::class, 'show']);
});
});API10: the partner client with TLS, timeouts, no redirects, a size cap, validation and bindings:
<?php
namespace App\Services;
use App\Support\BoundedBody;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use RuntimeException;
// API10: third-party API trust is earned per field. TLS only, short
// timeouts, no redirects, a size cap applied while streaming (not after the
// whole body is in memory), the same validation as user input, and bindings
// when the value reaches SQL.
class AddressEnrichment
{
private const MAX_BYTES = 65536;
public function enrich(string $address, int $tenantId): void
{
$response = Http::baseUrl('https://geo-partner.example')
->connectTimeout(2)
->timeout(5)
->withOptions(['allow_redirects' => false, 'stream' => true])
->acceptJson()
->get('/lookup', ['q' => $address]);
if ($response->status() !== 200 || ! str_starts_with((string) $response->header('Content-Type'), 'application/json')) {
throw new RuntimeException('Upstream refused: status '.$response->status());
}
$payload = json_decode(BoundedBody::read($response, self::MAX_BYTES), true, 16, JSON_THROW_ON_ERROR);
$data = Validator::make(is_array($payload) ? $payload : [], [
'name' => ['required', 'string', 'max:200'],
'city' => ['required', 'string', 'max:80', 'regex:/^[\pL .\'-]+$/u'],
'country' => ['required', 'string', 'size:2', 'alpha:ascii'],
])->validate();
DB::insert(
'INSERT INTO businesses (tenant_id, name, city, country) VALUES (?, ?, ?, ?)',
[$tenantId, $data['name'], $data['city'], strtoupper($data['country'])],
);
}
}The bounded reader both partner clients use: refuse a large Content-Length, then stream at most the cap:
<?php
namespace App\Support;
use Illuminate\Http\Client\Response;
use RuntimeException;
// API4/API10: read at most $maxBytes of a response that was requested with
// withOptions(['stream' => true]), so an oversized body is refused before it
// is buffered. A declared Content-Length above the cap is refused without
// reading anything; a missing or lying Content-Length is caught while reading.
final class BoundedBody
{
public static function read(Response $response, int $maxBytes): string
{
$declared = $response->header('Content-Length');
if ($declared !== '' && (! ctype_digit($declared) || (int) $declared > $maxBytes)) {
self::close($response);
throw new RuntimeException('Upstream body too large (Content-Length '.$declared.')');
}
$stream = $response->resource();
$body = '';
while (! feof($stream) && strlen($body) <= $maxBytes) {
$chunk = fread($stream, 8192);
if ($chunk === false) {
break;
}
$body .= $chunk;
}
fclose($stream);
if (strlen($body) > $maxBytes) {
throw new RuntimeException('Upstream body larger than '.$maxBytes.' bytes');
}
return $body;
}
private static function close(Response $response): void
{
$response->toPsrResponse()->getBody()->close();
}
}API7: the allow-list fetcher for user-supplied image URLs (used by ProfileController::importAvatar):
<?php
namespace App\Services;
use App\Support\BoundedBody;
use Illuminate\Support\Facades\Http;
use InvalidArgumentException;
// API7: fetch user-supplied image URLs only from allow-listed hosts, over
// https on 443, without userinfo, IP literals or redirects. The DNS-rebinding
// defence (resolve, check the IP, pin it) is SafeHttpClient in the OWASP
// Top 10 chapter; this class is the allow-list layer in front of it.
class RemoteImageFetcher
{
private const ALLOWED_HOSTS = ['images.example-cdn.com', 'secure.gravatar.com'];
private const MAX_BYTES = 5_242_880;
public function fetch(string $url): string
{
$parts = parse_url($url);
$host = strtolower($parts['host'] ?? '');
if (($parts['scheme'] ?? '') !== 'https'
|| isset($parts['user']) || isset($parts['pass'])
|| (isset($parts['port']) && $parts['port'] !== 443)
|| filter_var(trim($host, '[]'), FILTER_VALIDATE_IP) !== false
|| ! in_array($host, self::ALLOWED_HOSTS, true)) {
throw new InvalidArgumentException('Destination not allowed');
}
$response = Http::connectTimeout(2)->timeout(5)
->withOptions(['allow_redirects' => false, 'stream' => true])
->get($url);
if ($response->status() !== 200
|| ! str_starts_with((string) $response->header('Content-Type'), 'image/')) {
throw new InvalidArgumentException('Remote image rejected');
}
try {
return BoundedBody::read($response, self::MAX_BYTES);
} catch (\RuntimeException) {
throw new InvalidArgumentException('Remote image too large');
}
}
}API8: exact CORS origins (php artisan config:publish cors); the problem-details render closure is in bootstrap/app.php above:
<?php
// API8: published with `php artisan config:publish cors`. Exact origins,
// never a reflected Origin together with credentials.
return [
'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'PATCH', 'PUT', 'DELETE'],
'allowed_origins' => ['https://shop.example.com', 'https://admin.example.com'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Authorization', 'Content-Type', 'Accept', 'X-Request-Id'],
'exposed_headers' => ['Deprecation', 'Sunset', 'Link'],
'max_age' => 600,
'supports_credentials' => true,
];Feature tests against the fixed routes (two users in one tenant plus one in another), with the factory and the migration that make the suite reproducible:
<?php
namespace Tests\Feature;
use App\Models\Order;
use App\Models\User;
use App\Services\AddressEnrichment;
use App\Services\RemoteImageFetcher;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use Laravel\Sanctum\Sanctum;
use RuntimeException;
use Tests\TestCase;
// Two users in one tenant, a third in another: the minimum cast for
// authorization tests (OWASP: "Write tests to evaluate the vulnerability of
// the authorization mechanism").
class ApiSecurityTest extends TestCase
{
use RefreshDatabase;
private function user(array $attrs = []): User
{
return User::factory()->create($attrs + ['tenant_id' => 7, 'role' => 'user']);
}
private function orderFor(User $owner): Order
{
$order = new Order;
$order->forceFill(['user_id' => $owner->id, 'tenant_id' => $owner->tenant_id, 'number' => 'A-1', 'status' => 'paid', 'total_cents' => 1999])->save();
return $order;
}
public function test_bola_foreign_order_is_404_and_logged(): void
{
Log::spy();
$ana = $this->user();
$bob = $this->user();
$bobsOrder = $this->orderFor($bob);
Sanctum::actingAs($ana);
$this->getJson("/api/v2/orders/{$bobsOrder->id}")->assertNotFound();
$this->getJson('/api/v2/orders/999999')->assertNotFound();
Log::shouldHaveReceived('warning')->withArgs(fn ($msg, $ctx) => $msg === 'authz_fail' && $ctx['object_id'] === $bobsOrder->id)->once();
}
public function test_bola_other_tenant_cannot_load_the_row(): void
{
$owner = $this->user();
$order = $this->orderFor($owner);
Sanctum::actingAs($this->user(['tenant_id' => 8, 'role' => 'support']));
$this->getJson("/api/v2/orders/{$order->id}")->assertNotFound();
}
public function test_bopla_response_dto_hides_other_users_properties(): void
{
$sam = $this->user(['email' => 'sam@example.com']);
Sanctum::actingAs($this->user());
$this->getJson("/api/v2/users/{$sam->id}")
->assertOk()
->assertExactJson(['data' => ['id' => $sam->id, 'name' => $sam->name]]);
}
public function test_bopla_server_owned_properties_are_prohibited(): void
{
$ana = $this->user();
Sanctum::actingAs($ana);
$this->patchJson('/api/v2/me', ['name' => 'Ana', 'role' => 'admin'])
->assertUnprocessable()->assertJsonValidationErrors('role');
$this->assertSame('user', $ana->fresh()->role);
}
public function test_bfla_user_cannot_call_admin_export(): void
{
Sanctum::actingAs($this->user());
$this->getJson('/api/v2/admin/users')->assertForbidden();
Sanctum::actingAs($this->user(['role' => 'admin']));
$this->getJson('/api/v2/admin/users')->assertOk();
}
public function test_api2_email_change_needs_current_password(): void
{
Sanctum::actingAs($this->user());
$this->putJson('/api/v2/me/email', ['email' => 'new@example.com'])
->assertUnprocessable()->assertJsonValidationErrors('current_password');
}
public function test_api4_page_size_is_clamped(): void
{
$ana = $this->user();
DB::table('orders')->insert(collect(range(1, 500))->map(fn ($i) => [
'tenant_id' => 7, 'user_id' => $ana->id, 'number' => "A-{$i}", 'status' => 'paid', 'total_cents' => 100,
])->all());
Sanctum::actingAs($ana);
// Same attack as BeforeLeaksTest: the fixed route returns at most 100 rows.
$this->getJson('/api/v2/orders?per_page=100000')
->assertOk()->assertJsonCount(100, 'data')->assertJsonPath('per_page', 100);
}
public function test_api6_second_checkout_burst_is_limited(): void
{
$ana = $this->user();
Sanctum::actingAs($ana);
DB::table('products')->insert(['sku' => 'console-x', 'stock' => 100]);
DB::table('cart_items')->insert(['user_id' => $ana->id, 'sku' => 'console-x', 'created_at' => now()->subMinute()]);
$codes = collect(range(1, 5))->map(fn () => $this->postJson('/api/v2/checkout', ['sku' => 'console-x', 'device_id' => 'dev-a'])->status());
$this->assertSame([204, 204, 429, 429, 429], $codes->all());
$this->assertSame(98, DB::table('products')->where('sku', 'console-x')->value('stock'));
}
public function test_api7_internal_and_unlisted_urls_are_refused(): void
{
Http::preventStrayRequests();
foreach (['http://169.254.169.254/latest/meta-data/', 'https://127.0.0.1/', 'https://localhost:8080/', 'https://evil.example/a.png'] as $url) {
try {
app(RemoteImageFetcher::class)->fetch($url);
$this->fail("{$url} must be refused");
} catch (InvalidArgumentException) {
$this->addToAssertionCount(1);
}
}
}
public function test_api8_unexpected_error_is_a_generic_problem_document(): void
{
config(['app.debug' => false]);
Route::middleware('api')->get('/api/v2/boom', function () {
throw new RuntimeException('SQLSTATE[42P01]: relation "report_v2" does not exist');
});
$this->getJson('/api/v2/boom')
->assertStatus(500)
->assertHeader('Content-Type', 'application/problem+json')
->assertJsonPath('title', 'Internal Server Error')
->assertDontSee('report_v2');
}
public function test_api6_device_cap_holds_across_accounts(): void
{
DB::table('products')->insert(['sku' => 'console-x', 'stock' => 100]);
// Two other accounts already bought on this device.
DB::table('purchase_caps')->insert(['sku' => 'console-x', 'scope' => 'device', 'key' => 'dev-a', 'count' => 2]);
$third = $this->user();
DB::table('cart_items')->insert(['user_id' => $third->id, 'sku' => 'console-x', 'created_at' => now()->subMinute()]);
Sanctum::actingAs($third);
$this->postJson('/api/v2/checkout', ['sku' => 'console-x', 'device_id' => 'dev-a'])->assertStatus(429);
// The refusal rolled back the user counter taken before the device check.
$this->assertSame(0, (int) DB::table('purchase_caps')->where(['scope' => 'user', 'key' => (string) $third->id])->value('count'));
$this->assertSame(100, DB::table('products')->where('sku', 'console-x')->value('stock'));
}
public function test_api10_oversized_upstream_body_is_refused_before_buffering(): void
{
Http::fake(['geo-partner.example/*' => Http::response(['name' => 'Acme', 'city' => 'Delft', 'country' => 'NL'], 200, ['Content-Length' => '900000000'])]);
$this->expectException(RuntimeException::class);
app(AddressEnrichment::class)->enrich('1 Main St', 7);
}
public function test_api9_deprecated_version_announces_its_sunset(): void
{
$ana = $this->user();
$order = $this->orderFor($ana);
Sanctum::actingAs($ana);
$this->travelTo('2026-11-29 12:00:00');
$this->getJson("/api/v1/orders/{$order->id}")
->assertOk()
->assertHeader('Deprecation', '@1782863999')
->assertHeader('Sunset', 'Thu, 31 Dec 2026 23:59:59 GMT');
$this->travelTo('2027-01-01 00:00:00');
$this->getJson("/api/v1/orders/{$order->id}")->assertStatus(410);
}
public function test_api10_upstream_redirect_and_bad_payload_are_rejected(): void
{
Http::preventStrayRequests();
Http::fake(['geo-partner.example/*' => Http::response('', 308, ['Location' => 'https://attacker.example/'])]);
$this->expectException(RuntimeException::class);
app(AddressEnrichment::class)->enrich('1 Main St', 7);
}
public function test_api10_upstream_values_are_validated(): void
{
Http::fake(['geo-partner.example/*' => Http::response(['name' => 'Acme', 'city' => '<script>', 'country' => 'NL'])]);
$this->expectException(ValidationException::class);
app(AddressEnrichment::class)->enrich('1 Main St', 7);
}
}<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
protected $model = User::class;
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'password' => Hash::make('correct horse battery staple'),
'remember_token' => Str::random(10),
'tenant_id' => 7,
'role' => 'user',
'blocked' => false,
'mfa_secret' => 'JBSWY3DPEHPK3PXP',
];
}
public function admin(): static
{
return $this->state(['role' => 'admin']);
}
}<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Schema for the chapter's feature suite. Run after the framework's own
// users and Sanctum migrations (php artisan install:api creates
// personal_access_tokens).
return new class extends Migration
{
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->unsignedBigInteger('tenant_id')->default(7)->index();
$table->string('role', 20)->default('user');
$table->boolean('blocked')->default(false);
$table->string('mfa_secret')->nullable();
$table->text('avatar')->nullable();
});
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('tenant_id');
$table->foreignId('user_id')->constrained();
$table->string('number');
$table->string('status');
$table->unsignedBigInteger('total_cents');
$table->timestamps();
$table->index(['tenant_id', 'id']);
});
Schema::create('products', function (Blueprint $table) {
$table->string('sku')->primary();
$table->unsignedInteger('stock');
});
Schema::create('cart_items', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('sku');
$table->timestamp('created_at');
});
Schema::create('purchases', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained();
$table->string('sku');
$table->string('device_id')->nullable();
$table->timestamp('created_at');
});
// API6: one counter row per (sku, scope, key); the cap is enforced by
// a conditional UPDATE on this row, which the database serialises.
Schema::create('purchase_caps', function (Blueprint $table) {
$table->string('sku');
$table->string('scope', 10); // 'user' or 'device'
$table->string('key');
$table->unsignedInteger('count')->default(0);
$table->primary(['sku', 'scope', 'key']);
});
Schema::create('businesses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('tenant_id')->nullable();
$table->string('name');
$table->string('city')->nullable();
$table->string('country', 2)->nullable();
});
}
public function down(): void
{
Schema::dropIfExists('businesses');
Schema::dropIfExists('purchase_caps');
Schema::dropIfExists('purchases');
Schema::dropIfExists('cart_items');
Schema::dropIfExists('products');
Schema::dropIfExists('orders');
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['tenant_id', 'role', 'blocked', 'mfa_secret', 'avatar']);
});
}
};API9 in CI: the Laravel OpenAPI inventory and the diff that fails the job when code and spec disagree (run in the Lab):
{
"openapi": "3.1.0",
"info": {
"title": "Shop API (Laravel)",
"version": "2.3.0"
},
"paths": {
"/api/v2/me": {
"get": {
"operationId": "getMe",
"x-owner": "team-shop",
"x-audience": "public"
},
"patch": {
"operationId": "updateMe",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/me/email": {
"put": {
"operationId": "changeEmail",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/me/avatar/import": {
"post": {
"operationId": "importAvatar",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/users/{id}": {
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"get": {
"operationId": "getUser",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/orders": {
"get": {
"operationId": "listOrders",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/orders/{id}": {
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"get": {
"operationId": "getOrder",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/checkout": {
"post": {
"operationId": "checkout",
"x-owner": "team-shop",
"x-audience": "public"
}
},
"/api/v2/admin/users": {
"get": {
"operationId": "exportUsers",
"x-owner": "team-shop",
"x-audience": "internal"
}
},
"/api/v1/orders/{id}": {
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "integer"
}
}
],
"get": {
"operationId": "getOrderV1",
"x-owner": "team-shop",
"x-audience": "public",
"deprecated": true,
"x-deprecated-at": "2026-06-30T23:59:59Z",
"x-sunset": "2026-12-31T23:59:59Z",
"x-successor": "/api/v2/orders"
}
}
}
}#!/usr/bin/env bash
# API9: fail CI when the routes in the build and the OpenAPI inventory differ.
# Usage: scripts/inventory-diff.sh <route-list.json> [openapi.json]
# route-list.json: output of `php artisan route:list --json --path=api`
# Lines starting with "<" are shadow routes (in code, not in the spec);
# lines starting with ">" are missing routes (in the spec, not in code).
# Exit status: 0 when they agree, 1 when they differ (diff's own status).
set -euo pipefail
routes_json=$1
spec_json=${2:-openapi.json}
# Every method of a route becomes its own pair ("GET|HEAD|POST" -> three
# lines); HEAD is implied by GET in Laravel and OpenAPI, so it is dropped.
code=$(jq -r '.[] | .uri as $u | .method | split("|")[] | select(. != "HEAD") | . + " /" + $u' "$routes_json" | sort)
spec=$(jq -r '.paths | to_entries[] | .key as $p | .value | keys[]
| select(. != "parameters") | ascii_upcase + " " + $p' "$spec_json" | sort)
diff <(printf '%s\n' "$code") <(printf '%s\n' "$spec")The Laravel angle
- Laravel Policies and the Gate. "By default, Laravel automatically discover policies as long as the model and policy follow standard Laravel naming conventions" (
App\Models\Order→App\Policies\OrderPolicy);#[UsePolicy(OrderPolicy::class)]on the model names it explicitly. Call it withGate::authorize('view', $order)(throwsAuthorizationException, rendered as 403, or 404 when the policy returnsResponse::denyAsNotFound(); the docs: "hiding resources via a 404 response is such a common pattern for web applications, the denyAsNotFound method is offered for convenience"),$request->user()->can(...), thecan:update,postroute middleware,->can('update', 'post')on a route, or Laravel 13's#[Authorize('create', [Comment::class, 'post'])]controller attribute.Gate::aftersees every result; the docs note that its return value does not override a non-null gate result, so it is safe for logging. - Query scoping first. Policies run after the model is loaded; load it through the relation (
$request->user()->orders()->findOrFail($id)) or with an explicitwhere('tenant_id', ...)so a foreign tenant's row never reaches PHP. For nested routes,Route::scopeBindings()makes Laravel resolve/shops/{shop}/orders/{order}only when the order belongs to the shop. - Mass assignment. Laravel 13: "you will need to specify either a Fillable or Guarded attribute on your model class. These attributes are required because all Eloquent models are protected against mass assignment vulnerabilities by default." In Laravel 12 and older code the same thing is
protected $fillable = [...]andprotected $guarded = [...](the 12.x docs showprotected $guarded = [];to allow everything).#[Unguarded]makes you "always hand-craft the arrays passed to Eloquent's fill, create, and update methods".Model::preventSilentlyDiscardingAttributes($this->app->isLocal())turns silent drops into exceptions in development. - Form Request.
authorize()("you may determine if a user actually owns a blog comment they are attempting to update") andrules();$request->validated()and$request->safe()->only([...])return only validated keys.prohibited("The field under validation must be missing or empty") turns a probe forroleinto a 422 instead of a silent drop, which you can alert on. - API resources as response DTOs. A
JsonResource::toArray()lists properties explicitly;$this->when($condition, $value)adds a property only for some callers;#[Hidden([...])]on the model is the backstop when someone returns a model directly. - Rate limits per user and per resource.
RateLimiter::for('checkout', fn (Request $r) => [Limit::perMinute(5)->by('user:'.$r->user()?->id), Limit::perMinute(300)->by('sku:'.$r->input('sku'))]); the docs: "you may return an array of rate limits" and, when several limits share abyvalue, "you should ensure that each by value is unique" (hence the prefixes). Apply withthrottle:checkout. - HTTP client. "By default, the HTTP client will timeout after 30 seconds"; set
connectTimeout()andtimeout()per integration;Http::globalOptions(['allow_redirects' => false])turns redirects off for every call;Http::preventStrayRequests()in tests makes unfaked calls fail. - Sanctum tokens and abilities (
auth:sanctum,abilities:check-status,place-orders) are function-level scopes for API clients; they do not replace policies. Token design is in Authentication.
Solving the classic problems
Pentest finding: BOLA on /api/orders/{id} across tenants
Scope in SQL so the database cannot return a foreign row, keep the policy for owner-vs-support rules, return 404 for both cases, and add row-level security as the net under the code:
-- 1. Every read and write carries the tenant and, for customer endpoints, the owner
SELECT id, number, status, total_cents
FROM orders
WHERE id = $1 AND tenant_id = $2 AND user_id = $3;
-- 2. The index that makes the scope free
CREATE INDEX orders_tenant_id_idx ON orders (tenant_id, id);
-- 3. PostgreSQL row-level security keyed on a per-transaction setting
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);
-- the app runs, inside each transaction: SET LOCAL app.tenant_id = '7';
-- 4. Public ids that do not enumerate (PostgreSQL 18 has uuidv7(); older: gen_random_uuid() for v4)
ALTER TABLE orders ADD COLUMN public_id uuid NOT NULL DEFAULT gen_random_uuid() UNIQUE;| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Scoped query | WHERE tenant_id = $2 AND user_id = $3; $user->orders()->findOrFail($id) | The row cannot load | Every query must remember; review rule |
| Policy object | CanView(u, o); OrderPolicy::view + Gate::authorize | Central rules (owner, support, delegated access) | Must be called; tests per action |
| Row-level security | PostgreSQL CREATE POLICY with SET LOCAL | Holds when code forgets | Pool hygiene (SET LOCAL per transaction), superuser bypass, FORCE needed for owners |
| Random public ids | UUIDv4/UUIDv7 column, keep bigint PK | No enumeration, no volume leak | Not authorization |
/me/... routes | GET /me/orders/{id} with subject from the token | Fewer ids from the client | Admin and support still need id routes |
| Two-user tests in CI | A reads B's object for every resource and verb | Regressions caught | Fixture work |
authz_fail alerts | Rate per user on policy denials | Detects probing in production | Tuning |
BOPLA: the mobile app hides fields the API returns
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Response DTO per audience | PublicUser / SelfUser; UserResource with when() | New columns private by default | One class per shape |
| Input DTO / Form Request | UpdateInput + DisallowUnknownFields; rules() + prohibited | Probes visible as 400/422 | Keep rules in sync with the UI |
#[Fillable] / $fillable | Allow-list on the model | Second fence | Silent drop unless preventSilentlyDiscardingAttributes |
#[Hidden] | Backstop on serialisation | Catches return $user | Block-list: not the primary control |
| Response schema test | assertExactJson, OpenAPI response validation in CI | "schema-based response validation mechanism" | Test maintenance |
| GraphQL field auth | Per-field resolvers check the viewer | Same rule for every query shape | More resolver code |
Clean-up after the finding: rotate whatever leaked (mfa_secret means re-enrolling MFA; password hashes mean forced resets if the hash is weak), and search access logs for the endpoint to estimate exposure.
BFLA: a regular user exported every account
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Deny by default at registration | bfla.NewMux refuses a route without roles or AnyUser; in Laravel every route inside an authenticated group with an explicit can: | The forgotten route cannot exist | One line per route |
| Method in the pattern | DELETE /api/users/{id} registered separately | Method tampering gets 405 or its own policy | n/a |
| Admin controllers check themselves | #[Middleware('can:admin')], an admin base class | Moving the route keeps the check | Duplicate check (intended) |
| Role matrix test | Every route × every role, expected status | Finds new routes without policies | Generated test data |
| Separate admin surface | Admin API on its own host, VPN or SSO + device posture | Smaller blast radius | Operational cost |
| Remove from the client bundle | Admin-only code not shipped to users | Less discovery | Does not fix the server |
API6: the launch-day drop sold out to bots in 180 ms
Make the business rule a constraint the database enforces, not only a counter in memory:
-- One unit per customer per drop, enforced by the database
CREATE TABLE purchases (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
drop_id bigint NOT NULL,
user_id bigint NOT NULL,
device_id text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT one_per_user_per_drop UNIQUE (drop_id, user_id)
);
-- Stock decrement that cannot oversell
UPDATE products SET stock = stock - 1 WHERE sku = $1 AND stock >= 1; -- 0 rows = sold out
-- Account clusters: devices used by more than 3 buying accounts in this drop
SELECT device_id, count(DISTINCT user_id) AS accounts
FROM purchases WHERE drop_id = $1
GROUP BY device_id HAVING count(DISTINCT user_id) > 3;| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Per-user cap | UNIQUE (drop_id, user_id), MaxPerUser | Exact, race-free | Account farms |
| Per-device cap | MaxPerDevice, device fingerprinting | Hurts farms on one device | Spoofable, privacy review |
| Per-resource rate | Limit::perMinute(300)->by('sku:...') | Protects the scarce item and the backend | Legit spikes queue |
| Non-human timing | cart → checkout ≥ 1 s (server-side timestamps) | Free, catches naive scripts | Smart bots add delays |
| Challenge on doubt | 428 → CAPTCHA or step-up | Keeps humans flowing | Solver farms; accessibility |
| Queue or lottery | Waiting room, raffle for drops | Removes the speed advantage | Product change |
| Verified buyers | Purchase history, phone verification for drops | Raises account cost | Friction |
API9: a forgotten beta host without the rate limiter
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Discover | DNS and certificate-transparency enumeration of your own domains, cloud asset inventory, gateway and mesh traffic | Finds shadow hosts | Recurring work |
| OpenAPI as inventory | Spec with x-owner, x-audience, deprecated, x-sunset; CI diff against routes | Shadow routes fail the build | Spec discipline |
| Same controls everywhere | Rate limits and auth in the service, not only in a gateway in front of production | Beta = prod security | Duplicate config |
| Retire | Deprecation → Sunset → 410 → delete route, DNS and credentials | Zombies die | Client migration |
| No production data outside production | Synthetic data in staging and beta | Breach of beta leaks nothing real | Test-data tooling |
| Data-flow register | Every third party: data, purpose, approval | Answers "what did the partner get?" | Governance |
API10: the partner was breached and answers with redirects
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| No blind redirects | CheckRedirect allow-list; allow_redirects => false | Sensitive bodies stay put | Partner URL changes need config |
| Timeouts and caps | Timeout, LimitReader; connectTimeout, timeout, body length | Partner outages do not become yours | Tuning per partner |
| Validate responses | Lengths, patterns, enums, schema | Injection and garbage stop at the edge | Breaks when partner changes format (good: you notice) |
| Bind, encode, never splice | SQL parameters, HTML escaping of partner text | Payload stays data | n/a |
| Contract tests with hostile fixtures | Tests feed '; drop, <script>, 2 MB bodies, 308 | Regression-proof | Fixture upkeep |
| Egress control | Partner traffic through an egress proxy with a host allow-list | Defence in depth | Infrastructure |
| Vendor review | "assess their API security posture" before signing | Fewer bad partners | Procurement time |
Testing: two users, a role matrix, a spec diff
| Kind | What it does | Tools | Finds well | Misses |
|---|---|---|---|---|
| Authorization unit tests | Users × objects × actions table against the policy | Go testing, PHPUnit/Pest | API1, API3, API5 logic | Missing calls to the policy |
| Two-user feature tests | User A requests every object of user B, every verb | httptest, Laravel Sanctum::actingAs | Missing checks end to end | Untested routes |
| Role matrix | Every route × every role → expected status | Generated from the route list | New routes without a policy | Object-level rules |
| Manual replay | Intercepting proxy replays requests with another account's token; the Autorize README: it "automatically replays requests using low-privileged or unauthenticated contexts, and analyzes the server responses to determine whether access controls are properly enforced" | Burp Suite (Repeater, Autorize extension), OWASP ZAP | BOLA, BFLA, BOPLA in real traffic | Scale |
| Spec-driven testing | Schemathesis "automatically generates property-based tests from OpenAPI and GraphQL schemas"; the ZAP add-on "allows you to spider and import OpenAPI (Swagger) definitions, versions 1.2, 2.0, 3.0, and 3.1" | Schemathesis, ZAP OpenAPI add-on | Undocumented fields, 500s, schema drift | Authorization semantics |
| Spec vs route diff | Compares OpenAPI with registered routes | inventory.Diff, route:list --json + script | Shadow and missing routes | Hosts outside the repo |
| Attack-surface discovery | Finds hosts and versions you forgot | DNS/CT enumeration, cloud inventory, gateway logs | API9 shadow and zombie hosts | Internal-only APIs |
| Upstream contract tests | Hostile partner fixtures | httptest servers, Http::fake | API10 handling | Real partner behaviour |
The OWASP Authorization Testing Automation cheat sheet describes the same idea at scale: keep an authorization matrix as data and generate the tests from it. The IDOR cheat sheet's procedure is the minimum: "Create User A and User B", give each objects, "attempt to access User B's objects by modifying object references", for "read, create, update, delete, export, and administrative actions".
Choosing
| Situation | Primary control | Extra technique | Reason |
|---|---|---|---|
| Any endpoint that takes an object id | Scoped query + policy object | RLS, random public ids, authz_fail alerts | API1 is first for a reason |
| Multi-tenant SaaS | Tenant from the principal, in every query | PostgreSQL RLS with SET LOCAL | One missed WHERE leaks a customer |
| Any response that returns a model | Response DTO / JsonResource | #[Hidden], schema tests | New columns leak by default otherwise |
| Any write endpoint | Input DTO / Form Request with prohibited | #[Fillable] or $fillable, DisallowUnknownFields | Block-lists fail open |
| Admin functions | Deny by default route table, can:admin | Separate host, step-up auth | BFLA is guessing plus a missing check |
| Same path, several methods | Method in the pattern, policy per method | 405 for the rest | GET vs DELETE tampering |
| Scarce goods, bookings, sign-ups, referrals | Named flow rules: per user, per device, per resource | Challenges, queues, DB constraints | API6 abuse uses valid requests |
| Expensive or paid operations (SMS, AI, exports) | Per-user operation limits and spending caps | Billing alerts | API4 cost attacks |
| Public API with versions | OpenAPI as inventory, Deprecation/Sunset, 410 | Same security on every live version | Zombies and shadows |
| Calling partners | Hardened client (TLS, timeouts, no redirects, caps, validation) | Egress proxy, contract tests | API10 |
| GraphQL | Resolver- and field-level authorization | Depth, cost and batch limits; introspection off in production | One endpoint, many objects |
| Fetching user-supplied URLs | Allow-list + connect-time IP check | Isolated fetcher | API7 (see the web Top 10 chapter) |
In architecture: from a single process to a distributed system
Monolith: one process, one database
The easy case: one router, one policy layer, one database. Example: a Laravel 13 API with auth:sanctum on the group, a Policy per model found by discovery, JsonResource for every response, Form Requests for every write, throttle:api everywhere and throttle:checkout on the drop. The review checklist is a grep: findOrFail( without a scope, ->all() passed to create/update, return $model or response()->json($model), routes outside the authenticated group, #[Unguarded]. In Go the same monolith has one principal.Middleware, one route table built by NewMux (startup fails on a route without a policy), and policy functions per resource. Inventory is one routes file and one OpenAPI document diffed in CI.
Modular monolith: boundaries without the network
Modules call each other in process, and authorization tends to live only at the HTTP edge. Example: Billing exposes InvoiceService::find(int $id) to Support; the support screen passes any id and gets any tenant's invoice, because the HTTP policy never runs. Fix: module APIs take the actor (find(Actor $actor, int $id)) and apply the same policy and tenant scope inside; DTOs are the module contract, never Eloquent models crossing the boundary (a model handed across leaks every property and invites ->update($input) from the other module). One shared authz_fail logger and one inventory of module APIs.
Microservices: every arrow is a decision
The API gateway handles TLS, authentication, coarse rate limits, request size limits, CORS and the route allow-list (API2, API4, API8, API9), and can reject unknown routes. It cannot do object-level or property-level authorization, because it does not know who owns order 1002 or which fields of a user a support agent may see. Example flow: mobile app → gateway (validates the OAuth access token, adds X-User-Id, X-Tenant-Id only after stripping any client-sent copies, enforces throttle per user) → orders service (verifies the gateway's identity via mTLS or a signed internal token, checks tenant and owner, returns a DTO) → pricing service (internal, never on the public gateway, listed as audience: internal in the inventory). Every service treats internal callers as untrusted for object checks (a compromised or confused service is a BOLA path), and every service that calls a partner is an API10 consumer with its own hardened client. API2's microservice clause applies: no service is reachable "without authentication". The gateway layer is in API gateway, BFF and service mesh, service identity in Mutual TLS.
Distributed data: replicas, caches, search, regions
Authorization has to follow every copy of the data. A search index (Elasticsearch, OpenSearch) built from orders must store tenant_id and owner_id and filter on them in every query, otherwise /search?q= is a BOLA that bypasses the primary's policies. Caches must key personal responses by user (Cache-Control: private, cache keys with tenant and user) or one user's DTO is served to another. Analytics exports and data-lake copies need the same tenant filter and the same property allow-list (no password_hash in the warehouse). Business-flow counters (API6) need shared state across instances and regions: per-user limits in one Redis per region allow a bot to buy two in each region; either route a drop to one region or use a global counter with its latency cost. Replicas lag, so a just-revoked role may still read from a replica; admin checks read the primary or a short-TTL source of truth. Inventory across regions includes every regional host and every regional version.
Scaling path: 1x, 10x, 100x
| Scale | What changes |
|---|---|
| 1x (one team, one API) | Policies + scoped queries, DTOs both ways, route table with deny by default, two-user tests, authz_fail log, OpenAPI generated in CI, throttle per user |
| 10x (several services and teams) | Gateway for authn, limits and route allow-list; shared authorization library or a policy engine (OPA, Cedar, OpenFGA); role matrix tests generated from the inventory; flow limits in Redis; partner clients from one hardened package; SIEM alerts on authz_fail rates |
| 100x (platform, many regions, partners) | Central API inventory with owners and data flows (NIST REC-API-4), traffic-based discovery of shadow APIs, version lifecycle enforced by the platform (Deprecation/Sunset/410), bot management at the edge for named flows, relationship-based authorization (ReBAC) for sharing, vendor security reviews for every integration, bug bounty scoped to APIs |
Lab
Steps 1 to 3 and 9 ran on this machine (Go 1.27.4, PHP 8.5.0 CLI, jq); everything else is expected, not run (no Laravel application, no database, no network targets).
- Run the Go tests (real run, 2026-11-29):
$ cd docs/snippets/system-design/owasp-api-security-top-10/go
$ go test -race -count=1 ./...
ok academy/owasp-api-security-top-10/authn
ok academy/owasp-api-security-top-10/bfla
ok academy/owasp-api-security-top-10/bola
ok academy/owasp-api-security-top-10/bopla
ok academy/owasp-api-security-top-10/consume
ok academy/owasp-api-security-top-10/flows
ok academy/owasp-api-security-top-10/inventory
ok academy/owasp-api-security-top-10/misconfig
ok academy/owasp-api-security-top-10/principal
ok academy/owasp-api-security-top-10/resource
ok academy/owasp-api-security-top-10/ssrf- Real run:
gofmt -l .andgo vet ./...print nothing. Read the tests in this order and predict each assertion before you read it:bola_test.go(Ana reads Bob's order, enumerates 3 of 4 ids; after the fix the foreign and the missing id return byte-identical 404s and exactly oneauthz_failline),bopla_test.go(password_hashin the response;roleandblockedwritten; then the DTO output is exactly{"id":313,"name":"Sam"}),bfla_test.go(three admin calls succeed for a user; after the fix 403 for the user, 200 for the admin, 405 forPUT, andNewMuxrefuses a route with no policy),flows_test.go(one script buys 100 of 100; after the fix 2, a second account on the same device 0),inventory_test.go(/debug/varslive; after the fix startup fails withshadow=[GET /debug/vars], v1 carriesDeprecation: @1782863999, then 410),consume_test.go(the attacker server receives the 21-byte record; after the fixErrRedirecton the redirect,ErrEndpointfor anhttp://or off-list first hop, and 0 bytes). - Real run:
php -lon the 24 PHP files printsNo syntax errors detectedfor each. - Expected, not run (a Laravel 13 app with
php artisan install:apifor Sanctum, these files copied in place,Before/routes.phpasroutes/before.php, and the supplied migration and factory):php artisan test --filter='ApiSecurityTest|BeforeLeaksTest'passes 25 tests: 10 inBeforeLeaksTestthat pass by observing each leak, 15 inApiSecurityTestagainst the fixed routes. - Expected, not run: BOLA by hand against the app.
$ TOKEN_ANA=...; curl -s -o /dev/null -w '%{http_code}\n' -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v2/orders/1002
404
$ tail -n1 storage/logs/laravel.log
[2026-11-29 10:00:00] local.WARNING: authz_fail {"user_id":41,"ability":"view","resource":"App\\Models\\Order","object_id":1002}- Expected, not run: BOPLA probe.
curl -s -X PATCH -H "Authorization: Bearer $TOKEN_ANA" -H 'Content-Type: application/json' -H 'Accept: application/json' -d '{"name":"Ana","role":"admin"}' https://api.test/api/v2/mereturns422(the JSON error body needsAccept: application/json; without it Laravel answers a validation failure with a redirect) with{"message":"The role field is prohibited.","errors":{"role":["The role field is prohibited."]}}. - Expected, not run: BFLA.
curl -s -o /dev/null -w '%{http_code}' -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v2/admin/usersprints403. - Expected, not run: API9 lifecycle.
curl -sI -H "Authorization: Bearer $TOKEN_ANA" https://api.test/api/v1/orders/1001 | grep -iE 'deprecation|sunset|link'showsDeprecation: @1782863999,Sunset: Thu, 31 Dec 2026 23:59:59 GMT,Link: </api/v2/orders>; rel="successor-version"; with the clock after the sunset the status line isHTTP/2 410. - Real run: the inventory diff. In CI the first argument is
php artisan route:list --json --path=api > routes.json(expected, not run here); this run uses fixtures in that JSON shape, one matchingroutes/api.phpand one with a shadow route added:
$ cd docs/snippets/system-design/owasp-api-security-top-10/php
$ scripts/inventory-diff.sh tests/fixtures/route-list.json openapi.json; echo "exit=$?"
exit=0
$ scripts/inventory-diff.sh tests/fixtures/route-list-shadow.json openapi.json; echo "exit=$?"
1d0
< GET /api/debug/env
exit=1
$ scripts/inventory-diff.sh tests/fixtures/route-list-extra-method.json openapi.json; echo "exit=$?"
10d9
< POST /api/v2/orders
exit=1Each route's method field (GET|HEAD|POST) is expanded into one line per method (HEAD dropped, as GET implies it), so an undeclared POST on an existing path cannot hide behind its GET. The CI failure condition is the exit status: any < line (shadow: in code, not in the spec) or > line (missing: in the spec, not in code) makes diff exit 1 and fails the job. The Go twin is inventory.Mount, which refuses to start; inventory.Parse also rejects a path template such as {id} without a required path parameter, which OpenAPI 3.1 requires, after resolving parameters the OpenAPI way (an operation-level parameter overrides a path-level one with the same name and in).
Common misconceptions
| Belief | Reality |
|---|---|
| Authentication implies authorization | A valid token says who; BOLA, BFLA and BOPLA are all "authenticated and still wrong" |
| UUIDs prevent BOLA | They prevent enumeration; leaked ids still work without the object-level check (RFC 9562: "SHOULD NOT assume that UUIDs are hard to guess") |
Comparing the JWT sub with the path id fixes BOLA | OWASP: it addresses "only a small subset of cases" |
| 403 is more honest than 404 for foreign objects | 403 confirms the object exists; 404 for both cases removes the oracle |
| The client hides sensitive fields, so the API may return them | The response is the data; use a response DTO |
$guarded = ['role'] is safe | Block-lists fail open when columns are added; use $fillable / #[Fillable] |
| Validating the fields we expect prevents mass assignment | Unexpected fields must be rejected or ignored by an allow-list |
Admin endpoints under /admin are protected by the gateway path rule | Admin functions often live under /api/users too; check per route and method |
| Rate limiting per IP stops bots | Distributed bots use many IPs; protect the flow per user, device and resource |
| Business-flow abuse is not a security bug | OWASP lists it as API6; the API exposes the flow without compensating controls |
| Old versions are harmless if undocumented | Zombie and shadow APIs keep old weaknesses and real data |
| The gateway protects every host | Only the hosts routed through it; OWASP's beta host bypassed the limiter |
| Partner APIs are trusted sources | OWASP API10: validate, cap, time out, never follow redirects blindly |
| Our HTTP client is safe by default | Go's DefaultClient has no timeout and follows 10 redirects; Laravel's default timeout is 30 s |
| Injection was dropped from the API list, so it no longer matters | It reappears through API10 (upstream data) and API8 hardening |
Cheat sheet
| Topic | Remember |
|---|---|
| The list | 2023: BOLA, Broken Authentication, BOPLA, Resource Consumption, BFLA, Business Flows, SSRF, Misconfiguration, Inventory, Unsafe Consumption |
| Three authorization levels | Function (API5), object (API1), property (API3); check all three on every request |
| BOLA fix | Principal from context + scoped query + policy object + 404 for foreign + authz_fail |
| Laravel BOLA | where('tenant_id', ...)->findOrFail($id), Gate::authorize('view', $order), Response::denyAsNotFound() |
| Ids | UUIDv7/UUIDv4 public ids against enumeration; never instead of the check |
| BOPLA read | Response DTO / JsonResource; #[Hidden] only as backstop |
| BOPLA write | Input DTO + DisallowUnknownFields; Form Request + prohibited; #[Fillable] / $fillable, never $guarded = [] |
| BFLA | Deny by default; method in the route; can:admin group + controller attribute; role matrix test |
| API6 | Name the flow; limits per user, device, resource; cart-to-checkout timing; challenge; DB constraints |
| API4 | Clamp page size, cap body and batch, timeouts, spending limits |
| API9 | OpenAPI as inventory with owner and lifecycle; CI diff; Deprecation → Sunset → 410 → delete |
| API10 | TLS, host allow-list, no blind redirects, timeouts, size cap, validate fields, bind parameters |
| API2 | Re-authenticate for e-mail/MFA changes; reset endpoints rate-limited like login |
| API7 / API8 | URL allow-list + connect-time IP check; generic problem+json errors; exact CORS |
| Logging | authz_fail with user, ability, resource, object id; alert on rate per user |
| Tests | Two users per tenant + one foreign tenant; every resource × verb |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the difference between BOLA and BFLA, in one example each? Must-know
Answer
Answer: BOLA (API1): the caller may use the function but not on this object, e.g. Ana calls GET /orders/1002, which is Bob's order. BFLA (API5): the caller may not use the function at all, e.g. a regular user calls POST /api/invites/new or DELETE /api/users/2. OWASP: if the attacker reaches a function they should not have access to, "this is a case of Broken Function Level Authorization (BFLA) rather than BOLA". See API1 and API5.
2 — Why is "compare the JWT subject with the id in the path" not a BOLA fix? Must-know
Answer
Answer: It only covers routes where the id is the user (/users/{id}). Most objects (orders, invoices, documents, vehicles, shops) are owned through a relation, shared within a tenant or delegated; the check must load the object and evaluate a policy against its owner and tenant. OWASP says the comparison "could address only a small subset of cases".
3 — Should a foreign object return 403 or 404, and what must the log say? Important
Answer
Answer: 404, identical to a missing object, so the response does not confirm that the id exists; Laravel's Response::denyAsNotFound() does this. The log records an authz_fail event (user, ability, resource type, object id, request id) only when the object exists and the policy refused, so alerts measure probing and not typos.
4 — Do UUIDs fix BOLA? What do they fix? Must-know
Answer
Answer: No. Random ids (UUIDv4, UUIDv7's random part) stop enumeration and hide volume, so a BOLA cannot be exploited by a loop; an id leaked through a link, log or another response still works without the object-level check. RFC 9562 says UUIDs "MUST NOT be used as security capabilities". Use them as defence in depth.
5 — Which two 2019 risks became API3 BOPLA, and what is the fix on each side? Must-know
Answer
Answer: API3:2019 Excessive Data Exposure (read side) and API6:2019 Mass Assignment (write side), merged on the root cause, property-level authorization. Read: a response DTO (JsonResource, a Go struct per audience) that lists allowed properties. Write: an input DTO or Form Request (DisallowUnknownFields, prohibited, $fillable/#[Fillable]) that accepts only allowed properties.
6 — Why is $guarded weaker than $fillable? Important
Answer
Answer: $guarded is a block-list: every column not listed is writable, so a column added later (is_verified, credit_limit) becomes mass-assignable without anyone deciding it. $fillable (Laravel 13: #[Fillable]) is an allow-list that fails closed. OWASP's cheat sheet: "Do not rely on a block-list as the sole protection."
7 — How do you make "admin route without a check" impossible rather than unlikely? Important
Answer
Answer: Deny by default at registration: every route must declare its policy (roles, or an explicit "any authenticated user"), and the router refuses to start otherwise, as bfla.NewMux does. Put the method in the pattern so DELETE has its own policy and unregistered methods get 405. In Laravel, put every route in an authenticated group, admin routes in a can:admin group, and repeat the check on admin controllers with #[Middleware('can:admin')]; back it with a route × role matrix test.
8 — A drop sells out to bots although every request was valid. Name four controls and their limits. Must-know
Answer
Answer: A per-user cap (a database UNIQUE (drop_id, user_id)), defeated by account farms. A per-device cap with device fingerprinting, which can be spoofed and needs a privacy review. A non-human timing rule such as add-to-cart to checkout in under one second, which smarter bots get round by waiting. A per-resource rate (per SKU per minute), which makes legitimate spikes queue. Add a challenge (CAPTCHA, step-up) when in doubt, and consider a queue or lottery so speed stops being an advantage.
9 — What are shadow and zombie APIs, and how does OpenAPI help? Important
Answer
Answer: A shadow API runs but was never inventoried (debug route, beta host, partner endpoint); a zombie API was replaced but not removed (an old version without the new rate limit). With the OpenAPI document as the inventory (paths, methods, x-owner, x-audience, deprecated, x-sunset), CI diffs it against the routes in the build and fails on shadows, and the lifecycle middleware announces deprecation with Deprecation/Sunset and returns 410 after the sunset.
10 — List five things a client for a third-party API must do that http.DefaultClient does not. Important
Answer
Answer: Set a timeout (the default has none); refuse redirects off an allow-list (the default follows up to 10 and re-sends the body on 307/308); require TLS; cap the response body (io.LimitReader); check status and content type; then validate every field like user input and bind it as a SQL parameter. That is API10's list: TLS, validation, no blind redirects, resource limits, timeouts.
11 — Why can an API gateway not fix BOLA and BOPLA on its own? Good to know
Answer
Answer: The gateway sees the path, the method and the token, not the database: it cannot know that order 1002 belongs to user 57, or which fields of a user record this viewer may see. It can authenticate, rate-limit, enforce the route allow-list and coarse role or scope rules (API2, API4, API5 partly, API9); object- and property-level checks need domain data and live in the service.
12 — Why were Injection and Insufficient Logging dropped from the 2023 API list, and does that mean they no longer matter? Good to know
Answer
Answer: The release notes do not give a reason for either drop; they describe the list as one that "does not replace other TOP 10's", and injection is covered in depth by the web OWASP Top 10, while the API6 page still references the 2019 logging entry. Both still matter: API10's scenarios are injection through upstream data, and detecting BOLA probes depends on logging and alerting for authorization failures.
Glossary
| Term | Meaning |
|---|---|
| OWASP API Security Top 10 2023 | OWASP's second edition (after 2019) of the ten most critical API security risks, API1:2023 to API10:2023 |
| OWASP Risk Rating Methodology | The scoring used for every risk: exploitability, weakness prevalence, weakness detectability, technical impact (3/2/1 each) |
| Risk table (exploitability, prevalence, detectability, impact) | The per-risk score row at the top of each OWASP risk page |
| API1 Broken Object Level Authorization (BOLA) | The caller may use the endpoint but reaches objects that are not theirs by changing an id |
| IDOR | Insecure Direct Object Reference: the web name for the same failure (CWE-639) |
| Object-level authorization check | The per-request decision "may this caller perform this action on this object?" |
| Enumeration | Finding valid ids by trying them in sequence or by pattern |
| UUID vs sequential ids | Random (UUIDv4, UUIDv7) ids resist enumeration; sequential ids leak order and volume; neither is authorization |
| UUIDv7 | RFC 9562 UUID with a 48-bit Unix millisecond timestamp followed by random bits; time-ordered |
| Context-based ownership check | Reading the caller from the request context (never the request) and comparing it with the object's owner and tenant |
| Scoped query | A query whose WHERE includes the caller's tenant/owner, so foreign rows cannot load |
| Row-level security (RLS) | PostgreSQL feature that filters rows per policy, e.g. by current_setting('app.tenant_id') |
| API2 Broken Authentication | Weak login, token handling or recovery that lets attackers assume identities |
| Re-authentication | Asking for the password, passkey or MFA again before a sensitive change |
| API3 Broken Object Property Level Authorization (BOPLA) | Reading or writing object properties the caller must not access; merger of excessive data exposure and mass assignment |
| Excessive data exposure | Returning properties the caller should not read and relying on the client to hide them (API3:2019) |
| Mass assignment | Binding request fields onto an object so the client sets properties it should not (API6:2019, CWE-915); also autobinding, object injection |
| Allow-list of properties | The explicit list of properties an endpoint returns or accepts; everything else is excluded |
| Response DTO | A data transfer object that defines exactly what leaves the API for one audience |
| Input DTO | A type that defines exactly which properties a request may set |
$fillable | Laravel (12.x and older style) model property listing mass-assignable attributes; Laravel 13 #[Fillable] |
$guarded | Laravel model property listing attributes that are not mass-assignable (a block-list); $guarded = [] unguards all |
#[Hidden] | Laravel 13 model attribute that removes attributes from array/JSON serialisation |
DisallowUnknownFields | Go json.Decoder option that makes decoding fail on keys not in the target struct |
| API4 Unrestricted Resource Consumption | Missing limits on work, size, batch, time or spend per request or client |
| Spending limit | A cap (or billing alert) on paid third-party usage such as SMS or AI calls |
| API5 Broken Function Level Authorization (BFLA) | A caller invokes a function (often an admin endpoint) their role does not allow |
| Admin endpoints | Functions for privileged roles: user export, role changes, invites, impersonation |
| Method tampering | Changing GET to DELETE/PUT to reach an unguarded handler |
| Deny by default | Access is refused unless a rule grants it; in routing, no route without a policy |
| API6 Unrestricted Access to Sensitive Business Flows | A legitimate flow (buy, book, post, refer) exposed without limits on automated, excessive use |
| Bot abuse | Automated clients consuming a flow faster or more than a human could |
| Business logic abuse | Using correct features in an unintended way that harms the business; no technical bug required |
| Scalping | Buying limited stock to resell (OWASP OAT-005) |
| Device fingerprinting | Identifying a client device from its characteristics to cap or challenge it |
| Non-human pattern | Behaviour no person produces, e.g. add-to-cart to checkout in under a second |
| Rate limits per user and per resource | Limits keyed by account and by the scarce object (SKU, slot), not only by IP |
| API7 Server Side Request Forgery | The API fetches a client-supplied URL and can be steered to internal targets (CWE-918) |
| API8 Security Misconfiguration | Unsafe defaults, verbose errors, missing TLS, permissive CORS, inconsistent proxies |
| Problem details | RFC 9457 application/problem+json error format; here with only a correlation id |
| API9 Improper Inventory Management | Unknown or undocumented hosts, versions, routes and data flows |
| API inventory | The record of every API host, version, environment, audience, owner, operation and data flow |
| Shadow API | An API running outside the inventory and security review (NIST: "Rogue or shadow APIs") |
| Zombie API | A superseded API version that still runs (NIST: "Zombie or deprecated APIs") |
| OpenAPI as inventory | Using the OpenAPI document (with x-owner, deprecated, x-sunset) as the source of truth, diffed against code in CI |
| Versioning and deprecation | Running versions side by side with a published retirement plan |
Deprecation header | RFC 9745 response header (@<unix-time>) signalling a resource is or will be deprecated |
Sunset header | RFC 8594 response header with the date a URI is likely to stop responding |
| 410 Gone | Status for a version past its sunset |
| API10 Unsafe Consumption of APIs | Trusting third-party API responses: no TLS, no validation, blind redirects, no limits or timeouts |
| Third-party API trust | The level of trust given to a partner; for data, the same as an untrusted client |
| Input validation of upstream responses | Validating partner data (types, lengths, patterns, enums) before use, then binding it |
| Authorization middleware | A request filter that enforces authentication and coarse function-level rules before handlers |
| Policy objects | Classes or functions that decide allow/deny for an action on an object (Laravel Policies, Go policy functions) |
| Laravel Policies | Classes in app/Policies with one method per action, discovered by naming convention or #[UsePolicy] |
| Gate | Laravel's authorization facade: Gate::define, Gate::authorize, Gate::before, Gate::after |
| Form Request | Laravel request class with authorize() and rules(); validated() returns only allowed keys |
prohibited | Laravel validation rule: the field must be missing or empty |
API resource (JsonResource) | Laravel's response transformer, used here as the response DTO |
| Go handler authorization | Principal from context, route policy wrapper, policy function in the handler |
| API gateway | Edge component for TLS, authentication, rate limits, routing and the route allow-list |
authz_fail | OWASP Logging Vocabulary event for an unauthorized access attempt |
| Logging and alerting for authorization failures | Recording policy denials as security events and alerting on their rate |
| CWE references | The CWE weakness ids each OWASP risk page lists (e.g. CWE-639, CWE-915, CWE-285) |
| CWE-639 | Authorization Bypass Through User-Controlled Key |
| CWE-915 | Improperly Controlled Modification of Dynamically-Determined Object Attributes |
| CWE-213 | Exposure of Sensitive Information Due to Incompatible Policies |
| CWE-285 | Improper Authorization |
| CWE-1059 | Insufficient Technical Documentation (OWASP prints "Incomplete Documentation") |
| NIST SP 800-228 | Guidelines for API Protection for Cloud-Native Systems (June 2025, updated March 2026) |
| Authorization matrix | Table of roles × functions (and objects) used to generate authorization tests |
References
- OWASP API Security Top 10 2023, the list: https://owasp.org/API-Security/editions/2023/en/0x11-t10/
- OWASP API Security 2023, Introduction, Release Notes, API Security Risks (risk rating), Methodology and Data: introduction, release notes, risks, methodology and data, what's next for developers
- OWASP API Security 2023 risk pages: API1 BOLA, API2 Broken Authentication, API3 BOPLA, API4 Unrestricted Resource Consumption, API5 BFLA, API6 Sensitive Business Flows, API7 SSRF, API8 Security Misconfiguration, API9 Improper Inventory Management, API10 Unsafe Consumption of APIs
- OWASP API Security 2019 (for the mapping): list, API3:2019 Excessive Data Exposure, API6:2019 Mass Assignment
- OWASP API Security Project: https://owasp.org/www-project-api-security/
- OWASP Risk Rating Methodology: https://owasp.org/www-community/OWASP_Risk_Rating_Methodology
- OWASP Automated Threats to Web Applications: project, OAT-005 Scalping
- OWASP Cheat Sheets: REST Security, Mass Assignment, Authorization, Authorization Testing Automation, IDOR Prevention, Input Validation, Logging, Logging Vocabulary, Web Service Security, GraphQL
- MITRE CWE: CWE-285, CWE-639, CWE-862, CWE-863, CWE-915, CWE-213, CWE-1321, CWE-204, CWE-307, CWE-770, CWE-400, CWE-799, CWE-918, CWE-16, CWE-1059, CWE-20, CWE-200, CWE-319
- NIST SP 800-228, Guidelines for API Protection for Cloud-Native Systems (updated March 13, 2026): https://csrc.nist.gov/pubs/sp/800/228/upd1/final, PDF https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-228-upd1.pdf
- OpenAPI Specification 3.1.0: https://spec.openapis.org/oas/v3.1.0.html
- RFC 9745 (Deprecation header): https://www.rfc-editor.org/rfc/rfc9745.html; RFC 8594 (Sunset header): https://www.rfc-editor.org/rfc/rfc8594.html; RFC 9457 (Problem Details): https://www.rfc-editor.org/rfc/rfc9457.html; RFC 9562 (UUIDs): https://www.rfc-editor.org/rfc/rfc9562.html
- PostgreSQL: UUID functions (18), row security policies
- Laravel 13: Authorization, Eloquent (mass assignment), Eloquent serialization (hidden), Eloquent API resources, Validation (form requests), Routing (rate limiting, scoped bindings), Rate limiting, HTTP client, Middleware, Sanctum, Errors, Release notes (attributes); Laravel 12 Eloquent (
$fillable/$guardedproperties): https://laravel.com/docs/12.x/eloquent - Go: Go 1.22 release notes (routing patterns), Routing enhancements blog, source net/http client.go, net/http request.go (MaxBytesReader), net/http server.go (ServeMux), encoding/json stream.go (DisallowUnknownFields), encoding/json decode.go