Repository navigation
fix(router): fail closed in interceptors, cap bodies early, scope idempotency per principal - #123
Merged
Merged
Conversation
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".
Contributor
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
… 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.
Contributor
Conventional Commits ValidationPR Title: valid |
Contributor
Conventional Commits ValidationPR Title: valid |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Contributor
Conventional Commits ValidationPR Title: valid |
This branch was successfully deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes in the router, interceptors and idempotency store, from a security and performance review. Every fix has a regression test.
Fixes
AllowIPs,DenyIPs,RateLimitByIP) compared againstRemoteAddr, which isip:port.DenyIPsnever blocked anything andAllowIPsblocked everyone. They now parse the client IP, accept CIDR ranges and handle IPv6.Block(nil),Not(x, nil),Orwith all branches blocking, andParallel. They now return 403.Retry-Afterinstead of evicting others. There is also a global byte budget.time.Timecame out as zero; that is fixed.Behaviour changes
AllowIPsandDenyIPspanic on an invalid entry and refuse requests whose address can't be parsed.RateLimitByIPkeys on the bare IP.WithMaxRequestBodySize(-1)orSetRequestBodyLimit.IdempotencyMemoryMaxEntriesPerPrincipal(-1).Testing
go test -racepasses forinternal/router,internal/idempotency,interceptors,middlewareand the root package.golangci-lint --new-from-rev=mainis clean.