Files
archie/internal/webhookguard/ratelimit.go
T
sam 543b657472 feat(webhookguard): shared HMAC, rate-limit, and redaction mechanics
archie-core-7d5u.3 -- storage-agnostic building blocks for vetting inbound
webhook-shaped requests, extracted rather than duplicated:

- VerifyHMAC: behavior-preserving extraction of internal/channels/webhook's
  private validateHMAC. internal/channels/webhook now calls it instead of
  keeping its own copy; all 10 of that package's existing tests still pass
  unmodified, and the one now-redundant unit test was removed with a
  comment pointing to where its coverage relocated.
- RateLimiter: per-source token bucket. Source IDs come from a registered,
  operator-controlled set, not unbounded attacker input, so the bucket map
  is not itself bounded -- documented explicitly rather than left implicit.
- RedactPayload: key-name-based redaction, matching gateway/stream.go's
  sensitiveParameterKey marker list. Deliberately does NOT reuse that
  function's actual behavior: it replaces every string value regardless of
  key, correct for a bounded chat summary and wrong here -- a captured
  payload exists to be inspected for field mapping (t2db.3), so only values
  under a sensitive-looking key are touched.

Narrowed from 7d5u.3's original scope, which bundled capture storage and an
approval state machine into this package. Both moved to the beads that own
that state (t2db.1's capture store depends on 7d5u.2's still-open NATS
storage decision; t2db.4's binding is the only consumer of approval state
today) rather than building shared abstractions ahead of a second real
consumer.

Adversarially reviewed by a fresh subagent with zero surviving findings:
token-bucket math hand-traced on two scenarios and race-clean under -race,
the redaction/gateway-stream.go behavioral divergence verified by reading
both functions side by side, both the redaction and rate-limit guards
mutation-tested by disabling each and confirming the suite catches it.

task check exit 0, golangci-lint 0 issues, gofumpt clean.
2026-08-22 01:28:58 +10:00

70 lines
2.0 KiB
Go

package webhookguard
import (
"sync"
"time"
)
// RateLimiter caps request volume per source using a token bucket per
// source ID. Source IDs are assumed to come from a registered, operator-
// controlled set (per docs/prds/webhook-intake-security.md's "a source
// registers with a secret before its events can trigger anything"), not
// from unbounded attacker-supplied request data -- the bucket map is not
// itself bounded, because the key space is bounded by registration.
//
// A rejected request must be surfaced as an observable rejection by the
// caller (HTTP 429), never silently dropped -- see
// docs/prds/webhook-intake-security.md point 3.
type RateLimiter struct {
mu sync.Mutex
rate float64 // tokens added per second
burst float64 // bucket capacity, also the starting balance
now func() time.Time
buckets map[string]*tokenBucket
}
type tokenBucket struct {
tokens float64
lastSeen time.Time
}
// NewRateLimiter returns a limiter refilling at ratePerSecond tokens per
// second up to burst tokens. now is the clock to use; pass time.Now for
// production callers and an injected clock in tests.
func NewRateLimiter(ratePerSecond float64, burst int, now func() time.Time) *RateLimiter {
return &RateLimiter{
rate: ratePerSecond,
burst: float64(burst),
now: now,
buckets: make(map[string]*tokenBucket),
}
}
// Allow reports whether a request from source may proceed, consuming one
// token if so. A source seen for the first time starts with a full bucket
// (burst tokens) rather than empty, so the initial request from a newly
// registered source is never rejected outright.
func (r *RateLimiter) Allow(source string) bool {
r.mu.Lock()
defer r.mu.Unlock()
now := r.now()
b, ok := r.buckets[source]
if !ok {
b = &tokenBucket{tokens: r.burst, lastSeen: now}
r.buckets[source] = b
} else {
elapsed := now.Sub(b.lastSeen).Seconds()
if elapsed > 0 {
b.tokens = min(r.burst, b.tokens+elapsed*r.rate)
b.lastSeen = now
}
}
if b.tokens < 1 {
return false
}
b.tokens--
return true
}