diff --git a/idempotency.go b/idempotency.go index a43cb9cb9..ef0eb65d5 100644 --- a/idempotency.go +++ b/idempotency.go @@ -16,6 +16,39 @@ type IdempotencyOption = idempotency.Option // type as middleware.IdempotencyStore. type IdempotencyStore = idempotency.Store +// IdempotencyMemoryOption configures an in-memory idempotency store. It is the +// same type as middleware.MemoryIdempotencyOption, so these options can be +// passed to middleware.NewMemoryIdempotencyStore. +type IdempotencyMemoryOption = idempotency.MemoryOption + +// ErrIdempotencyQuotaExceeded is what the in-memory store returns, wrapped, +// when a principal already holds as many claims and stored responses as its +// quota allows. The idempotency middleware answers it with 429. +var ErrIdempotencyQuotaExceeded = idempotency.ErrQuotaExceeded + +// IdempotencyMemoryMaxBytes caps the approximate bytes the in-memory store's +// responses take across all principals (default 256 MiB). Past it the least +// recently used response is evicted. +func IdempotencyMemoryMaxBytes(n int64) IdempotencyMemoryOption { + return idempotency.WithMaxBytes(n) +} + +// IdempotencyMemoryMaxEntriesPerPrincipal caps the claims and stored responses +// one principal may hold in the in-memory store. The default is a tenth of the +// store-wide entry cap. A principal at the cap gets 429 for new keys until its +// earlier responses expire, rather than pushing out other principals' +// responses. A negative value removes the cap. +func IdempotencyMemoryMaxEntriesPerPrincipal(n int) IdempotencyMemoryOption { + return idempotency.WithMaxEntriesPerPrincipal(n) +} + +// IdempotencyMemoryMaxBytesPerPrincipal caps the approximate bytes one +// principal's responses may take in the in-memory store. The default is a +// tenth of the store-wide byte cap. A negative value removes the cap. +func IdempotencyMemoryMaxBytesPerPrincipal(n int64) IdempotencyMemoryOption { + return idempotency.WithMaxBytesPerPrincipal(n) +} + // IdempotencyBackend selects the store. Without it, every route shares one // process-wide in-memory store, which is right for a single instance and // wrong behind a load balancer: use a shared store there. @@ -41,6 +74,10 @@ func IdempotencyBackend(store IdempotencyStore) IdempotencyOption { // other status is stored and replayed until the TTL (24h by default). // - A response larger than middleware.IdempotencyMaxResponse (1 MiB) is sent // in full and replayed without its body, marked Idempotent-Truncated: true. +// - A principal that already holds its quota of stored responses (in the +// default in-memory store, a tenth of the store) gets 429 for a new key, +// with Retry-After, and the handler does not run. One caller cannot push +// another's stored responses out of the store. // - A request with no principal is not deduplicated: it runs as if it had // no key, and its response carries Idempotency-Skipped: anonymous. Every // anonymous caller shares the empty principal, so one could otherwise be diff --git a/interceptors/interceptors.go b/interceptors/interceptors.go index 69181d058..dcba6e444 100644 --- a/interceptors/interceptors.go +++ b/interceptors/interceptors.go @@ -193,7 +193,9 @@ var ( // RateLimit creates a rate limit interceptor with a custom checker. RateLimit = router.RateLimit - // RateLimitByIP creates a rate limit interceptor keyed by client IP. + // RateLimitByIP creates a rate limit interceptor keyed by client IP. The + // key is the address from RemoteAddr without its port, so every + // connection from one client shares a bucket. RateLimitByIP = router.RateLimitByIP ) @@ -202,10 +204,15 @@ var ( // --------------------------------------------------------------------------- var ( - // AllowIPs only allows specific IP addresses. + // AllowIPs only allows the listed clients. Entries are single addresses + // or CIDR ranges, IPv4 or IPv6, matched against the address in + // RemoteAddr. X-Forwarded-For is not read. It panics on an invalid entry. AllowIPs = router.AllowIPs - // DenyIPs blocks specific IP addresses. + // DenyIPs blocks the listed clients. Entries are single addresses or CIDR + // ranges, IPv4 or IPv6, matched against the address in RemoteAddr. A + // request whose address cannot be parsed is blocked too. It panics on an + // invalid entry. DenyIPs = router.DenyIPs ) diff --git a/internal/idempotency/memory.go b/internal/idempotency/memory.go index e8a431c37..7d77c541d 100644 --- a/internal/idempotency/memory.go +++ b/internal/idempotency/memory.go @@ -5,6 +5,8 @@ import ( "container/heap" "container/list" "context" + "errors" + "fmt" "sync" "time" ) @@ -12,11 +14,48 @@ import ( // DefaultMaxEntries caps how many completed responses a MemoryStore keeps. const DefaultMaxEntries = 10000 +// DefaultMaxBytes caps the approximate memory the completed responses in a +// MemoryStore take, across all principals. +const DefaultMaxBytes int64 = 256 << 20 // 256 MiB + +// principalShare is the default fraction of the store-wide caps one principal +// may use: a tenth of the entries and a tenth of the bytes. With the +// store-wide defaults that is 1000 entries and 25.6 MiB per principal. +const principalShare = 10 + +// entryOverhead approximates the bookkeeping a stored response costs beyond +// its key, header and body bytes, so a flood of empty responses is not free. +const entryOverhead = 256 + +// ErrQuotaExceeded is returned, wrapped in a *QuotaError, by Begin when the +// key's principal already holds as many claims and stored responses, or as +// many stored bytes, as its quota allows. Nothing is evicted to make room. +var ErrQuotaExceeded = errors.New("idempotency: principal is over its storage quota") + +// QuotaError is the error Begin returns when a principal is over its quota. +// errors.Is(err, ErrQuotaExceeded) matches it. +type QuotaError struct { + // Principal is the principal that is over quota. + Principal string + // RetryAfter is how long until the principal's soonest stored response + // expires and frees room. Zero when the store cannot tell. + RetryAfter time.Duration +} + +func (e *QuotaError) Error() string { + return fmt.Sprintf("%v (principal %q)", ErrQuotaExceeded, e.Principal) +} + +// Is reports whether target is ErrQuotaExceeded. +func (e *QuotaError) Is(target error) bool { return target == ErrQuotaExceeded } + // MemoryOption configures a MemoryStore. type MemoryOption func(*MemoryStore) -// WithMaxEntries caps the number of completed responses kept; the least -// recently used is evicted first. Values below 1 are ignored. +// WithMaxEntries caps the number of completed responses kept across all +// principals; the least recently used is evicted first. Values below 1 are +// ignored. Unless WithMaxEntriesPerPrincipal is given, one principal may hold +// a tenth of this. func WithMaxEntries(n int) MemoryOption { return func(s *MemoryStore) { if n > 0 { @@ -25,6 +64,44 @@ func WithMaxEntries(n int) MemoryOption { } } +// WithMaxBytes caps the approximate bytes the completed responses take across +// all principals; the least recently used is evicted first. Values below 1 +// are ignored. Unless WithMaxBytesPerPrincipal is given, one principal may +// hold a tenth of this. +func WithMaxBytes(n int64) MemoryOption { + return func(s *MemoryStore) { + if n > 0 { + s.maxBytes = n + } + } +} + +// WithMaxEntriesPerPrincipal caps the claims and stored responses one +// principal may hold. A principal at the cap has new keys refused with a +// *QuotaError until some of its responses expire. A negative value removes +// the cap, which lets one principal fill the store and push out other +// principals' responses; zero keeps the default. +func WithMaxEntriesPerPrincipal(n int) MemoryOption { + return func(s *MemoryStore) { + if n != 0 { + s.principalEntries = n + } + } +} + +// WithMaxBytesPerPrincipal caps the approximate bytes one principal's stored +// responses may take. A principal at the cap has new keys refused with a +// *QuotaError. A response that finishes while its principal is near the cap +// is still stored, so the cap can be overshot by the responses in flight. A +// negative value removes the cap; zero keeps the default. +func WithMaxBytesPerPrincipal(n int64) MemoryOption { + return func(s *MemoryStore) { + if n != 0 { + s.principalBytes = n + } + } +} + // WithClock replaces time.Now, for tests. func WithClock(now func() time.Time) MemoryOption { return func(s *MemoryStore) { @@ -35,21 +112,51 @@ func WithClock(now func() time.Time) MemoryOption { } // MemoryStore is a process-local Store. Claims expire with their lease, -// responses with their ExpiresAt, and completed responses beyond the cap are -// evicted least recently used first. Claims are not counted against the cap, -// so a burst of new keys never pushes out a stored response. +// responses with their ExpiresAt, and completed responses beyond the +// store-wide caps are evicted least recently used first. Claims are not +// counted against the store-wide caps, so a burst of new keys never pushes +// out a stored response. +// +// Each principal also has a quota of entries (claims and responses) and of +// bytes, by default a tenth of the store-wide caps. A principal at its quota +// has new keys refused rather than being allowed to evict anything. Without +// the quota, one principal sending fresh keys could push every other +// principal's stored responses out of the shared LRU, and a victim's retry +// would then run the handler a second time. With it, filling the store takes +// many principals, not one. // // Lapsed claims are swept on every Begin, soonest lease first, so a client that // abandons unique keys cannot grow the store without bound. Each claim is -// removed once, so the sweep costs O(log n) amortised per claim. +// removed once, so the sweep costs O(log n) amortised per claim. Expired +// responses are dropped when they are looked up, and a principal's expired +// responses are dropped when it reaches its quota. type MemoryStore struct { - mu sync.Mutex - maxEntries int - now func() time.Time - entries map[Key]*memEntry - completed *list.List // of *memEntry; front is most recently used - claims claimQueue // claimed entries, soonest leaseUntil first - lastToken Token + mu sync.Mutex + maxEntries int + maxBytes int64 + principalEntries int // 0 means derive from maxEntries; negative is unlimited + principalBytes int64 // 0 means derive from maxBytes; negative is unlimited + now func() time.Time + entries map[Key]*memEntry + completed *list.List // of *memEntry; front is most recently used + bytes int64 // size of every stored response + usage map[string]*principalUsage + claims claimQueue // claimed entries, soonest leaseUntil first + lastToken Token +} + +// principalUsage is what one principal holds in the store. +type principalUsage struct { + entries int // claims plus stored responses + bytes int64 // size of the stored responses + own *list.List // of *memEntry, every entry the principal holds + + // After a scan for expired responses, scanned is set and nextExpiry is + // the soonest ExpiresAt that remained (zero if none). Until then nothing + // can have expired, so a principal hammering at its quota does not cost + // a scan per request. + scanned bool + nextExpiry time.Time } // memEntry is either a claim (resp nil, token and done set, in claims) or a @@ -62,7 +169,9 @@ type memEntry struct { leaseUntil time.Time claimIdx int // index in MemoryStore.claims, -1 when not queued resp *Response + size int64 // approximate bytes resp takes; 0 for a claim lru *list.Element + own *list.Element // in the principal's usage.own } // claimQueue is a min-heap of claimed entries ordered by leaseUntil. @@ -98,15 +207,25 @@ func (q *claimQueue) Pop() any { func NewMemoryStore(opts ...MemoryOption) *MemoryStore { s := &MemoryStore{ maxEntries: DefaultMaxEntries, + maxBytes: DefaultMaxBytes, now: time.Now, entries: map[Key]*memEntry{}, completed: list.New(), + usage: map[string]*principalUsage{}, } for _, opt := range opts { opt(s) } + if s.principalEntries == 0 { + s.principalEntries = max(s.maxEntries/principalShare, 1) + } + + if s.principalBytes == 0 { + s.principalBytes = max(s.maxBytes/principalShare, 1) + } + return s } @@ -152,6 +271,10 @@ func (s *MemoryStore) Begin(_ context.Context, key Key, fingerprint string, leas s.drop(e) } + if err := s.checkQuota(key.Principal, now); err != nil { + return Begun{}, err + } + s.lastToken++ e := &memEntry{ @@ -163,6 +286,7 @@ func (s *MemoryStore) Begin(_ context.Context, key Key, fingerprint string, leas claimIdx: -1, } s.entries[key] = e + s.track(e) heap.Push(&s.claims, e) return Begun{State: Acquired, Token: e.token}, nil @@ -183,8 +307,12 @@ func (s *MemoryStore) Complete(_ context.Context, key Key, token Token, resp Res } if !ok { + // A Complete without a Begin is not checked against the quota, + // because the work it records has already happened, but it is + // counted. e = &memEntry{key: key, claimIdx: -1} s.entries[key] = e + s.track(e) } if resp.Fingerprint == "" { @@ -195,6 +323,7 @@ func (s *MemoryStore) Complete(_ context.Context, key Key, token Token, resp Res stored := copyResponse(resp) e.resp = &stored + s.resize(e, responseSize(key, &stored)) if e.lru == nil { e.lru = s.completed.PushFront(e) @@ -202,7 +331,11 @@ func (s *MemoryStore) Complete(_ context.Context, key Key, token Token, resp Res s.completed.MoveToFront(e.lru) } - for s.completed.Len() > s.maxEntries { + // The store-wide caps are a backstop. The per-principal quota keeps any + // one principal well below them, so reaching them takes many principals. + // The entry just stored is never the one evicted, even if it alone is + // over the byte cap. + for s.completed.Len() > s.maxEntries || (s.bytes > s.maxBytes && s.completed.Len() > 1) { oldest := s.completed.Back() s.drop(oldest.Value.(*memEntry)) } @@ -261,9 +394,139 @@ func (s *MemoryStore) drop(e *memEntry) { e.lru = nil } + s.resize(e, 0) + s.untrack(e) delete(s.entries, e.key) } +// track counts a new entry against its principal. Caller holds s.mu. +func (s *MemoryStore) track(e *memEntry) { + u := s.usage[e.key.Principal] + if u == nil { + u = &principalUsage{own: list.New()} + s.usage[e.key.Principal] = u + } + + u.entries++ + e.own = u.own.PushBack(e) +} + +// untrack reverses track. Caller holds s.mu. +func (s *MemoryStore) untrack(e *memEntry) { + if e.own == nil { + return + } + + u := s.usage[e.key.Principal] + u.own.Remove(e.own) + e.own = nil + u.entries-- + + if u.entries == 0 { + delete(s.usage, e.key.Principal) + } +} + +// resize sets the size e's response is accounted at. Caller holds s.mu. +func (s *MemoryStore) resize(e *memEntry, size int64) { + delta := size - e.size + if delta == 0 { + return + } + + e.size = size + s.bytes += delta + + u := s.usage[e.key.Principal] + if u == nil { + return + } + + u.bytes += delta + + // An entry that expires sooner than anything seen at the last scan + // moves the next useful scan forward. + if size > 0 && u.scanned { + if exp := e.resp.ExpiresAt; !exp.IsZero() && (u.nextExpiry.IsZero() || exp.Before(u.nextExpiry)) { + u.nextExpiry = exp + } + } +} + +// checkQuota returns a *QuotaError when principal cannot take another key. +// A principal at its quota first has its expired responses dropped, at most +// once per expiry, so a key frees up as soon as one of them lapses. Caller +// holds s.mu. +func (s *MemoryStore) checkQuota(principal string, now time.Time) error { + u := s.usage[principal] + if u == nil || !s.overQuota(u) { + return nil + } + + if !u.scanned || (!u.nextExpiry.IsZero() && !now.Before(u.nextExpiry)) { + s.dropExpired(u, now) + + // dropExpired may have removed the principal's last entry. + if u = s.usage[principal]; u == nil || !s.overQuota(u) { + return nil + } + } + + qe := &QuotaError{Principal: principal} + if !u.nextExpiry.IsZero() { + qe.RetryAfter = u.nextExpiry.Sub(now) + } + + return qe +} + +func (s *MemoryStore) overQuota(u *principalUsage) bool { + return (s.principalEntries > 0 && u.entries >= s.principalEntries) || + (s.principalBytes > 0 && u.bytes >= s.principalBytes) +} + +// dropExpired drops u's expired responses and records when the next one +// expires. Caller holds s.mu. +func (s *MemoryStore) dropExpired(u *principalUsage, now time.Time) { + var next time.Time + + for el := u.own.Front(); el != nil; { + e := el.Value.(*memEntry) + el = el.Next() + + if e.resp == nil || e.resp.ExpiresAt.IsZero() { + continue + } + + if !now.Before(e.resp.ExpiresAt) { + s.drop(e) + + continue + } + + if next.IsZero() || e.resp.ExpiresAt.Before(next) { + next = e.resp.ExpiresAt + } + } + + u.scanned = true + u.nextExpiry = next +} + +// responseSize approximates the memory a stored response takes. +func responseSize(key Key, r *Response) int64 { + n := entryOverhead + len(key.Principal) + len(key.Scope) + len(key.Value) + len(r.Fingerprint) + len(r.Body) + + for k, vs := range r.Header { + n += len(k) + for _, v := range vs { + n += len(v) + } + } + + return int64(n) +} + func copyResponse(r Response) Response { r.Header = r.Header.Clone() r.Body = bytes.Clone(r.Body) diff --git a/internal/idempotency/memory_test.go b/internal/idempotency/memory_test.go index 11d99248e..1cf68f0a9 100644 --- a/internal/idempotency/memory_test.go +++ b/internal/idempotency/memory_test.go @@ -229,8 +229,11 @@ func TestCompleteWithoutBeginStoresTheResponse(t *testing.T) { } } +// The eviction tests use one principal to exercise the store-wide LRU, so +// they lift the per-principal quota that would otherwise refuse its keys. + func TestEvictionCountsOnlyCompletedEntries(t *testing.T) { - s, _ := newTestStore(WithMaxEntries(2)) + s, _ := newTestStore(WithMaxEntries(2), WithMaxEntriesPerPrincipal(-1)) ctx := context.Background() key := func(v string) Key { return Key{Principal: "u", Scope: "s", Value: v} } @@ -271,7 +274,7 @@ func TestEvictionIsLeastRecentlyUsedNotFirstIn(t *testing.T) { for name, touch := range cases { t.Run(name, func(t *testing.T) { - s, _ := newTestStore(WithMaxEntries(2)) + s, _ := newTestStore(WithMaxEntries(2), WithMaxEntriesPerPrincipal(-1)) ctx := context.Background() _ = s.Complete(ctx, key("k1"), 0, Response{Status: 200}) @@ -610,7 +613,7 @@ func TestConcurrentBeginsOnOneKeyHaveExactlyOneWinner(t *testing.T) { // token differs from every token the key had before, so a holder of the old // one can neither complete nor release the new claim. func TestATokenStaysDistinctAcrossEvictionAndRecreation(t *testing.T) { - s, _ := newTestStore(WithMaxEntries(1)) + s, _ := newTestStore(WithMaxEntries(1), WithMaxEntriesPerPrincipal(-1)) ctx := context.Background() other := Key{Principal: "alice", Scope: "POST /orders", Value: "k2"} diff --git a/internal/idempotency/middleware.go b/internal/idempotency/middleware.go index 3b17a430c..9c4d983c4 100644 --- a/internal/idempotency/middleware.go +++ b/internal/idempotency/middleware.go @@ -11,6 +11,7 @@ import ( "net/http" "reflect" "slices" + "strconv" "strings" "sync" "time" @@ -223,6 +224,11 @@ func Clock(now func() time.Time) Option { // wait gets 409 with Retry-After: 1, so a client can tell the conflict is // temporary. // +// A store may refuse a new key because its principal is over a storage quota +// (Begin returns an error matching ErrQuotaExceeded, as MemoryStore does). The +// request then gets 429, with Retry-After when the store says how long, and +// the handler does not run. +// // A second layer inside the first (a group and a route that both opted in) // steps aside, because the outer layer already holds the claim. // @@ -471,6 +477,10 @@ func (h *handler) serve(ctx router.Context, next router.Handler, key Key, fp str for { begun, err := h.cfg.store.Begin(ctx.Context(), key, fp, h.cfg.lease) + if errors.Is(err, ErrQuotaExceeded) { + return writeQuotaExceeded(ctx, err) + } + if err != nil { return err } @@ -663,6 +673,20 @@ func writeBusy(ctx router.Context) error { return writeError(ctx, http.StatusConflict, "a request with this Idempotency-Key is still being processed") } +// writeQuotaExceeded answers a request whose principal has too many stored +// responses to take another key. The handler does not run, so the client can +// retry once Retry-After passes, when the principal's soonest response +// expires. +func writeQuotaExceeded(ctx router.Context, err error) error { + if qe, ok := errors.AsType[*QuotaError](err); ok && qe.RetryAfter > 0 { + seconds := int64((qe.RetryAfter + time.Second - 1) / time.Second) + ctx.Response().Header().Set("Retry-After", strconv.FormatInt(seconds, 10)) + } + + return writeError(ctx, http.StatusTooManyRequests, + "too many idempotent requests are stored for this caller; retry after the earlier ones expire") +} + func writeError(ctx router.Context, status int, message string) error { return ctx.JSON(status, map[string]string{"error": message}) } diff --git a/internal/idempotency/quota_test.go b/internal/idempotency/quota_test.go new file mode 100644 index 000000000..fa0a191c3 --- /dev/null +++ b/internal/idempotency/quota_test.go @@ -0,0 +1,279 @@ +package idempotency + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/xraph/forge/internal/router" +) + +func quotaKey(principal, v string) Key { + return Key{Principal: principal, Scope: "POST /pay", Value: v} +} + +// One principal used to be able to push every other principal's stored +// responses out of the shared LRU by sending fresh keys. A victim's retry then +// found nothing stored and ran the handler a second time. +func TestOnePrincipalCannotEvictAnother(t *testing.T) { + s, _ := newTestStore(WithMaxEntries(100)) + ctx := context.Background() + + if err := s.Complete(ctx, quotaKey("victim", "k1"), 0, Response{Status: 201}); err != nil { + t.Fatal(err) + } + + refused := 0 + + for i := range 1000 { + got, err := s.Begin(ctx, quotaKey("attacker", fmt.Sprintf("a%d", i)), "", time.Minute) + if _, ok := errors.AsType[*QuotaError](err); ok { + refused++ + + continue + } + + if err != nil || got.State != Acquired { + t.Fatalf("attacker Begin %d = %+v, %v", i, got, err) + } + + if err := s.Complete(ctx, quotaKey("attacker", fmt.Sprintf("a%d", i)), got.Token, Response{Status: 201}); err != nil { + t.Fatal(err) + } + } + + if refused != 990 { + t.Fatalf("refused %d attacker keys, want 990 (a principal may hold a tenth of 100)", refused) + } + + if got, _ := s.Begin(ctx, quotaKey("victim", "k1"), "", time.Minute); got.State != Replay { + t.Fatalf("victim's key = %v, want Replay", got.State) + } +} + +func TestQuotaCountsClaimsAndFreesOnRelease(t *testing.T) { + s, _ := newTestStore(WithMaxEntriesPerPrincipal(2)) + ctx := context.Background() + + a, _ := s.Begin(ctx, quotaKey("u", "a"), "", time.Minute) + _, _ = s.Begin(ctx, quotaKey("u", "b"), "", time.Minute) + + if _, err := s.Begin(ctx, quotaKey("u", "c"), "", time.Minute); !errors.Is(err, ErrQuotaExceeded) { + t.Fatalf("third claim = %v, want ErrQuotaExceeded", err) + } + + // Asking about a key the principal already holds is not a new key. + if got, err := s.Begin(ctx, quotaKey("u", "a"), "", time.Minute); err != nil || got.State != InFlight { + t.Fatalf("existing key = %+v, %v; want InFlight", got, err) + } + + // Another principal is unaffected. + if got, err := s.Begin(ctx, quotaKey("v", "c"), "", time.Minute); err != nil || got.State != Acquired { + t.Fatalf("other principal = %+v, %v; want Acquired", got, err) + } + + _ = s.Release(ctx, quotaKey("u", "a"), a.Token) + + if got, err := s.Begin(ctx, quotaKey("u", "c"), "", time.Minute); err != nil || got.State != Acquired { + t.Fatalf("after a release = %+v, %v; want Acquired", got, err) + } +} + +func TestQuotaFreesWhenResponsesExpire(t *testing.T) { + s, clock := newTestStore(WithMaxEntriesPerPrincipal(2)) + ctx := context.Background() + expires := clock.Now().Add(time.Hour) + + for _, v := range []string{"a", "b"} { + if err := s.Complete(ctx, quotaKey("u", v), 0, Response{Status: 200, ExpiresAt: expires}); err != nil { + t.Fatal(err) + } + } + + _, err := s.Begin(ctx, quotaKey("u", "c"), "", time.Minute) + + var qe *QuotaError + if !errors.As(err, &qe) { + t.Fatalf("Begin at quota = %v, want *QuotaError", err) + } + + if qe.RetryAfter != time.Hour || qe.Principal != "u" { + t.Fatalf("QuotaError = %+v, want principal u and RetryAfter 1h", qe) + } + + clock.Advance(30 * time.Minute) + + if _, err := s.Begin(ctx, quotaKey("u", "c"), "", time.Minute); !errors.As(err, &qe) || qe.RetryAfter != 30*time.Minute { + t.Fatalf("Begin half way = %v, want *QuotaError with RetryAfter 30m", err) + } + + clock.Advance(30 * time.Minute) + + if got, err := s.Begin(ctx, quotaKey("u", "c"), "", time.Minute); err != nil || got.State != Acquired { + t.Fatalf("Begin after expiry = %+v, %v; want Acquired", got, err) + } + + s.mu.Lock() + entries := len(s.entries) + s.mu.Unlock() + + if entries != 1 { + t.Fatalf("entries = %d, want only the new claim", entries) + } +} + +func TestQuotaCountsBytes(t *testing.T) { + s, _ := newTestStore(WithMaxBytesPerPrincipal(4<<10), WithMaxEntriesPerPrincipal(-1)) + ctx := context.Background() + body := []byte(strings.Repeat("x", 3<<10)) + + if err := s.Complete(ctx, quotaKey("u", "a"), 0, Response{Status: 200, Body: body}); err != nil { + t.Fatal(err) + } + + if _, err := s.Begin(ctx, quotaKey("u", "b"), "", time.Minute); err != nil { + t.Fatalf("under the byte quota = %v", err) + } + + if err := s.Complete(ctx, quotaKey("u", "b"), 0, Response{Status: 200, Body: body}); err == nil { + t.Fatal("Complete without the token should be refused while b is claimed") + } + + if err := s.Complete(ctx, quotaKey("u", "c"), 0, Response{Status: 200, Body: body}); err != nil { + t.Fatal(err) + } + + if _, err := s.Begin(ctx, quotaKey("u", "d"), "", time.Minute); !errors.Is(err, ErrQuotaExceeded) { + t.Fatalf("over the byte quota = %v, want ErrQuotaExceeded", err) + } +} + +func TestGlobalByteBudgetEvictsLeastRecentlyUsed(t *testing.T) { + s, _ := newTestStore(WithMaxBytes(10<<10), WithMaxBytesPerPrincipal(-1), WithMaxEntriesPerPrincipal(-1)) + ctx := context.Background() + body := []byte(strings.Repeat("x", 4<<10)) + + for _, v := range []string{"a", "b", "c"} { + if err := s.Complete(ctx, quotaKey("u", v), 0, Response{Status: 200, Body: body}); err != nil { + t.Fatal(err) + } + } + + if got, _ := s.Begin(ctx, quotaKey("u", "a"), "", time.Minute); got.State != Acquired { + t.Fatalf("a = %v, want Acquired (evicted to stay under the byte budget)", got.State) + } + + s.mu.Lock() + used := s.bytes + s.mu.Unlock() + + if used > 10<<10 { + t.Fatalf("store holds %d bytes, over the 10 KiB budget", used) + } +} + +func TestAccountingReturnsToZero(t *testing.T) { + s, clock := newTestStore() + ctx := context.Background() + + for i := range 50 { + k := quotaKey(fmt.Sprintf("p%d", i%5), fmt.Sprintf("k%d", i)) + got, _ := s.Begin(ctx, k, "", time.Minute) + + switch i % 3 { + case 0: + _ = s.Complete(ctx, k, got.Token, Response{Status: 200, Body: []byte("abc"), ExpiresAt: clock.Now().Add(time.Second)}) + case 1: + _ = s.Release(ctx, k, got.Token) + } + } + + clock.Advance(time.Hour) + + // Looking every key up drops expired responses; the sweep drops the + // lapsed claims. + for i := range 50 { + k := quotaKey(fmt.Sprintf("p%d", i%5), fmt.Sprintf("k%d", i)) + if got, _ := s.Begin(ctx, k, "", time.Minute); got.State == Acquired { + _ = s.Release(ctx, k, got.Token) + } + } + + s.mu.Lock() + defer s.mu.Unlock() + + if s.bytes != 0 || len(s.usage) != 0 || len(s.entries) != 0 { + t.Fatalf("bytes=%d usage=%d entries=%d, want all zero", s.bytes, len(s.usage), len(s.entries)) + } +} + +// Through the middleware, the PoC from the review: a victim stores one +// response, an attacker sends many fresh keys, and the victim retries. +func TestMiddleware_OverQuotaPrincipalGets429AndVictimReplays(t *testing.T) { + store := NewMemoryStore(WithMaxEntries(100)) + + var victimCharges atomic.Int32 + + r := router.NewRouter() + r.Use(func(next router.Handler) router.Handler { + return func(ctx router.Context) error { + ctx.Set("auth.subject", ctx.Request().Header.Get("X-Sub")) + + return next(ctx) + } + }) + + if err := r.POST("/pay", func(ctx router.Context) error { + if ctx.Request().Header.Get("X-Sub") == "victim" { + victimCharges.Add(1) + } + + return ctx.String(http.StatusCreated, strings.Repeat("x", 1000)) + }, router.WithMiddleware(Middleware(store))); err != nil { + t.Fatal(err) + } + + do := func(sub, key string) *httptest.ResponseRecorder { + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/pay", strings.NewReader(`{}`)) + req.Header.Set("X-Sub", sub) + req.Header.Set(HeaderName, key) + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + return rec + } + + do("victim", "k1") + + var last *httptest.ResponseRecorder + for i := range 100 { + last = do("attacker", fmt.Sprintf("a%d", i)) + } + + if last.Code != http.StatusTooManyRequests { + t.Fatalf("attacker over quota got %d, want 429", last.Code) + } + + if ra := last.Header().Get("Retry-After"); ra != "86400" { + t.Fatalf("Retry-After = %q, want the 24h TTL in seconds", ra) + } + + if !strings.Contains(last.Body.String(), "too many idempotent requests") { + t.Fatalf("429 body = %s", last.Body.String()) + } + + if rec := do("victim", "k1"); rec.Header().Get(ReplayedHeader) != "true" { + t.Fatalf("victim retry was not replayed: %d %v", rec.Code, rec.Header()) + } + + if n := victimCharges.Load(); n != 1 { + t.Fatalf("victim charged %d times for one key, want 1", n) + } +} diff --git a/internal/router/bind_error_test.go b/internal/router/bind_error_test.go new file mode 100644 index 000000000..8d2552856 --- /dev/null +++ b/internal/router/bind_error_test.go @@ -0,0 +1,116 @@ +package router + +import ( + "bytes" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type bindTransferReq struct { + TenantID string `path:"tenantId"` + UserID string `header:"X-User-Id"` + Amount int `json:"amount"` + Name string `json:"name" validate:"required"` +} + +type bindTransferResp struct { + OK bool `json:"ok"` +} + +func serveBind(t *testing.T, opts []RouteOption, body string) *httptest.ResponseRecorder { + t.Helper() + + r := NewRouter() + require.NoError(t, r.POST("/t/:tenantId", func(ctx Context, req *bindTransferReq) (*bindTransferResp, error) { + return &bindTransferResp{OK: true}, nil + }, opts...)) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/t/a", bytes.NewReader([]byte(body))) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-User-Id", "u") + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + return rec +} + +// Bind failures used to be sent back as "invalid request: ", +// which named Go types and struct fields and turned 413 into 400. +func TestBindError_DoesNotLeakGoTypes(t *testing.T) { + cases := []struct { + name string + body string + opts []RouteOption + status int + contains string + }{ + { + name: "wrong type names the JSON field only", + body: `{"amount":"x","name":"n"}`, + status: http.StatusBadRequest, + contains: `field \"amount\" has the wrong type (got JSON string)`, + }, + { + name: "syntax error is generic", + body: `{"amount":`, + status: http.StatusBadRequest, + contains: "malformed JSON", + }, + { + name: "bad token is generic", + body: `{"amount": nope}`, + status: http.StatusBadRequest, + contains: "malformed JSON", + }, + { + name: "body over the cap is 413", + body: `{"name":"` + strings.Repeat("a", 4096) + `"}`, + opts: []RouteOption{WithMaxBodySize(1024)}, + status: http.StatusRequestEntityTooLarge, + contains: "request body too large", + }, + { + name: "validation errors stay descriptive", + body: `{"amount":1}`, + status: http.StatusBadRequest, + contains: "name", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + rec := serveBind(t, tc.opts, tc.body) + body := rec.Body.String() + + assert.Equal(t, tc.status, rec.Code, body) + assert.Contains(t, body, tc.contains) + + for _, leak := range []string{"Go struct", "Go value", "bindTransferReq", "int", "router.", "failed to"} { + assert.NotContains(t, body, leak) + } + }) + } +} + +func TestBindError_UnknownErrorsAreGeneric(t *testing.T) { + r := NewRouter() + require.NoError(t, r.POST("/t/:tenantId", func(ctx Context, req *bindTransferReq) (*bindTransferResp, error) { + return &bindTransferResp{OK: true}, nil + })) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/t/a", strings.NewReader(``)) + req.Header.Set("Content-Type", "text/plain") + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + assert.Equal(t, http.StatusBadRequest, rec.Code) + assert.Contains(t, rec.Body.String(), `"invalid request"`) + assert.NotContains(t, rec.Body.String(), "content type") +} diff --git a/internal/router/body_limit.go b/internal/router/body_limit.go new file mode 100644 index 000000000..08870728c --- /dev/null +++ b/internal/router/body_limit.go @@ -0,0 +1,131 @@ +package router + +import ( + "errors" + "io" + "net/http" +) + +// limitedBody caps a request body at the router's limit from the moment the +// request enters the router, before any global middleware, route matching or +// mounted handler sees it. +// +// The cap used to be installed only in the per-route wrapper. Everything that +// runs before or instead of a route handler read the body unbounded: UseGlobal +// middleware, the 404 and 405 paths, and handlers mounted with Handle. A +// global middleware that buffered the body (to verify a signature, or log it) +// would read 64 MiB from a single request even on a path that does not exist. +// +// A plain http.MaxBytesReader cannot be loosened once installed, which would +// stop a route raising its own cap with WithMaxBodySize. limitedBody can be +// re-limited instead: the per-route wrapper calls setLimit with the route's +// cap, raising or lowering it, and SetRequestBodyLimit does the same for a +// mounted handler. Bytes already read count against the new limit. +type limitedBody struct { + src io.ReadCloser + + // w is the ResponseWriter the server handed the router. MaxBytesReader + // uses it to tell the server to close the connection once the cap is + // hit, which only works on the server's own writer. + w http.ResponseWriter + + // r is what reads go through: a MaxBytesReader over src sized to what is + // left of limit, or src itself when the body is unlimited. + r io.ReadCloser + limit int64 // 0 means unlimited + read int64 + err error // sticky once the cap is hit +} + +func newLimitedBody(w http.ResponseWriter, src io.ReadCloser, limit int64) *limitedBody { + b := &limitedBody{src: src, w: w} + b.setLimit(limit) + + return b +} + +// setLimit changes the cap. A limit of zero or less removes it. Once a read +// has failed for being over the cap the body stays failed, because the reader +// may already have consumed a byte past the old cap. +func (b *limitedBody) setLimit(limit int64) { + if limit < 0 { + limit = 0 + } + + if b.err != nil || (b.r != nil && limit == b.limit) { + return + } + + b.limit = limit + + if limit == 0 { + b.r = b.src + + return + } + + b.r = http.MaxBytesReader(b.w, b.src, max(limit-b.read, 0)) +} + +func (b *limitedBody) Read(p []byte) (int, error) { + if b.err != nil { + return 0, b.err + } + + n, err := b.r.Read(p) + b.read += int64(n) + + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + // The reader was sized to what was left of the limit, so its own + // error reports the remainder. Report the limit the caller set. + b.err = &http.MaxBytesError{Limit: b.limit} + err = b.err + } + + return n, err +} + +func (b *limitedBody) Close() error { + return b.src.Close() +} + +// applyRouteBodyLimit installs a route's body cap on r. When the router has +// already wrapped the body, the cap is changed in place, so a route can raise +// the router's limit as well as lower it. Otherwise, because the router has no +// limit or a middleware replaced the body, a MaxBytesReader is added. +func applyRouteBodyLimit(w http.ResponseWriter, r *http.Request, limit int64) { + if r.Body == nil || r.Body == http.NoBody { + return + } + + if lb, ok := r.Body.(*limitedBody); ok { + lb.setLimit(limit) + + return + } + + if limit > 0 { + r.Body = http.MaxBytesReader(w, r.Body, limit) + } +} + +// SetRequestBodyLimit changes the body cap the router put on r. It is for +// handlers mounted with Handle, which have no route options: a mounted upload +// endpoint calls it before reading to accept more than the router-wide limit. +// A limit of zero or less removes the cap. It reports false, and changes +// nothing, when r's body is not the one the router capped, because there is no +// router limit or a middleware replaced the body. +func SetRequestBodyLimit(r *http.Request, limit int64) bool { + if r == nil { + return false + } + + lb, ok := r.Body.(*limitedBody) + if !ok { + return false + } + + lb.setLimit(limit) + + return true +} diff --git a/internal/router/body_limit_test.go b/internal/router/body_limit_test.go new file mode 100644 index 000000000..cea984528 --- /dev/null +++ b/internal/router/body_limit_test.go @@ -0,0 +1,225 @@ +package router + +import ( + "bytes" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// readAllBody is what a buffering global middleware does: read everything, +// then hand the next handler a fresh reader over what it got. +func readAllBody(got *int, gotErr *error) Middleware { + return func(next Handler) Handler { + return func(ctx Context) error { + b, err := io.ReadAll(ctx.Request().Body) + *got, *gotErr = len(b), err + + ctx.Request().Body = io.NopCloser(bytes.NewReader(b)) + + return next(ctx) + } + } +} + +func post(t *testing.T, h http.Handler, path string, size int) *httptest.ResponseRecorder { + t.Helper() + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, path, bytes.NewReader(make([]byte, size))) + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + + return rec +} + +// The body cap was installed only in the per-route wrapper, so UseGlobal +// middleware read an unbounded body, on matched and unmatched paths alike. +func TestBodyLimit_AppliesToGlobalMiddleware(t *testing.T) { + const limit = 1 << 10 + + var ( + read int + err error + ) + + r := NewRouter(WithMaxRequestBodySize(limit)) + r.UseGlobal(readAllBody(&read, &err)) + require.NoError(t, r.POST("/x", func(ctx Context) error { return ctx.String(http.StatusOK, "ok") })) + + for _, path := range []string{"/x", "/does-not-exist"} { + t.Run(path, func(t *testing.T) { + read, err = 0, nil + + post(t, r, path, 64*limit) + + assert.LessOrEqual(t, read, limit, "global middleware read past the cap") + + var tooLarge *http.MaxBytesError + require.ErrorAs(t, err, &tooLarge) + assert.Equal(t, int64(limit), tooLarge.Limit) + }) + } +} + +func TestBodyLimit_AppliesToMountedHandler(t *testing.T) { + const limit = 1 << 10 + + var ( + read int + err error + ) + + r := NewRouter(WithMaxRequestBodySize(limit)) + require.NoError(t, r.Handle("/mount/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + b, e := io.ReadAll(req.Body) + read, err = len(b), e + }))) + + post(t, r, "/mount/upload", 8*limit) + + assert.LessOrEqual(t, read, limit) + + var tooLarge *http.MaxBytesError + assert.ErrorAs(t, err, &tooLarge) +} + +func TestBodyLimit_MountedHandlerCanRaiseLimit(t *testing.T) { + const limit = 1 << 10 + + var ( + read int + err error + moved bool + ) + + r := NewRouter(WithMaxRequestBodySize(limit)) + require.NoError(t, r.Handle("/upload/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + moved = SetRequestBodyLimit(req, 16*limit) + b, e := io.ReadAll(req.Body) + read, err = len(b), e + }))) + + post(t, r, "/upload/big", 8*limit) + + assert.True(t, moved) + require.NoError(t, err) + assert.Equal(t, 8*limit, read) +} + +// A route can still raise or lower the router's cap with WithMaxBodySize. +func TestBodyLimit_RouteOverridesRouterCap(t *testing.T) { + const limit = 1 << 10 + + type result struct { + read int + err error + } + + results := map[string]*result{} + handler := func(name string) func(Context) error { + results[name] = &result{} + + return func(ctx Context) error { + b, err := io.ReadAll(ctx.Request().Body) + results[name].read, results[name].err = len(b), err + + return ctx.String(http.StatusOK, "ok") + } + } + + r := NewRouter(WithMaxRequestBodySize(limit)) + require.NoError(t, r.POST("/default", handler("default"))) + require.NoError(t, r.POST("/raised", handler("raised"), WithMaxBodySize(16*limit))) + require.NoError(t, r.POST("/lowered", handler("lowered"), WithMaxBodySize(limit/4))) + require.NoError(t, r.POST("/unlimited", handler("unlimited"), WithMaxBodySize(-1))) + + post(t, r, "/default", 2*limit) + post(t, r, "/raised", 8*limit) + post(t, r, "/lowered", limit/2) + post(t, r, "/unlimited", 32*limit) + + var tooLarge *http.MaxBytesError + + require.ErrorAs(t, results["default"].err, &tooLarge) + assert.Equal(t, int64(limit), tooLarge.Limit) + + require.NoError(t, results["raised"].err) + assert.Equal(t, 8*limit, results["raised"].read) + + require.ErrorAs(t, results["lowered"].err, &tooLarge) + assert.Equal(t, int64(limit/4), tooLarge.Limit) + + require.NoError(t, results["unlimited"].err) + assert.Equal(t, 32*limit, results["unlimited"].read) +} + +// Bytes a global middleware has already read count against the route's cap. +func TestBodyLimit_RouteCapCountsBytesAlreadyRead(t *testing.T) { + const limit = 1 << 10 + + var ( + read int + err error + ) + + r := NewRouter(WithMaxRequestBodySize(limit)) + r.UseGlobal(func(next Handler) Handler { + return func(ctx Context) error { + // Peek at the first 100 bytes without replacing the body. + _, _ = io.ReadFull(ctx.Request().Body, make([]byte, 100)) + + return next(ctx) + } + }) + require.NoError(t, r.POST("/x", func(ctx Context) error { + b, e := io.ReadAll(ctx.Request().Body) + read, err = len(b), e + + return nil + }, WithMaxBodySize(4*limit))) + + post(t, r, "/x", 4*limit) + require.NoError(t, err) + assert.Equal(t, 4*limit-100, read) + + post(t, r, "/x", 4*limit+1) + + var tooLarge *http.MaxBytesError + require.ErrorAs(t, err, &tooLarge) + assert.Equal(t, int64(4*limit), tooLarge.Limit) + assert.LessOrEqual(t, read, 4*limit-100) +} + +func TestBodyLimit_NegativeRouterLimitInstallsNothing(t *testing.T) { + var body io.ReadCloser + + r := NewRouter(WithMaxRequestBodySize(-1)) + require.NoError(t, r.Handle("/m/*", http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + body = req.Body + }))) + + post(t, r, "/m/x", 10) + + _, wrapped := body.(*limitedBody) + assert.False(t, wrapped) + assert.False(t, SetRequestBodyLimit(httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/", nil), 1)) +} + +func TestLimitedBody_StaysFailedAfterCap(t *testing.T) { + b := newLimitedBody(httptest.NewRecorder(), io.NopCloser(bytes.NewReader(make([]byte, 100))), 10) + + _, err := io.ReadAll(b) + + var tooLarge *http.MaxBytesError + require.ErrorAs(t, err, &tooLarge) + + b.setLimit(1000) + + _, err = b.Read(make([]byte, 10)) + assert.True(t, errors.As(err, &tooLarge), "raising the cap after it was hit must not resume the body") +} diff --git a/internal/router/handler.go b/internal/router/handler.go index 0aa0808c5..360e9b888 100644 --- a/internal/router/handler.go +++ b/internal/router/handler.go @@ -1,12 +1,15 @@ package router import ( + "encoding/json" "errors" "fmt" + "io" "net/http" "reflect" "github.com/xraph/forge/internal/shared" + "github.com/xraph/go-utils/val" "github.com/xraph/vessel" ) @@ -273,7 +276,7 @@ func convertOpinionatedHandler(info *handlerInfo, container vessel.Vessel, error // Bind request from all sources (path, query, header, body) // BindRequest handles detection of body fields internally if err := ctx.BindRequest(req.Interface()); err != nil { - handleError(ctx, BadRequest(fmt.Sprintf("invalid request: %v", err))) + handleError(ctx, bindError(err)) return } @@ -300,10 +303,7 @@ func convertOpinionatedHandler(info *handlerInfo, container vessel.Vessel, error } if !resp.IsNil() { - body := processResponse(ctx, resp) - if body != nil { - _ = ctx.JSON(http.StatusOK, body) - } + writeTypedResponse(ctx, resp) } }} } @@ -353,7 +353,7 @@ func convertCombinedHandler(info *handlerInfo, container vessel.Vessel, errorHan // Bind request from all sources (path, query, header, body) // BindRequest handles detection of body fields internally if err := ctx.BindRequest(req.Interface()); err != nil { - handleError(ctx, BadRequest(fmt.Sprintf("invalid request: %v", err))) + handleError(ctx, bindError(err)) return } @@ -381,10 +381,7 @@ func convertCombinedHandler(info *handlerInfo, container vessel.Vessel, errorHan } if !resp.IsNil() { - body := processResponse(ctx, resp) - if body != nil { - _ = ctx.JSON(http.StatusOK, body) - } + writeTypedResponse(ctx, resp) } }} } @@ -484,24 +481,35 @@ func handleError(ctx Context, err error) { }) } -// processResponse handles response struct tags using shared logic. -// - Sets header:"..." fields as HTTP response headers -// - Unwraps body:"" fields to return just the body content -// - Falls back to full struct serialization if no special tags found. -// - Cleans sensitive fields if enabled for the route. -func processResponse(ctx Context, resp reflect.Value) any { - if resp.Kind() == reflect.Pointer && resp.IsNil() { - return nil +// bindError turns a BindRequest failure into the error the client sees. +// +// The raw error used to be formatted into a 400 as "invalid request: %v". +// That leaked Go type and field names ("cannot unmarshal string into Go +// struct field transferReq.amount of type int") and answered a body over the +// size cap with 400 instead of 413. Only what the client sent is named now: a +// JSON field, never a Go type. +func bindError(err error) error { + if _, ok := errors.AsType[*http.MaxBytesError](err); ok { + return NewHTTPError(http.StatusRequestEntityTooLarge, "request body too large") } - // Check if sensitive field cleaning is enabled for this route - cleanSensitive := false + // Validation failures are written for the client: each names a request + // field and what is wrong with it. + if verr, ok := errors.AsType[*val.ValidationError](err); ok { + return BadRequest("invalid request: " + verr.Error()) + } - if v := ctx.Get(ContextKeySensitiveFieldCleaning); v != nil { - if b, ok := v.(bool); ok { - cleanSensitive = b + if typeErr, ok := errors.AsType[*json.UnmarshalTypeError](err); ok { + if typeErr.Field != "" { + return BadRequest(fmt.Sprintf("invalid request: field %q has the wrong type (got JSON %s)", typeErr.Field, typeErr.Value)) } + + return BadRequest(fmt.Sprintf("invalid request: a value has the wrong type (got JSON %s)", typeErr.Value)) + } + + if _, ok := errors.AsType[*json.SyntaxError](err); ok || errors.Is(err, io.ErrUnexpectedEOF) { + return BadRequest("invalid request: malformed JSON") } - return shared.ProcessResponseValueWithSensitive(resp.Interface(), ctx.SetHeader, cleanSensitive) + return BadRequest("invalid request") } diff --git a/internal/router/interceptor.go b/internal/router/interceptor.go index d0d4b7f2e..08a62f1ad 100644 --- a/internal/router/interceptor.go +++ b/internal/router/interceptor.go @@ -6,7 +6,9 @@ type InterceptorResult struct { // Blocked indicates the request should not proceed Blocked bool - // Error is returned when the interceptor blocks the request + // Error is returned when the interceptor blocks the request. A blocked + // result with a nil Error is answered with 403 Forbidden, never let + // through. Error error // Values to merge into the context (enrichment) @@ -25,14 +27,29 @@ func AllowWithValues(values map[string]any) InterceptorResult { return InterceptorResult{Blocked: false, Values: values} } -// Block returns a result that blocks the request with an error. +// Block returns a result that blocks the request with an error. A nil err +// still blocks, with 403 Forbidden. func Block(err error) InterceptorResult { - return InterceptorResult{Blocked: true, Error: err} + return InterceptorResult{Blocked: true, Error: blockedError(err)} } -// BlockWithValues blocks the request but still provides values (useful for debugging/logging). +// BlockWithValues blocks the request but still provides values (useful for +// debugging/logging). A nil err still blocks, with 403 Forbidden. func BlockWithValues(err error, values map[string]any) InterceptorResult { - return InterceptorResult{Blocked: true, Error: err, Values: values} + return InterceptorResult{Blocked: true, Error: blockedError(err), Values: values} +} + +// blockedError is the error a blocked request is answered with. The executor +// used to return a blocked result's Error as is, and a nil error reads as +// success to its caller, so Block(err) with an err that happened to be nil, +// or Not(x, nil), let the request through to the handler. A block always +// fails closed now. +func blockedError(err error) error { + if err != nil { + return err + } + + return Forbidden("request blocked") } // InterceptorFunc is a function that inspects a request and decides diff --git a/internal/router/interceptor_executor.go b/internal/router/interceptor_executor.go index 34a7b5066..eeb29756c 100644 --- a/internal/router/interceptor_executor.go +++ b/internal/router/interceptor_executor.go @@ -25,7 +25,8 @@ func executeInterceptors( } if result.Blocked { - return result.Error + // A result built by hand can be blocked with no error. + return blockedError(result.Error) } } diff --git a/internal/router/interceptor_failclosed_test.go b/internal/router/interceptor_failclosed_test.go new file mode 100644 index 000000000..a429df812 --- /dev/null +++ b/internal/router/interceptor_failclosed_test.go @@ -0,0 +1,75 @@ +package router + +import ( + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// A blocked result whose Error is nil used to reach the handler: the executor +// returned the nil error, and nil reads as success. Every way of producing +// such a result has to answer 403 and leave the handler alone. +func TestInterceptor_BlockWithNilErrorFailsClosed(t *testing.T) { + var nilErr error + + allow := InterceptorFromFunc(func(ctx Context, route RouteInfo) InterceptorResult { return Allow() }) + deny := InterceptorFromFunc(func(ctx Context, route RouteInfo) InterceptorResult { return Block(nilErr) }) + rawDeny := InterceptorFromFunc(func(ctx Context, route RouteInfo) InterceptorResult { + return InterceptorResult{Blocked: true} + }) + + cases := map[string]Interceptor{ + "Block(nil)": deny, + "BlockWithValues(nil)": InterceptorFromFunc(func(ctx Context, route RouteInfo) InterceptorResult { + return BlockWithValues(nil, map[string]any{"k": 1}) + }), + "hand-built result": rawDeny, + "Not(allow, nil)": Not(allow, nil), + "Or(raw, raw)": Or(rawDeny, rawDeny), + "And(allow, raw)": And(allow, rawDeny), + "Parallel(allow, raw)": Parallel(allow, rawDeny), + "ParallelAny(raw, raw)": ParallelAny(rawDeny, rawDeny), + "When(true, raw)": When(func(Context, RouteInfo) bool { return true }, rawDeny), + "Parallel(nested Not nil)": Parallel(Not(allow, nil)), + "Or(Not(allow,nil), raw deny)": Or(Not(allow, nil), rawDeny), + } + + for name, in := range cases { + t.Run(name, func(t *testing.T) { + var ran atomic.Int32 + + r := NewRouter() + require.NoError(t, r.GET("/admin", func(ctx Context) error { + ran.Add(1) + + return ctx.String(http.StatusOK, "secret") + }, WithInterceptor(in))) + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/admin", nil)) + + assert.Equal(t, http.StatusForbidden, rec.Code) + assert.NotContains(t, rec.Body.String(), "secret") + assert.Zero(t, ran.Load(), "handler must not run") + }) + } +} + +func TestInterceptorChain_BlockWithNilErrorReturnsError(t *testing.T) { + chain := NewInterceptorChain([]Interceptor{ + InterceptorFromFunc(func(ctx Context, route RouteInfo) InterceptorResult { + return InterceptorResult{Blocked: true} + }), + }, nil) + + err := chain.Execute(nil, RouteInfo{}) + require.Error(t, err) + + var httpErr interface{ StatusCode() int } + require.ErrorAs(t, err, &httpErr) + assert.Equal(t, http.StatusForbidden, httpErr.StatusCode()) +} diff --git a/internal/router/interceptor_parallel.go b/internal/router/interceptor_parallel.go index 4cf194984..be39a3b08 100644 --- a/internal/router/interceptor_parallel.go +++ b/internal/router/interceptor_parallel.go @@ -80,23 +80,24 @@ func Parallel(interceptors ...Interceptor) Interceptor { // Collect results mergedValues := make(map[string]any) - var firstBlockError error + // Track the block separately from its error. Testing the error for + // nil let a block that carried no error through as an allow. + var ( + blocked bool + firstBlockError error + ) for pr := range results { - if pr.result.Blocked { - if firstBlockError == nil { - firstBlockError = pr.result.Error - } - - // Still collect values for debugging - maps.Copy(mergedValues, pr.result.Values) - } else { - // Merge values from successful interceptors - maps.Copy(mergedValues, pr.result.Values) + if pr.result.Blocked && !blocked { + blocked = true + firstBlockError = pr.result.Error } + + // Values are kept from blocked interceptors too, for debugging. + maps.Copy(mergedValues, pr.result.Values) } - if firstBlockError != nil { + if blocked { return BlockWithValues(firstBlockError, mergedValues) } diff --git a/internal/router/interceptors.go b/internal/router/interceptors.go index a7719b38b..288357cdb 100644 --- a/internal/router/interceptors.go +++ b/internal/router/interceptors.go @@ -386,70 +386,6 @@ func RateLimit(keyName string, checker func(ctx Context, key string) RateLimitRe }) } -// RateLimitByIP creates a rate limit interceptor keyed by client IP. -func RateLimitByIP(checker func(ctx Context, ip string) RateLimitResult) Interceptor { - return NewInterceptor("rate-limit:ip", func(ctx Context, route RouteInfo) InterceptorResult { - // Get client IP (simplified - in production, parse X-Forwarded-For, etc.) - clientIP := ctx.Request().RemoteAddr - - result := checker(ctx, clientIP) - - values := map[string]any{ - "ratelimit.remaining": result.Remaining, - "ratelimit.reset": result.ResetAt, - } - - if !result.Allowed { - return InterceptorResult{ - Blocked: true, - Error: NewHTTPError(429, "rate limit exceeded"), - Values: values, - } - } - - return AllowWithValues(values) - }) -} - -// --- IP/Network Interceptors --- - -// AllowIPs creates an interceptor that only allows specific IP addresses. -func AllowIPs(allowedIPs ...string) Interceptor { - ipSet := make(map[string]bool) - for _, ip := range allowedIPs { - ipSet[ip] = true - } - - return NewInterceptor("allow-ips", func(ctx Context, route RouteInfo) InterceptorResult { - clientIP := ctx.Request().RemoteAddr - // Note: In production, parse X-Forwarded-For, X-Real-IP, etc. - - if !ipSet[clientIP] { - return Block(Forbidden("IP not allowed")) - } - - return Allow() - }) -} - -// DenyIPs creates an interceptor that blocks specific IP addresses. -func DenyIPs(deniedIPs ...string) Interceptor { - ipSet := make(map[string]bool) - for _, ip := range deniedIPs { - ipSet[ip] = true - } - - return NewInterceptor("deny-ips", func(ctx Context, route RouteInfo) InterceptorResult { - clientIP := ctx.Request().RemoteAddr - - if ipSet[clientIP] { - return Block(Forbidden("IP blocked")) - } - - return Allow() - }) -} - // --- Time-Based Interceptors --- // TimeWindow creates an interceptor that only allows requests during specific hours. diff --git a/internal/router/interceptors_ip.go b/internal/router/interceptors_ip.go new file mode 100644 index 000000000..3e1f16b48 --- /dev/null +++ b/internal/router/interceptors_ip.go @@ -0,0 +1,184 @@ +package router + +import ( + "fmt" + "net" + "net/http" + "net/netip" + "strings" +) + +// The IP interceptors below read the peer address from Request.RemoteAddr. +// net/http sets that to "ip:port", and the port is the client's ephemeral +// port, so comparing RemoteAddr verbatim against a configured address never +// matches: DenyIPs let every listed address through, AllowIPs refused +// everyone, and RateLimitByIP gave every connection its own bucket. The +// address is now split from its port and parsed, and the lists accept CIDR +// ranges as well as single addresses. +// +// X-Forwarded-For and X-Real-IP are deliberately ignored, the same as +// middleware.ClientIP. A header is whatever the client chose to send, so +// trusting it unconditionally would let anyone pick the address these +// interceptors judge. Behind a trusted proxy, rewrite RemoteAddr from the +// forwarded header in a middleware that knows which hops to trust. + +// RemoteIP returns the client address of r, parsed from RemoteAddr with the +// port removed. An IPv4 address carried as IPv4-mapped IPv6 (::ffff:a.b.c.d), +// which a dual-stack listener reports, is returned as plain IPv4 and any IPv6 +// zone is dropped, so the result compares equal to the address an operator +// would write. ok is false when RemoteAddr holds no parseable address. +func RemoteIP(r *http.Request) (addr netip.Addr, ok bool) { + if r == nil { + return netip.Addr{}, false + } + + return parseRemoteAddr(r.RemoteAddr) +} + +func parseRemoteAddr(remote string) (netip.Addr, bool) { + host := remote + if h, _, err := net.SplitHostPort(remote); err == nil { + host = h + } + + // SplitHostPort fails on a bare address with no port, which some test + // servers and unix sockets produce. A bare IPv6 address may still carry + // brackets. + host = strings.TrimSuffix(strings.TrimPrefix(host, "["), "]") + + addr, err := netip.ParseAddr(host) + if err != nil { + return netip.Addr{}, false + } + + return addr.WithZone("").Unmap(), true +} + +// ipMatcher tests an address against a set of single addresses and ranges. +type ipMatcher struct { + prefixes []netip.Prefix +} + +// newIPMatcher parses each entry as a single address ("203.0.113.9", +// "2001:db8::1") or a CIDR range ("10.0.0.0/8", "2001:db8::/32"). An entry +// that is neither panics, naming the entry. These lists are configuration, +// and quietly skipping a typo would make DenyIPs let the address through. +func newIPMatcher(name string, entries []string) ipMatcher { + m := ipMatcher{prefixes: make([]netip.Prefix, 0, len(entries))} + + for _, raw := range entries { + p, err := parseIPEntry(raw) + if err != nil { + panic(fmt.Sprintf("router: %s: %v", name, err)) + } + + m.prefixes = append(m.prefixes, p) + } + + return m +} + +func parseIPEntry(raw string) (netip.Prefix, error) { + entry := strings.TrimSpace(raw) + + if strings.Contains(entry, "/") { + p, err := netip.ParsePrefix(entry) + if err != nil { + return netip.Prefix{}, fmt.Errorf("invalid CIDR range %q: %w", raw, err) + } + + // A range written in IPv4-mapped form (::ffff:10.0.0.0/104) is + // rewritten as the IPv4 range it covers, because client addresses + // are unmapped before they are compared. + if p.Addr().Is4In6() && p.Bits() >= 96 { + p = netip.PrefixFrom(p.Addr().Unmap(), p.Bits()-96) + } + + return p.Masked(), nil + } + + addr, err := netip.ParseAddr(entry) + if err != nil { + return netip.Prefix{}, fmt.Errorf("invalid IP address %q: %w", raw, err) + } + + addr = addr.WithZone("").Unmap() + + return netip.PrefixFrom(addr, addr.BitLen()), nil +} + +func (m ipMatcher) contains(addr netip.Addr) bool { + for _, p := range m.prefixes { + if p.Contains(addr) { + return true + } + } + + return false +} + +// RateLimitByIP creates a rate limit interceptor keyed by client IP. The key +// is the address from RemoteAddr without its port, in canonical form, so every +// connection from one client shares a bucket. When RemoteAddr cannot be +// parsed, the raw RemoteAddr is used as the key. +func RateLimitByIP(checker func(ctx Context, ip string) RateLimitResult) Interceptor { + return NewInterceptor("rate-limit:ip", func(ctx Context, route RouteInfo) InterceptorResult { + key := ctx.Request().RemoteAddr + if addr, ok := RemoteIP(ctx.Request()); ok { + key = addr.String() + } + + result := checker(ctx, key) + + values := map[string]any{ + "ratelimit.remaining": result.Remaining, + "ratelimit.reset": result.ResetAt, + } + + if !result.Allowed { + return InterceptorResult{ + Blocked: true, + Error: NewHTTPError(429, "rate limit exceeded"), + Values: values, + } + } + + return AllowWithValues(values) + }) +} + +// --- IP/Network Interceptors --- + +// AllowIPs creates an interceptor that only allows the listed clients. Each +// entry is a single address or a CIDR range, IPv4 or IPv6. A request whose +// address cannot be determined is refused. It panics on an entry that is +// neither an address nor a range. +func AllowIPs(allowedIPs ...string) Interceptor { + m := newIPMatcher("AllowIPs", allowedIPs) + + return NewInterceptor("allow-ips", func(ctx Context, route RouteInfo) InterceptorResult { + addr, ok := RemoteIP(ctx.Request()) + if !ok || !m.contains(addr) { + return Block(Forbidden("IP not allowed")) + } + + return Allow() + }) +} + +// DenyIPs creates an interceptor that blocks the listed clients. Each entry is +// a single address or a CIDR range, IPv4 or IPv6. A request whose address +// cannot be determined is also blocked, because it cannot be shown not to be +// on the list. It panics on an entry that is neither an address nor a range. +func DenyIPs(deniedIPs ...string) Interceptor { + m := newIPMatcher("DenyIPs", deniedIPs) + + return NewInterceptor("deny-ips", func(ctx Context, route RouteInfo) InterceptorResult { + addr, ok := RemoteIP(ctx.Request()) + if !ok || m.contains(addr) { + return Block(Forbidden("IP blocked")) + } + + return Allow() + }) +} diff --git a/internal/router/interceptors_ip_test.go b/internal/router/interceptors_ip_test.go new file mode 100644 index 000000000..bd8adc527 --- /dev/null +++ b/internal/router/interceptors_ip_test.go @@ -0,0 +1,116 @@ +package router + +import ( + "fmt" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// serveFrom sends one GET to r with RemoteAddr set to remote and returns the +// status. +func serveFrom(t *testing.T, r Router, remote string) int { + t.Helper() + + req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/x", nil) + req.RemoteAddr = remote + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + return rec.Code +} + +func ipRouter(t *testing.T, in Interceptor) Router { + t.Helper() + + r := NewRouter() + require.NoError(t, r.GET("/x", func(ctx Context) error { + return ctx.String(http.StatusOK, "ok") + }, WithInterceptor(in))) + + return r +} + +// net/http sets RemoteAddr to "ip:port". The IP interceptors used to compare +// that string verbatim, so DenyIPs never matched and AllowIPs matched nobody. +func TestDenyIPs_MatchesRemoteAddrWithPort(t *testing.T) { + r := ipRouter(t, DenyIPs("203.0.113.9", "10.0.0.0/8", "2001:db8::/32")) + + cases := []struct { + remote string + want int + }{ + {"203.0.113.9:51234", http.StatusForbidden}, + {"10.20.30.40:443", http.StatusForbidden}, + {"[2001:db8::7]:8080", http.StatusForbidden}, + {"[::ffff:203.0.113.9]:51234", http.StatusForbidden}, // dual-stack listener + {"[2001:db8::7%eth0]:8080", http.StatusForbidden}, // zone dropped + {"203.0.113.9", http.StatusForbidden}, // no port + {"198.51.100.1:51234", http.StatusOK}, + {"[2001:db9::1]:8080", http.StatusOK}, + {"not-an-address", http.StatusForbidden}, // unparseable fails closed + } + + for _, tc := range cases { + t.Run(tc.remote, func(t *testing.T) { + assert.Equal(t, tc.want, serveFrom(t, r, tc.remote)) + }) + } +} + +func TestAllowIPs_MatchesRemoteAddrWithPort(t *testing.T) { + r := ipRouter(t, AllowIPs("203.0.113.9", "192.168.0.0/16", "::ffff:172.16.0.0/108", "2001:db8::1")) + + cases := []struct { + remote string + want int + }{ + {"203.0.113.9:51234", http.StatusOK}, + {"192.168.4.5:1", http.StatusOK}, + {"172.16.9.9:1", http.StatusOK}, // mapped range written by the operator + {"[::ffff:192.168.4.5]:1", http.StatusOK}, + {"[2001:db8::1]:443", http.StatusOK}, + {"203.0.113.10:51234", http.StatusForbidden}, + {"[2001:db8::2]:443", http.StatusForbidden}, + {"", http.StatusForbidden}, + } + + for _, tc := range cases { + t.Run(tc.remote, func(t *testing.T) { + assert.Equal(t, tc.want, serveFrom(t, r, tc.remote)) + }) + } +} + +func TestRateLimitByIP_KeysOnAddressNotConnection(t *testing.T) { + keys := map[string]int{} + r := ipRouter(t, RateLimitByIP(func(ctx Context, ip string) RateLimitResult { + keys[ip]++ + + return RateLimitResult{Allowed: true} + })) + + for i := range 5 { + serveFrom(t, r, fmt.Sprintf("203.0.113.9:%d", 50000+i)) + serveFrom(t, r, fmt.Sprintf("[::ffff:203.0.113.9]:%d", 50000+i)) + } + + assert.Equal(t, map[string]int{"203.0.113.9": 10}, keys) +} + +func TestIPInterceptors_PanicOnInvalidEntry(t *testing.T) { + defer func() { + msg := fmt.Sprint(recover()) + assert.Contains(t, msg, "DenyIPs") + assert.Contains(t, msg, `"203.0.113.9:80"`) + }() + + assert.Panics(t, func() { AllowIPs("10.0.0.0/33") }) + assert.Panics(t, func() { AllowIPs("example.com") }) + + DenyIPs("203.0.113.9:80") +} diff --git a/internal/router/response.go b/internal/router/response.go new file mode 100644 index 000000000..b51fd51a9 --- /dev/null +++ b/internal/router/response.go @@ -0,0 +1,396 @@ +package router + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "reflect" + "sync" + + "github.com/xraph/forge/internal/shared" +) + +// This file turns a typed handler's response value into the JSON body. +// +// It replaces a path that processed every response twice. The router ran +// shared.ProcessResponseValueWithSensitive (headers, body unwrapping, +// sensitive-field cleaning) and then handed the result to ctx.JSON, which ran +// the same processing again in go-utils. With WithSensitiveFieldCleaning the +// whole response was deep-copied twice, and a body:"" field whose value had +// header or body tags of its own was unwrapped a second time. The router now +// processes once and writes the encoded body itself. +// +// The cleaning also built each struct copy from a zero value and filled in +// only the exported fields, so every unexported field was lost: a time.Time +// (all unexported fields) became 0001-01-01T00:00:00Z. A struct copy now +// starts from the original value, and a type that holds nothing to clean, +// such as time.Time, is not copied at all. + +// writeTypedResponse processes resp (headers, body unwrapping, sensitive +// fields) and writes it as a 200 JSON response. +func writeTypedResponse(ctx Context, resp reflect.Value) { + body := processResponse(ctx, resp) + if body == nil { + return + } + + writeJSONBody(ctx, http.StatusOK, body) +} + +// processResponse handles response struct tags: +// - sets header:"..." fields as HTTP response headers, +// - unwraps a body:"" field to return just its content, +// - otherwise returns the whole value, +// - cleans sensitive fields first when the route enables it. +func processResponse(ctx Context, resp reflect.Value) any { + if resp.Kind() == reflect.Pointer && resp.IsNil() { + return nil + } + + cleanSensitive := false + if b, ok := ctx.Get(ContextKeySensitiveFieldCleaning).(bool); ok { + cleanSensitive = b + } + + return processResponseValue(resp.Interface(), ctx.SetHeader, cleanSensitive) +} + +// processResponseValue is processResponse on a plain value. +func processResponseValue(v any, setHeader func(name, value string), cleanSensitive bool) any { + if v == nil { + return nil + } + + if cleanSensitive { + v = cleanSensitiveFields(v) + } + + rv := reflect.ValueOf(v) + if rv.Kind() == reflect.Pointer { + if rv.IsNil() { + return nil + } + + rv = rv.Elem() + } + + if rv.Kind() != reflect.Struct { + return v + } + + tags := responseTagsFor(rv.Type()) + + for _, h := range tags.headers { + if f := rv.Field(h.index); !f.IsZero() && setHeader != nil { + setHeader(h.name, fmt.Sprint(f.Interface())) + } + } + + if tags.body >= 0 { + return rv.Field(tags.body).Interface() + } + + return v +} + +// responseTags is where a response struct's header:"..." and body:"" fields +// are. Computed once per type. +type responseTags struct { + headers []headerField + body int // index of the body:"" field, -1 if none +} + +type headerField struct { + index int + name string +} + +var responseTagCache sync.Map // reflect.Type -> *responseTags + +func responseTagsFor(t reflect.Type) *responseTags { + if v, ok := responseTagCache.Load(t); ok { + return v.(*responseTags) //nolint:forcetypeassert // only *responseTags is stored + } + + tags := &responseTags{body: -1} + + for i := range t.NumField() { + field := t.Field(i) + if !field.IsExported() { + continue + } + + if name := field.Tag.Get("header"); name != "" && name != "-" { + tags.headers = append(tags.headers, headerField{index: i, name: name}) + } + + // The last body:"" field wins, as it always has. + if bodyTag, ok := field.Tag.Lookup("body"); ok && bodyTag == "" { + tags.body = i + } + } + + v, _ := responseTagCache.LoadOrStore(t, tags) + + return v.(*responseTags) //nolint:forcetypeassert // only *responseTags is stored +} + +var jsonBufferPool = sync.Pool{ + New: func() any { return new(bytes.Buffer) }, +} + +// maxPooledBuffer keeps one huge response from pinning its buffer in the pool. +const maxPooledBuffer = 1 << 20 + +// writeJSONBody encodes body and writes it with status. The body is encoded +// before anything is written, so a value that cannot be encoded becomes a 500 +// instead of a 200 with a truncated body. The output matches ctx.JSON: the +// same encoder settings and a trailing newline. +func writeJSONBody(ctx Context, status int, body any) { + buf, _ := jsonBufferPool.Get().(*bytes.Buffer) + if buf == nil { + buf = new(bytes.Buffer) + } + + buf.Reset() + + defer func() { + if buf.Cap() <= maxPooledBuffer { + jsonBufferPool.Put(buf) + } + }() + + if err := json.NewEncoder(buf).Encode(body); err != nil { + handleError(ctx, InternalError(fmt.Errorf("failed to encode JSON response: %w", err))) + + return + } + + w := ctx.Response() + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = w.Write(buf.Bytes()) +} + +// cleanSensitiveFields returns v with every sensitive:"..." field cleaned. A +// value whose type holds nothing to clean is returned as is; anything else is +// copied, so v itself is never changed. +func cleanSensitiveFields(v any) any { + if v == nil { + return nil + } + + return cleanSensitiveValue(reflect.ValueOf(v)).Interface() +} + +func cleanSensitiveValue(rv reflect.Value) reflect.Value { + if !rv.IsValid() || !typeNeedsCleaning(rv.Type()) { + return rv + } + + switch rv.Kind() { + case reflect.Pointer: + if rv.IsNil() { + return rv + } + + out := reflect.New(rv.Type().Elem()) + out.Elem().Set(cleanSensitiveValue(rv.Elem())) + + return out + + case reflect.Interface: + if rv.IsNil() { + return rv + } + + return cleanSensitiveValue(rv.Elem()) + + case reflect.Struct: + return cleanSensitiveStruct(rv) + + case reflect.Slice: + if rv.IsNil() { + return rv + } + + out := reflect.MakeSlice(rv.Type(), rv.Len(), rv.Len()) + for i := range rv.Len() { + out.Index(i).Set(cleanSensitiveValue(rv.Index(i))) + } + + return out + + case reflect.Array: + out := reflect.New(rv.Type()).Elem() + for i := range rv.Len() { + out.Index(i).Set(cleanSensitiveValue(rv.Index(i))) + } + + return out + + case reflect.Map: + if rv.IsNil() { + return rv + } + + out := reflect.MakeMapWithSize(rv.Type(), rv.Len()) + + iter := rv.MapRange() + for iter.Next() { + out.SetMapIndex(iter.Key(), cleanSensitiveValue(iter.Value())) + } + + return out + + default: + return rv + } +} + +// cleanSensitiveStruct copies rv, unexported fields included, then cleans the +// exported fields that are tagged sensitive or hold something that is. +func cleanSensitiveStruct(rv reflect.Value) reflect.Value { + out := reflect.New(rv.Type()).Elem() + out.Set(rv) + + for _, f := range sensitivePlanFor(rv.Type()).fields { + if f.config != nil { + out.Field(f.index).Set(applySensitiveCleaning(f.typ, f.config)) + } else { + out.Field(f.index).Set(cleanSensitiveValue(rv.Field(f.index))) + } + } + + return out +} + +// sensitivePlan lists the exported fields of a struct type that cleaning has +// to touch, with their parsed sensitive tags. Computed once per type. +type sensitivePlan struct { + fields []sensitiveField +} + +type sensitiveField struct { + index int + typ reflect.Type + config *shared.SensitiveFieldConfig // nil: recurse into the field +} + +var ( + sensitivePlanCache sync.Map // reflect.Type -> *sensitivePlan + needsCleaningCache sync.Map // reflect.Type -> bool +) + +func sensitivePlanFor(t reflect.Type) *sensitivePlan { + if v, ok := sensitivePlanCache.Load(t); ok { + return v.(*sensitivePlan) //nolint:forcetypeassert // only *sensitivePlan is stored + } + + plan := &sensitivePlan{} + + for i := range t.NumField() { + field := t.Field(i) + if !field.IsExported() { + continue + } + + if config := shared.ParseSensitiveTag(field.Tag.Get("sensitive")); config != nil { + plan.fields = append(plan.fields, sensitiveField{index: i, typ: field.Type, config: config}) + } else if typeNeedsCleaning(field.Type) { + plan.fields = append(plan.fields, sensitiveField{index: i, typ: field.Type}) + } + } + + v, _ := sensitivePlanCache.LoadOrStore(t, plan) + + return v.(*sensitivePlan) //nolint:forcetypeassert // only *sensitivePlan is stored +} + +// typeNeedsCleaning reports whether a value of type t can hold a sensitive +// field. Values of other types are passed through without a copy. +func typeNeedsCleaning(t reflect.Type) bool { + if v, ok := needsCleaningCache.Load(t); ok { + return v.(bool) //nolint:forcetypeassert // only bool is stored + } + + needs := computeNeedsCleaning(t, map[reflect.Type]bool{}) + needsCleaningCache.Store(t, needs) + + return needs +} + +// computeNeedsCleaning walks t. A type met again while it is still being +// walked is a recursive type, and is assumed to need cleaning: that can only +// cost a copy, never skip a sensitive field. +func computeNeedsCleaning(t reflect.Type, walking map[reflect.Type]bool) bool { + if v, ok := needsCleaningCache.Load(t); ok { + return v.(bool) //nolint:forcetypeassert // only bool is stored + } + + if walking[t] { + return true + } + + walking[t] = true + defer delete(walking, t) + + switch t.Kind() { + case reflect.Interface: + // The dynamic value could be anything. + return true + case reflect.Pointer, reflect.Slice, reflect.Array, reflect.Map: + return computeNeedsCleaning(t.Elem(), walking) + case reflect.Struct: + for field := range t.Fields() { + if !field.IsExported() { + continue + } + + if shared.ParseSensitiveTag(field.Tag.Get("sensitive")) != nil { + return true + } + + if computeNeedsCleaning(field.Type, walking) { + return true + } + } + + return false + default: + return false + } +} + +// applySensitiveCleaning returns the value a sensitive field of type t is +// replaced with. +func applySensitiveCleaning(t reflect.Type, config *shared.SensitiveFieldConfig) reflect.Value { + switch config.Mode { + case shared.SensitiveModeRedact: + return replacementString(t, "[REDACTED]") + case shared.SensitiveModeMask: + return replacementString(t, config.Mask) + default: + return reflect.Zero(t) + } +} + +// replacementString returns s as a value of t when t is a string or a pointer +// to one, and the zero value of t otherwise. +func replacementString(t reflect.Type, s string) reflect.Value { + switch { + case t.Kind() == reflect.String: + v := reflect.New(t).Elem() + v.SetString(s) + + return v + case t.Kind() == reflect.Pointer && t.Elem().Kind() == reflect.String: + v := reflect.New(t.Elem()) + v.Elem().SetString(s) + + return v + default: + return reflect.Zero(t) + } +} diff --git a/internal/router/response_bench_test.go b/internal/router/response_bench_test.go new file mode 100644 index 000000000..105029bd0 --- /dev/null +++ b/internal/router/response_bench_test.go @@ -0,0 +1,69 @@ +package router + +import ( + "bytes" + "fmt" + "net/http" + "net/http/httptest" + "testing" +) + +type benchSensitiveItem struct { + ID int `json:"id"` + Name string `json:"name"` + Password string `json:"password" sensitive:"true"` +} + +type benchSensitiveList struct { + Items []benchSensitiveItem `json:"items"` +} + +type benchSensitiveReq struct { + Slug string `json:"slug"` +} + +// BenchmarkOpinionatedHandler_SensitiveCleaning serves a typed handler that +// returns a 100 item list, with and without WithSensitiveFieldCleaning. The +// response used to be processed twice, once by the router and again inside +// ctx.JSON, so with cleaning on the whole list was deep-copied twice. +func BenchmarkOpinionatedHandler_SensitiveCleaning(b *testing.B) { + items := make([]benchSensitiveItem, 100) + for i := range items { + items[i] = benchSensitiveItem{ID: i, Name: "n", Password: "p"} + } + + body := []byte(`{"slug":"a"}`) + + for _, clean := range []bool{false, true} { + b.Run(fmt.Sprintf("sensitive=%v", clean), func(b *testing.B) { + r := NewRouter() + + var opts []RouteOption + if clean { + opts = append(opts, WithSensitiveFieldCleaning()) + } + + if err := r.POST("/x", func(ctx Context, req *benchSensitiveReq) (*benchSensitiveList, error) { + return &benchSensitiveList{Items: items}, nil + }, opts...); err != nil { + b.Fatal(err) + } + + rd := bytes.NewReader(body) + req := httptest.NewRequestWithContext(b.Context(), http.MethodPost, "/x", nil) + req.Header.Set("Content-Type", "application/json") + + w := &benchWriter{} + + b.ReportAllocs() + + for b.Loop() { + clear(w.h) + rd.Reset(body) + req.Body = nopCloser{rd} + req.ContentLength = int64(len(body)) + r.ServeHTTP(w, req) + } + }) + } +} diff --git a/internal/router/response_test.go b/internal/router/response_test.go new file mode 100644 index 000000000..c53c64cc6 --- /dev/null +++ b/internal/router/response_test.go @@ -0,0 +1,178 @@ +package router + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type cleanedEvent struct { + Created time.Time `json:"created"` + Expires *time.Time `json:"expires"` + Secret string `json:"secret" sensitive:"true"` + Note string `json:"note"` +} + +type emptyReq struct{} + +func serveTyped[T any](t *testing.T, handler func(Context, *emptyReq) (*T, error), opts ...RouteOption) *httptest.ResponseRecorder { + t.Helper() + + r := NewRouter() + require.NoError(t, r.POST("/x", handler, opts...)) + + req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/x", bytes.NewReader([]byte(`{}`))) + req.Header.Set("Content-Type", "application/json") + + rec := httptest.NewRecorder() + r.ServeHTTP(rec, req) + + return rec +} + +// Cleaning built each struct copy from a zero value and filled in only the +// exported fields, so a time.Time, whose fields are all unexported, came out +// as 0001-01-01T00:00:00Z. +func TestSensitiveCleaning_KeepsTimeValues(t *testing.T) { + created := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) + expires := created.Add(time.Hour) + + rec := serveTyped(t, func(ctx Context, _ *emptyReq) (*cleanedEvent, error) { + return &cleanedEvent{Created: created, Expires: &expires, Secret: "s", Note: "n"}, nil + }, WithSensitiveFieldCleaning()) + + require.Equal(t, http.StatusOK, rec.Code) + + var got cleanedEvent + require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &got)) + + assert.True(t, got.Created.Equal(created), "created = %v", got.Created) + require.NotNil(t, got.Expires) + assert.True(t, got.Expires.Equal(expires), "expires = %v", got.Expires) + assert.Empty(t, got.Secret) + assert.Equal(t, "n", got.Note) +} + +type withUnexported struct { + Name string `json:"name"` + Password string `json:"password" sensitive:"true"` + cache string +} + +func (w withUnexported) MarshalJSON() ([]byte, error) { + type plain struct { + Name string `json:"name"` + Password string `json:"password"` + Cache string `json:"cache"` + } + + return json.Marshal(plain{Name: w.Name, Password: w.Password, Cache: w.cache}) +} + +// A type with its own MarshalJSON sees its unexported state, and its +// sensitive fields are still cleaned. +func TestSensitiveCleaning_KeepsUnexportedStateAndCleansMarshalers(t *testing.T) { + in := withUnexported{Name: "a", Password: "p", cache: "c"} + + out, ok := cleanSensitiveFields(in).(withUnexported) + require.True(t, ok) + assert.Equal(t, withUnexported{Name: "a", cache: "c"}, out) + assert.Equal(t, "p", in.Password, "the original must not be changed") +} + +type namedSecret string + +type namedHolder struct { + Key namedSecret `json:"key" sensitive:"redact"` + Mask *namedSecret `json:"mask" sensitive:"mask:***"` + Any any `json:"any"` + Next *namedHolder `json:"next"` +} + +func TestSensitiveCleaning_NamedStringsInterfacesAndRecursion(t *testing.T) { + m := namedSecret("m") + in := &namedHolder{ + Key: "k", + Mask: &m, + Any: UserResponse{ID: "1", Password: "p"}, + Next: &namedHolder{Key: "k2", Any: map[string]any{"u": &UserResponse{Password: "p2"}}}, + } + + out, ok := cleanSensitiveFields(in).(*namedHolder) + require.True(t, ok) + + assert.Equal(t, namedSecret("[REDACTED]"), out.Key) + require.NotNil(t, out.Mask) + assert.Equal(t, namedSecret("***"), *out.Mask) + assert.Equal(t, UserResponse{ID: "1", APIKey: "[REDACTED]", Token: "***"}, out.Any) + assert.Equal(t, namedSecret("[REDACTED]"), out.Next.Key) + + nested, ok := out.Next.Any.(map[string]any)["u"].(*UserResponse) + require.True(t, ok) + assert.Empty(t, nested.Password) + + // The input is untouched. + assert.Equal(t, namedSecret("k"), in.Key) + assert.Equal(t, namedSecret("m"), m) + assert.Equal(t, "p2", in.Next.Any.(map[string]any)["u"].(*UserResponse).Password) +} + +type plainList struct { + Items []struct { + ID int `json:"id"` + } `json:"items"` +} + +// A value that holds nothing to clean is not copied. +func TestSensitiveCleaning_PassesThroughTypesWithNothingToClean(t *testing.T) { + in := &plainList{} + assert.Same(t, in, cleanSensitiveFields(in)) + + now := time.Now() + assert.Equal(t, now, cleanSensitiveFields(now)) +} + +type innerTagged struct { + Trace string `header:"X-Inner"` + Data string `body:""` +} + +type outerTagged struct { + Request string `header:"X-Request-ID"` + Payload innerTagged `body:""` +} + +// The response used to be processed twice: once by the router and again +// inside ctx.JSON. A body:"" value with header or body tags of its own was +// unwrapped a second time. +func TestTypedResponse_ProcessedOnce(t *testing.T) { + rec := serveTyped(t, func(ctx Context, _ *emptyReq) (*outerTagged, error) { + return &outerTagged{Request: "r1", Payload: innerTagged{Trace: "t1", Data: "d1"}}, nil + }) + + require.Equal(t, http.StatusOK, rec.Code) + assert.Equal(t, "r1", rec.Header().Get("X-Request-ID")) + assert.Empty(t, rec.Header().Get("X-Inner"), "the unwrapped body must not be processed again") + assert.Equal(t, "application/json", rec.Header().Get("Content-Type")) + assert.JSONEq(t, `{"Trace":"t1","Data":"d1"}`, rec.Body.String()) +} + +type unencodable struct { + C chan int `json:"c"` +} + +// The body is encoded before anything is written, so a value that cannot be +// encoded is a 500 rather than a 200 with a broken body. +func TestTypedResponse_EncodeFailureIs500(t *testing.T) { + rec := serveTyped(t, func(ctx Context, _ *emptyReq) (*unencodable, error) { + return &unencodable{C: make(chan int)}, nil + }) + + assert.Equal(t, http.StatusInternalServerError, rec.Code) +} diff --git a/internal/router/router.go b/internal/router/router.go index d1644e7bf..2c25d4772 100644 --- a/internal/router/router.go +++ b/internal/router/router.go @@ -418,13 +418,21 @@ func WithStreamObserver(o shared.StreamObserver) RouterOption { return &streamObserverOpt{o} } -// WithMaxRequestBodySize caps the request body for every route on this router, -// in bytes. Bodies exceeding the cap fail the read with a 413-shaped error -// instead of allocating without bound. +// WithMaxRequestBodySize caps the request body for every request this router +// serves, in bytes. Bodies exceeding the cap fail the read with a 413-shaped +// error instead of allocating without bound. +// +// The cap is installed as the request enters the router, so it also bounds +// UseGlobal middleware, requests that match no route, and handlers mounted +// with Handle. A route's WithMaxBodySize replaces it for that route's handler +// and route middleware, raising or lowering it. Global middleware runs before +// the route is known, so a global middleware that reads the whole body is +// held to this cap even on a route that raises its own. // // Defaults to DefaultMaxRequestBodySize. Pass a negative value to disable the // limit entirely (not recommended on internet-facing routes); override per route -// with WithMaxBodySize for upload endpoints. +// with WithMaxBodySize for upload endpoints, or call SetRequestBodyLimit from a +// mounted handler. func WithMaxRequestBodySize(bytes int64) RouterOption { return &maxBodySizeOpt{bytes} } diff --git a/internal/router/router_impl.go b/internal/router/router_impl.go index bcc54cd43..2548d7e9f 100644 --- a/internal/router/router_impl.go +++ b/internal/router/router_impl.go @@ -319,6 +319,10 @@ func (r *router) Any(path string, handler any, opts ...RouteOption) error { // or other routers. Unlike Any(), Handle() bypasses the forge handler conversion // and middleware system - the handler receives requests directly. // +// The router-wide body cap (WithMaxRequestBodySize) still applies, since a +// mounted handler has no route options to set its own. A mounted upload +// endpoint that needs more calls SetRequestBodyLimit before reading. +// // Example: // // // Mount a file server @@ -558,6 +562,17 @@ func (r *router) Stop(ctx context.Context) error { // ServeHTTP implements http.Handler. func (r *router) ServeHTTP(w http.ResponseWriter, req *http.Request) { + // Cap the body here, before global middleware, route matching, 404 and + // 405 handling or a mounted handler can read it. A route raises or + // lowers this cap in its own wrapper. See limitedBody. + if req.Body != nil && req.Body != http.NoBody { + if _, wrapped := req.Body.(*limitedBody); !wrapped { + if limit := r.resolveMaxBodySize(0); limit > 0 { + req.Body = newLimitedBody(w, req.Body, limit) + } + } + } + // Middleware is applied during route registration (see register() method), // so we just delegate to the adapter which has routes with middleware already applied. // This prevents double-wrapping of middleware. @@ -1070,14 +1085,14 @@ func applyMiddlewareAndInterceptors( r = r.WithContext(context.WithValue(r.Context(), forge_http.ContextKeyForSensitiveCleaning, true)) } - // Cap the request body before any handler, binder or middleware can - // read it. Without this, decoding is bounded only by what the client - // chooses to send, so a single unauthenticated request can drive - // arbitrary allocation. MaxBytesReader also signals the server to - // close the connection once the cap is hit. - if maxBodySize > 0 && r.Body != nil { - r.Body = http.MaxBytesReader(w, r.Body, maxBodySize) - } + // Cap the request body before any route handler, binder or route + // middleware can read it. Without this, decoding is bounded only by + // what the client chooses to send, so a single unauthenticated + // request can drive arbitrary allocation. The router has usually + // capped the body already, in ServeHTTP; this replaces that cap with + // the route's own, which may be higher or lower. A maxBodySize of 0 + // means the route has no limit. + applyRouteBodyLimit(w, r, maxBodySize) // Apply per-route timeout for non-streaming handlers. The server-level // WriteTimeout is 0 (disabled) to support SSE/WebSocket, so regular diff --git a/internal/router/validation.go b/internal/router/validation.go index 050dae694..0d4ccf1ef 100644 --- a/internal/router/validation.go +++ b/internal/router/validation.go @@ -10,6 +10,7 @@ import ( "regexp" "strconv" "strings" + "sync" ) // SchemaValidator validates data against JSON schemas. @@ -107,10 +108,9 @@ func (v *SchemaValidator) validateString(schema *Schema, value any, path string, errors.AddWithCode(path, fmt.Sprintf("String length must be at most %d", schema.MaxLength), ErrCodeMaxLength, value) } - // Pattern validation + // Pattern validation. An invalid pattern is skipped, as before. if schema.Pattern != "" { - matched, err := regexp.MatchString(schema.Pattern, str) - if err == nil && !matched { + if re := compiledPattern(schema.Pattern); re != nil && !re.MatchString(str) { errors.AddWithCode(path, "String does not match pattern: "+schema.Pattern, ErrCodePattern, value) } } @@ -443,20 +443,48 @@ func toMap(value any) (map[string]any, bool) { return nil, false } -func isValidEmail(email string) bool { - // Basic email validation - pattern := `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$` - matched, _ := regexp.MatchString(pattern, email) +// Every regular expression here used to be compiled on every call, which +// cost more than the rest of a validation pass put together. The fixed ones +// are compiled once; schema patterns are compiled once each and cached. +var ( + // emailPattern is a basic email check. + emailPattern = regexp.MustCompile(`^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`) + + // uuidPattern matches a UUID v4 in lower case. + uuidPattern = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$`) + + // patternCache maps a schema pattern to its *regexp.Regexp, or to a nil + // *regexp.Regexp when the pattern does not compile. Patterns come from + // schemas the application defines, so the set is bounded. + patternCache sync.Map +) - return matched +// compiledPattern returns pattern compiled, or nil when it is not a valid +// regular expression. A Regexp is safe for concurrent use. +func compiledPattern(pattern string) *regexp.Regexp { + if v, ok := patternCache.Load(pattern); ok { + re, _ := v.(*regexp.Regexp) + + return re + } + + re, err := regexp.Compile(pattern) + if err != nil { + re = nil + } + + v, _ := patternCache.LoadOrStore(pattern, re) + re, _ = v.(*regexp.Regexp) + + return re } -func isValidUUID(uuid string) bool { - // UUID v4 pattern - pattern := `^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$` - matched, _ := regexp.MatchString(pattern, strings.ToLower(uuid)) +func isValidEmail(email string) bool { + return emailPattern.MatchString(email) +} - return matched +func isValidUUID(uuid string) bool { + return uuidPattern.MatchString(strings.ToLower(uuid)) } // ValidateRequestBody validates the request body against a schema. diff --git a/internal/router/validation_bench_test.go b/internal/router/validation_bench_test.go new file mode 100644 index 000000000..4a7a84f6d --- /dev/null +++ b/internal/router/validation_bench_test.go @@ -0,0 +1,33 @@ +package router + +import "testing" + +// BenchmarkSchemaValidator_Patterns validates an object whose string fields +// carry a pattern and the email and uuid formats. Each of those used to compile +// its regular expression on every call. +func BenchmarkSchemaValidator_Patterns(b *testing.B) { + schema := &Schema{ + Type: "object", + Properties: map[string]*Schema{ + "slug": {Type: "string", Pattern: `^[a-z0-9]+(?:-[a-z0-9]+)*$`}, + "code": {Type: "string", Pattern: `^[A-Z]{3}-[0-9]{4}$`}, + "email": {Type: "string", Format: "email"}, + "id": {Type: "string", Format: "uuid"}, + }, + } + data := map[string]any{ + "slug": "hello-world", + "code": "ABC-1234", + "email": "someone@example.com", + "id": "3f1c8a52-9b1e-4c1a-8f2e-5d6b7a8c9d0e", + } + v := NewSchemaValidator() + + b.ReportAllocs() + + for b.Loop() { + if err := v.ValidateRequest(schema, data); err != nil { + b.Fatal(err) + } + } +} diff --git a/internal/router/validation_cache_test.go b/internal/router/validation_cache_test.go new file mode 100644 index 000000000..8bf1a9a37 --- /dev/null +++ b/internal/router/validation_cache_test.go @@ -0,0 +1,62 @@ +package router + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestCompiledPattern_CachesAndSkipsInvalid(t *testing.T) { + a := compiledPattern(`^[a-z]+-cache-test$`) + require.NotNil(t, a) + assert.Same(t, a, compiledPattern(`^[a-z]+-cache-test$`), "a pattern is compiled once") + + assert.Nil(t, compiledPattern(`([unclosed`)) + assert.Nil(t, compiledPattern(`([unclosed`), "an invalid pattern is remembered as invalid") +} + +func TestSchemaValidator_PatternAndFormatsStillValidate(t *testing.T) { + schema := &Schema{ + Type: "object", + Properties: map[string]*Schema{ + "slug": {Type: "string", Pattern: `^[a-z0-9]+(?:-[a-z0-9]+)*$`}, + "bad": {Type: "string", Pattern: `([unclosed`}, + "email": {Type: "string", Format: "email"}, + "id": {Type: "string", Format: "uuid"}, + }, + } + v := NewSchemaValidator() + + require.NoError(t, v.ValidateRequest(schema, map[string]any{ + "slug": "hello-world", + "bad": "anything", // an invalid pattern is skipped, not enforced + "email": "someone@example.com", + "id": "3F1C8A52-9B1E-4C1A-8F2E-5D6B7A8C9D0E", + })) + + err := v.ValidateRequest(schema, map[string]any{ + "slug": "Hello World", + "email": "not-an-email", + "id": "3f1c8a52-9b1e-1c1a-8f2e-5d6b7a8c9d0e", // version 1 + }) + require.Error(t, err) + + var verr *ValidationErrors + require.ErrorAs(t, err, &verr) + assert.Len(t, verr.Errors, 3) +} + +// The validation pass used to compile three regular expressions per call. +func TestSchemaValidator_PatternsDoNotRecompile(t *testing.T) { + schema := &Schema{Type: "string", Pattern: `^[A-Z]{3}-[0-9]{4}$`, Format: "email"} + v := NewSchemaValidator() + + allocs := testing.AllocsPerRun(100, func() { + _ = v.ValidateRequest(schema, "ABC-1234") + }) + + // Compiling either expression costs dozens of allocations; a cached + // lookup plus the error bookkeeping costs a handful. + assert.Less(t, allocs, 20.0) +} diff --git a/internal/shared/response.go b/internal/shared/response.go index 8157930aa..bc372164b 100644 --- a/internal/shared/response.go +++ b/internal/shared/response.go @@ -1,17 +1,6 @@ package shared -import ( - "fmt" - "reflect" - "strings" -) - -// sensitiveCleaningKey is a private type for context keys to avoid collisions. -type sensitiveCleaningKey struct{} - -// ContextKeyForSensitiveCleaning is the key used in request context for sensitive field cleaning. -// This is exported so it can be used by both the router and context packages. -var ContextKeyForSensitiveCleaning = sensitiveCleaningKey{} +import "strings" // SensitiveMode specifies how sensitive fields should be cleaned. type SensitiveMode int @@ -57,293 +46,3 @@ func ParseSensitiveTag(tagValue string) *SensitiveFieldConfig { return &SensitiveFieldConfig{Mode: SensitiveModeZero} } } - -// CleanSensitiveFields creates a cleaned copy of the value with sensitive fields processed. -// It handles nested structs, slices, arrays, and maps recursively. -func CleanSensitiveFields(v any) any { - if v == nil { - return nil - } - - rv := reflect.ValueOf(v) - cleaned := cleanSensitiveValue(rv) - - return cleaned.Interface() -} - -// cleanSensitiveValue recursively cleans sensitive fields from a reflect.Value. -func cleanSensitiveValue(rv reflect.Value) reflect.Value { - // Handle pointers - if rv.Kind() == reflect.Pointer { - if rv.IsNil() { - return rv - } - // Create a new pointer and clean the element - cleaned := cleanSensitiveValue(rv.Elem()) - result := reflect.New(rv.Elem().Type()) - result.Elem().Set(cleaned) - - return result - } - - // Handle interfaces - if rv.Kind() == reflect.Interface { - if rv.IsNil() { - return rv - } - - return cleanSensitiveValue(rv.Elem()) - } - - switch rv.Kind() { - case reflect.Struct: - return cleanSensitiveStruct(rv) - case reflect.Slice: - return cleanSensitiveSlice(rv) - case reflect.Array: - return cleanSensitiveArray(rv) - case reflect.Map: - return cleanSensitiveMap(rv) - default: - return rv - } -} - -// cleanSensitiveStruct creates a cleaned copy of a struct with sensitive fields processed. -func cleanSensitiveStruct(rv reflect.Value) reflect.Value { - rt := rv.Type() - result := reflect.New(rt).Elem() - - for i := range rt.NumField() { - field := rt.Field(i) - fieldVal := rv.Field(i) - - // Skip unexported fields - if !field.IsExported() { - continue - } - - // Check for sensitive tag - sensitiveTag := field.Tag.Get("sensitive") - config := ParseSensitiveTag(sensitiveTag) - - if config != nil { - // Apply sensitive field cleaning - cleanedVal := applySensitiveCleaning(fieldVal, field.Type, config) - result.Field(i).Set(cleanedVal) - } else { - // Recursively clean nested values - cleanedVal := cleanSensitiveValue(fieldVal) - result.Field(i).Set(cleanedVal) - } - } - - return result -} - -// cleanSensitiveSlice creates a cleaned copy of a slice with sensitive fields processed. -func cleanSensitiveSlice(rv reflect.Value) reflect.Value { - if rv.IsNil() { - return rv - } - - result := reflect.MakeSlice(rv.Type(), rv.Len(), rv.Cap()) - - for i := range rv.Len() { - cleaned := cleanSensitiveValue(rv.Index(i)) - result.Index(i).Set(cleaned) - } - - return result -} - -// cleanSensitiveArray creates a cleaned copy of an array with sensitive fields processed. -func cleanSensitiveArray(rv reflect.Value) reflect.Value { - result := reflect.New(rv.Type()).Elem() - - for i := range rv.Len() { - cleaned := cleanSensitiveValue(rv.Index(i)) - result.Index(i).Set(cleaned) - } - - return result -} - -// cleanSensitiveMap creates a cleaned copy of a map with sensitive fields processed. -func cleanSensitiveMap(rv reflect.Value) reflect.Value { - if rv.IsNil() { - return rv - } - - result := reflect.MakeMap(rv.Type()) - - iter := rv.MapRange() - for iter.Next() { - key := iter.Key() - val := iter.Value() - cleanedVal := cleanSensitiveValue(val) - result.SetMapIndex(key, cleanedVal) - } - - return result -} - -// applySensitiveCleaning applies the appropriate cleaning based on the config. -func applySensitiveCleaning(fieldVal reflect.Value, fieldType reflect.Type, config *SensitiveFieldConfig) reflect.Value { - switch config.Mode { - case SensitiveModeZero: - return reflect.Zero(fieldType) - - case SensitiveModeRedact: - return getRedactedValue(fieldType) - - case SensitiveModeMask: - return getMaskedValue(fieldType, config.Mask) - - default: - return reflect.Zero(fieldType) - } -} - -// getRedactedValue returns the "[REDACTED]" value for supported types. -func getRedactedValue(fieldType reflect.Type) reflect.Value { - // Handle pointers - if fieldType.Kind() == reflect.Pointer { - elemType := fieldType.Elem() - if elemType.Kind() == reflect.String { - s := "[REDACTED]" - result := reflect.New(elemType) - result.Elem().SetString(s) - - return result - } - // For non-string pointers, return nil - return reflect.Zero(fieldType) - } - - // Handle direct string type - if fieldType.Kind() == reflect.String { - return reflect.ValueOf("[REDACTED]") - } - - // For non-string types, return zero value - return reflect.Zero(fieldType) -} - -// getMaskedValue returns the custom masked value for supported types. -func getMaskedValue(fieldType reflect.Type, mask string) reflect.Value { - // Handle pointers - if fieldType.Kind() == reflect.Pointer { - elemType := fieldType.Elem() - if elemType.Kind() == reflect.String { - result := reflect.New(elemType) - result.Elem().SetString(mask) - - return result - } - // For non-string pointers, return nil - return reflect.Zero(fieldType) - } - - // Handle direct string type - if fieldType.Kind() == reflect.String { - return reflect.ValueOf(mask) - } - - // For non-string types, return zero value - return reflect.Zero(fieldType) -} - -// ResponseProcessor handles response struct processing. -// It extracts headers and unwraps body fields based on struct tags. -type ResponseProcessor struct { - // HeaderSetter is called for each header:"..." tagged field with non-zero value. - HeaderSetter func(name, value string) - // CleanSensitive when true, processes sensitive fields. - CleanSensitive bool -} - -// ProcessResponse handles response struct tags: -// - Calls HeaderSetter for header:"..." fields with non-zero values -// - Returns the unwrapped body if a body:"" tag is found -// - Cleans sensitive fields if CleanSensitive is true -// - Falls back to original value if no special tags found. -func (p *ResponseProcessor) ProcessResponse(v any) any { - if v == nil { - return nil - } - - // Clean sensitive fields first if enabled - if p.CleanSensitive { - v = CleanSensitiveFields(v) - } - - rv := reflect.ValueOf(v) - - // Handle pointer - if rv.Kind() == reflect.Pointer { - if rv.IsNil() { - return nil - } - - rv = rv.Elem() - } - - if rv.Kind() != reflect.Struct { - return v - } - - rt := rv.Type() - - var bodyValue any - - hasBodyUnwrap := false - - for i := range rt.NumField() { - field := rt.Field(i) - if !field.IsExported() { - continue - } - - // Set headers via callback - if headerName := field.Tag.Get("header"); headerName != "" && headerName != "-" { - fieldVal := rv.Field(i) - if !fieldVal.IsZero() && p.HeaderSetter != nil { - p.HeaderSetter(headerName, fmt.Sprint(fieldVal.Interface())) - } - } - - // Check for body:"" unwrap marker - if bodyTag, hasTag := field.Tag.Lookup("body"); hasTag && bodyTag == "" { - bodyValue = rv.Field(i).Interface() - hasBodyUnwrap = true - } - } - - if hasBodyUnwrap { - return bodyValue - } - - return v -} - -// ProcessResponseValue is a convenience function that processes a response value -// with the given header setter callback. -func ProcessResponseValue(v any, headerSetter func(name, value string)) any { - processor := &ResponseProcessor{ - HeaderSetter: headerSetter, - } - - return processor.ProcessResponse(v) -} - -// ProcessResponseValueWithSensitive is a convenience function that processes a response value -// with the given header setter callback and sensitive field cleaning. -func ProcessResponseValueWithSensitive(v any, headerSetter func(name, value string), cleanSensitive bool) any { - processor := &ResponseProcessor{ - HeaderSetter: headerSetter, - CleanSensitive: cleanSensitive, - } - - return processor.ProcessResponse(v) -} diff --git a/internal/shared/response_sensitive_test.go b/internal/shared/response_sensitive_test.go index 11a185ae4..10e2eafcb 100644 --- a/internal/shared/response_sensitive_test.go +++ b/internal/shared/response_sensitive_test.go @@ -84,368 +84,3 @@ func TestParseSensitiveTag(t *testing.T) { }) } } - -func TestCleanSensitiveFields_BasicStruct(t *testing.T) { - type User struct { - ID string `json:"id"` - Email string `json:"email"` - Password string `json:"password" sensitive:"true"` - APIKey string `json:"api_key" sensitive:"redact"` - Token string `json:"token" sensitive:"mask:***"` - } - - input := &User{ - ID: "123", - Email: "test@example.com", - Password: "secret123", - APIKey: "sk-1234567890", - Token: "jwt-token-here", - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.(*User) - if !ok { - t.Fatalf("Expected *User, got %T", result) - } - - // Non-sensitive fields should be unchanged - if cleaned.ID != "123" { - t.Errorf("ID = %q, want %q", cleaned.ID, "123") - } - - if cleaned.Email != "test@example.com" { - t.Errorf("Email = %q, want %q", cleaned.Email, "test@example.com") - } - - // sensitive:"true" should be zero value - if cleaned.Password != "" { - t.Errorf("Password = %q, want empty string", cleaned.Password) - } - - // sensitive:"redact" should be "[REDACTED]" - if cleaned.APIKey != "[REDACTED]" { - t.Errorf("APIKey = %q, want %q", cleaned.APIKey, "[REDACTED]") - } - - // sensitive:"mask:***" should be "***" - if cleaned.Token != "***" { - t.Errorf("Token = %q, want %q", cleaned.Token, "***") - } -} - -func TestCleanSensitiveFields_PointerFields(t *testing.T) { - type Config struct { - Name string `json:"name"` - Secret *string `json:"secret" sensitive:"true"` - APIToken *string `json:"api_token" sensitive:"redact"` - } - - secret := "my-secret" - token := "my-token" - input := &Config{ - Name: "test", - Secret: &secret, - APIToken: &token, - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.(*Config) - if !ok { - t.Fatalf("Expected *Config, got %T", result) - } - - if cleaned.Name != "test" { - t.Errorf("Name = %q, want %q", cleaned.Name, "test") - } - - // Pointer with sensitive:"true" should be nil - if cleaned.Secret != nil { - t.Errorf("Secret = %v, want nil", cleaned.Secret) - } - - // Pointer string with sensitive:"redact" should be pointer to "[REDACTED]" - if cleaned.APIToken == nil { - t.Errorf("APIToken = nil, want pointer to [REDACTED]") - } else if *cleaned.APIToken != "[REDACTED]" { - t.Errorf("*APIToken = %q, want %q", *cleaned.APIToken, "[REDACTED]") - } -} - -func TestCleanSensitiveFields_NestedStruct(t *testing.T) { - type Credentials struct { - Username string `json:"username"` - Password string `json:"password" sensitive:"true"` - } - - type User struct { - ID string `json:"id"` - Creds Credentials `json:"credentials"` - } - - input := &User{ - ID: "123", - Creds: Credentials{ - Username: "john", - Password: "secret", - }, - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.(*User) - if !ok { - t.Fatalf("Expected *User, got %T", result) - } - - if cleaned.ID != "123" { - t.Errorf("ID = %q, want %q", cleaned.ID, "123") - } - - if cleaned.Creds.Username != "john" { - t.Errorf("Creds.Username = %q, want %q", cleaned.Creds.Username, "john") - } - - if cleaned.Creds.Password != "" { - t.Errorf("Creds.Password = %q, want empty string", cleaned.Creds.Password) - } -} - -func TestCleanSensitiveFields_Slice(t *testing.T) { - type Token struct { - ID string `json:"id"` - Value string `json:"value" sensitive:"redact"` - } - - input := []Token{ - {ID: "1", Value: "secret1"}, - {ID: "2", Value: "secret2"}, - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.([]Token) - if !ok { - t.Fatalf("Expected []Token, got %T", result) - } - - if len(cleaned) != 2 { - t.Fatalf("len(cleaned) = %d, want 2", len(cleaned)) - } - - for i, token := range cleaned { - expectedID := string(rune('1' + i)) - if token.ID != expectedID { - t.Errorf("cleaned[%d].ID = %q, want %q", i, token.ID, expectedID) - } - - if token.Value != "[REDACTED]" { - t.Errorf("cleaned[%d].Value = %q, want %q", i, token.Value, "[REDACTED]") - } - } -} - -func TestCleanSensitiveFields_SliceOfPointers(t *testing.T) { - type Token struct { - ID string `json:"id"` - Value string `json:"value" sensitive:"true"` - } - - input := []*Token{ - {ID: "1", Value: "secret1"}, - {ID: "2", Value: "secret2"}, - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.([]*Token) - if !ok { - t.Fatalf("Expected []*Token, got %T", result) - } - - if len(cleaned) != 2 { - t.Fatalf("len(cleaned) = %d, want 2", len(cleaned)) - } - - for i, token := range cleaned { - if token == nil { - t.Errorf("cleaned[%d] = nil, want non-nil", i) - - continue - } - - if token.Value != "" { - t.Errorf("cleaned[%d].Value = %q, want empty string", i, token.Value) - } - } -} - -func TestCleanSensitiveFields_Map(t *testing.T) { - type Secret struct { - Name string `json:"name"` - Value string `json:"value" sensitive:"mask:****"` - } - - input := map[string]Secret{ - "key1": {Name: "secret1", Value: "value1"}, - "key2": {Name: "secret2", Value: "value2"}, - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.(map[string]Secret) - if !ok { - t.Fatalf("Expected map[string]Secret, got %T", result) - } - - for key, secret := range cleaned { - if secret.Value != "****" { - t.Errorf("cleaned[%q].Value = %q, want %q", key, secret.Value, "****") - } - } -} - -func TestCleanSensitiveFields_NilInput(t *testing.T) { - result := CleanSensitiveFields(nil) - if result != nil { - t.Errorf("CleanSensitiveFields(nil) = %v, want nil", result) - } -} - -func TestCleanSensitiveFields_NonStruct(t *testing.T) { - // Non-struct types should be returned as-is - input := "hello" - - result := CleanSensitiveFields(input) - if result != input { - t.Errorf("CleanSensitiveFields(%q) = %v, want %q", input, result, input) - } - - inputInt := 42 - - resultInt := CleanSensitiveFields(inputInt) - if resultInt != inputInt { - t.Errorf("CleanSensitiveFields(%d) = %v, want %d", inputInt, resultInt, inputInt) - } -} - -func TestCleanSensitiveFields_NonStringTypes(t *testing.T) { - type Config struct { - PublicCount int `json:"public_count"` - SecretCount int `json:"secret_count" sensitive:"true"` - PrivateFloat float64 `json:"private_float" sensitive:"redact"` - } - - input := &Config{ - PublicCount: 100, - SecretCount: 42, - PrivateFloat: 3.14, - } - - result := CleanSensitiveFields(input) - - cleaned, ok := result.(*Config) - if !ok { - t.Fatalf("Expected *Config, got %T", result) - } - - // Public field unchanged - if cleaned.PublicCount != 100 { - t.Errorf("PublicCount = %d, want 100", cleaned.PublicCount) - } - - // Non-string types with sensitive tags get zero values - if cleaned.SecretCount != 0 { - t.Errorf("SecretCount = %d, want 0", cleaned.SecretCount) - } - - // Redact on non-string types also gets zero value (can't put [REDACTED] in int) - if cleaned.PrivateFloat != 0 { - t.Errorf("PrivateFloat = %f, want 0", cleaned.PrivateFloat) - } -} - -func TestCleanSensitiveFields_UnexportedFields(t *testing.T) { - type Config struct { - Public string `json:"public"` - Private string `json:"private" sensitive:"true"` //nolint:unused // intentional for testing unexported fields - } - - input := &Config{ - Public: "visible", - } - - // This should not panic and should work with exported fields only - result := CleanSensitiveFields(input) - - cleaned, ok := result.(*Config) - if !ok { - t.Fatalf("Expected *Config, got %T", result) - } - - if cleaned.Public != "visible" { - t.Errorf("Public = %q, want %q", cleaned.Public, "visible") - } -} - -func TestProcessResponseValueWithSensitive_Integration(t *testing.T) { - type Response struct { - ID string `json:"id"` - Secret string `json:"secret" sensitive:"redact"` - CacheCtl string `header:"Cache-Control"` - } - - headers := make(map[string]string) - headerSetter := func(name, value string) { - headers[name] = value - } - - input := &Response{ - ID: "123", - Secret: "super-secret", - CacheCtl: "no-cache", - } - - // With sensitive cleaning enabled - result := ProcessResponseValueWithSensitive(input, headerSetter, true) - - cleaned, ok := result.(*Response) - if !ok { - t.Fatalf("Expected *Response, got %T", result) - } - - if cleaned.Secret != "[REDACTED]" { - t.Errorf("Secret = %q, want %q", cleaned.Secret, "[REDACTED]") - } - - // Headers should still be set - if headers["Cache-Control"] != "no-cache" { - t.Errorf("Cache-Control header = %q, want %q", headers["Cache-Control"], "no-cache") - } -} - -func TestProcessResponseValueWithSensitive_Disabled(t *testing.T) { - type Response struct { - ID string `json:"id"` - Secret string `json:"secret" sensitive:"redact"` - } - - input := &Response{ - ID: "123", - Secret: "super-secret", - } - - // With sensitive cleaning disabled - result := ProcessResponseValueWithSensitive(input, nil, false) - - returned, ok := result.(*Response) - if !ok { - t.Fatalf("Expected *Response, got %T", result) - } - - // Secret should NOT be cleaned when disabled - if returned.Secret != "super-secret" { - t.Errorf("Secret = %q, want %q (should be unchanged when disabled)", returned.Secret, "super-secret") - } -} diff --git a/router.go b/router.go index b64ca94e8..9787bb11c 100644 --- a/router.go +++ b/router.go @@ -1,6 +1,7 @@ package forge import ( + "net/http" "time" "github.com/xraph/forge/errors" @@ -144,6 +145,15 @@ func WithMaxBodySize(bytes int64) RouteOption { return router.WithMaxBodySize(bytes) } +// SetRequestBodyLimit changes the body cap the router put on r, for handlers +// mounted with Router.Handle, which have no route options. Call it before +// reading the body; a limit of zero or less removes the cap. It returns false +// and changes nothing when r's body is not the one the router capped (the +// router has no limit, or a middleware replaced the body). +func SetRequestBodyLimit(r *http.Request, limit int64) bool { + return router.SetRequestBodyLimit(r, limit) +} + func WithMetadata(key string, value any) RouteOption { return router.WithMetadata(key, value) }