Skip to content

fix(router): fail closed in interceptors, cap bodies early, scope idempotency per principal - #123

Merged
juicycleff merged 9 commits into
mainfrom
fix/router-interceptors
Nov 18, 2026
Merged

juicycleff merged 9 commits into
mainfrom
fix/router-interceptors

Conversation

@juicycleff

Copy link
Copy Markdown
Contributor

Fixes in the router, interceptors and idempotency store, from a security and performance review. Every fix has a regression test.

Fixes

  • IP interceptors (AllowIPs, DenyIPs, RateLimitByIP) compared against RemoteAddr, which is ip:port. DenyIPs never blocked anything and AllowIPs blocked everyone. They now parse the client IP, accept CIDR ranges and handle IPv6.
  • Interceptors failed open when they blocked without an error: Block(nil), Not(x, nil), Or with all branches blocking, and Parallel. They now return 403.
  • The body cap only applied inside route handlers. Global middleware, 404/405 handling and mounted handlers could read unlimited bodies. The router-wide cap now applies before global middleware runs, and routes can still raise or lower it.
  • Idempotency used one LRU for every principal. One user could evict another's stored responses and turn their retry into a double charge. Each principal now has an entry and byte quota, and a principal over quota gets 429 with Retry-After instead of evicting others. There is also a global byte budget.
  • Validation compiled schema regexes on every request. They are compiled once (about 20 µs and 336 allocs down to about 1 µs and 1 alloc).
  • Typed responses were processed twice, deep-copying the response twice with sensitive cleaning on (about 49 µs and 425 allocs down to 13.7 µs and 122). Cleaning also blanked unexported state, so time.Time came out as zero; that is fixed.
  • Bind errors returned raw decoder errors with Go type names, and a too-large body came back as 400. Errors are now mapped: 413 for too large, field-level messages for type errors, a generic message otherwise.

Behaviour changes

  • AllowIPs and DenyIPs panic on an invalid entry and refuse requests whose address can't be parsed.
  • RateLimitByIP keys on the bare IP.
  • Blocked interceptors with no error now return 403.
  • The router-wide body cap now covers global middleware, unmatched paths and mounted handlers. Opt out with WithMaxRequestBodySize(-1) or SetRequestBodyLimit.
  • A principal past its idempotency quota gets 429 for new keys. Opt out with IdempotencyMemoryMaxEntriesPerPrincipal(-1).
  • Bind error messages no longer include raw decoder output.

Testing

go test -race passes for internal/router, internal/idempotency, interceptors, middleware and the root package. golangci-lint --new-from-rev=main is clean.

AllowIPs, DenyIPs and RateLimitByIP compared Request.RemoteAddr verbatim
against the configured addresses. net/http sets RemoteAddr to "ip:port"
with the client's ephemeral port, so DenyIPs never blocked anyone,
AllowIPs blocked everyone and RateLimitByIP gave every connection its own
bucket.

The address is now split from its port with net.SplitHostPort and parsed
with net/netip. IPv4-mapped IPv6 addresses from dual-stack listeners are
unmapped and IPv6 zones dropped, so they compare equal to what an
operator writes. Entries may be single addresses or CIDR ranges, and an
invalid entry panics at construction instead of being silently ignored,
since a skipped typo in a deny list lets the address through. A request
whose address cannot be parsed is refused by both AllowIPs and DenyIPs.
X-Forwarded-For is still ignored on purpose, as in middleware.ClientIP.
The executor returned a blocked result's Error as is, and the route
wrapper treats a nil error as success. Block(err) with an err that
happened to be nil, a hand-built InterceptorResult{Blocked: true},
Not(x, nil), and Or or ParallelAny over such results all let the
request through to the handler. Parallel also tested the first block's
error for nil rather than the block itself, so it turned the same case
into an allow.

Block and BlockWithValues now substitute 403 Forbidden for a nil error,
the executor does the same for results built by hand, and Parallel
tracks whether anything blocked separately from the error it carried.
The MaxBytesReader body cap was installed only in the per-route wrapper.
UseGlobal middleware, the 404 and 405 paths and handlers mounted with
Handle all read the body unbounded, so a global middleware that buffered
the body read 64 MiB from one request even on a path that does not
exist.

Router.ServeHTTP now wraps the body in a re-limitable reader capped at
the router-wide limit before anything else runs. The per-route wrapper
changes that cap in place rather than stacking a second MaxBytesReader,
so WithMaxBodySize can still raise a route's limit as well as lower it,
with bytes already read counting against the new limit. Mounted handlers
have no route options, so SetRequestBodyLimit (also exported from
forge) lets one raise its own cap before reading.

Global middleware runs before the route is known, so one that reads the
whole body is held to the router-wide cap even on a route that raises
its own. WithMaxRequestBodySize(-1) still turns the router cap off.
MemoryStore kept one LRU across every principal, capped at 10000
entries regardless of size. One principal sending fresh keys could push
every other principal's stored responses out, and a victim's retry then
found nothing and ran the handler again, charging twice. The cap also
counted entries, not bytes, so 10000 responses of up to 1 MiB each were
allowed.

