Files
web/mw/rate_limit.go
Rene Nochebuena c4ef1948f6 feat(web): initial implementation — server, mw, httputil, health (v1.0.0)
Introduces code.nochebuena.dev/einherjar/web — the HTTP transport layer of the
Einherjar framework. Absorbs httpserver, httpmw, and httputil from micro-lib,
replacing gorilla/mux with chi, adopting SecurityBag-native middleware, and
centralizing error handling through a single httputil.Error function.

server:
- Server interface — embeds lifecycle.Component and chi.Router
- Config struct (EINHERJAR_SERVER_* env vars); DefaultConfig
- New(logger, cfg, opts...) Server; WithMiddleware option
- Binds TCP synchronously in OnStart; logs "server: listening" on success
- Graceful shutdown within ShutdownTimeout on OnStop

mw:
- Recover — catches panics, returns 500, logs at Error
- RequestID — injects UUID v7 (UUID v4 fallback) into context and X-Request-ID header
- RequestLogger — structured access log per request
- CORS / CORSAllowAll — chi-based, applied only when origins non-empty
- IPRateLimit / UserRateLimit — pluggable RateLimiterStore interface
- InMemoryRateLimiterStore — token-bucket backed by golang.org/x/time/rate;
  background goroutine evicts stale entries every 5 minutes
- StatusRecorder — wraps ResponseWriter to capture HTTP status code

httputil:
- Handle[Req, Res] / HandleNoBody[Res] / HandleEmpty[Req] — generic handler adapters
- Error(logger, w, r, err) — derives log level from status (≥500→Error, 4xx→Warn,
  499→Info); writes standardized JSON body; logz enriches *xerrors.Err automatically
- JSON(w, status, v) / NoContent(w) — response helpers
- HandlerFunc adapter type

health:
- NewHandler / NewHandlerWithConfig — runs all Checkable checks concurrently;
  returns JSON {status, components} with per-component latency and error
- Config struct (EINHERJAR_HEALTH_CHECK_TIMEOUT, default 5s)

Root factory:
- web.New(logger, cfg...) Server — composes Recover+RequestID+RequestLogger+CORS
  in outermost-first order; CORS applied only when AllowedOrigins non-empty

- server.Server interface and web/server/identifiable.go: embeds observability.Identifiable;
  ModulePath and ModuleVersion read via runtime/debug.ReadBuildInfo() — prints in launcher banner
2026-05-29 15:48:11 +00:00

74 lines
2.3 KiB
Go

package mw
import (
"encoding/json"
"net/http"
"strings"
"code.nochebuena.dev/einherjar/contracts/logging"
"code.nochebuena.dev/einherjar/contracts/security"
)
// IPRateLimit returns middleware that rate-limits requests by client IP address.
// The IP is extracted from X-Forwarded-For (first value) or RemoteAddr.
// When the store returns an error the middleware fails open: the error is logged
// and the request is allowed through.
func IPRateLimit(store RateLimiterStore, logger logging.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r)
ok, err := store.Allow(r.Context(), key)
if err != nil {
logger.WithContext(r.Context()).Warn("rate_limit: store error, failing open", "err", err.Error())
} else if !ok {
rateLimitExceeded(w)
return
}
next.ServeHTTP(w, r)
})
}
}
// UserRateLimit returns middleware that rate-limits by authenticated user ID.
// Falls back to client IP when no [security.Identity] is present in the context.
// When the store returns an error the middleware fails open.
func UserRateLimit(store RateLimiterStore, logger logging.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := clientIP(r)
if id, ok := security.FromContext(r.Context()); ok && id.UID != "" {
key = id.UID
}
ok, err := store.Allow(r.Context(), key)
if err != nil {
logger.WithContext(r.Context()).Warn("rate_limit: store error, failing open", "err", err.Error())
} else if !ok {
rateLimitExceeded(w)
return
}
next.ServeHTTP(w, r)
})
}
}
func clientIP(r *http.Request) string {
if fwd := r.Header.Get("X-Forwarded-For"); fwd != "" {
parts := strings.SplitN(fwd, ",", 2)
return strings.TrimSpace(parts[0])
}
addr := r.RemoteAddr
if i := strings.LastIndex(addr, ":"); i >= 0 {
return addr[:i]
}
return addr
}
func rateLimitExceeded(w http.ResponseWriter) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusTooManyRequests)
_ = json.NewEncoder(w).Encode(map[string]string{
"code": "RESOURCE_EXHAUSTED",
"message": "too many requests",
})
}