API Security Hardening Checklist: Input, Output Headers, Processing, Monitoring, CI/CD
"Define what the application accepts and reject values outside those rules. Do not try to recognize every malicious string." — OWASP Cheat Sheet Series, Input Validation Cheat Sheet
Summary: A hardened API is boring at the edges: it accepts only the methods, media types, sizes and shapes it was designed for, answers everything else with the correct status code in one error format, sends the same set of output headers on every response, never prints a stack trace or a secret, gives up on slow clients, writes one redacted log line per request with a request id, and refuses to ship when a dependency, a secret or a debug flag is wrong. This chapter turns the roadmap.sh "API Security Best Practices" checklist into a runnable Go middleware chain and its Laravel 13 equivalent, with a test for every behaviour and a curl audit script that was run against the Go server (real output below). Focus: API security checklist groups (Input, Processing, Output, Monitoring, CI & CD, plus the Authentication, JWT, Access Control and OAuth groups linked to their owners); allow-list validation, schema-first contracts, JSON depth and schema validation; HTTP method allow-list (405 Method Not Allowed + Allow), Content-Type validation (415 Unsupported Media Type), Accept validation (406 Not Acceptable), request body size limit (413 Content Too Large, http.MaxBytesReader); security headers (X-Content-Type-Options nosniff, X-Frame-Options, Content-Security-Policy default-src 'none', Strict-Transport-Security, Referrer-Policy, Cache-Control no-store), fingerprinting and how to remove Server and X-Powered-By headers; Problem Details RFC 9457, correct status codes, no stack traces, no sensitive data in responses; debug mode off (APP_DEBUG); read/write/idle timeouts and slowloris; CORS preflight and credentials; request id, correlation id, redaction, PII in logs, centralised logging, alerting, IDS/IPS, WAF; Kong, Envoy, APISIX and Nginx at the edge, OpenAPI validation at the edge; dependency scanning, SAST, DAST, secrets scanning, govulncheck, composer audit, code review rules, rollback strategy, blue-green, feature flags, API inventory. Learning goal: Given an API, run the curl audit script against it, read every FAIL line as a checklist item, and close it with the right layer: a Go middleware (harden.SecurityHeaders, AllowMethods, JSONOnly, LimitBody, DecodeJSON, Recover, RequestID, AccessLog, CORS, NewServer), a Laravel middleware or config (SecurityHeaders, EnforceJsonApi, config/cors.php, APP_DEBUG=false, a Monolog redaction tap), a gateway directive (Nginx client_max_body_size, Kong request-size-limiting, Envoy request_headers_timeout, APISIX request-validation) or a CI gate (govulncheck, composer audit, gitleaks, ZAP baseline).
This chapter owns the hardening checklist: the cross-cutting controls every endpoint gets regardless of what it does. The risk taxonomy of APIs (BOLA, BOPLA, BFLA, unrestricted resource consumption, business flows, inventory, unsafe consumption) is in OWASP API Security Top 10; application vulnerabilities in handlers (injection, XSS, CSRF, SSRF, XXE, uploads) are in OWASP Top 10; API keys, HMAC request signing and webhook signatures are in API keys, request signing and webhooks. Passwords, MFA and sessions are in Authentication, tokens in JWT deep dive, delegated access in OAuth 2.0 and OIDC, throttling in Rate limiting, TLS in TLS in practice and HTTP evolution, the pipeline and incident process in Secure SDLC. The Go mechanics of middleware and servers are in Go middlewares and Go HTTP server and client.
Page map
| If you are looking for | Go to |
|---|---|
| The checklist groups, the codes and the headers in three tables | Everything in one minute |
| Why a checklist and not "secure code" | Why it exists |
| roadmap.sh, OWASP cheat sheets, the RFCs behind the codes | Where it comes from |
| All 50 checklist items: implemented here or linked | The checklist, item by item |
| Allow-list validation, schema-first, JSON depth | Input validation |
405 and the Allow header, TRACE, method override | HTTP method allow-list |
415 and 406, Content-Type and Accept | Content-Type and Accept validation |
413, MaxBytesReader, chunked bodies | Request body size limit |
| Tokens in headers, not in URLs | Authorization header |
| nosniff, frame options, CSP, HSTS, Referrer-Policy, no-store | Security headers |
Server, X-Powered-By, version banners | Fingerprinting |
| RFC 9457, status codes, no stack traces | Error responses |
| Response allow-lists, card numbers, internal fields | No sensitive data in responses |
APP_DEBUG, pprof, debug pages | Debug mode off |
| Slowloris, read/write/idle timeouts, handler deadlines | Timeouts |
Preflight, Access-Control-Allow-Credentials, Vary: Origin | CORS |
| Request id, correlation id, redaction, PII | Logging |
| Centralised logging, alerting, IDS/IPS, WAF | Monitoring |
| Kong, Envoy, APISIX, Nginx, OpenAPI validation | API gateway |
| SAST, DAST, SCA, secrets scanning, code review | CI/CD gates |
| Rollback, blue-green, feature flags | Rollback strategy |
| Every endpoint accounted for | API inventory |
| XML entities, uploads, SSRF, async work, UUIDs | Processing items owned elsewhere |
| Middleware order, codes, knobs, defaults | Mechanics |
| Code | Go, Laravel, At the edge |
| Pentest findings and how to close them | Solving the classic problems |
| Which control at which layer | Choosing |
| Monolith to distributed system | In architecture |
| Hands-on, with real output | Lab |
Everything in one minute
The checklist groups. roadmap.sh groups 50 items into nine boxes. Four of them (Input, Processing, Output, Monitoring) are cross-cutting code that this chapter implements; CI & CD and Access Control are split between this chapter and the edge; Authentication, JWT and OAuth belong to their own chapters.
| Group | What it protects against | Typical items | Where it lives |
|---|---|---|---|
| Input | Requests the API was never designed for | Method allow-list, Content-Type validation, input validation, Authorization header, API gateway | Input validation, methods, negotiation, body limit |
| Processing | Expensive, unsafe or leaky work | Authenticated endpoints, no personal ids in URLs, XML entity expansion off, uploads via CDN, async heavy work, debug off | Debug, timeouts, links |
| Output | Browsers misreading responses, leaks | nosniff, X-Frame-Options: deny, Content-Security-Policy: default-src 'none', no fingerprint headers, forced content type, no secrets, proper codes | Headers, fingerprinting, errors, output data |
| Monitoring | Attacks nobody notices | Centralised logging, agents, alerts, no sensitive data in logs, IDS/IPS | Logging, monitoring |
| CI & CD | Shipping known holes | Tests, code review without self-approval, security analysis, dependency checks, rollback | CI/CD, rollback |
| Access Control | Network-level exposure | Throttling, HTTPS and HSTS, no directory listing, private APIs on allow-listed IPs | HSTS, gateway, links |
| Authentication | Weak login | Standard auth, no reinvented crypto, max retry and jail, encryption of sensitive data | Linked owners |
| JWT | Forged or bloated tokens | Strong secret, algorithm from the backend, short TTL, no secrets in the payload | Linked owners |
| OAuth | Stolen codes and tokens | redirect_uri checked server-side, code flow, state, scopes | Linked owners |
The status codes a hardened API actually sends. Every one of them goes out as application/problem+json (RFC 9457) with the security headers and a request id.
| Code | RFC 9110 name | Sent when | Who sends it in the Go chain |
|---|---|---|---|
| 400 | Bad Request | Malformed JSON, unknown field, too deep, trailing data | DecodeJSON |
| 401 | Unauthorized | Missing or invalid credentials | Auth middleware (linked) |
| 403 | Forbidden | Authenticated but not allowed; CORS preflight from a foreign origin | Policy layer; CORS |
| 404 | Not Found | Unknown route or an id that fails the allow-list | ServeMux, handler |
| 405 | Method Not Allowed | Method outside the allow-list or the route; always with Allow | AllowMethods, ServeMux |
| 406 | Not Acceptable | Accept excludes every type the API produces | JSONOnly |
| 413 | Content Too Large | Body above the limit (declared or streamed) | LimitBody, DecodeJSON |
| 415 | Unsupported Media Type | Body present but not application/json | JSONOnly |
| 422 | Unprocessable Content | Well-formed JSON with invalid values | Handler validation |
| 429 | Too Many Requests | Rate limit hit | Gateway or limiter (linked) |
| 500 | Internal Server Error | Panic or unexpected error; no stack trace | Recover |
| 503 | Service Unavailable | Handler deadline exceeded | http.TimeoutHandler |
The output headers for a JSON API. Values from the OWASP REST Security and HTTP Headers cheat sheets; the Go and Laravel middlewares below send exactly these.
| Header | Value | What it stops |
|---|---|---|
X-Content-Type-Options | nosniff | A browser guessing that your JSON is HTML or script |
Content-Security-Policy | default-src 'none'; frame-ancestors 'none' | Any script, style, image or framing if a response is ever rendered |
X-Frame-Options | DENY | Framing in old browsers without frame-ancestors |
Cache-Control | no-store | Shared caches and the back button keeping personal data |
Referrer-Policy | no-referrer | URLs leaking to third parties |
Strict-Transport-Security | max-age=63072000; includeSubDomains (HTTPS only) | SSL stripping on the next visit |
Content-Type | application/json or application/problem+json, set by the server | MIME confusion; never copied from Accept |
Server, X-Powered-By | removed | Version fingerprinting |
Why it exists
Most API breaches do not need a clever exploit. They need one endpoint that accepts a method nobody tested, a body nobody limited, a debug page nobody turned off, a header nobody set, or a log line that kept a token. Each of those is a default: net/http ships with no timeouts and no body limit, PHP adds X-Powered-By unless told otherwise, Nginx prints its version, Laravel's published config/cors.php starts with 'allowed_origins' => ['*'], and a fresh Kong CORS plugin with no origins allows all of them. A checklist exists because defaults are chosen for "it works on first run", not for "it survives the internet", and because the controls are cross-cutting: they belong in one middleware chain, one gateway config and one pipeline, not in every handler.
| Choice | Gain | Cost |
|---|---|---|
| Accept anything, reject only known-bad (denylist) | Nothing breaks on day one | Every new trick is a new bypass; encodings defeat the list |
| Accept only what the contract says (allow-list) | Unknown input never reaches business code | The contract must be written down (OpenAPI, DTOs, rules) |
| Controls inside each handler | Local and explicit | Forgotten on the 40th endpoint; inconsistent codes |
| Controls in one middleware chain | Every route gets them, tests prove them once | Order matters; a wrong order silently disables a layer |
| Controls only at the gateway | One place for many services | Internal callers bypass the gateway; the app still trusts input |
| Gateway and application (defence in depth) | One layer's bug is caught by the other | Two configs to keep consistent |
| Verbose errors | Fast debugging | Stack traces, SQL and paths for attackers |
| Generic errors with a request id | Nothing leaks; support finds the log line | A log pipeline that keeps and indexes the id |
An everyday picture. A company mailroom. Letters come from anyone. The mailroom only accepts envelopes addressed to departments that exist (route allow-list), of the formats the company handles (media types), below a weight limit (body size), and it does not keep the door open for someone who takes an hour to hand over one letter (timeouts). Every outgoing letter is in the company envelope with the same stamps (headers), never with internal memos stapled to it (no sensitive data), and a refused letter goes back with a standard refusal slip and a reference number (problem details with a request id) rather than an explanation of how the vault works (stack trace). The mailroom logbook records the reference number, sender and outcome, but never the contents of a letter marked confidential (redaction). We reuse the mailroom throughout.
Three common misunderstandings, up front
- "Security headers are for websites; my API returns JSON." The OWASP REST Security Cheat Sheet agrees that "if the API is only consumed by non-browser clients (e.g. mobile apps, server-to-server calls, command-line tools), most of these headers will have no effect since they are directives for browsers." But any API reachable from a browser (an SPA, a developer opening the URL, an attacker's page) can be framed, sniffed or cached, and the headers cost nothing. Send them on every response, including errors.
- "The framework validates input." Frameworks parse input; they do not know that
quantitymust be 1 to 100, thatskuhas a format, or thatrolemust not be accepted at all. The Input Validation Cheat Sheet: "Converting text to an integer only establishes a type: it does not establish an acceptable quantity." - "The gateway handles all that." A gateway is a good first wall (size, rate, TLS, schema), but internal callers, a misrouted health check or a second ingress bypass it, and only the application knows which fields are sensitive. Every control in this chapter is shown at the application layer; At the edge repeats the cheap ones at the gateway.
Where it comes from
- roadmap.sh "API Security Best Practices" (published 2023-02-21 according to its front matter, "Detailed list of best practices to make your APIs secure") is the checklist this chapter follows: 50 items in nine groups. The page at roadmap.sh is rendered client-side; this chapter used the source data from the
developer-roadmaprepository (src/data/best-practices/api-security/:api-security.jsonfor the item labels and groups, one Markdown file per item for its text), read at commit2571a7cbecause the directory has since been removed from the default branch of the repository (nownilbuild/developer-roadmap). Item wording below is quoted from that data. - OWASP Cheat Sheet Series is the precise companion: the REST Security Cheat Sheet (method allow-list with 405, content types with 415 and 406, 413 for size, the API header table, generic errors, CORS, sensitive data in URLs, status code table), HTTP Headers, Input Validation, Error Handling, Logging, Transport Layer Security, Content Security Policy and HTML5 Security (CORS). Where roadmap.sh and OWASP differ (roadmap says
X-Frame-Options: deny; OWASP calls it "Legacy header superseded by Content-Security-Policy: frame-ancestors 'none'" but still recommends it for old browsers), this chapter sends both. - The status codes are defined in RFC 9110 (HTTP Semantics, 2022), which renamed 413 from "Payload Too Large" (RFC 7231) to "Content Too Large" and 422 to "Unprocessable Content"; RFC 9110 also says that for 405 "The origin server MUST generate an Allow header field". Go's
http.StatusText(413)still returns "Request Entity Too Large" (the RFC 2616 phrase), which is why the lab's status line and the problemtitlediffer. - Problem Details: RFC 7807 (2016) defined
application/problem+json; RFC 9457 (2023) "obsoletes RFC 7807" and keeps the same members (type,title,status,detail,instance, plus extensions). - HSTS is RFC 6797 (2012). Its section 7.2 is why the Go middleware checks for TLS: "An HSTS Host MUST NOT include the STS header field in HTTP responses conveyed over non-secure transport."
- Go:
http.MaxBytesReaderhas existed since Go 1.0; Go 1.19 made it return the typed*http.MaxBytesError("will now return the defined error type MaxBytesError when its read limit is exceeded"); Go 1.22 added method patterns toServeMux("Registering a handler with a method, like "POST /items/create", restricts invocations of the handler to requests with the given method"), which also answers 405 withAllow. This module targetsgo 1.24and was tested with Go 1.27.4. - OWASP API Security Top 10 (2023) names the risks these controls reduce: API4:2023 Unrestricted Resource Consumption (sizes, timeouts), API8:2023 Security Misconfiguration (headers, CORS, debug, verbose errors), API9:2023 Improper Inventory Management. The risks themselves are taught in OWASP API Security Top 10.
The checklist, item by item
Every roadmap.sh item, with its group, and either the section that implements it here or the owner page that teaches it (one sentence each in Linked owners and Processing items owned elsewhere). "Link" rows are deliberate: the owner pages go deeper than a checklist can.
| Group | roadmap.sh item | Here or linked | Where |
|---|---|---|---|
| Authentication | Avoid 'Basic Authentication', use standard (e.g. JWT) | Link | Authentication |
| Authentication | Do not reinvent the wheel in authentication mechanisms | Link | Authentication |
| Authentication | Use 'Max Retry' and jail features in Login | Rate limiting link | Rate limiting |
| Authentication | Use encryption on all sensitive data | Link | Cryptography in practice |
| JWT | Use good JWT Secret to make brute force attacks difficult | Link | JWT deep dive |
| JWT | Do not extract the algorithm from the header, use backend | Link | JWT deep dive |
| JWT | Make token expiration (TTL, RTTL) as short as possible | Link | JWT deep dive |
| JWT | Avoid storing sensitive data in JWT payload | Link | JWT deep dive |
| JWT | Keep the payload small to reduce the size of the JWT | Link | JWT deep dive |
| Access Control | Limit requests (throttling) to avoid DDoS / Brute Force | Rate limiting link | Rate limiting, DDoS |
| Access Control | Use HTTPS on server side and secure ciphers | Link | TLS in practice |
| Access Control | Use HSTS header with SSL to avoid SSL Strip attacks | Here | Security headers |
| Access Control | Turn off directory listings | Here (edge) | Fingerprinting, At the edge |
| Access Control | Private APIs to be only accessible from safe listed IPs | Here (edge) + link | At the edge, API keys and IP allow-lists |
| OAuth | Always validate redirect_uri on server-side | Link | OAuth 2.0 and OIDC |
| OAuth | Avoid response_type=token and try to exchange for code | Link | OAuth 2.0 and OIDC |
| OAuth | Use state parameter to prevent CSRF attacks | Link | OAuth 2.0 and OIDC |
| OAuth | Have default scope, and validate scope for each application | Link | OAuth 2.0 and OIDC |
| Input | Use proper HTTP methods for the operation | Here | HTTP method allow-list |
| Input | Validate content-type on request header | Here | Content-Type and Accept |
| Input | Validate user input to avoid common vulnerabilities | Here | Input validation |
| Input | Use standard Authorization header for sensitive data | Here | Authorization header |
| Input | Use only server-side encryption | Link | Cryptography in practice |
| Input | Use an API Gateway for caching, Rate Limit policies etc | Here (edge) | API gateway |
| Processing | Check if all the endpoints are protected behind authentication | Link (method described, not implemented in this module) | API inventory, OWASP API Security Top 10 |
| Processing | Avoid user's personal ID in the resource URLs | Link | OWASP API Top 10 (BOLA) |
| Processing | Prefer using UUID over auto-increment IDs | Link | Processing items |
| Processing | Disable entity parsing if you are parsing XML to avoid XXE attacks | Link | OWASP Top 10 (XXE) |
| Processing | Disable entity expansion if using XML, YML or any other language | Link | OWASP Top 10 (XXE) |
| Processing | Use CDN for file uploads | File upload hardening link | File uploads, S3 and CDN |
| Processing | Avoid HTTP blocking if you are using huge amount of data | Here (timeouts) + link | Timeouts, Processing items |
| Processing | Make sure to turn the debug mode off in production | Here | Debug mode off |
| Processing | Use non-executable stacks when available | Link | Processing items |
| Output | Send X-Content-Type-Options: nosniff header | Here | Security headers |
| Output | Send X-Frame-Options: deny header | Here | Security headers |
| Output | Send Content-Security-Policy: default-src 'none' header | Here | Security headers |
| Output | Remove fingerprinting headers (i.e. x-powered-by etc) | Here | Fingerprinting |
| Output | Force content-type for your response | Here | Content-Type and Accept |
| Output | Avoid returning sensitive data (credentials, sec. tokens etc) | Here | No sensitive data in responses |
| Output | Return proper response codes as per the operation | Here | Error responses |
| CI & CD | Audit your design and implementation with unit/integration tests | Here | Go tests, Lab |
| CI & CD | Use a code review process and disregard self-approval | Here | CI/CD gates |
| CI & CD | Continuously run security analysis on your code | Here + link | CI/CD gates, Secure SDLC |
| CI & CD | Check your dependencies for known vulnerabilities | Here | CI/CD gates |
| CI & CD | Design a rollback solution for deployments | Here + link | Rollback strategy |
| Monitoring | Use centralized logins for all services and components | Here (logging) + link (SSO) | Monitoring, OAuth 2.0, OIDC and SSO |
| Monitoring | Use agents to monitor all requests, responses and errors | Here | Logging |
| Monitoring | Use alerts for SMS, Slack, Email, Kibana, Cloudwatch, etc. | Here | Monitoring |
| Monitoring | Ensure that you aren't logging any sensitive data | Here | Logging |
| Monitoring | Use an IDS and/or IPS system to monitor everything | Here (concept) + link | Monitoring, DDoS and network security |
Two notes on wording. "Use centralized logins" sits in the Monitoring group, and its detail page covers two things: single sign-on across services ("set up a single sign-on (SSO) system ... using protocols like OAuth or SAML", owned by OAuth 2.0, OIDC and SSO) and "centralized logging tools like ELK stack, Splunk, or Graylog", which this chapter implements in Monitoring. "SSRF guard link": the checklist has no SSRF item, but every API that fetches URLs needs the dialer-level guard taught in OWASP Top 10 (SSRF) and API7:2023 in OWASP API Security Top 10.
The concept catalogue
Input validation: allow-list validation, schema-first, JSON depth and schema validation Must-know
In plain words: Write down exactly what a valid request looks like (fields, types, lengths, ranges, formats) and reject everything else before your business code runs. Do not try to list the bad things.
Common misunderstanding: "Validation is about stopping SQL injection." Injection is stopped at the sink (placeholders, encoding; see OWASP Top 10). Validation's job is narrower and wider at once: keep the request inside the contract so the business code only ever sees values it was designed for, and fail cheaply. The OWASP Input Validation Cheat Sheet warns that "Removing suspicious characters can change meaning and still does not provide query parameterization or output encoding."
Definition: Allow-list validation (OWASP: "Define what the application accepts and reject values outside those rules") checks each field against a positive rule: type, length, range, format (regex anchored with \A…\z), enumerations, and the set of allowed field names. Schema-first means the contract (OpenAPI 3.x document, JSON Schema, protobuf) is written first and both the gateway and the code validate against it. JSON depth and schema validation adds parser limits: OWASP says "Apply request size limits before buffering or parsing input, and configure parser limits such as maximum nesting depth" because "A schema check after parsing cannot protect a parser that has already exhausted resources." Order: size limit → parse with depth limit → reject unknown fields and trailing data → field rules → business rules.
1 POST /v1/orders Content-Type: application/json Content-Length: 61
2 LimitBody 64 KiB cap -> 413 if larger
3 checkDepth tokens scanned, depth <= 16 -> 400 "JSON nested too deeply"
4 Decode DisallowUnknownFields -> 400 unknown field "price"
5 Decode one value, no trailing data -> 400 "body must contain a single JSON value"
6 validate() sku ^[A-Z0-9-]{3,32}$, 1 <= quantity <= 100, currency in {EUR, USD}
7 -> 422 with errors{sku, quantity, currency}
8 handler business rules (stock, price) on values it can trustReal scenario: a mobile client sends "quantity": -5 and the order total becomes a refund; a JSON body of 100,000 nested arrays pins a CPU in a recursive parser; an extra "price": 0 field is bound by a lax mapper (mass assignment, in OWASP Top 10); a sku with a newline ends up in a CSV export and breaks the warehouse import.
| Layer | Allow-list tool | Unknown fields | Depth / size |
|---|---|---|---|
Go encoding/json | Struct types + your validate() | Decoder.DisallowUnknownFields() | No size limit; internal maxNestingDepth = 10000; add MaxBytesReader and a token-depth scan |
| Go libraries | go-playground/validator struct tags, santhosh-tekuri/jsonschema, kin-openapi request validation | Schema additionalProperties: false | Schema maxLength, maxItems |
| Laravel | Form Request rules(), Rule::in, regex, between, $request->validated() | Silently dropped by validated(); reject with an after() hook | post_max_size, ValidatePostSize, web server limit |
| OpenAPI at the edge | Kong OAS Validation (Enterprise), APISIX request-validation, Envoy with an external validator | additionalProperties: false | APISIX client-control max_body_size, Kong request-size-limiting |
Fix / how to use it: Go DecodeJSON plus a validate() method returning field errors; Laravel StoreOrderRequest with an after() hook that rejects unknown keys; at the edge, APISIX request-validation with the same JSON Schema. Log validation failures at info level with the request id: the REST cheat sheet says "Assume that someone who is performing hundreds of failed input validations per second is up to no good."
HTTP method allow-list and 405 Method Not Allowed Must-know
In plain words: Each route answers only the verbs it was built for. Anything else, including verbs that do nothing harmful today, gets 405 and a list of what is allowed.
Common misunderstanding: "An unknown method just falls through to the default handler." That fall-through is the bug: a handler that serves any method on /v1/orders/42 turns DELETE, TRACE or a made-up FOO into a read (the "before" server in the lab does exactly that), and frameworks that honour X-HTTP-Method-Override let a POST become a DELETE past a proxy that only allowed POST. OWASP calls this verb tampering.
Definition: The REST Security Cheat Sheet: "Apply an allowlist of permitted HTTP Methods e.g. GET, POST, PUT." and "Reject all requests not matching the allowlist with HTTP response code 405 Method not allowed." RFC 9110 15.5.6 adds that a 405 response MUST carry Allow with the resource's supported methods. Two layers: a global allow-list (no TRACE, CONNECT, WebDAV verbs, override headers) and per-route patterns (GET /v1/orders/{id}, POST /v1/orders). The HTTP method allow-list is also an authorization question: "Make sure the caller is authorized to use the incoming HTTP method on the resource collection, action, and record."
1 TRACE /v1/orders/6f1c... AllowMethods: TRACE not in {GET, HEAD, POST, OPTIONS}
2 -> 405, Allow: GET, HEAD, POST, OPTIONS, problem+json
3 POST /v1/orders/6f1c... AllowMethods: ok -> ServeMux: only "GET /v1/orders/{id}"
4 -> 405, Allow: GET, HEAD (set by ServeMux), rewritten to problem+json
5 POST /v1/orders/6f1c... X-HTTP-Method-Override: DELETE
6 -> 400 "method override headers are not accepted"Real scenario: a TRACE reflected Authorization headers back (cross-site tracing on old stacks); Route::any() in Laravel exposed a state-changing action to GET, so a link preview bot triggered it; a gateway allowed only GET on /reports but the app honoured X-HTTP-Method-Override: DELETE.
| Product | Default behaviour | Method allow-list |
|---|---|---|
Go ServeMux (1.22+) | Method patterns; wrong method on a known path → 405 + Allow via http.Error (text/plain) | Patterns per route; global middleware for the rest |
| Laravel router | Wrong verb on a known URI → MethodNotAllowedHttpException (405, Allow header) | Route::get/post/...; avoid Route::any, Route::match(['*']) |
| Nginx | Passes every method to the upstream | limit_except GET POST OPTIONS { deny all; } (GET also allows HEAD; keep OPTIONS or CORS preflights die; others get 403, not 405) |
| Kong | Route methods field restricts matching; unmatched → 404 from the router | Route methods: [GET, POST] |
| Envoy | Route match on :method header | Route headers matcher on :method |
Fix / how to use it: Go AllowMethods plus method patterns; Laravel explicit Route::get/Route::post and the problem renderer in bootstrap/app.php that keeps the exception's Allow header. Test it: the Go test asserts Allow on every 405.
Content-Type validation (415) and Accept validation (406) Must-know
In plain words: If a request has a body, it must say it is JSON, and it must be JSON. If the client says it only accepts XML, tell it you only speak JSON. And you, not the client, decide what Content-Type your response carries.
Common misunderstanding: "Reject every request without Content-Type." A GET has no body and needs no Content-Type; rejecting it breaks clients for nothing. The REST cheat sheet is precise: "For requests with a body, require a supported Content-Type according to the endpoint contract and reject unsupported media types with 415 Unsupported Media Type. Do not require Content-Type solely for requests without a body. Reserve 406 Not Acceptable for response content negotiation." The second mistake is echoing: "Do NOT simply copy the Accept header to the Content-type header of the response."
Definition: Content-Type validation: for a request with content (positive Content-Length or chunked), parse the media type (mime.ParseMediaType), require application/json, allow only charset=utf-8 if a charset is given; otherwise 415 Unsupported Media Type, and RFC 9110 15.5.16 says the Accept response header "can be used to indicate" what would have worked. Accept validation: if Accept is present, take the quality of application/json from the most specific matching range (RFC 9110 12.5.1: "the most specific reference has precedence"; application/json beats application/* beats */*), so application/json;q=0, */*;q=1 excludes JSON. A range matches only if its non-q parameters match the representation too: application/json;profile=v2 does not match the plain application/json this API sends (so application/json;profile=v2;q=1, application/json;q=0 is a 406), while charset=utf-8 does (JSON is UTF-8). Weights must follow the RFC grammar (0 to 1, at most three decimals); q=NaN, q=inf or q=1e0 make that range ignored. If the resulting quality is 0 or nothing matches, answer 406 Not Acceptable. application/problem+json alone does not count, because success bodies are application/json (RFC 9110: no acceptable representation "and the server is unwilling to supply a default representation"). The roadmap item "Force content-type for your response" is the output half: always set Content-Type yourself.
1 POST /v1/orders Content-Type: text/plain body {"sku":"MUG-01"}
2 JSONOnly: body present, media type text/plain -> 415, Accept: application/json
3 POST /v1/orders (chunked, no Content-Type)
4 JSONOnly: ContentLength == -1 means body -> 415
5 GET /v1/orders/6f1c... Accept: application/xml
6 JSONOnly: no JSON range with q > 0 -> 406
7 GET /v1/orders/6f1c... Accept: text/html, */*;q=0.1
8 */* with q=0.1 accepted -> 200 application/jsonReal scenario: an endpoint parsed application/x-www-form-urlencoded as well as JSON, so a cross-site HTML form (no preflight for that type) could post to it with the user's cookie; an XML-capable endpoint, reachable only because nobody checked Content-Type, was the XXE entry point; a server that copied Accept: text/html into Content-Type let an attacker's page render a JSON error containing reflected input as HTML.
| Product | Content-Type check | Accept check |
|---|---|---|
| Go stdlib | None; json.Decoder reads any bytes | None |
| Go chain (this chapter) | JSONOnly: 415 + Accept | JSONOnly: 406, q-values with most-specific-range precedence |
| Laravel | $request->isJson(); no automatic 415 | $request->accepts() returns true as soon as any listed range matches, ignoring q and precedence (InteractsWithContentTypes::accepts), so EnforceJsonApi::jsonQuality() applies the same rules as the Go code; exceptions render JSON or HTML "based on the Accept header" |
| APISIX | request-validation header_schema | same plugin |
| Kong | OAS Validation (Enterprise) against the spec's requestBody content | Response content types in the spec |
Fix / how to use it: Go JSONOnly; Laravel EnforceJsonApi in the api group. Laravel's shouldRenderJsonWhen makes every api/* error JSON even when the client asked for HTML.
Request body size limit, 413 Content Too Large and MaxBytesReader Must-know
In plain words: Decide the biggest body each endpoint can legitimately receive and stop reading at that size, whether or not the client told you the length up front.
Common misunderstanding: "I check Content-Length, so I am safe." A chunked request has no Content-Length (Go reports ContentLength == -1), and a client can declare a small length and keep sending. Only a reader that counts bytes as they arrive (http.MaxBytesReader) is a limit; the header check is a fast path.
Definition: The REST cheat sheet: "Define an appropriate request size limit and reject requests exceeding the limit with HTTP response status 413 Request Entity Too Large." RFC 9110 calls the code 413 Content Too Large and lets the server close the connection. In Go, http.MaxBytesReader(w, r.Body, n) "is similar to io.LimitReader but is intended for limiting the size of incoming request bodies"; a read past the limit returns *http.MaxBytesError (error text "http: request body too large"), and "If possible, it tells the ResponseWriter to close the connection after the limit has been reached." That last part only works if you pass the writer net/http created: the hint is an unexported method on the server's own response type, so a wrapped ResponseWriter silently loses it. LimitBody unwraps to the innermost writer (every wrapper in the chain has Unwrap()), and a test over a real connection proves the server closes it.
1 client: POST /v1/orders Transfer-Encoding: chunked (no Content-Length)
2 LimitBody: r.ContentLength == -1, no fast-path reject; Body = MaxBytesReader(innermost(w), Body, 64 KiB)
3 handler: io.ReadAll reads 64 KiB + 1 byte
4 MaxBytesReader: returns *http.MaxBytesError, marks the connection to close
5 DecodeJSON: errors.As(err, *MaxBytesError) -> 413 problem "request body too large"
6 server: sends 413 with Connection: close, stops reading the attacker's streamReal scenario: a 2 GB upload to a JSON endpoint was buffered by io.ReadAll and the pod was OOM-killed (API4:2023); a JSON log-ingest endpoint with no limit became the cheapest DoS on the platform; a Laravel app had post_max_size=8M in PHP but Nginx's client_max_body_size 1m default rejected legitimate 2 MB requests with an HTML 413 the mobile client could not parse.
| Layer | Knob | Default | Response |
|---|---|---|---|
Go net/http | http.MaxBytesReader (per handler) | No body limit at all | Your code decides; this chapter sends 413 problem |
Go net/http headers | Server.MaxHeaderBytes | DefaultMaxHeaderBytes = 1 << 20 (1 MB) | 431 Request Header Fields Too Large |
| PHP | post_max_size, upload_max_filesize | "8M" / "2M" (built-in defaults in the php.net ini list) | Laravel ValidatePostSize throws (global middleware) |
| Nginx | client_max_body_size | 1m | "413 (Request Entity Too Large)", HTML page |
| Kong | request-size-limiting allowed_payload_size, size_unit, require_content_length | 128 megabytes | 413 |
| Envoy | envoy.filters.http.buffer max_request_bytes | required field | 413 |
| APISIX | client-control max_body_size (bytes) | unset | 413 |
Fix / how to use it: Go LimitBody + DecodeJSON; Laravel LimitRequestBody for per-route caps below post_max_size; the outer wall at the edge (Nginx client_max_body_size 64k on JSON locations). Pick the limit per endpoint: 64 KiB for orders, larger only for routes that need it (uploads go direct to object storage, file upload hardening link).
Authorization header, not the URL, for credentials Important
In plain words: Tokens, API keys and passwords travel in headers (or the body of a POST), never in the query string, because URLs are written down everywhere.
Common misunderstanding: "The query string is encrypted by TLS, so ?api_key= is fine." TLS protects the wire; the URL is then stored in the access log of every proxy, the gateway, the CDN, browser history and Referer headers. The REST cheat sheet: "Passwords, security tokens, and API keys should not appear in the URL, as this can be captured in web server logs, which makes them intrinsically valuable."
Definition: Use the standard Authorization request header (Authorization: Bearer <token>, RFC 6750 for OAuth bearer tokens; the scheme for API keys is in API keys and request signing). The roadmap item says "Use standard Authorization header for sensitive data", and its Authentication group adds "Avoid 'Basic Authentication', use standard (e.g. JWT)". Server-side: never log the header, strip it before forwarding to third parties, and log only the path (not the query) so a misbehaving client that still sends ?access_token= does not leak it into your logs either.
1 bad: GET /v1/orders?access_token=sk_live_9f... -> nginx access.log, CDN log, Referer
2 good: GET /v1/orders Authorization: Bearer sk_live_9f...
3 AccessLog writes path=/v1/orders (no query), no headers
4 NewLogger ReplaceAttr: key "authorization" -> "[REDACTED]" even if a developer logs itReal scenario: a "magic link" token in the URL was forwarded in Referer to an analytics script; partner API keys in query strings were visible to everyone with read access to the CDN logs; a support engineer pasted a URL with a token into a ticket.
Fix / how to use it: clients send Authorization; the Go AccessLog logs r.URL.Path only and NewLogger redacts authorization, token, access_token, api_key; Laravel's RedactSensitiveData tap does the same for Monolog context. Pair with Referrer-Policy: no-referrer.
Security headers for APIs: nosniff, frame options, CSP, HSTS, Referrer-Policy, no-store Must-know
In plain words: A fixed set of response headers tells browsers never to guess the content type, never to frame or execute anything from your API, never to cache it, never to leak the URL, and to use HTTPS only. Set them once, in middleware, on every response.
Common misunderstanding: "Headers only matter on HTML pages." An API response can be opened directly in a browser tab, framed by an attacker's page, sniffed as HTML when a JSON string contains markup, or kept in a shared cache. The OWASP REST cheat sheet lists Cache-Control: no-store, Content-Security-Policy: frame-ancestors 'none', Content-Type, Strict-Transport-Security, X-Content-Type-Options: nosniff and X-Frame-Options: DENY as headers that "should be included in all API responses that may be consumed by browser clients", and Content-Security-Policy: default-src 'none' and Referrer-Policy: no-referrer as defence in depth for responses that might be rendered.
Definition and values:
| Header | API value | Why (source) |
|---|---|---|
X-Content-Type-Options | nosniff | "prevents browsers from performing MIME sniffing, and inappropriately interpreting responses as HTML" (OWASP REST) |
X-Frame-Options | DENY | "Legacy header superseded by Content-Security-Policy: frame-ancestors 'none'", kept for old browsers (OWASP REST); roadmap: "Send X-Frame-Options: deny header" |
Content-Security-Policy | default-src 'none'; frame-ancestors 'none' | No resource may load and no one may frame the response; MDN: "default-src is a fallback for all other fetch directives" |
Cache-Control | no-store | "Instructs compliant private and shared HTTP caches not to store the response" (OWASP REST); MDN: no-cache "does not mean "don't cache"" |
Referrer-Policy | no-referrer | "Non-HTML responses should not trigger additional requests" (OWASP REST); browser default is strict-origin-when-cross-origin (MDN) |
Strict-Transport-Security | max-age=63072000; includeSubDomains | HTTPS only for two years; MUST NOT be sent over plain HTTP (RFC 6797 7.2) |
Permissions-Policy | camera=(), microphone=(), geolocation=(), payment=() | Disables browser features if the response is rendered (OWASP REST example) |
Content-Type | set by the server | "If not specified or if specified incorrectly, a browser might attempt to guess the content type" (OWASP REST) |
1 handler sets Content-Type: application/json; writes {"id":"...","sku":"<img src=x onerror=...>"}
2 without nosniff: an old browser opened directly may sniff and render HTML
3 with nosniff + CSP default-src 'none': no sniffing; even if rendered, no script, no image
4 attacker page: <iframe src="https://api.example/v1/me"> -> frame-ancestors 'none' blocks it
5 shared proxy cache: Cache-Control: no-store -> /v1/me is never stored for the next userReal scenario: an error page reflecting a query parameter was served as text/html by a misconfigured fallback and became reflected XSS on the API domain (which shared cookies with the app); a corporate proxy cached /v1/me for the first user and served it to the next; a password-reset URL leaked through Referer.
| Product | Default | How to set the API header set |
|---|---|---|
Go net/http | None (only http.Error adds X-Content-Type-Options: nosniff) | harden.SecurityHeaders |
| Laravel 13 | None for API routes | SecurityHeaders middleware prepended to the global stack (outside HandleCors), or bepsvpt/secure-headers (README: version 9.1.1, "Supported Laravel Version 5.1 ~ 13.x"), CSP via spatie/laravel-csp ("requires PHP 8.3 or higher and Laravel 12 or 13") |
| Nginx | None | add_header Name value always; (the always parameter, since 1.7.5, adds it "regardless of the response code"); inherited only "if and only if there are no add_header directives defined on the current level" |
| Kong | None | response-transformer plugin config.add.headers |
| Envoy | None | response_headers_to_add on the route or virtual host |
| APISIX | None | response-rewrite headers.set |
Fix / how to use it: Go SecurityHeaders (HSTS only when r.TLS != nil or a trusted proxy says X-Forwarded-Proto: https); Laravel SecurityHeaders prepended to the global stack, outside HandleCors and ValidatePostSize, so CORS preflights and 404/405/413/500 get it too (a feature test checks the preflight); at the edge for static content. The curl audit checks each value.
Fingerprinting: remove Server and X-Powered-By headers Important
In plain words: Do not announce your web server, language and framework versions in every response. It saves an attacker the first step of matching your stack to a CVE list.
Common misunderstanding: "Removing the headers hides the stack." It removes the cheapest signal, nothing more; the OWASP HTTP Headers Cheat Sheet notes: "Remember that attackers have other means of fingerprinting the server technology" (error page formats, cookie names like laravel_session, TLS fingerprints, timing). Do it because it is free and it keeps version numbers out of scanner reports, not because it is a defence.
Definition: Fingerprinting is identifying software and versions from responses. The headers that leak most: Server (nginx/1.18.0, Apache/2.4.41 (Ubuntu)), X-Powered-By (PHP/8.1.2, Express), X-AspNet-Version, X-Runtime, version strings in default error pages, and directory listings (roadmap: "Turn off directory listings"). OWASP's recommendation for Server: "Remove this header or set non-informative values"; for X-Powered-By: "Remove all X-Powered-By headers." Removal must happen at write time: an inner handler or a proxied upstream sets them after your middleware ran.
1 before: Server: orders-api/0.9.1 (go1.22.1; linux) X-Powered-By: academy-framework/2.3
2 attacker: search "go1.22.1 net/http CVE" -> pick an advisory fixed in a later release
3 after: stripWriter deletes Server, X-Powered-By, X-AspNet-Version, X-Runtime at WriteHeader
4 edge: nginx server_tokens off; proxy_hide_header X-Powered-By| Product | What it emits by default | Off switch |
|---|---|---|
| Nginx | Server: nginx/1.x.y and the version on error pages (server_tokens on) | server_tokens off; (Server: nginx remains); proxy_hide_header X-Powered-By; for upstream headers (Nginx already hides the upstream Server, Date, X-Pad, X-Accel-...) |
| PHP | X-Powered-By: PHP/8.x | expose_php = Off in php.ini; header_remove('X-Powered-By') |
Go net/http | No Server header | Nothing to do, but strip what handlers and upstreams add |
| Envoy | server: envoy | server_header_transformation: PASS_THROUGH or set server_name; the default is OVERWRITE ("Overwrite any Server header with the contents of server_name") |
| Kong | Server: kong/x.y and Via | headers setting in kong.conf (not verified here); response-transformer remove.headers for upstream headers |
| APISIX | Server: APISIX/x.y | response-rewrite headers.remove; server_tokens in the APISIX Nginx config (not verified here) |
Fix / how to use it: Go SecurityHeaders' stripWriter; Laravel SecurityHeaders + expose_php = Off; Nginx block in At the edge. Test with curl -sI and fail CI if Server contains a digit.
Error responses: Problem Details RFC 9457, correct status codes, no stack traces Must-know
In plain words: Every error has the right status code, the same JSON shape and a reference number. What went wrong inside stays in the log under that number.
Common misunderstanding: "A detailed error helps the client fix the request." Detail about the request helps ("quantity": "must be between 1 and 100"); detail about the server (stack trace, SQL, file paths, library names, internal IPs) helps only an attacker. The REST cheat sheet: "Do not pass technical details (e.g. call stacks or other internal hints) to the client." RFC 9457 section 5: "Generators providing links to occurrence information are encouraged to avoid making implementation details such as a stack dump available through the HTTP interface".
Definition: Problem Details (RFC 9457): Content-Type: application/problem+json and a JSON object with type (a URI; about:blank means "only the status code"), title (short, same for every occurrence), status (copy of the HTTP code), detail (this occurrence, client-safe), instance, plus extension members (here request_id and errors for field errors). Correct status codes: the REST cheat sheet's rule "don't just use 200 for success or 404 for error" and its warning "Do not return 200 with an empty body when an API key is missing or invalid". 4xx says "you can fix it", 5xx says "we broke". Error responses without stack traces: catch panics and exceptions at the outermost handler, log the stack with the request id, return a generic problem.
1 handler panics: "db: connection refused at 10.0.3.7:5432 user=orders_rw"
2 Recover: recover() -> log.Error("panic", request_id=647202a4..., stack="goroutine 33 [running]: ...")
3 Recover: WriteProblem(500, "internal error")
4 client: {"type":"about:blank","title":"Internal Server Error","status":500,
5 "detail":"internal error","request_id":"647202a4b7fd59f1cd5f3315"}
6 support: grep request_id=647202a4b7fd59f1cd5f3315 in the central log -> full stackReal scenario: a 500 page printed a Postgres connection string with the password (API8:2023); different endpoints answered "not found" as 200 {}, 404 HTML and 400 text, so the client treated an auth failure as "no data" and showed an empty account; 404 vs 403 on other users' objects told an attacker which order ids existed (use 404 for objects the caller may not know about).
| Stack | Default error output | Problem Details support |
|---|---|---|
Go net/http | http.Error: text/plain, status text; panics are logged by the server and the connection is closed | None built in; harden.WriteProblem + ProblemErrors rewrite |
| Laravel 13 | JSON {"message": ...} for JSON requests; with APP_DEBUG=true adds exception, file, line, trace | Custom $exceptions->render(...) in bootstrap/app.php |
| Symfony / API Platform | Problem JSON for API Platform resources | Built in (API Platform) |
| Nginx | HTML error pages with version (unless server_tokens off) | error_page + a JSON return per code |
| Kong / APISIX | JSON {"message": ...} | Custom error templates (not shown here) |
Fix / how to use it: Go WriteProblem, ProblemErrors, Recover (the ProblemErrors wrapper also turns ServeMux's plain-text 404/405 and TimeoutHandler's 503 into problems); Laravel's renderer in bootstrap/app.php.
No sensitive data in responses: output allow-lists Must-know
In plain words: Responses are built from an explicit list of fields, not by serialising the database row. New columns stay private until someone decides otherwise.
Common misunderstanding: "The frontend does not display that field, so it is fine." The field is in the JSON; anyone with the browser's network tab or curl reads it. This is BOPLA (API3:2023, excessive data exposure) in OWASP API Security Top 10; this chapter owns the mechanical control.
Definition: A response DTO (Go struct with JSON tags only on public fields, Laravel JsonResource::toArray) is the output allow-list. Roadmap: "Avoid returning sensitive data (credentials, sec. tokens etc)". Sensitive includes credentials, tokens, password hashes, full card numbers (show the last four at most; the exact PCI DSS display rule is not quoted here), internal scores, other users' data, internal ids and hostnames.
1 storage struct: ID, SKU, Quantity, CardNumber, RiskScore
2 before: json.Encode(order) -> {"card_number":"4111111111111111","risk_score":0.12,...}
3 after: orderView{ID, SKU, Quantity, CardLast: last 4} -> {"card_last4":"1111",...}
4 test: response must not contain "card_number" or the full PANFix / how to use it: Go orderView in app.go with a test that greps for the card number; Laravel OrderResource plus $hidden on the model as a second net, and the feature test assertJsonMissingPath('card_number').
Debug mode off: APP_DEBUG, pprof and debug pages Must-know
In plain words: Production never runs with debug output. Better: a production process with debug on refuses to start.
Common misunderstanding: "We only turned it on for an hour to investigate." An hour is enough for a scanner. Laravel's configuration docs: "If the variable is set to true in production, you risk exposing sensitive configuration values to your application's end users." The roadmap puts it in Processing: "Make sure to turn the debug mode off in production".
Definition: Debug mode off means: Laravel APP_DEBUG=false (config/app.php: 'debug' => (bool) env('APP_DEBUG', false), so an unset variable is already safe), APP_ENV=production; PHP display_errors=Off; Go: no net/http/pprof import on the public mux (the import registers /debug/pprof/ on http.DefaultServeMux), no verbose error details; framework debug bars (Telescope, Debugbar, Ignition) not installed or gated. A debug-off guard is a startup check that fails hard.
1 $ APP_ENV=production APP_DEBUG=true ./apiserver -addr 127.0.0.1:18490
2 2026/11/29 12:59:12 unsafe production configuration: debug mode is on
3 exit=1 (real run, see Lab)
4 Laravel: AppServiceProvider::boot throws RuntimeException when isProduction() && config('app.debug')| Stack | Debug switch | Guard |
|---|---|---|
| Laravel 13 | APP_DEBUG in .env; cached by php artisan config:cache | AppServiceProvider check; CI grep on deployment manifests |
| PHP | display_errors, display_startup_errors, expose_php | php -i check in the image build |
| Go | Your own flag; net/http/pprof side-effect import | harden.Config.Validate(); pprof on a separate localhost listener |
| Django / Spring (for comparison) | DEBUG=True; Actuator endpoints | Settings check; management.endpoints.web.exposure.include |
Fix / how to use it: Go Config.Validate called in main; Laravel AppServiceProvider. Debug information still exists: it lives in the log, keyed by request id.
Timeouts: read/write/idle timeouts, slowloris and handler deadlines Must-know
In plain words: Every phase of a connection gets a deadline: receiving headers, receiving the body, running the handler, writing the response, and waiting idle for the next request. Without them, a few slow clients hold all your connections.
Common misunderstanding: "WriteTimeout stops slow handlers." WriteTimeout closes the connection when the deadline passes, but the handler keeps running and the client sees a reset, not a status code. Use http.TimeoutHandler (or a context deadline) for the handler and the server timeouts for the connection. A second one: the Cloudflare guide (written for Go 1.6–1.8) says TimeoutHandler sends "a 504 Gateway Timeout"; the current net/http source says it "responds with a 503 Service Unavailable error", which is what the lab shows.
Definition: http.Server fields (Go source comments): ReadHeaderTimeout "is the amount of time allowed to read request headers"; ReadTimeout "is the maximum duration for reading the entire request, including the body", and "most users will prefer to use ReadHeaderTimeout"; WriteTimeout "is the maximum duration before timing out writes of the response. It is reset whenever a new request's header is read"; IdleTimeout "is the maximum amount of time to wait for the next request when keep-alives are enabled". Zero does not always mean "off": a zero ReadHeaderTimeout falls back to ReadTimeout ("If zero, the value of ReadTimeout is used"), and so does a zero IdleTimeout; only when ReadTimeout is also zero (or negative) is there no limit. A zero ReadTimeout or WriteTimeout means no timeout for that field. So http.Server{ReadTimeout: 10 * time.Second} already bounds headers and idle connections at 10s, while the zero http.Server used by http.ListenAndServe bounds nothing. Slowloris sends headers one byte at a time and never finishes; ReadHeaderTimeout is the defence. On a header timeout Go closes the connection without a response (isCommonNetReadError: "don't reply"); Nginx answers 408 after client_header_timeout (default 60s). The roadmap item "Avoid HTTP blocking if you are using huge amount of data" is the same idea applied to work: move long jobs to a queue and answer 202.
1 t=0.0s slowloris: connect; send "GET / HTTP/1.1\r\nHost: x\r\nX-Slow: 1\r\n" and stop
2 no ReadHeaderTimeout: connection open forever; 10,000 of them exhaust file descriptors
3 ReadHeaderTimeout=200ms (test): t=0.2s server closes; client reads EOF, 0 bytes
4 t=0.0s GET /v1/lab/slow (handler sleeps 5s, honours ctx)
5 t=1.0s TimeoutHandler: ctx cancelled, 503 written, ProblemErrors turns it into problem+json| Phase | Go http.Server / helper | Nginx | Envoy |
|---|---|---|---|
| Headers | ReadHeaderTimeout (silent close; zero falls back to ReadTimeout) | client_header_timeout 60s (408) | request_headers_timeout (disabled by default; "should be configured in the presence of untrusted downstreams") |
| Whole request / body | ReadTimeout | client_body_timeout 60s (between two reads, not the whole body) | request_timeout (disabled by default) |
| Handler | http.TimeoutHandler (503), context.WithTimeout | proxy_read_timeout towards the upstream | route timeout |
| Response write | WriteTimeout | send_timeout | stream_idle_timeout |
| Keep-alive idle | IdleTimeout (falls back to ReadTimeout) | keepalive_timeout | common_http_protocol_options.idle_timeout |
| Header size | MaxHeaderBytes (1 MB default) → 431 | large_client_header_buffers | max_request_headers_kb |
Fix / how to use it: Go NewServer with DefaultTimeouts (5s headers, 10s read, 15s write, 60s idle, 8s handler) and WithHandlerTimeout; Laravel runs behind PHP-FPM and Nginx, so the timeouts there are request_terminate_timeout (FPM), max_execution_time (PHP) and the Nginx directives above.
CORS: preflight, credentials and an explicit origin allow-list Important
In plain words: CORS headers tell a browser which other websites may read your API's responses with JavaScript. Grant it to a short list of exact origins, and never to "whoever asks" when cookies are involved.
Common misunderstanding: "CORS protects my API." CORS only controls what a browser lets a page read; curl, servers and attackers' scripts outside a browser ignore it. It is a read permission you hand out, not authentication. The opposite mistake is worse: reflecting any Origin into Access-Control-Allow-Origin together with Access-Control-Allow-Credentials: true lets every website read the logged-in user's data.
Definition: For "non-simple" requests (methods other than GET/HEAD/POST, or Content-Type: application/json, or custom headers) the browser first sends a preflight: OPTIONS with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server answers with Access-Control-Allow-Origin (one exact origin), -Methods, -Headers, -Max-Age, and Access-Control-Allow-Credentials: true if cookies or HTTP auth may be sent. MDN: "When responding to a credentialed requests request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the * wildcard." Add Vary: Origin so caches do not serve one origin's grant to another. OWASP REST: "Disable CORS headers if cross-domain calls are not supported/expected." The mechanics of cookies, SameSite and CORS are in Web sessions, cookies and CORS.
1 browser on https://shop.example: OPTIONS /v1/orders Origin: https://shop.example
2 Access-Control-Request-Method: POST
3 CORS: origin in allow-list, POST allowed -> 204, ACAO: https://shop.example, ACAC: true, Max-Age: 600
4 browser sends POST with the cookie; reads the 201
5 page on https://evil.example: same preflight -> 403, no ACAO; the browser never sends the POST
6 https://shop.example.evil.example: exact match fails (no suffix or regex matching)| Product | Default | Pitfall |
|---|---|---|
Laravel 13 (HandleCors, global) | Published config/cors.php: 'allowed_origins' => ['*'], 'supports_credentials' => false, 'paths' => ['api/*', 'sanctum/csrf-cookie'] | Turning on supports_credentials without replacing * |
Kong cors plugin | credentials false; schema note: "If you don't specify any allowed domains, all origins are allowed." | Empty origins list |
| Go stdlib | No CORS handling | Hand-written reflection of Origin |
| Envoy | CORS filter + per-route cors policy | allow_origin_string_match with a prefix that matches attacker subdomains |
APISIX cors plugin | allow_origins: "*" (not verified here) | allow_credential: true with * |
Fix / how to use it: Go CORS with exact origins, Vary: Origin, 403 for foreign preflights; Laravel config/cors.php listing FRONTEND_URL.
Logging: request id, correlation id, redaction and PII in logs Must-know
In plain words: One structured line per request, carrying an id that also goes back to the client in a header; secrets and personal data are masked before the line is written.
Common misunderstanding: "Log everything; we can filter later." Whatever you log is copied to the log shipper, the central store, backups and every engineer's terminal. The OWASP Logging Cheat Sheet lists what "should usually not be recorded directly in the logs, but instead should be removed, masked, sanitized, hashed, or encrypted": session identifiers, access tokens, sensitive personal data and some forms of PII, authentication passwords, database connection strings, encryption keys, bank and card data. The roadmap item is shorter: "Ensure that you aren't logging any sensitive data."
Definition: A request id identifies one request at one service; a correlation id (OWASP's "Interaction identifier") follows one user action across services. In practice one id does both when the gateway sets X-Request-ID and each service keeps it (only if it is well-formed and comes from a trusted hop) and forwards it; W3C traceparent does the same for traces. Redaction replaces values by key (authorization, password, token, email, card_number) at the logger, so a developer's log.Info("login", "password", p) still writes [REDACTED]. PII in logs is a privacy-law problem as much as a security one: GDPR treats an email address in a log as personal data. Also log the path, never the query string, and never request bodies. OWASP REST: "Take care of log injection attacks by sanitizing log data beforehand"; the request-id regex ^[A-Za-z0-9._-]{8,64}$ is that sanitising step for the one client-supplied value that goes into every line.
1 gateway: X-Request-ID: gw-7f3a9c2e (generated at the edge)
2 orders (trustIncoming=true): keeps gw-7f3a9c2e, logs {"request_id":"gw-7f3a9c2e","path":"/v1/orders","status":201}
3 orders -> payments: forwards X-Request-ID: gw-7f3a9c2e
4 client sends X-Request-ID: "abc\nlevel=ERROR msg=fake" -> fails the regex, replaced by a new id
5 log line: {"level":"WARN","msg":"http_request","request_id":"...","method":"GET","path":"/v1/orders","status":401}
6 query string ?access_token=... and the Authorization header never appearA security-event table makes the log queryable for alerting and audits (PostgreSQL; the same shape works in a log store such as Loki or OpenSearch):
CREATE TABLE security_events (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
request_id text NOT NULL CHECK (request_id ~ '^[A-Za-z0-9._-]{8,64}$'),
event text NOT NULL CHECK (event IN ('auth.failed', 'authz.denied', 'input.rejected', 'cors.denied', 'panic')),
status smallint NOT NULL,
client_ip inet NOT NULL,
route text NOT NULL, -- path pattern, never the raw URL with its query
actor_hash text -- HMAC of the user id, not the email
);
CREATE INDEX security_events_ip_time ON security_events (client_ip, occurred_at DESC);
-- Alert rule: more than 100 rejected inputs or failed logins from one IP in 5 minutes.
SELECT client_ip, count(*) AS events
FROM security_events
WHERE occurred_at > now() - interval '5 minutes'
AND event IN ('auth.failed', 'input.rejected')
GROUP BY client_ip
HAVING count(*) > 100
ORDER BY events DESC;| Stack | Request id | Redaction |
|---|---|---|
Go log/slog (1.21+) | Middleware + context value; X-Request-ID header | HandlerOptions.ReplaceAttr by key (harden.NewLogger) |
| Laravel 13 | Context::add('request_id', ...) (context "is automatically appended as metadata to any log entries"); docs example uses Log::withContext and a Request-Id header | Channel tap with a Monolog processor (RedactSensitiveData) |
| Nginx | $request_id variable, proxy_set_header X-Request-ID $request_id | Custom log_format without $args, $http_authorization |
| Envoy | Generates x-request-id by default | Access log format without the header |
| OpenTelemetry | traceparent / trace id | Collector attributes / redaction processor |
Fix / how to use it: Go RequestID, AccessLog, NewLogger; Laravel AssignRequestId and RedactSensitiveData. Observability as a whole (metrics, traces, log pipelines) is in Observability.
Monitoring: centralised logging, alerting, IDS/IPS and WAF Important
In plain words: Logs from every service go to one place, a few rules page a human when attack patterns appear, and network sensors and a web application firewall watch for what the app cannot see.
Common misunderstanding: "We have logs, so we have monitoring." The OWASP Top 10:2025 renamed A09 to "Security Logging and Alerting Failures" because logs nobody reads do not detect anything. An alert needs a threshold, an owner and a runbook.
Definition: Centralised logging: ship structured logs (JSON lines) from every service and the gateway to one store (Elasticsearch/OpenSearch with Kibana, Loki with Grafana, CloudWatch Logs, Datadog), retain them, restrict who reads them. Alerting: rules on the store (roadmap: "Use alerts for SMS, Slack, Email, Kibana, Cloudwatch, etc."), e.g. 401/403 bursts per IP or per account, spikes of 413/415/400 (scanning), any panic event, 5xx rate. IDS/IPS: intrusion detection / prevention systems inspect traffic for known attack signatures (Suricata, Snort, cloud equivalents such as AWS GuardDuty for detection); IDS alerts, IPS blocks. WAF: a web application firewall in front of the API (AWS WAF, Cloudflare WAF, ModSecurity with the OWASP Core Rule Set, Coraza) blocks generic attack payloads and enforces rate and geo rules; useful as a shield, never a replacement for the controls above. Network detail is in DDoS and network security.
1 09:00:00-09:00:40 4,200 x POST /v1/login from 203.0.113.9 -> 401 (auth.failed)
2 09:00:40 alert rule "auth.failed > 100 / 5 min per IP" fires -> Slack #sec-oncall + PagerDuty
3 09:01:10 on-call: WAF rule blocks 203.0.113.9; rate limit tightened for /v1/login
4 09:05:00 incident ticket with the request ids of the first and last events| Signal | Source | Alert |
|---|---|---|
| 401/403 burst | Access log status, security_events | > 100 per IP or account in 5 minutes |
| 400/413/415/422 burst | Access log | Scanner or fuzzer; > 500 per IP in 5 minutes |
panic events | Error log | Any, per release |
| 5xx rate | Metrics | > 1 % for 5 minutes |
| New route returning 200 | Inventory diff | Any route not in the OpenAPI document |
| Known attack signature | IDS/IPS, WAF | Per rule severity |
API gateway: Kong, Envoy, APISIX, Nginx and OpenAPI validation at the edge Important
In plain words: A gateway in front of all services enforces the cheap, uniform rules once: TLS, sizes, timeouts, rate limits, header hygiene, and optionally the OpenAPI contract, before traffic reaches application code.
Common misunderstanding: "With a gateway, services can trust their input." Services are also reached by internal callers, jobs and other ingresses; and only the service knows its business rules and which fields are sensitive. The roadmap item is "Use an API Gateway for caching, Rate Limit policies etc", and its detail page describes the gateway as "a centralized point of control for managing and securing API traffic": a point of control, not a replacement.
Definition: An API gateway (Kong, Envoy-based gateways, Apache APISIX, Nginx or a cloud gateway) terminates TLS, authenticates, rate limits, routes, transforms headers and logs. OpenAPI validation at the edge validates requests against the published OpenAPI document (paths, methods, parameters, body schema) before forwarding: Kong's OAS Validation plugin (Kong Gateway Enterprise only), APISIX request-validation (JSON Schema for headers and body, rejected_code default 400), Envoy with an external authorization or WASM validator. This is the schema-first payoff: one document drives docs, client generation, gateway validation and contract tests. Gateway architecture (BFF, service mesh) is in API gateway, BFF and service mesh.
1 client -> CDN/WAF (TLS, bot rules) -> gateway -> orders service
2 gateway: request-size-limiting 64 KB -> 413; OAS validation: unknown path -> 404, bad body -> 400
3 gateway: rate limit 100/min per key -> 429 (see rate limiting)
4 gateway: response-transformer removes Server, X-Powered-By; adds nosniff
5 orders: the Go chain runs again (defence in depth): headers, 405/406/413/415, validation| Concern | Kong | Envoy | APISIX | Nginx |
|---|---|---|---|---|
| Body limit | request-size-limiting (allowed_payload_size, default 128 MB) | buffer filter max_request_bytes → 413 | client-control max_body_size | client_max_body_size (default 1m) → 413 |
| Header timeout | Not a plugin; set in Kong's Nginx configuration (not shown here) | request_headers_timeout | Nginx config template | client_header_timeout (60s) → 408 |
| Strip fingerprint | response-transformer remove.headers | server_header_transformation | response-rewrite headers.remove | server_tokens off, proxy_hide_header |
| Add headers | response-transformer add.headers | response_headers_to_add | response-rewrite headers.set | add_header ... always |
| OpenAPI validation | OAS Validation (Enterprise) | External validator | request-validation (JSON Schema) | Not built in |
| CORS | cors plugin (empty origins = all) | CORS filter | cors plugin | add_header by hand |
The concrete config blocks are in At the edge.
CI/CD gates: dependency scanning, SAST, DAST, secrets scanning, code review rules Must-know
In plain words: The pipeline refuses to merge or deploy when the code has a known-vulnerable dependency, a committed secret, a pattern a scanner flags, a failing security test, or a review that was not done by someone else.
Common misunderstanding: "We run a scanner, so we are covered." Each tool sees one thing: SAST sees code patterns, SCA sees dependency versions, secrets scanning sees strings, DAST sees the running app. None sees a missing authorization check in business logic; that is what tests and review are for. And a scanner that only reports, without failing the build, is decoration.
Definition:
- Dependency scanning (SCA):
govulncheck ./...(Go; "only surfaces vulnerabilities that actually affect you, based on which functions in your code are transitively calling vulnerable functions") andcomposer audit(PHP; exit code "0 No issues; 1 Found packages matching dependency policies", options--locked,--no-dev,--abandoned=fail), plus Dependabot or Renovate to raise update PRs. - SAST: static analysis of source: gosec, staticcheck, semgrep, PHPStan/Psalm with security rules.
- Secrets scanning: gitleaks ("a tool for detecting secrets like passwords, API keys, and tokens in git repos, files, and whatever else";
gitleaks gitscans history,gitleaks dira directory;detectandprotectwere deprecated in v8.19.0), GitHub secret scanning and push protection. - DAST: dynamic scanning of a running staging deployment: OWASP ZAP baseline (
zap-baseline.py -t <url>, exit "0: Success", "1: At least 1 FAIL", "2: At least one WARN and no FAILs", "3: Any other failure"); this chapter's curl audit script is a tiny, deterministic DAST for exactly this checklist. - Code review rules: roadmap "Use a code review process and disregard self-approval": branch protection with at least one approval from someone other than the author, CODEOWNERS for security-sensitive paths (middleware, auth,
config/cors.php), required status checks, no admin bypass. - Tests: roadmap "Audit your design and implementation with unit/integration tests": every middleware here has a test.
1 PR opened -> gofmt/vet, go test -race, php artisan test (unit + integration)
2 -> gosec, semgrep, PHPStan (SAST)
3 -> govulncheck ./..., composer audit --locked (SCA, fail on findings)
4 -> gitleaks git --redact (secrets)
5 review -> CODEOWNERS approval, author cannot approve
6 merge -> deploy to staging -> audit.sh + ZAP baseline (DAST) -> promoteThe pipeline mechanics (runners, caching, environments) are in CI/CD pipelines; the process view (threat modelling, SBOM, incident response) is in Secure SDLC.
Rollback strategy: blue-green, canary and feature flags Good to know
In plain words: Before you deploy, know how you undo it in minutes, including when the release has already changed the database.
Common misunderstanding: "Rollback means redeploying the previous image." That works only if the previous version still understands the database and the messages the new one wrote. A security fix that cannot be rolled back safely is one nobody dares to deploy quickly.
Definition: Roadmap: "Design a rollback solution for deployments." Blue-green: two identical environments, switch traffic, switch back on failure. Canary: send a few percent of traffic to the new version, watch error and security signals, then widen. Feature flags: ship code dark, turn behaviour on per tenant, turn it off without a deploy (also a kill switch for a vulnerable feature). Database changes use expand-and-contract so both versions run on one schema. Details: Deployment strategies and Schema migrations.
API inventory: every endpoint accounted for Good to know
In plain words: Keep a list of every route in every version and environment, who owns it, and what protects it. An endpoint nobody knows about gets none of the controls above.
Common misunderstanding: "Our OpenAPI document is the inventory." The document lists what someone remembered to describe; the inventory has to be generated from what is actually deployed (routes in code, gateway routes, DNS names) and diffed against the document, otherwise the undocumented /v1 and the staging host are exactly the endpoints that are missing.
Definition: API9:2023 Improper Inventory Management covers forgotten versions (/v1 still live after /v2), debug and staging hosts, and undocumented routes. Mechanically: generate the route list from code (go tests over the ServeMux patterns, php artisan route:list --json), diff it against the OpenAPI document in CI, and assert that every route outside an explicit public list has authentication middleware (the roadmap item "Check if all the endpoints are protected behind authentication"). This chapter's Go module has no authentication layer (that is in Authentication), so it does not implement this test; it is the method, not shipped code. The inventory process itself is in OWASP API Security Top 10; versioning in API versioning.
Processing items owned elsewhere: XML entities, uploads, SSRF, async work, UUIDs, stacks Good to know
- XML entity parsing and expansion ("Disable entity parsing if you are parsing XML to avoid XXE attacks", "Disable entity expansion if using XML, YML or any other language"): the safest option is not to accept XML at all (Content-Type validation does that); otherwise see XXE in OWASP Top 10. Go's
encoding/xmldoes not resolve external entities. - Uploads via CDN ("Use CDN for file uploads"): presigned URLs straight to object storage, scanning and serving from a separate domain; the file upload hardening link is File uploads, S3 and CDN.
- SSRF guard link: any API that fetches a URL supplied by a client needs the connect-time IP check from OWASP Top 10 (SSRF).
- Avoid HTTP blocking for huge data: accept the job, return
202 Acceptedwith a status URL, process in a worker; retries need API idempotency. - UUIDs over auto-increment ids and no personal ids in URLs: unguessable ids reduce enumeration, but they are not authorization; the real fix is the object-level check (BOLA) in OWASP API Security Top 10. The Go handler here accepts only a UUID-shaped id and answers 404 for anything else.
- Non-executable stacks: a compiler and OS property (NX bit,
-z noexecstack), on by default for Go binaries and modern PHP builds; container hardening (read-only root, no new privileges) is in Container security.
Linked owners: authentication, JWT, OAuth, rate limiting, TLS Good to know
- Authentication (standard mechanisms, no home-made crypto, max retry and jail): Authentication: passwords, MFA, sessions.
- JWT (strong secret, algorithm fixed by the server, short TTL, small payload without secrets): JWT deep dive.
- OAuth (
redirect_uriexact match, code flow with PKCE instead ofresponse_type=token,state, scopes): OAuth 2.0, OIDC and SSO. - Throttling (rate limiting link: token bucket, sliding window, distributed limits, 429 with
Retry-After): Rate limiting. - TLS and HSTS (versions, cipher suites, certificates, HSTS preload): TLS in practice and HTTP evolution; service-to-service in Mutual TLS.
- API keys, HMAC signatures, IP allow-lists for private APIs: API keys, request signing and webhooks.
Mechanics
Middleware order and why it matters
harden.Chain(h, a, b, c) serves a(b(c(h))): the first middleware listed sees the request first and the response last. The order in app.New follows one rule: anything that must apply to rejections sits outside the layers that reject.
| Position | Middleware | Why here |
|---|---|---|
| 1 | RequestID | The id must exist before anything logs or rejects |
| 2 | AccessLog | Logs every outcome, including rejections and panics turned into 500 |
| 3 | SecurityHeaders | Headers set before any inner layer writes; strips fingerprints at write time |
| 4 | ProblemErrors | Rewrites plain-text errors from ServeMux and TimeoutHandler produced below it |
| 5 | Recover | Catches panics from everything below, including those re-raised by TimeoutHandler |
| 6 | CORS | Preflights (OPTIONS) answered before the method and media-type checks would reject them |
| 7 | AllowMethods | Cheap global reject (405) before reading anything |
| 8 | JSONOnly | 406/415 before the body is read |
| 9 | LimitBody | Wraps the body before any reader touches it; unwraps to net/http's writer |
| 10 | WithHandlerTimeout | Deadline and context cancel for routing and the handler |
| 11 | ServeMux | Method patterns and path values; 404/405 for the rest |
Two traps the tests guard against. A ResponseWriter wrapper without Unwrap() hides http.ResponseController features and the MaxBytesReader close hint (proved by TestLimitClosesConnectionThroughWrappers, which fails if LimitBody passes the wrapped writer). And a header middleware placed inside Recover or after the router would leave 500s and 404s without headers (proved by TestEveryResponseIsHardened).
Status codes, names and who emits them
| Code | RFC 9110 name | Go http.StatusText | Laravel / Symfony source | Emitted here by |
|---|---|---|---|---|
| 400 | Bad Request | Bad Request | BadRequestHttpException | DecodeJSON, method override |
| 403 | Forbidden | Forbidden | AuthorizationException → 403 | CORS (foreign preflight) |
| 404 | Not Found | Not Found | NotFoundHttpException, ModelNotFoundException | ServeMux, id allow-list |
| 405 | Method Not Allowed | Method Not Allowed | MethodNotAllowedHttpException (with Allow) | AllowMethods, ServeMux |
| 406 | Not Acceptable | Not Acceptable | custom (EnforceJsonApi) | JSONOnly |
| 408 | Request Timeout | Request Timeout | n/a | Nginx client_header_timeout; Go closes silently |
| 413 | Content Too Large | Request Entity Too Large | PostTooLargeException (not verified here) | LimitBody, DecodeJSON |
| 415 | Unsupported Media Type | Unsupported Media Type | custom (EnforceJsonApi) | JSONOnly |
| 422 | Unprocessable Content | Unprocessable Entity | ValidationException | handler validate() |
| 429 | Too Many Requests | Too Many Requests | ThrottleRequestsException | rate limiter (linked) |
| 431 | Request Header Fields Too Large | Request Header Fields Too Large | n/a | Go server when MaxHeaderBytes is exceeded |
| 500 | Internal Server Error | Internal Server Error | any uncaught Throwable | Recover |
| 501 | Not Implemented | Not Implemented | n/a | Go server for an unsupported Transfer-Encoding |
| 503 | Service Unavailable | Service Unavailable | MaintenanceModeException path | http.TimeoutHandler |
Error strings worth recognising: http: request body too large (*http.MaxBytesError), json: unknown field "price" (DisallowUnknownFields, mapped to the client-safe unknown field "price"), http: Handler timeout (http.ErrHandlerTimeout, what a handler's Write returns after TimeoutHandler fired).
The exact knobs
| Knob | Where | Value used in this chapter |
|---|---|---|
http.MaxBytesReader | Go handler / LimitBody | 64 KiB (1 KiB in tests) |
Decoder.DisallowUnknownFields | Go encoding/json | on |
MaxJSONDepth | harden | 16 (stdlib internal limit is 10000) |
Server.ReadHeaderTimeout | Go | 5s |
Server.ReadTimeout | Go | 10s |
Server.WriteTimeout | Go | 15s |
Server.IdleTimeout | Go | 60s |
Server.MaxHeaderBytes | Go | 32 KiB (default 1 MB) |
http.TimeoutHandler | Go | 8s (1s in the lab server) |
HSTS max-age | both | 63072000 (two years), includeSubDomains, TLS only |
APP_DEBUG, APP_ENV | Laravel .env | false, production |
expose_php, display_errors | php.ini | Off, Off |
post_max_size | php.ini | above the largest route limit (global ValidatePostSize) |
config/cors.php | Laravel | explicit allowed_origins, supports_credentials true, max_age 600 |
trustProxies(at: ...) | Laravel bootstrap/app.php | the load balancer CIDR only |
client_max_body_size | Nginx | 64k on JSON locations |
client_header_timeout, client_body_timeout | Nginx | 10s, 10s |
server_tokens | Nginx | off |
allowed_payload_size, size_unit | Kong request-size-limiting | 64, kilobytes |
request_headers_timeout | Envoy HCM | 5s |
max_body_size | APISIX client-control | 65536 |
Product defaults that need changing
| Product | Default | Hardened |
|---|---|---|
Go http.Server | All timeouts zero: with ReadTimeout zero, the header and idle fallbacks are zero too, so nothing is bounded; 1 MB headers, no body limit | harden.NewServer + LimitBody |
Go http.ListenAndServe | Uses a zero http.Server | Never use it for public listeners |
Laravel config/cors.php | allowed_origins *, credentials false | Explicit origins |
Laravel config/app.php | 'debug' => (bool) env('APP_DEBUG', false) | Keep; never set true in production .env |
| PHP | expose_php on in many distro builds (not verified per distro) | Off |
| Nginx | client_max_body_size 1m, server_tokens on, client_header_timeout 60s | Per-location limits, off, shorter timeouts |
Kong request-size-limiting | 128 MB, require_content_length false | Route-level limit; require_content_length where clients always send it |
Kong cors | Empty origins = all origins | Explicit origins |
| Envoy HCM | server_header_transformation: OVERWRITE (server: envoy), request_headers_timeout disabled, stream_idle_timeout 5 minutes | Set header timeout, pass through or blank the server header |
APISIX request-validation | Rejects with 400 | Keep; set rejected_msg to a problem JSON string |
Go
Before: one handler, no checklist
The naive version works for the happy path and fails 29 of 31 audit checks (see Lab): every method reads the order, the whole record including the card number is serialised, Accept is copied into Content-Type, the body is unlimited, the panic handler prints the stack, the log line contains the URL and the Authorization header, and there are no timeouts.
// Package before is the same orders API written the way many first versions
// are: it works, and it fails almost every item of the checklist.
package before
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"runtime/debug"
"strings"
)
type order struct {
ID string `json:"id"`
SKU string `json:"sku"`
Quantity int `json:"quantity"`
CardNumber string `json:"card_number"` // the whole record is serialised
RiskScore float64 `json:"risk_score"`
}
// New returns the naive handler. Debug output is "temporarily" on.
func New() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "orders-api/0.9.1 (go1.22.1; linux)")
w.Header().Set("X-Powered-By", "academy-framework/2.3")
defer func() {
if v := recover(); v != nil {
// "Helpful" error page: the panic text and the whole stack.
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "panic: %v\n\n%s", v, debug.Stack())
}
}()
// Logs the full URL, query string and Authorization header.
log.Printf("%s %s auth=%q", r.Method, r.URL.String(), r.Header.Get("Authorization"))
switch {
case r.URL.Path == "/v1/lab/panic":
panic("db: connection refused at 10.0.3.7:5432 user=orders_rw")
case strings.HasPrefix(r.URL.Path, "/v1/orders/") && r.Method != http.MethodPost:
// Any method reads the order: GET, TRACE, DELETE, FOO.
id := strings.TrimPrefix(r.URL.Path, "/v1/orders/")
o := order{ID: id, SKU: "MUG-01", Quantity: 2, CardNumber: "4111111111111111", RiskScore: 0.12}
w.Header().Set("Content-Type", r.Header.Get("Accept")) // copies Accept
_ = json.NewEncoder(w).Encode(o)
case r.URL.Path == "/v1/orders":
// No size limit, any Content-Type, unknown fields ignored.
body, _ := io.ReadAll(r.Body)
var o order
if err := json.Unmarshal(body, &o); err != nil {
http.Error(w, "json.Unmarshal into before.order: "+err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK) // 200 instead of 201
_ = json.NewEncoder(w).Encode(o)
default:
w.WriteHeader(http.StatusOK) // "not found" as an empty 200
}
})
}package before
import (
"net/http/httptest"
"strings"
"testing"
)
// These tests pass: they document what the naive version gets wrong.
func TestBeforeFailsTheChecklist(t *testing.T) {
h := New()
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("TRACE", "/v1/orders/42", nil))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "4111111111111111") {
t.Fatalf("expected TRACE to be served with the full card number")
}
if rec.Header().Get("Server") == "" || rec.Header().Get("X-Powered-By") == "" {
t.Fatalf("expected fingerprinting headers")
}
if rec.Header().Get("X-Content-Type-Options") != "" {
t.Fatalf("expected no security headers")
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("GET", "/v1/lab/panic", nil))
if !strings.Contains(rec.Body.String(), "goroutine") || !strings.Contains(rec.Body.String(), "10.0.3.7") {
t.Fatalf("expected the stack trace and the internal address in the body")
}
rec = httptest.NewRecorder()
big := `{"sku":"` + strings.Repeat("A", 1<<20) + `"}`
r := httptest.NewRequest("POST", "/v1/orders", strings.NewReader(big))
r.Header.Set("Content-Type", "text/plain")
h.ServeHTTP(rec, r)
if rec.Code != 200 {
t.Fatalf("expected a 1 MiB text/plain body to be accepted, got %d", rec.Code)
}
}After: the middleware chain
One package, harden, one file per checklist group, all stdlib (go 1.24). The chain and the unwrapping helper:
// Package harden is the API security checklist as a Go middleware chain.
// Each file implements one checklist group; Chain wires them in order.
package harden
import "net/http"
// Middleware wraps a handler.
type Middleware func(http.Handler) http.Handler
// Chain applies middlewares so that the first one listed is the outermost:
// Chain(h, a, b, c) serves a(b(c(h))).
func Chain(h http.Handler, mws ...Middleware) http.Handler {
for i := len(mws) - 1; i >= 0; i-- {
h = mws[i](h)
}
return h
}
// unwrapper is implemented by every ResponseWriter wrapper in this package,
// so http.ResponseController and MaxBytesReader can reach the real writer.
type unwrapper interface{ Unwrap() http.ResponseWriter }
// innermost returns the writer created by net/http, below all wrappers.
func innermost(w http.ResponseWriter) http.ResponseWriter {
for {
u, ok := w.(unwrapper)
if !ok {
return w
}
w = u.Unwrap()
}
}Output: security headers and fingerprint stripping at write time:
package harden
import (
"net/http"
"strconv"
)
// HeaderOptions configures SecurityHeaders.
type HeaderOptions struct {
// HSTSMaxAge in seconds; 0 disables HSTS. RFC 6797 section 7.2: the header
// MUST NOT be sent over non-secure transport, so it is only set on TLS
// requests (or when TrustForwardedProto and X-Forwarded-Proto is https).
HSTSMaxAge int
TrustForwardedProto bool
}
// apiHeaders is the OWASP REST Security Cheat Sheet set for JSON APIs that
// may be read by browsers.
var apiHeaders = map[string]string{
"Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
}
// fingerprintHeaders are removed at write time, after every inner handler
// (or a reverse-proxied upstream) had its chance to set them.
var fingerprintHeaders = []string{"Server", "X-Powered-By", "X-AspNet-Version", "X-Runtime"}
// SecurityHeaders sets the output headers of the checklist and strips
// fingerprinting headers.
func SecurityHeaders(opt HeaderOptions) Middleware {
hsts := ""
if opt.HSTSMaxAge > 0 {
hsts = "max-age=" + strconv.Itoa(opt.HSTSMaxAge) + "; includeSubDomains"
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
for k, v := range apiHeaders {
h.Set(k, v)
}
if hsts != "" && isHTTPS(r, opt.TrustForwardedProto) {
h.Set("Strict-Transport-Security", hsts)
}
next.ServeHTTP(&stripWriter{ResponseWriter: w}, r)
})
}
}
func isHTTPS(r *http.Request, trustProxy bool) bool {
if r.TLS != nil {
return true
}
return trustProxy && r.Header.Get("X-Forwarded-Proto") == "https"
}
type stripWriter struct {
http.ResponseWriter
done bool
}
func (s *stripWriter) strip() {
if s.done {
return
}
s.done = true
for _, k := range fingerprintHeaders {
s.Header().Del(k)
}
}
func (s *stripWriter) WriteHeader(code int) {
s.strip()
s.ResponseWriter.WriteHeader(code)
}
func (s *stripWriter) Write(b []byte) (int, error) {
s.strip()
return s.ResponseWriter.Write(b)
}
func (s *stripWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }Output: RFC 9457 problem details, and the rewrite of net/http's own plain-text errors:
package harden
import (
"encoding/json"
"net/http"
"strings"
)
// Problem is an RFC 9457 problem details object. RequestID and Errors are
// extension members; nothing else about the failure leaves the server.
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
RequestID string `json:"request_id,omitempty"`
Errors map[string]string `json:"errors,omitempty"`
}
// HTTPError is returned by helpers (DecodeJSON) and turned into a Problem.
type HTTPError struct {
Status int
Detail string
Errors map[string]string
}
func (e *HTTPError) Error() string { return e.Detail }
// RFC 9110 names; net/http.StatusText still uses the older RFC 7231 phrases
// for 413 ("Request Entity Too Large") and 422 ("Unprocessable Entity").
var titles = map[int]string{
http.StatusRequestEntityTooLarge: "Content Too Large",
http.StatusUnprocessableEntity: "Unprocessable Content",
}
func title(status int) string {
if t, ok := titles[status]; ok {
return t
}
return http.StatusText(status)
}
// WriteProblem writes an application/problem+json response. The detail must
// be safe for the client: no stack traces, SQL, file paths or secrets.
func WriteProblem(w http.ResponseWriter, r *http.Request, status int, detail string, fieldErrors map[string]string) {
p := Problem{
Type: "about:blank",
Title: title(status),
Status: status,
Detail: detail,
RequestID: RequestIDFrom(r.Context()),
Errors: fieldErrors,
}
h := w.Header()
h.Del("Content-Length")
h.Set("Content-Type", "application/problem+json")
h.Set("X-Content-Type-Options", "nosniff")
h.Set("Cache-Control", "no-store")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(p)
}
// WriteError maps an error from a helper to a problem response.
func WriteError(w http.ResponseWriter, r *http.Request, err error) {
if he, ok := err.(*HTTPError); ok {
WriteProblem(w, r, he.Status, he.Detail, he.Errors)
return
}
WriteProblem(w, r, http.StatusInternalServerError, "internal error", nil)
}
// ProblemErrors rewrites plain-text error responses produced by net/http
// itself (ServeMux 404/405 via http.Error, TimeoutHandler 503) into problem
// details, so every rejection has the same shape and no default text leaks.
func ProblemErrors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(&problemWriter{ResponseWriter: w, r: r}, r)
})
}
type problemWriter struct {
http.ResponseWriter
r *http.Request
wrote bool
swallowing bool
}
func (p *problemWriter) WriteHeader(code int) {
if p.wrote {
return
}
p.wrote = true
ct := p.Header().Get("Content-Type")
if code >= 400 && (ct == "" || strings.HasPrefix(ct, "text/plain")) {
p.swallowing = true
WriteProblem(p.ResponseWriter, p.r, code, "", nil)
return
}
p.ResponseWriter.WriteHeader(code)
}
func (p *problemWriter) Write(b []byte) (int, error) {
if !p.wrote {
p.WriteHeader(http.StatusOK)
}
if p.swallowing {
return len(b), nil // drop net/http's default text body
}
return p.ResponseWriter.Write(b)
}
func (p *problemWriter) Unwrap() http.ResponseWriter { return p.ResponseWriter }Input: the HTTP method allow-list:
package harden
import (
"net/http"
"strings"
)
// AllowMethods is the global HTTP method allow-list. Anything else (TRACE,
// CONNECT, made-up verbs, method-override tricks) gets 405 with an Allow
// header, as RFC 9110 section 15.5.6 requires. Per-route methods are
// enforced again by ServeMux patterns such as "POST /v1/orders".
func AllowMethods(methods ...string) Middleware {
allowed := make(map[string]bool, len(methods))
for _, m := range methods {
allowed[m] = true
}
allow := strings.Join(methods, ", ")
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !allowed[r.Method] {
w.Header().Set("Allow", allow)
WriteProblem(w, r, http.StatusMethodNotAllowed, "method not allowed", nil)
return
}
// Method override headers let a POST pretend to be a DELETE in
// some frameworks; this API never honours them.
if r.Header.Get("X-HTTP-Method-Override") != "" || r.Header.Get("X-HTTP-Method") != "" {
WriteProblem(w, r, http.StatusBadRequest, "method override headers are not accepted", nil)
return
}
next.ServeHTTP(w, r)
})
}
}Input: Content-Type validation and Accept validation:
package harden
import (
"mime"
"net/http"
"regexp"
"strconv"
"strings"
)
// JSONOnly enforces the content contract of a JSON API:
// - a request that carries a body must declare Content-Type
// application/json (charset utf-8 only), else 415 Unsupported Media Type;
// - the Accept header, if present, must give application/json a quality
// above zero via its most specific matching range, else 406 Not
// Acceptable.
//
// The response Content-Type is always set by the server, never copied from
// the Accept header.
func JSONOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !acceptsJSON(r.Header.Values("Accept")) {
WriteProblem(w, r, http.StatusNotAcceptable, "this API only produces application/json", nil)
return
}
if hasBody(r) {
mt, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
cs := strings.ToLower(params["charset"])
if err != nil || mt != "application/json" || (cs != "" && cs != "utf-8") {
// RFC 9110 15.5.16: Accept in a 415 response lists what would work.
w.Header().Set("Accept", "application/json")
WriteProblem(w, r, http.StatusUnsupportedMediaType, "send application/json", nil)
return
}
}
next.ServeHTTP(w, r)
})
}
// hasBody reports whether the request carries content: a positive
// Content-Length, or an unknown length (chunked transfer coding).
func hasBody(r *http.Request) bool {
return r.ContentLength > 0 || r.ContentLength == -1
}
// acceptsJSON applies RFC 9110 section 12.5.1 for the one representation
// this API produces, application/json (UTF-8, no other parameters):
// - a range matches only if its type/subtype matches AND every non-q
// parameter matches the representation, so "application/json;profile=v2"
// does not match plain JSON (charset=utf-8 does: JSON is UTF-8);
// - among matching ranges the most specific wins (type/subtype with
// parameters > type/subtype > type/* > */*), and its q is the quality;
// - q must follow the RFC grammar (0 to 1, at most three decimals);
// a malformed weight makes that range ignored;
// - q=0 means "not acceptable".
//
// application/problem+json does not count: success bodies are
// application/json, so a client that only accepts problem documents gets 406.
func acceptsJSON(values []string) bool {
if len(values) == 0 {
return true // no Accept header means any media type is acceptable
}
best, q := -1, 0.0 // specificity of the best match so far, and its q
for _, v := range values {
for _, part := range strings.Split(v, ",") {
mt, params, err := mime.ParseMediaType(strings.TrimSpace(part))
if err != nil {
continue
}
spec := -1
switch mt {
case "application/json":
spec = 2
case "application/*":
spec = 1
case "*/*":
spec = 0
}
if spec < 0 {
continue
}
f := 1.0
for k, pv := range params {
switch {
case k == "q":
if !qValue.MatchString(pv) {
spec = -1 // malformed weight: ignore this range
} else {
f, _ = strconv.ParseFloat(pv, 64)
}
case spec == 2 && k == "charset" && strings.EqualFold(pv, "utf-8"):
spec = 3 // matches our representation and is more specific
default:
spec = -1 // a parameter our representation does not have
}
if spec < 0 {
break
}
}
if spec < 0 || spec < best {
continue
}
if spec > best || f > q { // more specific wins; same specificity: highest q
best, q = spec, f
}
}
}
return best >= 0 && q > 0
}
// qValue is the RFC 9110 section 12.4.2 weight grammar:
// qvalue = ( "0" [ "." 0*3DIGIT ] ) / ( "1" [ "." 0*3("0") ] )
var qValue = regexp.MustCompile(`^(0(\.[0-9]{0,3})?|1(\.0{0,3})?)$`)Input: the request body size limit:
package harden
import "net/http"
// LimitBody caps the request body. A declared Content-Length above the limit
// is rejected before the handler runs; a chunked or lying body is cut by
// http.MaxBytesReader, which makes the decoder fail with *http.MaxBytesError
// (mapped to 413 by DecodeJSON).
func LimitBody(maxBytes int64) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.ContentLength > maxBytes {
w.Header().Set("Connection", "close")
WriteProblem(w, r, http.StatusRequestEntityTooLarge, "request body too large", nil)
return
}
// Pass the writer created by net/http: MaxBytesReader can only
// tell the server to close the connection after the limit is
// hit when it sees that writer, not one of our wrappers.
r.Body = http.MaxBytesReader(innermost(w), r.Body, maxBytes)
next.ServeHTTP(w, r)
})
}
}Input: strict JSON decoding with a depth limit:
package harden
import (
"bytes"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
)
// MaxJSONDepth is far below encoding/json's own hard limit (10000 levels in
// encoding/json/scanner.go); no request body of this API nests deeper.
const MaxJSONDepth = 16
// DecodeJSON reads one JSON object into dst with strict rules: the body is
// already capped by LimitBody, nesting is limited, unknown fields and
// trailing data are rejected. Errors are *HTTPError with a client-safe
// detail and the right status (400, 413).
func DecodeJSON(r *http.Request, dst any) error {
body, err := io.ReadAll(r.Body)
if err != nil {
var mbe *http.MaxBytesError
if errors.As(err, &mbe) {
return &HTTPError{Status: http.StatusRequestEntityTooLarge, Detail: "request body too large"}
}
return &HTTPError{Status: http.StatusBadRequest, Detail: "could not read body"}
}
if err := checkDepth(body, MaxJSONDepth); err != nil {
return err
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return &HTTPError{Status: http.StatusBadRequest, Detail: clientSafe(err)}
}
if dec.More() {
return &HTTPError{Status: http.StatusBadRequest, Detail: "body must contain a single JSON value"}
}
if _, err := dec.Token(); err != io.EOF {
return &HTTPError{Status: http.StatusBadRequest, Detail: "body must contain a single JSON value"}
}
return nil
}
// checkDepth walks the tokens once and rejects documents nested deeper than
// max, before any allocation into Go values.
func checkDepth(body []byte, max int) error {
dec := json.NewDecoder(bytes.NewReader(body))
depth := 0
for {
tok, err := dec.Token()
if err == io.EOF {
return nil
}
if err != nil {
return &HTTPError{Status: http.StatusBadRequest, Detail: "malformed JSON"}
}
if d, ok := tok.(json.Delim); ok {
switch d {
case '{', '[':
depth++
if depth > max {
return &HTTPError{Status: http.StatusBadRequest, Detail: "JSON nested too deeply"}
}
case '}', ']':
depth--
}
}
}
}
// clientSafe keeps the useful part of a decode error (which field, which
// type) and drops Go type names of internal structs.
func clientSafe(err error) string {
var ute *json.UnmarshalTypeError
var se *json.SyntaxError
switch {
case errors.As(err, &ute):
return "field " + ute.Field + " has the wrong type"
case errors.As(err, &se), errors.Is(err, io.ErrUnexpectedEOF):
return "malformed JSON"
case strings.HasPrefix(err.Error(), "json: unknown field "):
return "unknown field " + strings.TrimPrefix(err.Error(), "json: unknown field ")
case errors.Is(err, io.EOF):
return "empty body"
default:
return "invalid JSON body"
}
}Processing: panics become generic 500s, stacks go to the log:
package harden
import (
"fmt"
"log/slog"
"net/http"
"runtime/debug"
)
// Recover turns a panic into a 500 problem response. The stack trace goes to
// the server log with the request id; the client only sees the id, which
// support can look up. With debug on (never in production, see Config) the
// panic value is added to the detail.
func Recover(log *slog.Logger, debugMode bool) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler {
panic(v) // net/http's own signal to abort the response
}
log.ErrorContext(r.Context(), "panic",
slog.String("request_id", RequestIDFrom(r.Context())),
slog.String("panic", fmt.Sprint(v)),
slog.String("stack", string(debug.Stack())),
)
detail := "internal error"
if debugMode {
detail = fmt.Sprint(v)
}
WriteProblem(w, r, http.StatusInternalServerError, detail, nil)
}()
next.ServeHTTP(w, r)
})
}
}Processing: the debug-off guard:
package harden
import (
"errors"
"fmt"
)
// Config is the part of the service configuration the checklist cares about.
type Config struct {
Env string // "production", "staging", "local"
Debug bool // verbose errors (panic text in problem details)
ExposePprof bool // net/http/pprof on the public listener
MaxBodyBytes int64
}
// ErrUnsafeConfig is returned by Validate; main refuses to start on it.
var ErrUnsafeConfig = errors.New("unsafe production configuration")
// Validate is the debug-off guard: a production process with debug output,
// profiling on the public port or no body limit does not start at all.
func (c Config) Validate() error {
if c.Env != "production" {
return nil
}
switch {
case c.Debug:
return fmt.Errorf("%w: debug mode is on", ErrUnsafeConfig)
case c.ExposePprof:
return fmt.Errorf("%w: pprof is exposed", ErrUnsafeConfig)
case c.MaxBodyBytes <= 0:
return fmt.Errorf("%w: no request body size limit", ErrUnsafeConfig)
}
return nil
}Processing: server timeouts and the handler deadline:
package harden
import (
"net/http"
"time"
)
// Timeouts for an internet-facing JSON API. In http.Server a zero
// ReadTimeout or WriteTimeout means no timeout, and a zero ReadHeaderTimeout
// or IdleTimeout falls back to ReadTimeout; set all of them explicitly.
type Timeouts struct {
ReadHeader time.Duration // headers must arrive in this time (slowloris)
Read time.Duration // whole request, including the body
Write time.Duration // from end of headers to end of response
Idle time.Duration // keep-alive wait for the next request
Handler time.Duration // http.TimeoutHandler: 503 after this
}
// DefaultTimeouts are conservative values for small JSON requests.
var DefaultTimeouts = Timeouts{
ReadHeader: 5 * time.Second,
Read: 10 * time.Second,
Write: 15 * time.Second,
Idle: 60 * time.Second,
Handler: 8 * time.Second,
}
// NewServer returns an http.Server with every timeout and the header size
// limit set. Handler deadlines are applied by WithHandlerTimeout.
func NewServer(addr string, h http.Handler, t Timeouts) *http.Server {
return &http.Server{
Addr: addr,
Handler: h,
ReadHeaderTimeout: t.ReadHeader,
ReadTimeout: t.Read,
WriteTimeout: t.Write,
IdleTimeout: t.Idle,
MaxHeaderBytes: 32 << 10, // 32 KiB instead of the 1 MB default
}
}
// WithHandlerTimeout cancels the request context and answers 503 Service
// Unavailable when the handler runs longer than d. The body is rewritten
// into a problem by ProblemErrors.
func WithHandlerTimeout(d time.Duration) Middleware {
return func(next http.Handler) http.Handler {
return http.TimeoutHandler(next, d, "")
}
}Browsers: CORS with an explicit allow-list:
package harden
import (
"net/http"
"strings"
)
// CORSOptions is an explicit allow-list. There is no wildcard mode: an API
// that sends cookies or Authorization from a browser must name its origins.
type CORSOptions struct {
Origins []string // exact origins, e.g. "https://shop.example"
Methods []string // methods a preflight may ask for
Headers []string // request headers a preflight may ask for
AllowCredentials bool
MaxAgeSeconds string
}
// CORS answers preflights and adds CORS headers for allowed origins only.
// Requests without an Origin header (curl, server-to-server) pass through
// untouched: CORS is a browser read permission, not authentication.
func CORS(o CORSOptions) Middleware {
origins := map[string]bool{}
for _, v := range o.Origins {
origins[v] = true
}
methods := map[string]bool{}
for _, m := range o.Methods {
methods[m] = true
}
headers := map[string]bool{}
for _, h := range o.Headers {
headers[strings.ToLower(h)] = true
}
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
if origin == "" {
next.ServeHTTP(w, r)
return
}
h := w.Header()
h.Add("Vary", "Origin") // caches must key on Origin
preflight := r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != ""
if !origins[origin] {
if preflight {
WriteProblem(w, r, http.StatusForbidden, "origin not allowed", nil)
return
}
next.ServeHTTP(w, r) // no CORS headers: the browser hides the response
return
}
h.Set("Access-Control-Allow-Origin", origin) // echo only after the allow-list check
if o.AllowCredentials {
h.Set("Access-Control-Allow-Credentials", "true")
}
if !preflight {
h.Set("Access-Control-Expose-Headers", RequestIDHeader)
next.ServeHTTP(w, r)
return
}
if !methods[r.Header.Get("Access-Control-Request-Method")] {
WriteProblem(w, r, http.StatusForbidden, "method not allowed for CORS", nil)
return
}
for _, rh := range strings.Split(r.Header.Get("Access-Control-Request-Headers"), ",") {
if rh = strings.TrimSpace(strings.ToLower(rh)); rh != "" && !headers[rh] {
WriteProblem(w, r, http.StatusForbidden, "header not allowed for CORS", nil)
return
}
}
h.Set("Access-Control-Allow-Methods", strings.Join(o.Methods, ", "))
h.Set("Access-Control-Allow-Headers", strings.Join(o.Headers, ", "))
if o.MaxAgeSeconds != "" {
h.Set("Access-Control-Max-Age", o.MaxAgeSeconds)
}
w.WriteHeader(http.StatusNoContent)
})
}
}Monitoring: request id and the redacted access log:
package harden
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"regexp"
)
type ctxKey int
const requestIDKey ctxKey = 0
// RequestIDHeader is echoed on every response and logged on every line.
const RequestIDHeader = "X-Request-ID"
// An incoming id is only reused when it comes from a trusted proxy and is
// short and boring: never let a client write arbitrary bytes into your logs.
var validID = regexp.MustCompile(`^[A-Za-z0-9._-]{8,64}$`)
// RequestID assigns a request id (the correlation id of this hop). With
// trustIncoming, a well-formed id set by the gateway is kept so one id
// follows the call across services.
func RequestID(trustIncoming bool) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get(RequestIDHeader)
if !trustIncoming || !validID.MatchString(id) {
id = newID()
}
w.Header().Set(RequestIDHeader, id)
ctx := context.WithValue(r.Context(), requestIDKey, id)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// RequestIDFrom returns the id stored by RequestID, or "".
func RequestIDFrom(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey).(string)
return id
}
func newID() string {
b := make([]byte, 12)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}package harden
import (
"io"
"log/slog"
"net/http"
"strings"
"time"
)
// sensitiveKeys are attribute names whose values never reach a log line.
var sensitiveKeys = map[string]bool{
"authorization": true, "cookie": true, "set-cookie": true, "password": true,
"token": true, "access_token": true, "refresh_token": true, "api_key": true,
"secret": true, "card_number": true, "email": true,
}
// NewLogger returns a JSON slog logger whose handler redacts sensitive
// attributes wherever they appear, including inside groups.
func NewLogger(w io.Writer) *slog.Logger {
return slog.New(slog.NewJSONHandler(w, &slog.HandlerOptions{
ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
if sensitiveKeys[strings.ToLower(a.Key)] {
return slog.String(a.Key, "[REDACTED]")
}
return a
},
}))
}
// AccessLog writes one structured line per request: request id, method,
// path WITHOUT the query string (queries carry tokens and PII), status,
// size and duration. Bodies and headers are never logged.
func AccessLog(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(sw, r)
level := slog.LevelInfo
if sw.status >= 500 {
level = slog.LevelError
} else if sw.status == http.StatusUnauthorized || sw.status == http.StatusForbidden {
level = slog.LevelWarn // feed for brute-force and BOLA alerts
}
log.LogAttrs(r.Context(), level, "http_request",
slog.String("request_id", RequestIDFrom(r.Context())),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", sw.status),
slog.Int("bytes", sw.bytes),
slog.Int64("duration_ms", time.Since(start).Milliseconds()),
)
})
}
}
type statusWriter struct {
http.ResponseWriter
status int
bytes int
wrote bool
}
func (s *statusWriter) WriteHeader(code int) {
if !s.wrote {
s.status, s.wrote = code, true
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusWriter) Write(b []byte) (int, error) {
s.wrote = true
n, err := s.ResponseWriter.Write(b)
s.bytes += n
return n, err
}
func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter }The API that wires it all, with an output DTO and allow-list validation:
// Package app is a small orders API wired through the hardening chain.
package app
import (
"encoding/json"
"log/slog"
"net/http"
"regexp"
"time"
"academy/api-security-hardening-checklist/harden"
)
// Options configures New.
type Options struct {
Config harden.Config
Log *slog.Logger
Timeouts harden.Timeouts
Origins []string
Lab bool // registers /v1/lab/* routes used by the audit script
}
// New returns the API with the full middleware chain, outermost first.
func New(o Options) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /v1/orders/{id}", getOrder)
mux.HandleFunc("POST /v1/orders", createOrder)
if o.Lab {
mux.HandleFunc("GET /v1/lab/panic", func(http.ResponseWriter, *http.Request) {
panic("db: connection refused at 10.0.3.7:5432 user=orders_rw")
})
mux.HandleFunc("GET /v1/lab/slow", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(5 * time.Second):
writeJSON(w, http.StatusOK, map[string]string{"status": "late"})
case <-r.Context().Done(): // TimeoutHandler cancelled us
}
})
}
return harden.Chain(mux,
harden.RequestID(false), // monitoring: correlation id first
harden.AccessLog(o.Log), // monitoring: one redacted line per request
harden.SecurityHeaders(harden.HeaderOptions{HSTSMaxAge: 63072000}), // output
harden.ProblemErrors, // output: RFC 9457 for net/http's own errors
harden.Recover(o.Log, o.Config.Debug), // processing: no stack traces out
harden.CORS(harden.CORSOptions{ // browsers: explicit origins only
Origins: o.Origins,
Methods: []string{"GET", "POST"},
Headers: []string{"Content-Type", "Authorization", "X-Request-ID"},
AllowCredentials: true,
MaxAgeSeconds: "600",
}),
harden.AllowMethods("GET", "HEAD", "POST", "OPTIONS"), // input: method allow-list
harden.JSONOnly, // input: 415 / 406
harden.LimitBody(o.Config.MaxBodyBytes), // input: 413
harden.WithHandlerTimeout(o.Timeouts.Handler), // processing: 503 after the deadline
)
}
// order is the stored record; orderView is what leaves the API. Internal
// fields never get a JSON tag on the public type.
type order struct {
ID string
SKU string
Quantity int
CardNumber string
RiskScore float64
}
type orderView struct {
ID string `json:"id"`
SKU string `json:"sku"`
Quantity int `json:"quantity"`
CardLast string `json:"card_last4"`
}
var (
uuidRe = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
skuRe = regexp.MustCompile(`^[A-Z0-9-]{3,32}$`)
)
func getOrder(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !uuidRe.MatchString(id) { // allow-list: a UUID or nothing
harden.WriteProblem(w, r, http.StatusNotFound, "", nil)
return
}
o := order{ID: id, SKU: "MUG-01", Quantity: 2, CardNumber: "4111111111111111", RiskScore: 0.12}
writeJSON(w, http.StatusOK, orderView{ID: o.ID, SKU: o.SKU, Quantity: o.Quantity, CardLast: o.CardNumber[len(o.CardNumber)-4:]})
}
type createOrderInput struct {
SKU string `json:"sku"`
Quantity int `json:"quantity"`
Currency string `json:"currency"`
}
func (in createOrderInput) validate() map[string]string {
errs := map[string]string{}
if !skuRe.MatchString(in.SKU) {
errs["sku"] = "must match ^[A-Z0-9-]{3,32}$"
}
if in.Quantity < 1 || in.Quantity > 100 {
errs["quantity"] = "must be between 1 and 100"
}
if in.Currency != "EUR" && in.Currency != "USD" {
errs["currency"] = "must be EUR or USD"
}
return errs
}
func createOrder(w http.ResponseWriter, r *http.Request) {
var in createOrderInput
if err := harden.DecodeJSON(r, &in); err != nil {
harden.WriteError(w, r, err)
return
}
if errs := in.validate(); len(errs) > 0 {
harden.WriteProblem(w, r, http.StatusUnprocessableEntity, "validation failed", errs)
return
}
id := "6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f"
w.Header().Set("Location", "/v1/orders/"+id)
writeJSON(w, http.StatusCreated, orderView{ID: id, SKU: in.SKU, Quantity: in.Quantity})
}
func writeJSON(w http.ResponseWriter, status int, v any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}The lab server (refuses to start with debug on in production):
// Command apiserver runs the hardened API (or the "before" version) on a
// local port for the curl audit lab.
package main
import (
"flag"
"log"
"net/http"
"os"
"time"
"academy/api-security-hardening-checklist/app"
"academy/api-security-hardening-checklist/before"
"academy/api-security-hardening-checklist/harden"
)
func main() {
addr := flag.String("addr", "127.0.0.1:18488", "listen address")
mode := flag.String("mode", "after", "after (hardened) or before (naive)")
flag.Parse()
cfg := harden.Config{
Env: os.Getenv("APP_ENV"),
Debug: os.Getenv("APP_DEBUG") == "true",
MaxBodyBytes: 64 << 10, // 64 KiB: the largest valid order is far smaller
}
if err := cfg.Validate(); err != nil {
log.Fatal(err) // debug-off guard: refuse to start
}
var h http.Handler
if *mode == "before" {
h = before.New()
srv := &http.Server{Addr: *addr, Handler: h} // no timeouts at all
log.Fatal(srv.ListenAndServe())
}
t := harden.DefaultTimeouts
t.Handler = time.Second // short so the lab can show the 503 quickly
h = app.New(app.Options{
Config: cfg,
Log: harden.NewLogger(os.Stderr),
Timeouts: t,
Origins: []string{"https://shop.example"},
Lab: true,
})
log.Fatal(harden.NewServer(*addr, h, t).ListenAndServe())
}Tests that prove each item
Every behaviour above has a test; the most instructive ones are shown. End to end, every response (success, 405, 413, 415, 422, 404, 500, 503) carries the headers and no fingerprint, and every rejection is application/problem+json:
package app
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"academy/api-security-hardening-checklist/harden"
)
const orderURL = "/v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f"
func newAPI(logs io.Writer) http.Handler {
t := harden.DefaultTimeouts
t.Handler = 200 * time.Millisecond
return New(Options{
Config: harden.Config{Env: "production", MaxBodyBytes: 1024},
Log: harden.NewLogger(logs),
Timeouts: t,
Origins: []string{"https://shop.example"},
Lab: true,
})
}
func req(method, url, ctype, body string) *http.Request {
var b io.Reader
if body != "" {
b = strings.NewReader(body)
}
r := httptest.NewRequest(method, url, b)
if ctype != "" {
r.Header.Set("Content-Type", ctype)
}
return r
}
// Every response, success or rejection, carries the output headers, a
// request id, and no fingerprint; every rejection is problem+json.
func TestEveryResponseIsHardened(t *testing.T) {
cases := []struct {
name string
r *http.Request
want int
}{
{"get order", req("GET", orderURL, "", ""), 200},
{"create order", req("POST", "/v1/orders", "application/json", `{"sku":"MUG-01","quantity":2,"currency":"EUR"}`), 201},
{"TRACE", req("TRACE", orderURL, "", ""), 405},
{"route method", req("POST", orderURL, "application/json", `{}`), 405},
{"text/plain body", req("POST", "/v1/orders", "text/plain", `{}`), 415},
{"oversized body", req("POST", "/v1/orders", "application/json", `{"sku":"`+strings.Repeat("A", 2048)+`"}`), 413},
{"unknown field", req("POST", "/v1/orders", "application/json", `{"sku":"MUG-01","quantity":1,"currency":"EUR","price":0}`), 400},
{"invalid values", req("POST", "/v1/orders", "application/json", `{"sku":"x","quantity":0,"currency":"BTC"}`), 422},
{"not a uuid", req("GET", "/v1/orders/1%20OR%201=1", "", ""), 404},
{"unknown route", req("GET", "/.env", "", ""), 404},
{"panic", req("GET", "/v1/lab/panic", "", ""), 500},
{"handler timeout", req("GET", "/v1/lab/slow", "", ""), 503},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, c.r)
h := rec.Header()
if rec.Code != c.want {
t.Fatalf("status %d, want %d: %s", rec.Code, c.want, rec.Body.String())
}
for _, k := range []string{"X-Content-Type-Options", "Cache-Control", "Content-Security-Policy", "X-Frame-Options", "X-Request-ID"} {
if h.Get(k) == "" {
t.Errorf("missing %s", k)
}
}
if h.Get("Server") != "" || h.Get("X-Powered-By") != "" {
t.Errorf("fingerprint headers present")
}
if c.want >= 400 && h.Get("Content-Type") != "application/problem+json" {
t.Errorf("rejection Content-Type %q", h.Get("Content-Type"))
}
if strings.Contains(rec.Body.String(), "goroutine") || strings.Contains(rec.Body.String(), "10.0.3.7") {
t.Errorf("internal detail leaked: %s", rec.Body.String())
}
})
}
}
func TestResponseHasNoSensitiveFields(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, req("GET", orderURL, "", ""))
var m map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &m); err != nil {
t.Fatal(err)
}
if _, ok := m["card_number"]; ok || strings.Contains(rec.Body.String(), "4111111111111111") {
t.Fatalf("full card number in response: %s", rec.Body.String())
}
if _, ok := m["RiskScore"]; ok {
t.Fatalf("internal field in response")
}
if m["card_last4"] != "1111" {
t.Fatalf("view: %v", m)
}
}
func TestCreateReturns201WithLocation(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, req("POST", "/v1/orders", "application/json", `{"sku":"MUG-01","quantity":2,"currency":"EUR"}`))
if rec.Code != 201 || !strings.HasPrefix(rec.Header().Get("Location"), "/v1/orders/") {
t.Fatalf("%d %v", rec.Code, rec.Header())
}
}
func TestValidationProblemListsFields(t *testing.T) {
rec := httptest.NewRecorder()
newAPI(io.Discard).ServeHTTP(rec, req("POST", "/v1/orders", "application/json", `{"sku":"x","quantity":0,"currency":"BTC"}`))
var p harden.Problem
_ = json.Unmarshal(rec.Body.Bytes(), &p)
if p.Title != "Unprocessable Content" || len(p.Errors) != 3 {
t.Fatalf("%+v", p)
}
}
func TestPanicIsLoggedWithStackServerSide(t *testing.T) {
var logs bytes.Buffer
rec := httptest.NewRecorder()
newAPI(&logs).ServeHTTP(rec, req("GET", "/v1/lab/panic", "", ""))
if !strings.Contains(logs.String(), "goroutine") || !strings.Contains(logs.String(), rec.Header().Get("X-Request-ID")) {
t.Fatalf("logs: %s", logs.String())
}
}Headers, including HSTS only over TLS (an httptest.NewTLSServer) and fingerprint stripping after the inner handler set Server: nginx/1.18.0:
package harden
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestSecurityHeadersAndFingerprintStripping(t *testing.T) {
inner := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// An inner handler or a proxied upstream sets fingerprinting headers
// AFTER the middleware ran; they must still be gone.
w.Header().Set("Server", "nginx/1.18.0")
w.Header().Set("X-Powered-By", "PHP/8.1.2")
okHandler.ServeHTTP(w, r)
})
h := SecurityHeaders(HeaderOptions{HSTSMaxAge: 63072000})(inner)
rec := do(t, h, httptest.NewRequest("GET", "/v1/orders", nil))
want := map[string]string{
"Cache-Control": "no-store",
"Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'",
"X-Content-Type-Options": "nosniff",
"X-Frame-Options": "DENY",
"Referrer-Policy": "no-referrer",
}
for k, v := range want {
if got := rec.Header().Get(k); got != v {
t.Errorf("%s = %q, want %q", k, got, v)
}
}
for _, k := range []string{"Server", "X-Powered-By"} {
if v := rec.Header().Get(k); v != "" {
t.Errorf("%s leaked: %q", k, v)
}
}
if v := rec.Header().Get("Strict-Transport-Security"); v != "" {
t.Errorf("HSTS sent over plain HTTP (RFC 6797 7.2 forbids it): %q", v)
}
}
func TestHSTSOnlyOverTLS(t *testing.T) {
srv := httptest.NewTLSServer(SecurityHeaders(HeaderOptions{HSTSMaxAge: 63072000})(okHandler))
defer srv.Close()
resp, err := srv.Client().Get(srv.URL + "/")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if got := resp.Header.Get("Strict-Transport-Security"); got != "max-age=63072000; includeSubDomains" {
t.Fatalf("HSTS over TLS = %q", got)
}
}
func TestHSTSBehindTrustedProxy(t *testing.T) {
h := SecurityHeaders(HeaderOptions{HSTSMaxAge: 300, TrustForwardedProto: true})(okHandler)
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("X-Forwarded-Proto", "https")
if got := do(t, h, r).Header().Get("Strict-Transport-Security"); got != "max-age=300; includeSubDomains" {
t.Fatalf("HSTS behind TLS-terminating proxy = %q", got)
}
}Body limit: declared length, chunked body, and the connection close over a real socket through the wrappers:
package harden
import (
"bytes"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func decodeHandler(w http.ResponseWriter, r *http.Request) {
var v map[string]any
if err := DecodeJSON(r, &v); err != nil {
WriteError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func TestDeclaredLengthRejectedBeforeHandler(t *testing.T) {
called := false
h := LimitBody(1024)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true }))
r := httptest.NewRequest("POST", "/v1/orders", bytes.NewReader(make([]byte, 4096)))
rec := do(t, h, r)
if rec.Code != 413 || called {
t.Fatalf("status %d, handler called %v; want 413 without calling the handler", rec.Code, called)
}
if p := problemOf(t, rec); p.Title != "Content Too Large" {
t.Fatalf("title %q, want the RFC 9110 name", p.Title)
}
}
func TestChunkedBodyCutByMaxBytesReader(t *testing.T) {
h := LimitBody(1024)(http.HandlerFunc(decodeHandler))
big := `{"a":"` + strings.Repeat("x", 4096) + `"}`
r := httptest.NewRequest("POST", "/v1/orders", strings.NewReader(big))
r.ContentLength = -1 // unknown length, as with Transfer-Encoding: chunked
if rec := do(t, h, r); rec.Code != 413 {
t.Fatalf("chunked oversize: %d, want 413", rec.Code)
}
}
// Over a real connection, the limit must still reach net/http's own writer
// through the wrappers (stripWriter, statusWriter), so the server closes the
// connection instead of draining an attacker's endless body.
func TestLimitClosesConnectionThroughWrappers(t *testing.T) {
h := Chain(http.HandlerFunc(decodeHandler),
AccessLog(NewLogger(io.Discard)), SecurityHeaders(HeaderOptions{}), LimitBody(1024))
srv := httptest.NewServer(h)
defer srv.Close()
pr, pw := io.Pipe()
go func() {
_, _ = pw.Write([]byte(`{"a":"` + strings.Repeat("x", 8192)))
_ = pw.Close()
}()
req, _ := http.NewRequest("POST", srv.URL+"/", pr) // chunked: length unknown
req.Header.Set("Content-Type", "application/json")
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != 413 {
t.Fatalf("status %d, want 413", resp.StatusCode)
}
if !resp.Close {
t.Fatalf("server kept the connection open after the body limit was hit")
}
}Negotiation table (415, 406, q-values, chunked without a type):
package harden
import (
"io"
"net/http/httptest"
"strings"
"testing"
)
func TestJSONOnly(t *testing.T) {
cases := []struct {
name, method, ctype, accept, body string
chunked bool
want int
}{
{"json body", "POST", "application/json", "", `{}`, false, 200},
{"json utf-8", "POST", "application/json; charset=utf-8", "application/json", `{}`, false, 200},
{"text/plain body", "POST", "text/plain", "", `{}`, false, 415},
{"form body", "POST", "application/x-www-form-urlencoded", "", `a=1`, false, 415},
{"xml body", "POST", "application/xml", "", `<a/>`, false, 415},
{"latin1 charset", "POST", "application/json; charset=iso-8859-1", "", `{}`, false, 415},
{"missing content-type", "POST", "", "", `{}`, false, 415},
{"chunked without type", "POST", "", "", `{}`, true, 415},
{"GET without body needs no type", "GET", "", "", ``, false, 200},
{"accept xml only", "GET", "", "application/xml", ``, false, 406},
{"accept json q=0", "GET", "", "application/json;q=0, text/html", ``, false, 406},
{"accept wildcard", "GET", "", "text/html, */*;q=0.1", ``, false, 200},
{"accept problem+json only", "GET", "", "application/problem+json", ``, false, 406},
{"explicit json q=0 beats wildcard", "GET", "", "application/json;q=0, application/problem+json;q=0, */*;q=1", ``, false, 406},
{"specific json beats application/* q=0", "GET", "", "application/*;q=0, application/json", ``, false, 200},
{"wildcard q=0", "GET", "", "*/*;q=0", ``, false, 406},
{"application/* accepted", "GET", "", "application/*;q=0.5", ``, false, 200},
{"json with params", "GET", "", "application/json; charset=utf-8", ``, false, 200},
{"malformed q ignored", "GET", "", "application/json;q=abc", ``, false, 406},
{"q=NaN ignored", "GET", "", "application/json;q=NaN", ``, false, 406},
{"q=1e0 ignored", "GET", "", "application/json;q=1e0", ``, false, 406},
{"q=inf ignored", "GET", "", "application/json;q=inf", ``, false, 406},
{"q above 1 ignored", "GET", "", "application/json;q=1.5", ``, false, 406},
{"q four decimals ignored", "GET", "", "application/json;q=0.1234", ``, false, 406},
{"malformed json q falls back to wildcard", "GET", "", "application/json;q=NaN, */*;q=0.2", ``, false, 200},
{"q=0.001 accepted", "GET", "", "application/json;q=0.001", ``, false, 200},
{"profile range does not match plain json", "GET", "", "application/json;profile=v2;q=1, application/json;q=0", ``, false, 406},
{"profile range alone", "GET", "", "application/json;profile=v2", ``, false, 406},
{"profile range does not hide wildcard", "GET", "", "application/json;profile=v2, */*", ``, false, 200},
{"charset utf-8 is more specific", "GET", "", "application/json;q=0, application/json;charset=utf-8", ``, false, 200},
{"charset latin1 does not match", "GET", "", "application/json;charset=iso-8859-1", ``, false, 406},
}
h := JSONOnly(okHandler)
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
var body io.Reader
if c.body != "" {
body = strings.NewReader(c.body)
}
r := httptest.NewRequest(c.method, "/v1/orders", body)
if c.chunked {
r.ContentLength = -1
}
if c.ctype != "" {
r.Header.Set("Content-Type", c.ctype)
}
if c.accept != "" {
r.Header.Set("Accept", c.accept)
}
rec := do(t, h, r)
if rec.Code != c.want {
t.Fatalf("status %d, want %d", rec.Code, c.want)
}
if c.want == 415 && rec.Header().Get("Accept") != "application/json" {
t.Fatalf("415 without Accept response header")
}
if c.want >= 400 {
problemOf(t, rec)
}
})
}
}Slowloris over a raw TCP connection, the handler deadline, and the server fields:
package harden
import (
"bufio"
"io"
"net"
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestNewServerSetsEveryTimeout(t *testing.T) {
s := NewServer(":0", okHandler, DefaultTimeouts)
if s.ReadHeaderTimeout == 0 || s.ReadTimeout == 0 || s.WriteTimeout == 0 || s.IdleTimeout == 0 {
t.Fatalf("a zero timeout means no timeout: %+v", s)
}
if s.MaxHeaderBytes != 32<<10 {
t.Fatalf("MaxHeaderBytes %d", s.MaxHeaderBytes)
}
}
// A slowloris client sends a header line and then nothing. With
// ReadHeaderTimeout set, Go closes the connection without a response
// (nginx would answer 408); without it the connection stays open.
func TestSlowlorisHeaderTimeout(t *testing.T) {
srv := httptest.NewUnstartedServer(okHandler)
srv.Config.ReadHeaderTimeout = 200 * time.Millisecond
srv.Start()
defer srv.Close()
conn, err := net.Dial("tcp", srv.Listener.Addr().String())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
_, _ = io.WriteString(conn, "GET / HTTP/1.1\r\nHost: x\r\nX-Slow: 1\r\n") // never finishes
_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
start := time.Now()
n, err := bufio.NewReader(conn).Read(make([]byte, 1))
if err != io.EOF || n != 0 {
t.Fatalf("read %d bytes, err %v; want a silent close (EOF)", n, err)
}
if el := time.Since(start); el > 2*time.Second {
t.Fatalf("closed after %v; ReadHeaderTimeout not applied", el)
}
}
func TestHandlerTimeoutIs503Problem(t *testing.T) {
slow := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done() // a well-behaved handler stops when cancelled
})
h := Chain(slow, ProblemErrors, WithHandlerTimeout(50*time.Millisecond))
rec := do(t, h, httptest.NewRequest("GET", "/v1/report", nil))
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("status %d, want 503 (http.TimeoutHandler)", rec.Code)
}
problemOf(t, rec)
}Redaction and log-injection-safe request ids:
package harden
import (
"bytes"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestAccessLogLineIsRedacted(t *testing.T) {
var buf bytes.Buffer
log := NewLogger(&buf)
h := Chain(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}), RequestID(false), AccessLog(log))
r := httptest.NewRequest("GET", "/v1/orders?access_token=sk_live_SECRET&email=ana@example.com", nil)
r.Header.Set("Authorization", "Bearer sk_live_SECRET")
rec := do(t, h, r)
line := buf.String()
if strings.Contains(line, "sk_live_SECRET") || strings.Contains(line, "ana@example.com") {
t.Fatalf("secret or PII in log: %s", line)
}
var m map[string]any
if err := json.Unmarshal([]byte(line), &m); err != nil {
t.Fatal(err)
}
if m["path"] != "/v1/orders" || m["status"] != float64(401) || m["level"] != "WARN" {
t.Fatalf("unexpected line: %s", line)
}
if m["request_id"] != rec.Header().Get(RequestIDHeader) {
t.Fatalf("log request_id %v != response header %q", m["request_id"], rec.Header().Get(RequestIDHeader))
}
}
func TestLoggerRedactsSensitiveAttributes(t *testing.T) {
var buf bytes.Buffer
NewLogger(&buf).Info("login",
slog.String("user_id", "42"),
slog.String("password", "hunter2"),
slog.Group("req", slog.String("Authorization", "Bearer abc.def.ghi")),
)
out := buf.String()
for _, leak := range []string{"hunter2", "abc.def.ghi"} {
if strings.Contains(out, leak) {
t.Fatalf("leaked %q: %s", leak, out)
}
}
if !strings.Contains(out, `"user_id":"42"`) {
t.Fatalf("non-sensitive attribute lost: %s", out)
}
}package harden
import (
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
)
func echoID(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(RequestIDFrom(r.Context())))
}
func TestRequestIDGenerated(t *testing.T) {
rec := do(t, RequestID(false)(http.HandlerFunc(echoID)), httptest.NewRequest("GET", "/", nil))
id := rec.Header().Get(RequestIDHeader)
if !regexp.MustCompile(`^[0-9a-f]{24}$`).MatchString(id) || rec.Body.String() != id {
t.Fatalf("header %q, context %q", id, rec.Body.String())
}
}
func TestRequestIDIncoming(t *testing.T) {
cases := []struct {
name, in string
trust bool
reused bool
}{
{"untrusted client id ignored", "gw-7f3a9c2e", false, false},
{"trusted gateway id kept", "gw-7f3a9c2e", true, true},
{"log injection replaced", "abc\nlevel=ERROR msg=fake", true, false},
{"oversized replaced", strings.Repeat("a", 65), true, false},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set(RequestIDHeader, c.in)
got := do(t, RequestID(c.trust)(http.HandlerFunc(echoID)), r).Header().Get(RequestIDHeader)
if (got == c.in) != c.reused {
t.Fatalf("got %q, reused=%v, want reused=%v", got, got == c.in, c.reused)
}
})
}
}The remaining tests (methods_test.go, jsonin_test.go, recover_test.go, cors_test.go, config_test.go, problem_test.go) are in the same directory.
The Go angle
- Go middleware chain: a middleware is
func(http.Handler) http.Handler; there is no framework-level ordering, so the order in oneChaincall is the security design. Wrappers ofhttp.ResponseWritershould implementUnwrap() http.ResponseWriter(Go 1.20http.ResponseControlleruses it) or they hide features from everything below. More patterns are in Go middlewares. ServeMuxsince Go 1.22 does per-route method allow-lists ("POST /v1/orders"),GETalso registersHEAD, and a wrong method on a known path returns 405 withAllow; its error body istext/plainfromhttp.Error, which is whyProblemErrorsexists.http.ErrorsetsContent-Type: text/plain; charset=utf-8andX-Content-Type-Options: nosniffand deletesContent-Length; it is fine for internal tools, not for an API that promises one error format.- Body limits:
http.MaxBytesReader(typed*http.MaxBytesErrorsince 1.19);io.LimitReadersilently truncates, which turns an oversized body into a confusing JSON syntax error instead of a 413. - Timeouts: in
http.Server, a zeroReadTimeout/WriteTimeoutmeans no timeout, while a zeroReadHeaderTimeoutorIdleTimeoutfalls back toReadTimeout(and is unbounded only if that is zero too); set all four explicitly;ReadHeaderTimeoutis the slowloris defence and the onego vet-adjacent linters (gosec G112) ask for;http.TimeoutHandleranswers 503 and cancels the request context, so handlers must passr.Context()down to the database and HTTP clients. Per-request deadlines can be adjusted withhttp.NewResponseController(w).SetReadDeadline/SetWriteDeadline(Go 1.20) for streaming endpoints. On TLS listeners the handshake is bounded too:tlsHandshakeTimeoutinserver.go"returns the minimum of any positive ReadHeaderTimeout, ReadTimeout, or WriteTimeout". - Logging:
log/slog(Go 1.21) withReplaceAttrfor redaction; keys are matched case-insensitively here because developers writeAuthorizationandauthorization. - JSON:
encoding/jsonhas no size limit and an internal nesting limit of 10000;DisallowUnknownFieldsand a check for trailing data (dec.More(), thenToken()returningio.EOF) make decoding strict. Theencoding/json/v2work (experimentalGOEXPERIMENT=jsonv2in Go 1.25) changes defaults; this module stays on v1. - Tooling:
govulncheck ./...(reachability-aware SCA),gosec ./...(G112 for missingReadHeaderTimeout, G114 forhttp.ListenAndServewithout timeouts),go test -race.
Laravel
Example: middleware, CORS, debug guard, problem details, redaction
Output headers and fingerprint removal, prepended to the global stack so it wraps HandleCors (preflights) and the other early returns:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Output headers for a JSON API (OWASP REST Security Cheat Sheet set) and
* removal of fingerprinting headers. Prepended to the global stack (before
* HandleCors) so preflights and error responses (404, 405, 413, 500) get
* the headers too.
*/
class SecurityHeaders
{
private const HEADERS = [
'Cache-Control' => 'no-store',
'Content-Security-Policy' => "default-src 'none'; frame-ancestors 'none'",
'X-Content-Type-Options' => 'nosniff',
'X-Frame-Options' => 'DENY',
'Referrer-Policy' => 'no-referrer',
'Permissions-Policy' => 'camera=(), microphone=(), geolocation=(), payment=()',
];
public function handle(Request $request, Closure $next): Response
{
$response = $next($request);
foreach (self::HEADERS as $name => $value) {
$response->headers->set($name, $value);
}
// RFC 6797: never send HSTS over plain HTTP. isSecure() honours
// X-Forwarded-Proto only from proxies listed in trustProxies().
if ($request->isSecure()) {
$response->headers->set('Strict-Transport-Security', 'max-age=63072000; includeSubDomains');
}
// PHP adds X-Powered-By itself unless php.ini has expose_php=Off;
// header_remove() covers the SAPI header, the bag covers the rest.
$response->headers->remove('X-Powered-By');
$response->headers->remove('Server');
header_remove('X-Powered-By');
return $response;
}
}415 and 406 for the api group (the router already does 405 with Allow):
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* 415 for a body that is not application/json, 406 for an Accept header
* that excludes JSON. Laravel's router already answers 405 (with Allow) for
* a method the route does not define.
*/
class EnforceJsonApi
{
public function handle(Request $request, Closure $next): Response
{
// Not $request->accepts(): it returns true as soon as any listed range
// matches, ignoring q=0 and precedence (InteractsWithContentTypes).
if ($request->headers->has('Accept')
&& self::jsonQuality((string) $request->headers->get('Accept')) <= 0.0) {
return $this->problem($request, 406, 'This API only produces application/json.');
}
$hasBody = (int) $request->headers->get('Content-Length', '0') > 0
|| $request->headers->has('Transfer-Encoding');
if ($hasBody && ! $request->isJson()) {
return $this->problem($request, 415, 'Send application/json.')
->header('Accept', 'application/json');
}
return $next($request);
}
/**
* RFC 9110 12.5.1 for application/json (UTF-8, no other parameters):
* the most specific matching range sets the quality; ranges with other
* parameters do not match; malformed q values make a range ignored.
*/
public static function jsonQuality(string $accept): float
{
$best = -1;
$quality = 0.0;
foreach (explode(',', $accept) as $range) {
$parts = array_map('trim', explode(';', $range));
$type = strtolower(array_shift($parts));
$specificity = match ($type) {
'application/json' => 2,
'application/*' => 1,
'*/*' => 0,
default => -1,
};
$q = 1.0;
foreach ($parts as $param) {
[$name, $value] = array_pad(array_map('trim', explode('=', $param, 2)), 2, '');
$name = strtolower($name);
$value = trim($value, '"');
if ($name === 'q' && preg_match('/\A(0(\.[0-9]{0,3})?|1(\.0{0,3})?)\z/', $value) === 1) {
$q = (float) $value;
} elseif ($specificity === 2 && $name === 'charset' && strcasecmp($value, 'utf-8') === 0) {
$specificity = 3;
} else {
$specificity = -1; // malformed q or a parameter JSON does not have
break;
}
}
if ($specificity < 0 || $specificity < $best) {
continue;
}
if ($specificity > $best || $q > $quality) {
[$best, $quality] = [$specificity, $q];
}
}
return $best >= 0 ? $quality : 0.0;
}
private function problem(Request $request, int $status, string $detail): Response
{
return response()->json([
'type' => 'about:blank',
'title' => Response::$statusTexts[$status],
'status' => $status,
'detail' => $detail,
'request_id' => $request->attributes->get('request_id'),
], $status, ['Content-Type' => 'application/problem+json']);
}
}Per-route body cap below post_max_size:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Per-route body cap, stricter than php.ini post_max_size (which the global
* ValidatePostSize middleware enforces). Usage: ->middleware('body.limit:65536').
* The web server limit (nginx client_max_body_size) must be the outer wall:
* PHP-FPM has already received the body by the time this runs.
*/
class LimitRequestBody
{
public function handle(Request $request, Closure $next, int $maxBytes = 65536): Response
{
$declared = (int) $request->headers->get('Content-Length', '0');
if ($declared > $maxBytes || strlen($request->getContent()) > $maxBytes) {
return response()->json([
'type' => 'about:blank',
'title' => 'Content Too Large',
'status' => 413,
'detail' => 'Request body too large.',
], 413, ['Content-Type' => 'application/problem+json', 'Connection' => 'close']);
}
return $next($request);
}
}Request id through Context, so every log line and queued job carries it:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Context;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
/**
* Request id / correlation id. Context::add() makes Laravel append it to
* every log entry and to queued jobs dispatched during this request.
*/
class AssignRequestId
{
public function handle(Request $request, Closure $next): Response
{
$incoming = (string) $request->headers->get('X-Request-ID', '');
// Keep the gateway's id only if it is short and boring; a client
// must not be able to write newlines or megabytes into the logs.
$id = preg_match('/\A[A-Za-z0-9._-]{8,64}\z/', $incoming) === 1
? $incoming
: (string) Str::uuid();
$request->attributes->set('request_id', $id);
Context::add('request_id', $id);
$response = $next($request);
$response->headers->set('X-Request-ID', $id);
return $response;
}
}Redaction as a logging channel tap:
<?php
namespace App\Logging;
use Illuminate\Log\Logger;
use Monolog\LogRecord;
/**
* Logging channel tap: a Monolog processor that masks secrets and PII in
* the context and extra arrays before any handler formats the record.
* config/logging.php: 'tap' => [App\Logging\RedactSensitiveData::class].
*/
class RedactSensitiveData
{
private const KEYS = [
'authorization', 'cookie', 'set-cookie', 'password', 'password_confirmation',
'token', 'access_token', 'refresh_token', 'api_key', 'secret', 'card_number', 'email',
];
public function __invoke(Logger $logger): void
{
foreach ($logger->getHandlers() as $handler) {
$handler->pushProcessor(fn (LogRecord $record): LogRecord => $record->with(
context: $this->redact($record->context),
extra: $this->redact($record->extra),
));
}
}
private function redact(array $data): array
{
foreach ($data as $key => $value) {
if (is_string($key) && in_array(strtolower($key), self::KEYS, true)) {
$data[$key] = '[REDACTED]';
} elseif (is_array($value)) {
$data[$key] = $this->redact($value);
}
}
return $data;
}
}Allow-list validation that rejects unknown fields:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;
/**
* Allow-list validation: type, length, range and format per field, and
* unknown fields are an error instead of being silently dropped.
*/
class StoreOrderRequest extends FormRequest
{
private const FIELDS = ['sku', 'quantity', 'currency'];
public function rules(): array
{
return [
'sku' => ['required', 'string', 'regex:/\A[A-Z0-9-]{3,32}\z/'],
'quantity' => ['required', 'integer', 'between:1,100'],
'currency' => ['required', Rule::in(['EUR', 'USD'])],
];
}
public function after(): array
{
return [
function (Validator $validator) {
foreach (array_diff(array_keys($this->all()), self::FIELDS) as $unknown) {
$validator->errors()->add($unknown, 'Unknown field.');
}
},
];
}
}The output allow-list:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* The output allow-list: only these keys leave the API, whatever columns
* the model gains later (card_number, risk_score, internal_notes ...).
*/
class OrderResource extends JsonResource
{
public function toArray(Request $request): array
{
return [
'id' => $this->uuid,
'sku' => $this->sku,
'quantity' => $this->quantity,
'card_last4' => substr((string) $this->card_number, -4),
];
}
}<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreOrderRequest;
use App\Http\Resources\OrderResource;
use App\Models\Order;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Gate;
class OrderController extends Controller
{
public function show(Order $order): OrderResource
{
// Route model binding by uuid (see Order::getRouteKeyName); ownership
// checks belong to the policy layer, not to this checklist.
Gate::authorize('view', $order);
return new OrderResource($order);
}
public function store(StoreOrderRequest $request): JsonResponse
{
$order = $request->user()->orders()->create($request->validated());
return (new OrderResource($order))
->response()
->setStatusCode(201)
->header('Location', route('orders.show', $order));
}
}Explicit verbs and route middleware:
<?php
use App\Http\Controllers\OrderController;
use Illuminate\Support\Facades\Route;
// Explicit verbs only: no Route::any(), no Route::match() with '*'.
// A wrong verb on a known URI gets 405 with an Allow header from the router.
Route::middleware(['auth:sanctum', 'throttle:api', 'body.limit:65536'])
->prefix('v1')
->group(function () {
Route::get('orders/{order:uuid}', [OrderController::class, 'show'])
->whereUuid('order')
->name('orders.show');
Route::post('orders', [OrderController::class, 'store'])->name('orders.store');
});Wiring, trusted proxies, JSON for every API error, RFC 9457 rendering:
<?php
use App\Http\Middleware\AssignRequestId;
use App\Http\Middleware\EnforceJsonApi;
use App\Http\Middleware\LimitRequestBody;
use App\Http\Middleware\SecurityHeaders;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Global and outermost: prepend() puts these before HandleCors,
// ValidatePostSize and maintenance mode, so CORS preflights and those
// early rejections still pass back through SecurityHeaders.
$middleware->prepend(SecurityHeaders::class);
$middleware->prepend(AssignRequestId::class); // now first of all
$middleware->api(prepend: [EnforceJsonApi::class]);
$middleware->alias(['body.limit' => LimitRequestBody::class]);
// Only the load balancer may set X-Forwarded-* (isSecure, client IP).
$middleware->trustProxies(at: ['10.0.0.0/8']);
})
->withExceptions(function (Exceptions $exceptions): void {
// API errors are always JSON, whatever the Accept header says.
$exceptions->shouldRenderJsonWhen(
fn (Request $request, Throwable $e) => $request->is('api/*') || $request->expectsJson()
);
// RFC 9457 problem details; stack traces stay in the log.
$exceptions->render(function (Throwable $e, Request $request) {
// Render callbacks run before Laravel's own AuthenticationException
// handling, so 401 must be mapped here or it would become a 500.
if (! $request->is('api/*') || $e instanceof HttpResponseException) {
return null; // default rendering
}
$status = match (true) {
$e instanceof AuthenticationException => 401,
$e instanceof ValidationException => 422,
$e instanceof HttpExceptionInterface => $e->getStatusCode(),
default => 500,
};
$problem = [
'type' => 'about:blank',
'title' => Response::$statusTexts[$status] ?? 'Error',
'status' => $status,
'request_id' => $request->attributes->get('request_id'),
];
if ($e instanceof ValidationException) {
$problem['errors'] = $e->errors();
}
if (config('app.debug')) {
$problem['detail'] = $e->getMessage(); // local only, see AppServiceProvider
}
$headers = $e instanceof HttpExceptionInterface ? $e->getHeaders() : []; // keeps Allow on 405
$headers['Content-Type'] = 'application/problem+json';
return response()->json($problem, $status, $headers);
});
})->create();The debug-off guard:
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\ServiceProvider;
use RuntimeException;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
// Debug-off guard: a production process with APP_DEBUG=true does
// not boot, so the Ignition/whoops page can never reach a client.
if ($this->app->isProduction() && config('app.debug')) {
throw new RuntimeException('APP_DEBUG must be false in production.');
}
JsonResource::withoutWrapping();
// The 'api' limiter used by routes/api.php (throttle:api): 60 requests
// a minute per user, or per IP for unauthenticated calls -> 429.
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
}
}A strict config/cors.php (publish it first with php artisan config:publish cors):
<?php
// Published with `php artisan config:publish cors`. The framework default is
// 'allowed_origins' => ['*'] with supports_credentials false; an API that a
// browser calls with cookies (Sanctum SPA) must list its origins instead.
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['GET', 'POST'],
'allowed_origins' => [env('FRONTEND_URL', 'https://shop.example')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'Authorization', 'X-Request-ID', 'X-XSRF-TOKEN'],
'exposed_headers' => ['X-Request-ID'],
'max_age' => 600,
'supports_credentials' => true,
];Feature tests for the same behaviours as the Go tests:
<?php
namespace Tests\Feature;
use App\Http\Middleware\EnforceJsonApi;
use App\Models\Order;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Route;
use RuntimeException;
use Tests\TestCase;
class ApiHardeningTest extends TestCase
{
use RefreshDatabase;
public function test_every_api_response_has_the_output_headers(): void
{
$response = $this->getJson('/api/v1/orders/'.fake()->uuid());
$response->assertStatus(401) // unauthenticated: 401, not 500
->assertHeader('Content-Type', 'application/problem+json')
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('X-Frame-Options', 'DENY')
->assertHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'")
->assertHeaderMissing('X-Powered-By')
->assertHeaderMissing('Strict-Transport-Security');
// Symfony may append "private" to Cache-Control; no-store is what counts.
$this->assertStringContainsString('no-store', (string) $response->headers->get('Cache-Control'));
$this->assertNotEmpty($response->headers->get('X-Request-ID'));
}
public function test_wrong_verb_is_405_with_allow(): void
{
$response = $this->deleteJson('/api/v1/orders')
->assertStatus(405)
->assertHeader('Content-Type', 'application/problem+json');
// RFC 9110: a 405 MUST list the supported methods.
$this->assertStringContainsString('POST', (string) $response->headers->get('Allow'));
}
public function test_cors_preflight_carries_the_security_headers(): void
{
$response = $this->call('OPTIONS', '/api/v1/orders', [], [], [], [
'HTTP_ORIGIN' => 'https://shop.example',
'HTTP_ACCESS_CONTROL_REQUEST_METHOD' => 'POST',
]);
$this->assertTrue($response->isSuccessful());
$response->assertHeader('Access-Control-Allow-Origin', 'https://shop.example')
->assertHeader('X-Content-Type-Options', 'nosniff')
->assertHeader('Content-Security-Policy', "default-src 'none'; frame-ancestors 'none'");
}
public function test_non_json_body_is_415(): void
{
$this->actingAs(User::factory()->create())
->call('POST', '/api/v1/orders', [], [], [], ['CONTENT_TYPE' => 'text/plain', 'HTTP_ACCEPT' => 'application/json'], '{"sku":"MUG-01"}')
->assertStatus(415);
}
public function test_accept_without_json_is_406(): void
{
$this->get('/api/v1/orders/'.fake()->uuid(), ['Accept' => 'application/xml'])
->assertStatus(406);
}
public function test_accept_precedence_matches_the_go_rules(): void
{
$cases = [
'application/json;q=0, */*;q=1' => 0.0,
'application/json;profile=v2;q=1, application/json;q=0' => 0.0,
'application/problem+json' => 0.0,
'application/json;q=NaN' => 0.0,
'application/json;q=1e0' => 0.0,
'application/*;q=0, application/json' => 1.0,
'text/html, */*;q=0.1' => 0.1,
'application/json;q=0, application/json;charset=utf-8' => 1.0,
];
foreach ($cases as $accept => $want) {
$this->assertSame($want, EnforceJsonApi::jsonQuality($accept), $accept);
}
}
public function test_unknown_fields_and_bad_values_are_422(): void
{
$this->actingAs(User::factory()->create())
->postJson('/api/v1/orders', ['sku' => 'x', 'quantity' => 0, 'currency' => 'BTC', 'price' => 0])
->assertStatus(422)
->assertJsonStructure(['errors' => ['sku', 'quantity', 'currency', 'price']]);
}
public function test_response_never_contains_the_card_number(): void
{
$user = User::factory()->create();
$order = Order::factory()->for($user)->create(['card_number' => '4111111111111111']);
$this->actingAs($user)->getJson('/api/v1/orders/'.$order->uuid)
->assertOk()
->assertJsonMissingPath('card_number')
->assertJsonPath('card_last4', '1111');
}
public function test_server_errors_do_not_leak_traces(): void
{
config(['app.debug' => false]);
Route::middleware('api')->get('/api/v1/lab/panic', function () {
throw new RuntimeException('db: connection refused at 10.0.3.7:5432 user=orders_rw');
});
$response = $this->getJson('/api/v1/lab/panic')
->assertStatus(500)
->assertHeader('Content-Type', 'application/problem+json')
->assertJsonMissingPath('trace')
->assertJsonMissingPath('exception')
->assertJsonMissingPath('file')
->assertJsonMissingPath('detail');
foreach (['10.0.3.7', 'orders_rw', 'RuntimeException', '.php'] as $leak) {
$this->assertStringNotContainsString($leak, $response->getContent());
}
$this->assertNotEmpty($response->json('request_id'));
}
public function test_unknown_route_is_a_problem_404(): void
{
$this->getJson('/api/v1/orders/not-a-uuid')
->assertStatus(404)
->assertHeader('Content-Type', 'application/problem+json');
}
}The logging channel that uses the tap, in config/logging.php:
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
'tap' => [App\Logging\RedactSensitiveData::class],
],If you prefer a package for the headers, the secure-headers package (bepsvpt/secure-headers) replaces the custom SecurityHeaders middleware:
// composer require bepsvpt/secure-headers
// php artisan vendor:publish --provider="Bepsvpt\SecureHeaders\SecureHeadersServiceProvider"
->withMiddleware(function (Middleware $middleware): void {
$middleware->append(\Bepsvpt\SecureHeaders\SecureHeadersMiddleware::class);
})The Laravel angle
- Laravel middleware in Laravel 11+ is registered in
bootstrap/app.php:$middleware->append()/prepend()for the global stack,$middleware->api(prepend: [...])for theapigroup,$middleware->alias([...])for route middleware with parameters (body.limit:65536). The default global stack (from the docs) isValidatePathEncoding,InvokeDeferredCallbacks,TrustProxies,HandleCors,PreventRequestsDuringMaintenance,ValidatePostSize,TrimStrings,ConvertEmptyStringsToNull;TrustHostsis commented out and worth enabling ($middleware->trustHosts()) to reject forgedHostheaders. - CORS is built in: "Laravel can automatically respond to CORS OPTIONS HTTP requests with values that you configure" through
HandleCors; the defaults are permissive until you publish and editconfig/cors.php. - APP_DEBUG decides whether exception responses include the exception class, file, line and trace (not verified in the saved docs beyond "how much information about an error is actually displayed to the user");
php artisan config:cachefreezes it, so a wrong value survives until the next cache rebuild. - Errors: Laravel picks HTML or JSON "based on the Accept header of the request";
shouldRenderJsonWhenforces JSON forapi/*. Therendercallback inbootstrap/app.phpis the single place to emit RFC 9457 and keepAllowfromMethodNotAllowedHttpException::getHeaders(). Render callbacks run before the framework's own handling ofAuthenticationExceptionandHttpResponseException(Handler::renderin 13.x callsrenderViaCallbacksfirst), so the callback maps authentication failures to 401 itself and returnsnullforHttpResponseException; without that arm every unauthenticated call would become a 500. - Validation:
$request->validated()drops unknown keys silently; dropping is safe for mass assignment but hides client bugs and probing, so theafter()hook reports them as 422. - Logging:
Context::add()for ids that should be on every log line and in queued jobs,Context::addHidden()for values that must travel with jobs but never be logged; Monolog processors via a channeltapfor redaction. - Edge and PHP: Laravel runs behind Nginx (or Caddy, or FrankenPHP/Octane); body size, header timeouts and
server_tokenslive there, andexpose_php = Offbelongs inphp.ini.composer auditin CI; Enlightn or Larastan for static checks.
At the edge: gateway configuration
The same controls, one layer earlier. Values match the application so a request rejected at the edge would also be rejected by the app.
Nginx in front of Laravel (PHP-FPM) or the Go service:
server {
listen 443 ssl;
server_name api.example.com;
server_tokens off; # "Server: nginx" without the version
autoindex off; # no directory listings
client_header_timeout 10s; # slowloris: 408 after 10s without full headers
client_body_timeout 10s; # between two body reads
client_max_body_size 64k; # 413 above 64 KiB on JSON routes
keepalive_timeout 60s;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Content-Security-Policy "default-src 'none'; frame-ancestors 'none'" always;
add_header Referrer-Policy "no-referrer" always;
add_header Cache-Control "no-store" always;
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always;
location /v1/ {
limit_except GET POST OPTIONS { deny all; } # GET implies HEAD; OPTIONS for CORS preflights; others 403
proxy_hide_header X-Powered-By; # Server is already hidden from the upstream
proxy_set_header X-Request-ID $request_id;
proxy_pass http://orders;
}
location /internal/ {
allow 10.0.0.0/8; # private API: safe-listed IPs only
deny all;
proxy_pass http://orders;
}
}Remember the add_header inheritance rule: a location that declares its own add_header loses all of the server-level ones (Nginx 1.29.3 added add_header_inherit to change that).
Kong (declarative config, open-source plugins; the schemas are in the saved schema.lua files):
_format_version: "3.0"
services:
- name: orders
url: http://orders:8080
routes:
- name: orders-v1
paths: ["/v1"]
methods: ["GET", "HEAD", "POST", "OPTIONS"]
plugins:
- name: request-size-limiting
config:
allowed_payload_size: 64
size_unit: kilobytes
require_content_length: false
- name: response-transformer
config:
remove:
headers: ["Server", "X-Powered-By"]
add:
headers:
- "X-Content-Type-Options:nosniff"
- "Cache-Control:no-store"
- "Content-Security-Policy:default-src 'none'; frame-ancestors 'none'"
- name: cors
config:
origins: ["https://shop.example"] # empty would allow all origins
methods: ["GET", "POST"]
headers: ["Content-Type", "Authorization", "X-Request-ID"]
credentials: true
max_age: 600Envoy (HTTP connection manager excerpt):
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress_http
server_header_transformation: PASS_THROUGH # default OVERWRITE sends "server: envoy"
request_headers_timeout: 5s # disabled by default
request_timeout: 15s
stream_idle_timeout: 30s # default 5 minutes
http_filters:
- name: envoy.filters.http.buffer
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer
max_request_bytes: 65536 # 413 above this
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
route_config:
response_headers_to_add:
- header: { key: X-Content-Type-Options, value: nosniff }
- header: { key: Cache-Control, value: no-store }
response_headers_to_remove: ["x-powered-by"]APISIX (route with JSON Schema validation at the edge):
{
"uri": "/v1/orders",
"methods": ["POST"],
"plugins": {
"client-control": { "max_body_size": 65536 },
"request-validation": {
"header_schema": {
"type": "object",
"required": ["Content-Type"],
"properties": { "Content-Type": { "type": "string", "pattern": "^application/json" } }
},
"body_schema": {
"type": "object",
"additionalProperties": false,
"required": ["sku", "quantity", "currency"],
"properties": {
"sku": { "type": "string", "pattern": "^[A-Z0-9-]{3,32}$" },
"quantity": { "type": "integer", "minimum": 1, "maximum": 100 },
"currency": { "type": "string", "enum": ["EUR", "USD"] }
}
},
"rejected_code": 400
},
"response-rewrite": {
"headers": {
"set": { "X-Content-Type-Options": "nosniff", "Cache-Control": "no-store" },
"remove": ["Server", "X-Powered-By"]
}
}
},
"upstream": { "type": "roundrobin", "nodes": { "orders:8080": 1 } }
}These blocks are written from the directive documentation and the plugin schemas saved with this chapter (Nginx core, headers and proxy modules; Kong schema.lua files; Envoy http_connection_manager.proto, buffer.proto and route.proto; APISIX client-control, request-validation and response-rewrite pages). They were not run against a live gateway (no Docker in this build) and were not validated by nginx -t, deck validate, envoy --mode validate or the APISIX Admin API; treat them as expected, not run.
Solving the classic problems
Pentest finding: "Server and X-Powered-By disclose versions"
The report lists Server: nginx/1.18.0 and X-Powered-By: PHP/8.1.2 on every response, plus the Nginx version on its 404 page.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Edge | server_tokens off, proxy_hide_header X-Powered-By | One change for every app behind it | Server: nginx remains; internal traffic not covered |
| PHP | expose_php = Off | Removes the header at the source | Needs an image rebuild |
| Application | SecurityHeaders strips at write time | Also covers upstreams the app proxies | Must sit outside the handlers |
| CI check | curl -sI in the audit script; fail on a digit in Server | Regressions are caught | Only for the URLs the script knows |
Pentest finding: "Stack trace and connection string in a 500"
A malformed request to /api/v1/orders returned the Ignition or whoops page (or Go's panic text) with the database host and user. Fix in this order: APP_DEBUG=false and the boot guard (Laravel) or Config.Validate (Go); the RFC 9457 renderer that never includes getMessage() in production; a Recover middleware outermost; then rotate the leaked credential, because it was public for as long as the page was. Add the curl check "500 without stack trace or internal address".
Incident: "A 10 MB JSON body took the pods down"
A client bug (or an attacker) posted a huge JSON array to an endpoint that called io.ReadAll then json.Unmarshal. Memory went to 3x the body size and the pods were OOM-killed.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Gateway limit | Nginx client_max_body_size 64k, Kong request-size-limiting | Never reaches the app | Must be per route; HTML error from Nginx |
LimitBody | Content-Length fast path + MaxBytesReader | Catches chunked and lying clients; 413 problem | Per route sizing |
| Depth limit | checkDepth before decoding | Stops nesting bombs that are small in bytes | One extra token pass |
| Streaming decode | json.Decoder over the limited body for arrays | Constant memory for large lists | More code |
Incident: "Thousands of idle connections, the Go service stops accepting"
ss -tn shows thousands of ESTABLISHED connections from a few IPs that sent partial headers. The service used http.ListenAndServe(":8080", mux), which has no timeouts. Fix: harden.NewServer with ReadHeaderTimeout (proved by TestSlowlorisHeaderTimeout), IdleTimeout, and the gateway's header timeout in front; gosec G112/G114 in CI so it does not come back.
Finding: "Bearer tokens in access logs"
A partner integration sent ?access_token= and the Nginx and app logs stored it for 90 days. Fix: reject or strip credentials in query strings at the gateway; log r.URL.Path only and redact by key in the logger; change the partner to Authorization: Bearer; then treat the stored tokens as leaked: revoke them and purge the log indices (backups too).
Finding: "CORS reflects any Origin with credentials"
Access-Control-Allow-Origin echoed the request's Origin and Access-Control-Allow-Credentials: true was set, so any website could read /v1/me for a logged-in user.
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Exact allow-list | CORSOptions.Origins, Laravel allowed_origins | No foreign origin is ever granted | Each new frontend needs a config change |
| No credentials | Token in Authorization from the SPA, no cookies | CORS mistakes no longer expose sessions | Token storage moves to the SPA |
| Same origin | Serve the SPA and API under one origin via the gateway | No CORS at all | Routing work at the edge |
Finding: "TRACE and PUT enabled on a read-only API"
The scanner found that TRACE echoed the request (including Authorization) and PUT /v1/orders/42 returned 200. Fix: AllowMethods globally, method patterns per route, limit_except at Nginx, and a test that asserts 405 with Allow for each unused verb.
Testing and CI gates
A GitHub Actions job that turns the CI & CD group into failing checks (versions are the ones current when this was written; pin your own):
name: security
on: [pull_request]
jobs:
go:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with: { fetch-depth: 0 }
- uses: actions/setup-go@v5
with: { go-version: "1.27" }
- run: test -z "$(gofmt -l .)" && go vet ./... && go test -race -count=1 ./...
- run: go run golang.org/x/vuln/cmd/govulncheck@latest ./... # SCA, fails on reachable vulns
- run: go run github.com/securego/gosec/v2/cmd/gosec@latest ./... # SAST (G112, G114, ...)
- uses: gitleaks/gitleaks-action@v2 # secrets scanning
env: { GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" }
php:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: composer install --no-interaction --prefer-dist
- run: composer audit --locked --abandoned=fail # exit 1 on advisories
- run: php artisan test
dast:
needs: [go]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: bash docs/snippets/system-design/api-security-hardening-checklist/go/audit/audit.sh https://staging.example.com
- run: docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.comBranch protection completes the code review rules: require the security checks, require one approval from a CODEOWNER, dismiss stale approvals on new commits, and do not allow the author (or admins) to bypass. The workflow above is expected, not run here (no CI runner in this build).
Choosing
| Situation | Primary control | Extra technique | Reason |
|---|---|---|---|
| Any public JSON API | Go chain or Laravel middleware from this chapter | Same rules at the gateway | Defence in depth; the app is the last layer that sees every caller |
| Many services, one team per service | Gateway for size, timeouts, headers, rate limits | Shared middleware library per language | Uniform edge, service keeps business validation |
| Partner or public API with a contract | OpenAPI document, schema-first | Validation at the edge (APISIX, Kong Enterprise) + DTO validation in code | Rejected before it costs anything; docs and code cannot drift |
| Browser SPA on another origin | Exact CORS allow-list | Credentials only if cookies are needed; Vary: Origin | CORS is a read grant to named sites |
| Server-to-server only | No CORS headers at all | mTLS or signed requests | No browser, no CORS; identity matters more |
| Large uploads | Presigned URLs to object storage | Size and type limits on the presign | Keeps big bodies away from the API |
| Long reports or exports | 202 + job + status URL | Idempotency key | No handler runs for minutes |
| Behind a TLS-terminating proxy | HSTS from the edge or with TrustForwardedProto | trustProxies(at: ...) | r.TLS is nil behind a proxy |
| Logs with PII | Redaction at the logger | Hash user ids, short retention | Logs are copied everywhere |
| Any repository | govulncheck / composer audit + gitleaks in CI | Renovate or Dependabot | Known CVEs and leaked keys are the cheapest attacks |
| Releases with schema changes | Expand-and-contract migrations | Blue-green or canary, feature flags | A rollback must be possible |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One middleware chain covers every route. Example: a Laravel monolith behind one Nginx: SecurityHeaders and AssignRequestId prepended to the global stack, EnforceJsonApi in the api group, config/cors.php with the SPA's origin, APP_DEBUG=false guarded at boot, Nginx with client_max_body_size, server_tokens off and header timeouts. The audit script runs against staging on every deploy. The only hard part is the routes that need exceptions (an upload route with a larger limit), which get route middleware with parameters rather than a weaker global rule.
Modular monolith: boundaries without the network
Modules share the HTTP edge, so the chain is still one, but each module owns its DTOs and validation. Example: Orders and Billing modules in one Go binary register their routes on the same ServeMux through app.New; a module may not bypass Chain by registering on http.DefaultServeMux (a lint rule or a test over the mux patterns enforces it). Response DTOs live in the module, so Billing cannot leak card fields through an Orders endpoint that embeds an invoice.
Microservices: every arrow is a decision
The gateway enforces the uniform edge (TLS, HSTS, size, header timeouts, rate limits, CORS for the SPA, fingerprint stripping) and generates X-Request-ID; every service still runs its own chain because internal callers do not pass the gateway. Example flow: browser → Kong (request-size-limiting 64 KB, cors, response-transformer) → orders (Go chain with RequestID(trustIncoming: true) so the gateway's id is kept; validation; problem details) → payments over mTLS with the same X-Request-ID → logs from all three land in one index and are joined by the id. Each service exports its route list; CI diffs the union against the gateway routes and the OpenAPI documents (API inventory). Gateway placement is in API gateway, BFF and service mesh; service identity in Mutual TLS.
Distributed data: replicas, caches, regions
Hardening headers interact with every cache on the path. Cache-Control: no-store must reach the CDN and shared proxies for personal responses, or the first user's /v1/me is served to the next; public, non-personal endpoints can opt in to caching explicitly (public, max-age=60) and must then carry Vary for every header that changes the response (Origin for CORS). Problem details and request ids must survive the CDN (some CDNs replace 5xx bodies with their own HTML; configure them to pass through origin errors). Logs from several regions need one time base (UTC, RFC 3339) and one id format to be joinable; redaction must happen before logs cross a region boundary that has different data-residency rules.
Scaling path: 1x, 10x, 100x
| Scale | What changes |
|---|---|
| 1x (one app, one team) | The middleware chain or Laravel middleware, Nginx limits, CI with govulncheck/composer audit/gitleaks, the curl audit on staging |
| 10x (several services and teams) | Gateway (Kong, Envoy, APISIX) owns the edge controls; a shared hardening library per language; central logging with alert rules; OpenAPI per service with CI diff (inventory); ZAP baseline in staging |
| 100x (platform, many regions) | Schema-first contracts validated at the edge; policy-as-code for gateway config; WAF and IDS/IPS managed centrally; per-region log pipelines with redaction at the source; security champions and CODEOWNERS for the hardening library; canary releases with security metrics as rollback triggers |
Lab
Steps 1 to 5 were run on this machine (macOS, Go 1.27.4, /bin/bash 3.2.57, curl) on 2026-11-29; the output below is pasted unedited except where marked. Steps 6 to 9 are expected, not run (no Laravel app, no Docker, no scanners installed in this build).
- Format, vet and test the module (real run):
$ cd docs/snippets/system-design/api-security-hardening-checklist/go
$ gofmt -l . && go vet ./...
$ go test -race -count=1 ./...
ok academy/api-security-hardening-checklist/app
ok academy/api-security-hardening-checklist/before
? academy/api-security-hardening-checklist/cmd/apiserver [no test files]
ok academy/api-security-hardening-checklist/harden(timings removed). go test -v counts 50 passing tests and subtests in harden and 18 in app and before.
- Start the hardened server and run the audit script against it (real run; port 18488 chosen to avoid clashes; the binary was built in a scratch directory, shown here as
/tmp/apiserver):
$ go build -o /tmp/apiserver ./cmd/apiserver
$ APP_ENV=production /tmp/apiserver -addr 127.0.0.1:18488 &
$ bash audit/audit.sh http://127.0.0.1:18488
== Output: security headers on GET /v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f
PASS X-Content-Type-Options contains nosniff
PASS X-Frame-Options contains DENY
PASS Content-Security-Policy contains default-src 'none'
PASS Cache-Control contains no-store
PASS Referrer-Policy contains no-referrer
PASS Server absent
PASS X-Powered-By absent
SKIP Strict-Transport-Security (plain HTTP: RFC 6797 forbids HSTS here)
PASS Content-Type is application/json
PASS X-Request-ID present
PASS no sensitive fields in body
== Input: methods, media types, size, schema
PASS TRACE -> 405
PASS 405 carries Allow
PASS POST text/plain -> 415
PASS Accept: application/xml -> 406
PASS 2 MiB body (Content-Length) -> 413
PASS 2 MiB body (chunked) -> 413
PASS JSON nested 100 deep -> 400
PASS unknown field price -> 400
PASS invalid values -> 422
PASS valid order -> 201
== Processing: errors and timeouts
PASS handler panic -> 500
PASS 500 is application/problem+json
PASS 500 without stack trace or internal address
PASS GET /.env -> 404
PASS 404 is application/problem+json
PASS 405 is application/problem+json
PASS 415 is application/problem+json
PASS slow handler cut by the deadline -> 503
== CORS
PASS preflight from allowed origin -> 204
PASS ACAO echoes the allowed origin only
PASS no ACAO for a foreign origin
== Result: 31 passed, 0 failed, 1 skipped
$ echo $?
0The script itself (bash 3.2 compatible, no request ids or timings in its output, so two runs print the same lines):
#!/usr/bin/env bash
# audit.sh - curl audit of an API against the hardening checklist.
# Usage: audit.sh http://127.0.0.1:18488 (exit 1 if any check fails)
# Works with bash 3.2 (macOS) and GNU or BSD tools. Prints no ids or times,
# so two runs against the same server give the same output.
# Environment (defaults fit the Go lab server):
# API_PREFIX=/v1 e.g. /api/v1 for Laravel
# ORDER_ID=<uuid> an order that exists and the caller may read
# AUTH_HEADER= e.g. "Authorization: Bearer <token>" (never logged)
# UNKNOWN_FIELD_CODE=400 Laravel's StoreOrderRequest answers 422
# DEEP_JSON_CODE=400 Go's depth limit; Laravel's validation answers 422
# LAB_ROUTES=1 0 skips the /lab/panic and /lab/slow checks
# ORIGIN=https://shop.example an origin the CORS allow-list contains
set -u
BASE=${1:-http://127.0.0.1:18488}
P=${API_PREFIX:-/v1}
ORDER=$P/orders/${ORDER_ID:-6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f}
UNKNOWN=${UNKNOWN_FIELD_CODE:-400}
DEEP=${DEEP_JSON_CODE:-400}
LAB=${LAB_ROUTES:-1}
ORIGIN=${ORIGIN:-https://shop.example}
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
pass=0 fail=0 skip=0
ok() { pass=$((pass + 1)); printf 'PASS %s\n' "$1"; }
bad() { fail=$((fail + 1)); printf 'FAIL %s (%s)\n' "$1" "$2"; }
skp() { skip=$((skip + 1)); printf 'SKIP %s (%s)\n' "$1" "$2"; }
# req NAME [curl args...]: stores status in $TMP/NAME.code, headers, body.
req() {
n=$1; shift
if [ -n "${AUTH_HEADER:-}" ]; then set -- -H "$AUTH_HEADER" "$@"; fi
curl -s -o "$TMP/$n.body" -D "$TMP/$n.hdr" -w '%{http_code}' "$@" >"$TMP/$n.code" 2>/dev/null
}
code() { cat "$TMP/$1.code"; }
hdr() { tr -d '\r' <"$TMP/$1.hdr" | grep -i "^$2:" | head -1 | cut -d: -f2- | sed 's/^ *//'; }
body_has() { grep -q -- "$2" "$TMP/$1.body"; }
expect_code() { # NAME WANT LABEL
got=$(code "$1")
if [ "$got" = "$2" ]; then ok "$3 -> $2"; else bad "$3 -> $2" "got $got"; fi
}
expect_problem() { # NAME LABEL
ct=$(hdr "$1" Content-Type)
case "$ct" in
application/problem+json*) ok "$2 is application/problem+json" ;;
*) bad "$2 is application/problem+json" "Content-Type: ${ct:-none}" ;;
esac
}
echo "== Output: security headers on GET $ORDER"
req get "$BASE$ORDER"
for pair in "X-Content-Type-Options|nosniff" "X-Frame-Options|DENY" \
"Content-Security-Policy|default-src 'none'" "Cache-Control|no-store" \
"Referrer-Policy|no-referrer"; do
name=${pair%%|*}; want=${pair#*|}; got=$(hdr get "$name")
case "$got" in
*"$want"*) ok "$name contains $want" ;;
*) bad "$name contains $want" "got '${got:-absent}'" ;;
esac
done
for name in Server X-Powered-By; do
got=$(hdr get "$name")
if [ -z "$got" ]; then ok "$name absent"; else bad "$name absent" "got '$got'"; fi
done
case "$BASE" in
https:*) if [ -n "$(hdr get Strict-Transport-Security)" ]; then ok "HSTS present"; else bad "HSTS present" "absent"; fi ;;
*) skp "Strict-Transport-Security" "plain HTTP: RFC 6797 forbids HSTS here" ;;
esac
case "$(hdr get Content-Type)" in
application/json*) ok "Content-Type is application/json" ;;
*) bad "Content-Type is application/json" "got '$(hdr get Content-Type)'" ;;
esac
if [ -n "$(hdr get X-Request-ID)" ]; then ok "X-Request-ID present"; else bad "X-Request-ID present" "absent"; fi
if body_has get card_number; then bad "no sensitive fields in body" "card_number returned"; else ok "no sensitive fields in body"; fi
echo "== Input: methods, media types, size, schema"
req trace -X TRACE "$BASE$ORDER"
expect_code trace 405 "TRACE"
if [ -n "$(hdr trace Allow)" ]; then ok "405 carries Allow"; else bad "405 carries Allow" "no Allow header"; fi
req ctype -X POST -H 'Content-Type: text/plain' --data '{"sku":"MUG-01"}' "$BASE$P/orders"
expect_code ctype 415 "POST text/plain"
req accept -H 'Accept: application/xml' "$BASE$ORDER"
expect_code accept 406 "Accept: application/xml"
head -c 2097152 /dev/zero | tr '\0' 'A' >"$TMP/big.json"
req big -X POST -H 'Content-Type: application/json' --data-binary @"$TMP/big.json" "$BASE$P/orders"
expect_code big 413 "2 MiB body (Content-Length)"
req chunked -X POST -H 'Content-Type: application/json' -H 'Transfer-Encoding: chunked' --data-binary @"$TMP/big.json" "$BASE$P/orders"
expect_code chunked 413 "2 MiB body (chunked)"
deep=$(printf '%0.s[' $(seq 1 100))$(printf '%0.s]' $(seq 1 100))
req deep -X POST -H 'Content-Type: application/json' --data "$deep" "$BASE$P/orders"
expect_code deep "$DEEP" "JSON nested 100 deep"
req unknown -X POST -H 'Content-Type: application/json' --data '{"sku":"MUG-01","quantity":1,"currency":"EUR","price":0}' "$BASE$P/orders"
expect_code unknown "$UNKNOWN" "unknown field price"
req invalid -X POST -H 'Content-Type: application/json' --data '{"sku":"x","quantity":0,"currency":"BTC"}' "$BASE$P/orders"
expect_code invalid 422 "invalid values"
req created -X POST -H 'Content-Type: application/json' --data '{"sku":"MUG-01","quantity":2,"currency":"EUR"}' "$BASE$P/orders"
expect_code created 201 "valid order"
echo "== Processing: errors and timeouts"
if [ "$LAB" = 1 ]; then
req panic "$BASE$P/lab/panic"
expect_code panic 500 "handler panic"
expect_problem panic "500"
if body_has panic goroutine || body_has panic 10.0.3.7; then bad "500 without stack trace or internal address" "leaked"; else ok "500 without stack trace or internal address"; fi
else
skp "handler panic -> 500" "LAB_ROUTES=0"
fi
req notfound -H 'Accept: application/json' "$BASE/.env"
expect_code notfound 404 "GET /.env"
expect_problem notfound "404"
expect_problem trace "405"
expect_problem ctype "415"
if [ "$LAB" = 1 ]; then
req slow --max-time 4 "$BASE$P/lab/slow"
expect_code slow 503 "slow handler cut by the deadline"
else
skp "slow handler cut by the deadline" "LAB_ROUTES=0"
fi
echo "== CORS"
req pre -X OPTIONS -H "Origin: $ORIGIN" -H 'Access-Control-Request-Method: POST' "$BASE$P/orders"
expect_code pre 204 "preflight from allowed origin"
if [ "$(hdr pre Access-Control-Allow-Origin)" = "$ORIGIN" ]; then ok "ACAO echoes the allowed origin only"; else bad "ACAO echoes the allowed origin only" "got '$(hdr pre Access-Control-Allow-Origin)'"; fi
req evil -X OPTIONS -H 'Origin: https://evil.example' -H 'Access-Control-Request-Method: POST' "$BASE$P/orders"
if [ -z "$(hdr evil Access-Control-Allow-Origin)" ]; then ok "no ACAO for a foreign origin"; else bad "no ACAO for a foreign origin" "got '$(hdr evil Access-Control-Allow-Origin)'"; fi
echo "== Result: $pass passed, $fail failed, $skip skipped"
[ "$fail" -eq 0 ]The script is configurable through environment variables (API_PREFIX, ORDER_ID, AUTH_HEADER, UNKNOWN_FIELD_CODE, DEEP_JSON_CODE, LAB_ROUTES, ORIGIN; the /.env probe sends Accept: application/json so a Laravel app renders its problem JSON; defaults fit the Go server). A second real run against the same Go server with the lab routes switched off and an Authorization header sent (the Go lab API ignores it); only the section headers and SKIP lines are shown, every other line is a PASS as in the default run. The same variables are what adapt it to the Laravel app (step 7, expected, not run):
$ LAB_ROUTES=0 AUTH_HEADER='Authorization: Bearer lab-token' bash audit/audit.sh http://127.0.0.1:18488
== Output: security headers on GET /v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f
SKIP Strict-Transport-Security (plain HTTP: RFC 6797 forbids HSTS here)
== Input: methods, media types, size, schema
== Processing: errors and timeouts
SKIP handler panic -> 500 (LAB_ROUTES=0)
SKIP slow handler cut by the deadline (LAB_ROUTES=0)
== CORS
== Result: 27 passed, 0 failed, 3 skipped
$ echo $?
0- The same script against the "before" server (real run): 29 of 31 checks fail. Each FAIL line is a checklist item.
$ /tmp/apiserver -mode before -addr 127.0.0.1:18489 &
$ bash audit/audit.sh http://127.0.0.1:18489
== Output: security headers on GET /v1/orders/6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f
FAIL X-Content-Type-Options contains nosniff (got 'absent')
FAIL X-Frame-Options contains DENY (got 'absent')
FAIL Content-Security-Policy contains default-src 'none' (got 'absent')
FAIL Cache-Control contains no-store (got 'absent')
FAIL Referrer-Policy contains no-referrer (got 'absent')
FAIL Server absent (got 'orders-api/0.9.1 (go1.22.1; linux)')
FAIL X-Powered-By absent (got 'academy-framework/2.3')
SKIP Strict-Transport-Security (plain HTTP: RFC 6797 forbids HSTS here)
FAIL Content-Type is application/json (got '*/*')
FAIL X-Request-ID present (absent)
FAIL no sensitive fields in body (card_number returned)
== Input: methods, media types, size, schema
FAIL TRACE -> 405 (got 200)
FAIL 405 carries Allow (no Allow header)
FAIL POST text/plain -> 415 (got 200)
FAIL Accept: application/xml -> 406 (got 200)
FAIL 2 MiB body (Content-Length) -> 413 (got 500)
FAIL 2 MiB body (chunked) -> 413 (got 500)
FAIL JSON nested 100 deep -> 400 (got 500)
FAIL unknown field price -> 400 (got 200)
FAIL invalid values -> 422 (got 200)
FAIL valid order -> 201 (got 200)
== Processing: errors and timeouts
PASS handler panic -> 500
FAIL 500 is application/problem+json (Content-Type: text/plain; charset=utf-8)
FAIL 500 without stack trace or internal address (leaked)
FAIL GET /.env -> 404 (got 200)
FAIL 404 is application/problem+json (Content-Type: none)
FAIL 405 is application/problem+json (Content-Type: */*)
FAIL 415 is application/problem+json (Content-Type: text/plain; charset=utf-8)
FAIL slow handler cut by the deadline -> 503 (got 200)
== CORS
FAIL preflight from allowed origin -> 204 (got 500)
FAIL ACAO echoes the allowed origin only (got '')
PASS no ACAO for a foreign origin
== Result: 2 passed, 29 failed, 1 skipped
$ echo $?
1What the "before" server sends for TRACE and for a panic (real run; the panic body is cut after the first frames and the home directory in file paths is replaced by …):
$ curl -si -X TRACE http://127.0.0.1:18489/v1/orders/42
HTTP/1.1 200 OK
Content-Type: */*
Server: orders-api/0.9.1 (go1.22.1; linux)
X-Powered-By: academy-framework/2.3
Date: Sun, 29 Nov 2026 09:29:02 GMT
Content-Length: 91
{"id":"42","sku":"MUG-01","quantity":2,"card_number":"4111111111111111","risk_score":0.12}
$ curl -s http://127.0.0.1:18489/v1/lab/panic | head -6
panic: db: connection refused at 10.0.3.7:5432 user=orders_rw
goroutine 70 [running]:
runtime/debug.Stack()
/opt/homebrew/Cellar/go/1.27.4/libexec/src/runtime/debug/stack.go:26 +0x64
academy/api-security-hardening-checklist/before.New.func1.1()- The hardened server's answers to the same requests (real run,
curl -si; request ids differ per run):
$ curl -si http://127.0.0.1:18488/v1/lab/panic
HTTP/1.1 500 Internal Server Error
Cache-Control: no-store
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
Content-Type: application/problem+json
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Request-Id: 647202a4b7fd59f1cd5f3315
Date: Sun, 29 Nov 2026 09:29:12 GMT
Content-Length: 134
{"type":"about:blank","title":"Internal Server Error","status":500,"detail":"internal error","request_id":"647202a4b7fd59f1cd5f3315"}
$ head -c 100000 /dev/zero | tr '\0' 'A' > 100k.json # a 100,000-byte body, above the 64 KiB limit
$ curl -si -X POST -H "Content-Type: application/json" --data-binary @100k.json http://127.0.0.1:18488/v1/orders
HTTP/1.1 413 Request Entity Too Large
Cache-Control: no-store
Connection: close
Content-Security-Policy: default-src 'none'; frame-ancestors 'none'
Content-Type: application/problem+json
Permissions-Policy: camera=(), microphone=(), geolocation=(), payment=()
Referrer-Policy: no-referrer
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-Request-Id: ea0cd1f3b6fe09d1e0b2dff0
Date: Sun, 29 Nov 2026 09:29:12 GMT
Content-Length: 138
{"type":"about:blank","title":"Content Too Large","status":413,"detail":"request body too large","request_id":"ea0cd1f3b6fe09d1e0b2dff0"}Note the status line 413 Request Entity Too Large (Go's http.StatusText) next to the problem title Content Too Large (RFC 9110), and Connection: close. The panic's stack trace went to the server's stderr as one JSON line with the same request_id.
- The debug-off guard (real run):
$ APP_ENV=production APP_DEBUG=true /tmp/apiserver -addr 127.0.0.1:18490
2026/11/29 12:59:12 unsafe production configuration: debug mode is on
$ echo $?
1- Expected, not run: dependency and code scanning on the Go module.
$ go run golang.org/x/vuln/cmd/govulncheck@latest ./...
No vulnerabilities found.
$ go run github.com/securego/gosec/v2/cmd/gosec@latest ./...govulncheck reports per Go toolchain and module versions; a stdlib advisory fixed after Go 1.27.4 would show up here with the call path. gosec is expected to flag the "before" branch of cmd/apiserver/main.go (an http.Server without ReadHeaderTimeout) as G112; the exact output depends on the gosec version, so none is pasted.
- Expected, not run (a Laravel 13 app with the PHP files of this chapter,
php artisan config:publish corsdone, Sanctum installed):
$ php artisan test --filter=ApiHardeningTest
PASS Tests\Feature\ApiHardeningTest
✓ every api response has the output headers
✓ wrong verb is 405 with allow
✓ non json body is 415
✓ accept without json is 406
✓ unknown fields and bad values are 422
✓ response never contains the card number
✓ cors preflight carries the security headers
✓ server errors do not leak traces
✓ unknown route is a problem 404
Tests: 9 passed
$ composer audit --locked
No security vulnerability advisories found.
$ API_PREFIX=/api/v1 ORDER_ID=<uuid of a seeded order> AUTH_HEADER='Authorization: Bearer <sanctum token>' \
UNKNOWN_FIELD_CODE=422 DEEP_JSON_CODE=422 LAB_ROUTES=0 bash audit.sh https://app.testExpected, not run: secrets scanning.
gitleaks git -von the repository prints each finding with file, line and rule; add a fake key such asAKIA+ 16 characters to a test file and it is reported;gitleaks git --redactkeeps the secret out of CI logs.Expected, not run: DAST in staging.
docker run -t ghcr.io/zaproxy/zaproxy:stable zap-baseline.py -t https://staging.example.comexits 0, 1 (FAIL), 2 (WARN only) or 3 (other failure) per the ZAP docs; with the headers in place the header-related rules move from WARN to PASS.
Further experiments: set ReadHeaderTimeout to zero in server_test.go and watch TestSlowlorisHeaderTimeout fail after 3 seconds; replace innermost(w) with w in bodylimit.go and watch TestLimitClosesConnectionThroughWrappers fail (both mutations were tried during the build and failed as expected); move SecurityHeaders below AllowMethods in app.go and watch the TRACE case of TestEveryResponseIsHardened lose its headers (that one was not tried).
Common misconceptions
| Belief | Reality |
|---|---|
| Security headers do nothing for a JSON API | They do nothing for curl; they matter as soon as a browser touches the API, and they cost nothing (OWASP REST lists them for "all API responses that may be consumed by browser clients") |
Checking Content-Length limits the body | Chunked requests have no length; only MaxBytesReader (or a gateway buffer limit) is a limit |
| A 405 is just a status code | RFC 9110: a 405 MUST carry Allow; without a global method allow-list, unknown verbs reach handlers |
Every request needs a Content-Type | Only requests with a body; OWASP: "Do not require Content-Type solely for requests without a body" |
WriteTimeout stops slow handlers | It closes the connection; the handler keeps running. Use http.TimeoutHandler or a context deadline |
http.TimeoutHandler returns 504 | It returns 503 Service Unavailable (current net/http source); the 504 in older blog posts is outdated |
| Go answers a slowloris client with 408 | Go closes the connection silently on a header-read timeout; Nginx answers 408 |
| HSTS belongs on every response | RFC 6797: it MUST NOT be sent over plain HTTP; send it over TLS (or from the TLS-terminating edge) |
| CORS protects the API | CORS tells browsers which sites may read responses; non-browser clients ignore it. It is a grant, not a guard |
Access-Control-Allow-Origin: * with credentials works | Browsers refuse it; developers then reflect Origin, which is worse. List exact origins |
Removing Server hides the stack | It removes the cheapest signal only; OWASP: attackers "have other means of fingerprinting" |
| Debug mode is fine for a quick look in production | One scanner pass is enough to harvest the page; Laravel warns it can expose "sensitive configuration values" |
| Logging the full request helps incident response | It copies tokens and PII into every log store; log ids and outcomes, redact by key |
| The gateway validates, so services need not | Internal callers bypass the gateway; only the service knows its business rules and sensitive fields |
| A scanner in CI means we are secure | SAST, SCA, secrets scanning and DAST each see one slice; none sees missing authorization; findings must fail the build |
Cheat sheet
| Topic | Remember |
|---|---|
| Order of the chain | Request id → access log → headers → problem rewrite → recover → CORS → method allow-list → JSON only → body limit → handler timeout → router |
| Methods | Global allow-list + per-route patterns; 405 with Allow; reject method-override headers |
| Media types | Body present → must be application/json (415 + Accept); Accept without JSON → 406; never copy Accept into Content-Type |
| Body size | Content-Length fast path + http.MaxBytesReader with net/http's own writer; 413; gateway limit outside |
| JSON | Depth limit before decode, DisallowUnknownFields, single value, then field rules (422) |
| Headers | nosniff, DENY, default-src 'none'; frame-ancestors 'none', no-store, no-referrer, HSTS on TLS only |
| Fingerprints | Strip Server, X-Powered-By at write time; server_tokens off; expose_php = Off |
| Errors | RFC 9457 application/problem+json, request id, no stack traces; 4xx for client faults, 5xx for ours |
| Responses | Output DTO / JsonResource; never serialise the storage model |
| Debug | Production with debug on must not start (Config.Validate, AppServiceProvider) |
| Timeouts | ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, TimeoutHandler (503); zero header/idle values fall back to ReadTimeout, zero read/write means none; set all four |
| CORS | Exact origins, Vary: Origin, credentials only with explicit origins, 403 for foreign preflights |
| Logs | One JSON line per request, path without query, redaction by key, request id in every line and response header |
| CI | govulncheck, composer audit --locked, gosec/semgrep, gitleaks, ZAP baseline + audit.sh on staging, CODEOWNERS review |
| Releases | Rollback plan before deploy: blue-green or canary, feature flags, expand-and-contract migrations |
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 — Why does LimitBody pass innermost(w) to http.MaxBytesReader instead of w? Important
Answer
Answer: MaxBytesReader tells the server to close the connection after the limit is hit by calling an unexported method on net/http's own response type. A wrapper (stripWriter, statusWriter) does not have that method, so the hint is silently lost and the server may keep draining the attacker's body. Every wrapper in the chain implements Unwrap(), and innermost walks down to the real writer; TestLimitClosesConnectionThroughWrappers fails if you pass w. See Request body size limit.
2 — A GET without a Content-Type header: 415 or not? And a chunked POST without one? Must-know
Answer
Answer: The GET passes: it has no body, and OWASP says "Do not require Content-Type solely for requests without a body." The chunked POST has a body of unknown length (ContentLength == -1 in Go), so it must declare application/json; without it the answer is 415 with an Accept: application/json response header. See Content-Type and Accept validation.
3 — What must a 405 response contain, and what are the two layers that produce it here? Must-know
Answer
Answer: RFC 9110 says the origin server MUST send an Allow header listing the supported methods. In the Go chain, AllowMethods rejects methods outside the global allow-list (TRACE, CONNECT, made-up verbs), and ServeMux method patterns reject a known path with the wrong method (for example POST on GET /v1/orders/{id}); ProblemErrors turns the mux's plain-text 405 into problem JSON while keeping Allow. See HTTP method allow-list.
4 — Why is HSTS not sent by the lab server, and how do you send it behind a TLS-terminating load balancer? Important
Answer
Answer: RFC 6797 7.2: "An HSTS Host MUST NOT include the STS header field in HTTP responses conveyed over non-secure transport." The lab runs plain HTTP on localhost, so the audit script reports HSTS as SKIP. Behind a load balancer r.TLS is nil; either set HSTS at the edge, or enable TrustForwardedProto (Go) / trustProxies(at: ...) and $request->isSecure() (Laravel) so X-Forwarded-Proto: https from the trusted proxy counts. See Security headers.
5 — Which http.Server field stops slowloris, what does Go send when it fires, and how does that differ from Nginx? Must-know
Answer
Answer: ReadHeaderTimeout. When the headers do not arrive in time, Go closes the connection without writing a response (a "common net read error": "don't reply"); the test reads EOF with zero bytes. Nginx's client_header_timeout (default 60s) answers 408 Request Timeout. With all http.Server timeouts at zero, a few thousand slow clients can hold every connection. See Timeouts.
6 — What status does http.TimeoutHandler send, and why is WriteTimeout not a substitute? Important
Answer
Answer: 503 Service Unavailable (current net/http source; older articles say 504), and it cancels the request context so a well-behaved handler stops. WriteTimeout only closes the connection when its deadline passes: the client gets a reset instead of a status, and the handler keeps running and holding resources. Use both: the handler deadline for the work, the server timeout for the socket. See Timeouts.
7 — Your API returns {"error": "pq: password authentication failed for user orders_rw"} with status 200. List what is wrong. Must-know
Answer
Answer: Wrong status (200 for a failure; it should be 500, and the client cannot tell success from failure), internal detail (driver name, database user) in the body, no problem-details shape, probably no request id to correlate with the log. Fix: catch at the outermost layer, log the error with the request id, return application/problem+json with status 500, a generic detail and the request_id; RFC 9457 warns against exposing implementation details. See Error responses.
8 — Why can a JSON body of 20 KB still be dangerous, and which check catches it? Important
Answer
Answer: Twenty kilobytes of [ characters is ten thousand levels of nesting; recursive parsers and later processing (validation, logging, re-serialisation) can blow the stack or the CPU, and the size limit does not notice. OWASP: "configure parser limits such as maximum nesting depth". checkDepth scans tokens once and rejects deeper than MaxJSONDepth (16) with 400 before decoding; Go's own internal limit is 10000. See Input validation.
9 — The browser SPA needs cookies on cross-origin API calls. What exact CORS response does the preflight need, and what must never be in it? Must-know
Answer
Answer: Access-Control-Allow-Origin with the one exact origin (after an allow-list check), Access-Control-Allow-Credentials: true, the allowed methods and headers, a Max-Age, and Vary: Origin. Never * with credentials (MDN: the server "must specify an origin ... instead of specifying the * wildcard"), and never a reflected Origin without the check, which grants every website access to the user's data. See CORS.
10 — What should never appear in an access log line, and how do the Go and Laravel examples enforce it? Must-know
Answer
Answer: Tokens, API keys, session ids, passwords, card data, connection strings and personal data such as emails (OWASP Logging Cheat Sheet "Data to exclude"). Go: AccessLog logs r.URL.Path (no query string) and no headers, and NewLogger's ReplaceAttr turns sensitive keys into [REDACTED] wherever they appear. Laravel: the RedactSensitiveData tap adds a Monolog processor that masks the same keys in context and extra. See Logging.
11 — Name the four kinds of CI security checks in this chapter and one tool for each. Important
Answer
Answer: SCA / dependency scanning: govulncheck (reachability-aware) and composer audit (exit 1 on findings). SAST: gosec (G112 for missing ReadHeaderTimeout), semgrep, PHPStan. Secrets scanning: gitleaks (gitleaks git). DAST: OWASP ZAP baseline and this chapter's audit.sh against staging. Plus code review rules: CODEOWNERS approval, no self-approval. See CI/CD gates.
12 — Why is a UUID in the URL not a fix for "Avoid user's personal ID in the resource URLs"? Good to know
Answer
Answer: An unguessable id makes enumeration harder, but ids leak (logs, shared links, other API responses), and once known, a missing object-level authorization check still hands the object to anyone. The control is the ownership check on every request (BOLA, API1:2023), taught in OWASP API Security Top 10; the UUID is a second layer. See Processing items owned elsewhere.
13 — Where do X-Frame-Options: DENY and frame-ancestors 'none' overlap, and why does this chapter send both? Good to know
Answer
Answer: Both forbid framing. OWASP calls X-Frame-Options a "Legacy header superseded by Content-Security-Policy: frame-ancestors 'none'" that is "Still recommended for compatibility with older browsers that do not support CSP Level 2", and the roadmap checklist asks for X-Frame-Options: deny explicitly. Sending both costs a few bytes and satisfies scanners and old clients. See Security headers.
Glossary
| Term | Meaning |
|---|---|
| API security checklist | A list of cross-cutting controls every API endpoint should have; here the roadmap.sh "API Security Best Practices" list (50 items, 9 groups) |
| Hardening | Changing defaults so that only the intended behaviour is possible |
| Allow-list validation | Accepting only values that match positive rules (type, length, range, format, field names); everything else is rejected |
| Denylist | Rejecting known-bad values; brittle, avoided here |
| Schema-first | Writing the contract (OpenAPI, JSON Schema) before the code, and validating against it at the edge and in code |
| OpenAPI | Machine-readable description of an HTTP API (paths, methods, parameters, schemas) |
| OpenAPI validation at the edge | A gateway validating requests against the OpenAPI document before forwarding |
| JSON depth and schema validation | Limiting nesting depth and checking structure (fields, types, additionalProperties: false) of JSON input |
| HTTP method allow-list | The set of methods an API or route accepts; others get 405 |
| 405 Method Not Allowed | Method known but not supported by the resource; must carry Allow |
Allow header | Lists the methods a resource supports; required in a 405 |
| Method override | X-HTTP-Method-Override and similar headers that let a request claim another method; rejected here |
| Content-Type validation | Requiring a request body to declare a supported media type |
| 415 Unsupported Media Type | The request content's format is not supported |
| Accept validation | Checking that the client accepts a media type the API produces |
| 406 Not Acceptable | No acceptable representation per the Accept header |
| Request body size limit | Maximum number of body bytes a route reads |
| 413 Content Too Large | RFC 9110 name for "body too large" (formerly Payload Too Large / Request Entity Too Large) |
| MaxBytesReader | net/http reader that caps a request body and returns *http.MaxBytesError |
| 431 Request Header Fields Too Large | Headers above MaxHeaderBytes |
| Authorization header | Standard request header for credentials (Bearer tokens, other schemes) |
| Security headers | Response headers that switch on browser protections |
| X-Content-Type-Options nosniff | Tells browsers to trust the declared Content-Type and never sniff |
| X-Frame-Options | Legacy framing control (DENY); superseded by frame-ancestors |
| Content-Security-Policy | Browser policy for loadable resources; default-src 'none' blocks everything for API responses |
frame-ancestors | CSP directive controlling who may frame the response |
| Strict-Transport-Security (HSTS) | Tells browsers to use HTTPS only for max-age seconds; only over TLS |
| Referrer-Policy | Controls what URL is sent in Referer; no-referrer for APIs |
| Cache-Control no-store | Directive forbidding caches from storing the response |
| Permissions-Policy | Disables browser features (camera, geolocation) for the response |
| Fingerprinting | Identifying software and versions from responses |
| Server / X-Powered-By | Response headers that often reveal the web server and language versions |
| Problem Details (RFC 9457) | Standard JSON error format application/problem+json with type, title, status, detail, instance |
| Extension member | Extra field in a problem object (request_id, errors) |
| Correct status codes | Using the semantically right code (4xx client, 5xx server), never 200 for failures |
| Stack trace | The call stack at an error; logged server-side, never returned |
| Output DTO | A type that lists exactly which fields leave the API (Go view struct, Laravel JsonResource) |
| Debug mode | Verbose error output and developer tooling; APP_DEBUG in Laravel |
| Debug-off guard | Startup check that refuses to run production with debug on |
APP_DEBUG | Laravel environment variable feeding config('app.debug') |
| Timeouts | Deadlines per connection phase: read header, read, write, idle, handler |
ReadHeaderTimeout | Go limit for receiving request headers; slowloris defence |
IdleTimeout | Go limit for waiting on the next keep-alive request |
| Slowloris | Attack that holds connections by sending headers very slowly |
http.TimeoutHandler | Go wrapper that answers 503 and cancels the context after a deadline |
| CORS | Cross-Origin Resource Sharing: headers that tell browsers which origins may read responses |
| Preflight | Browser OPTIONS request asking permission for a non-simple cross-origin request |
| Credentials (CORS) | Cookies or HTTP auth on cross-origin requests; requires an exact origin and Access-Control-Allow-Credentials: true |
Vary: Origin | Tells caches the response depends on the Origin header |
| Request id | Identifier of one request, returned in X-Request-ID and logged on every line |
| Correlation id | Identifier that follows one user action across services (often the same value as the request id) |
| Redaction | Masking sensitive values before they are logged |
| PII in logs | Personal data (emails, names, ids) written to logs; minimised and masked |
| Centralised logging | Shipping logs from all services to one searchable store |
| Alerting | Rules on logs or metrics that notify a human (Slack, PagerDuty, SMS) |
| IDS/IPS | Intrusion detection / prevention systems that inspect traffic for attack signatures |
| WAF | Web application firewall filtering HTTP requests by rules (e.g. OWASP Core Rule Set) |
| API gateway | Reverse proxy that centralises TLS, auth, limits, routing and header policy (Kong, Envoy, APISIX, Nginx) |
| Kong | Nginx/OpenResty-based API gateway with plugins (request-size-limiting, response-transformer, cors) |
| Envoy | L7 proxy used standalone or in meshes; HTTP connection manager timeouts and header options |
| APISIX | Apache API gateway with plugins (request-validation, client-control, response-rewrite) |
| Nginx | Web server and reverse proxy (client_max_body_size, server_tokens, add_header) |
| Laravel middleware | Classes with handle() registered in bootstrap/app.php (global, groups, aliases) |
| secure-headers package | bepsvpt/secure-headers, a Laravel package that sets security headers from a config file |
| Go middleware chain | func(http.Handler) http.Handler functions composed in a fixed order |
| curl audit script | audit.sh: a deterministic set of curl checks for this checklist, usable as a tiny DAST |
| Dependency scanning (SCA) | Checking dependencies against vulnerability databases |
govulncheck | Go's reachability-aware vulnerability scanner |
composer audit | Composer command that checks installed packages for advisories, abandoned and malware packages |
| SAST | Static application security testing on source code (gosec, semgrep, PHPStan) |
| DAST | Dynamic testing of a running application (OWASP ZAP) |
| Secrets scanning | Finding committed credentials (gitleaks, GitHub secret scanning) |
| Code review rules | Branch protection, required approvals by someone other than the author, CODEOWNERS |
| Rollback strategy | A planned way to undo a release quickly, including data changes |
| Blue-green | Two environments; switch traffic to deploy and back to roll back |
| Feature flags | Runtime switches that enable or disable behaviour without a deploy |
| API inventory | The maintained list of every endpoint, version and host, with owner and protection |
References
- roadmap.sh, API Security Best Practices: https://roadmap.sh/best-practices/api-security; source data used (commit
2571a7c): api-security.json, api-security.md - OWASP Cheat Sheet Series: REST Security, REST Assessment, HTTP Headers, Input Validation, Error Handling, Logging, Transport Layer Security, Content Security Policy, HTML5 Security (CORS)
- OWASP API Security Top 10 2023: list, API8:2023 Security Misconfiguration
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110; RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457; RFC 6797, HTTP Strict Transport Security: https://www.rfc-editor.org/rfc/rfc6797
- MDN: X-Content-Type-Options, X-Frame-Options, Content-Security-Policy, Strict-Transport-Security, Referrer-Policy, Cache-Control, Server, CORS, 405, 406, 413, 415
- Go source and release notes: net/http request.go (MaxBytesReader), net/http server.go (Server timeouts, TimeoutHandler, Error), net/http status.go, net/http responsecontroller.go, encoding/json scanner.go, Go 1.19, Go 1.20, Go 1.21, Go 1.22, Go 1.25
- Go vulnerability management and govulncheck: https://go.dev/doc/security/vuln/, tutorial
- Cloudflare blog, The complete guide to Go net/http timeouts (secondary, written for Go 1.6–1.8): https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/
- Laravel 13: Middleware, Routing (CORS), Configuration (debug mode), Errors, Logging, Context, Validation, Requests, Eloquent API resources, Deployment; framework
config/cors.php: https://github.com/laravel/framework/blob/13.x/config/cors.php - bepsvpt/secure-headers: https://github.com/bepsvpt/secure-headers; spatie/laravel-csp: https://github.com/spatie/laravel-csp
- Kong plugins: Request Size Limiting, Response Transformer, CORS, OAS Validation; schemas: request-size-limiting, response-transformer, cors
- Envoy: HTTP connection manager proto, HTTP header manipulation, Buffer filter proto, Route proto
- Apache APISIX plugins: request-validation, response-rewrite, client-control
- Nginx: ngx_http_core_module, ngx_http_headers_module, ngx_http_proxy_module
- Composer CLI (audit): https://getcomposer.org/doc/03-cli.md; OWASP ZAP baseline scan: https://www.zaproxy.org/docs/docker/baseline-scan/; gitleaks: https://github.com/gitleaks/gitleaks; gosec: https://github.com/securego/gosec and rules