Each principal now has a quota of entries (claims plus responses) and of
approximate bytes, by default a tenth of the store-wide caps. A
principal at its quota has new keys refused with a *QuotaError matching
ErrQuotaExceeded instead of evicting anything; its expired responses are
dropped first, at most once per expiry, so it is not stuck. The
middleware answers the refusal with 429 and a Retry-After for when the
principal's soonest response expires, without running the handler.

The store also has a global byte budget (WithMaxBytes, default 256 MiB)
next to the entry cap. Both still evict least recently used, but with
the quota in place reaching them takes many principals, not one.

WithMaxEntriesPerPrincipal and WithMaxBytesPerPrincipal set the quotas,
and a negative value removes one. The forge package exports the new
options as IdempotencyMemory* so they can be passed to
middleware.NewMemoryIdempotencyStore.
SchemaValidator compiled a regular expression on every call: the
schema's pattern in validateString, and the email and uuid format
checks in isValidEmail and isValidUUID. Compiling cost more than the
rest of the validation pass put together.

The email and uuid expressions are now package-level, and schema
patterns are compiled once and cached in a sync.Map keyed by the
pattern. An invalid pattern is cached as nil and still skipped, as
before.

BenchmarkSchemaValidator_Patterns (object with two patterns, an email
and a uuid field), Apple M5 Max:

  before: 15.4-31.9 us/op  31.7 KB/op  336 allocs/op
  after:  0.86-1.28 us/op     24 B/op    1 allocs/op
A typed handler's response went through
shared.ProcessResponseValueWithSensitive in the router and then through
ctx.JSON, which ran the same processing again in go-utils. With
WithSensitiveFieldCleaning the whole response was deep-copied twice, and
a body:"" value that carried header or body tags of its own was
unwrapped a second time.

The router now processes the value once and writes the encoded body
itself, with the same encoder settings and trailing newline ctx.JSON
used. The body is encoded before anything is written, so a value that
cannot be encoded is a 500 instead of a 200 with a broken body. Header
and body tag positions and parsed sensitive tags are cached per type,
and a value whose type holds nothing to clean is passed through without
a copy.

Cleaning also built each struct copy from a zero value and filled in
only the exported fields, so every unexported field was lost and a
time.Time came out as 0001-01-01. A copy now starts from the original
value and then cleans the exported fields, so time.Time and types with
their own MarshalJSON keep their state while tagged fields are still
cleaned. Named string types are now redacted and masked instead of
panicking on the type mismatch.

BenchmarkOpinionatedHandler_SensitiveCleaning, typed handler returning a
100 item list, Apple M5 Max:

  sensitive=false  before: 9.0-14.3 us/op  1.1 KB/op   15 allocs/op
                   after:  7.6-7.7 us/op   1.2 KB/op   16 allocs/op
  sensitive=true   before: 40.5-58.4 us/op 24.5 KB/op 425 allocs/op
                   after:  13.6-13.8 us/op 10.7 KB/op 122 allocs/op

The one extra allocation in both rows is the router-level body limiter
from the previous commit, not this change.
Typed handlers answered every BindRequest failure with
BadRequest("invalid request: " + err). That sent the raw decoder error to
the client, which names Go types and struct fields ("cannot unmarshal
string into Go struct field transferReq.amount of type int"), and turned
a body over the size cap into 400 instead of 413.

Bind errors are now mapped before they reach the client. A body over the
cap is 413 Payload Too Large. A JSON type mismatch names only the JSON
field and the kind of value sent. A syntax error or truncated body is
"malformed JSON". Validation errors keep their message, since each one
names a request field and what is wrong with it. Anything else is a
plain "invalid request".
@vercel

vercel Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
forge Ready Ready Preview Nov 18, 2026 12:54am UTC

Request Review

… uses

The router now processes typed responses itself in internal/router/response.go.
That left CleanSensitiveFields, ResponseProcessor, ProcessResponseValue,
ProcessResponseValueWithSensitive and the sensitive cleaning context key in
internal/shared with no callers anywhere in the repo, still carrying the old
bug that blanked time.Time values. The sensitive tag parsing stays, because
the router uses it.
@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 7 follow conventional format

@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 8 follow conventional format

@github-actions github-actions Bot added fix and removed fix labels Nov 16, 2026
@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 9 follow conventional format

@github-actions github-actions Bot added fix and removed fix labels Nov 18, 2026
@juicycleff
juicycleff merged commit 39f7779 into main Nov 18, 2026
45 checks passed
@juicycleff
juicycleff deleted the fix/router-interceptors branch November 18, 2026 01:31

This branch was successfully deployed

1 active deployment
Preview — 710c3dd9 Deployed Nov 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant