Documentation
¶
Overview ¶
Package middleware provides reusable HTTP middleware for production hardening.
Components include:
- TrustedProxies: Client IP and HTTPS answers behind a proxy that ends TLS; forwarding headers count only from listed proxies, and an empty list trusts nobody
- ClientIPExtractor: Older client-IP wrapper over TrustedProxies
- RateLimiter: Global and per-key rate limiting with configurable key functions
- ConnLimiter: Concurrent connection limiting for WebSocket endpoints
- OriginChecker: Origin allowlist for WebSocket upgrade requests
- CORS: Origin-aware CORS header middleware
- Recovery: Panic recovery with structured logging
- RequestLogger: Structured HTTP request logging (includes request ID when available)
- RequestID: Request ID generation/propagation via X-Request-Id header
- BodyLimiter: Request body size limiting via http.MaxBytesReader
- HealthCheck: Health/readiness endpoint handler for load balancers and k8s probes
- Guard: Composable middleware chain
Helpers:
- CheckPlaintext: Startup check that refuses credentials over plain HTTP on a non-loopback address
- ApplyDefaults: Sets sensible timeout defaults on http.Server (note: SSE endpoints require WriteTimeout = 0 separately to prevent the server from closing long-lived streaming connections)
All components are nil-safe: a nil component acts as a no-op passthrough. No application-specific imports — designed for embedding in any Go HTTP server.
Index ¶
- Variables
- func ApplyDefaults(srv *http.Server)
- func CORS(checker *OriginChecker, opts ...CORSOption) func(http.Handler) http.Handler
- func CheckPlaintext(addr string, tls bool, proxies TrustedProxies) error
- func ClientIP(r *http.Request) string
- func ContextWithRequestID(ctx context.Context, id string) context.Context
- func Recovery(next http.Handler) http.Handler
- func RequestIDFromContext(ctx context.Context) string
- func RequestLogger(skipPaths ...string) func(http.Handler) http.Handler
- func RequireContentType(accepted ...string) func(http.Handler) http.Handler
- func SetDefaultTrustedProxies(tp TrustedProxies)
- func SetTrustedProxies(cidrs []string)
- type BodyLimiter
- type CORSOption
- type ClientIPExtractor
- type ConnLimiter
- type Guard
- type HealthCheck
- type HealthOption
- type OriginChecker
- type RateLimitConfig
- type RateLimiter
- type RequestID
- type TrustedProxies
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrPlaintextCredentials = errors.New("servicekit/middleware: refusing to serve credentials over plain HTTP on a non-loopback address; enable TLS or name the trusted proxies that end it")
ErrPlaintextCredentials is returned by CheckPlaintext when a service would accept credentials over plain HTTP from the network.
Functions ¶
func ApplyDefaults ¶ added in v0.0.7
ApplyDefaults sets sensible timeout defaults on an http.Server, only overwriting fields that are zero-valued.
Defaults:
- ReadTimeout: 10s
- WriteTimeout: 30s
- IdleTimeout: 120s
- ReadHeaderTimeout: 5s
For SSE or long-lived streaming endpoints, callers should either set WriteTimeout to a non-zero value before calling ApplyDefaults (it won't overwrite), or set WriteTimeout = 0 after calling this function to disable the write deadline for streaming responses.
Example ¶
ExampleApplyDefaults demonstrates setting sensible timeout defaults on http.Server. For SSE or WebSocket endpoints, set WriteTimeout = 0 after calling ApplyDefaults to prevent the server from killing long-lived connections.
package main
import (
"fmt"
"net/http"
mw "github.com/panyam/servicekit/middleware"
)
func main() {
srv := &http.Server{Addr: ":8080"}
mw.ApplyDefaults(srv)
// For SSE/WebSocket servers, override WriteTimeout
srv.WriteTimeout = 0
fmt.Printf("ReadTimeout: %v, WriteTimeout: %v, IdleTimeout: %v\n",
srv.ReadTimeout, srv.WriteTimeout, srv.IdleTimeout)
}
Output: ReadTimeout: 10s, WriteTimeout: 0s, IdleTimeout: 2m0s
func CORS ¶
func CORS(checker *OriginChecker, opts ...CORSOption) func(http.Handler) http.Handler
CORS returns middleware that sets CORS headers based on an OriginChecker.
Behavior:
- If checker is nil (no allowlist): reflect any origin back
- If checker is set and the request Origin matches: reflect the origin back
- If checker is set and the request Origin doesn't match: no CORS headers (browser will block the response)
- OPTIONS preflight requests are handled and return 204
Use CORSOption values to customize allowed methods, headers, and exposed headers. Defaults: methods GET/POST/OPTIONS, headers Content-Type/Authorization, no exposed headers.
This replaces the naive "Access-Control-Allow-Origin: *" pattern with origin validation. The same OriginChecker used for WebSocket origin checks is reused here for consistency.
func CheckPlaintext ¶ added in v0.2.5
func CheckPlaintext(addr string, tls bool, proxies TrustedProxies) error
CheckPlaintext is a startup check for a service that accepts credentials (passwords, bearer tokens, session cookies). Call it with the listen address, whether this process serves TLS, and the trusted proxies.
It returns nil when any of these holds:
- tls is true;
- proxies is non-empty, so a proxy is expected to end TLS in front;
- addr binds only a loopback address ("127.0.0.1:8080", "[::1]:8080", "localhost:8080").
Otherwise it returns an error wrapping ErrPlaintextCredentials. That includes ":8080" and "0.0.0.0:8080", which bind every interface, and any hostname other than "localhost", since a name can resolve anywhere. An addr that is not host:port returns a parse error instead.
Naming proxies does not prove TLS is on in front of them. The check catches the default-config mistake, where a service meant for a proxy is started bare on a public port.
func ClientIP ¶
ClientIP extracts the real client IP using the default extractor. Configure trusted proxies via SetDefaultTrustedProxies. Until that is called, every peer is trusted (see NewClientIPExtractor).
func ContextWithRequestID ¶ added in v0.0.7
ContextWithRequestID returns a new context with the given request ID.
func Recovery ¶
Recovery returns middleware that recovers from panics in downstream handlers. On panic, it logs the error and stack trace, then returns 500 to the client. Without this, a single bad request can crash the entire server.
func RequestIDFromContext ¶ added in v0.0.7
RequestIDFromContext extracts the request ID from context, or "" if absent.
func RequestLogger ¶
RequestLogger logs HTTP requests with method, path, status, duration, and client IP. When a request ID is present in the context (set by the RequestID middleware), it is automatically included in the log output as "request_id". Skips logging for specified paths (e.g. /healthz for noisy liveness probes).
func RequireContentType ¶ added in v0.0.20
RequireContentType returns middleware that rejects POST, PUT, and PATCH requests whose Content-Type header does not match any of the accepted types (prefix match). GET, DELETE, OPTIONS, and HEAD requests are passed through since they typically have no body.
Returns 415 Unsupported Media Type for requests with a missing or mismatched Content-Type. This is a defense-in-depth measure against CSRF via cross-origin form submissions (browsers send forms as application/x-www-form-urlencoded without CORS preflight).
Example:
// Single type
mux.Handle("/api", middleware.RequireContentType("application/json")(handler))
// Multiple types
mux.Handle("/rpc", middleware.RequireContentType("application/json", "application/json-rpc")(handler))
func SetDefaultTrustedProxies ¶ added in v0.2.5
func SetDefaultTrustedProxies(tp TrustedProxies)
SetDefaultTrustedProxies configures the package-level ClientIP, which RequestLogger, ConnLimiter, Recovery, OriginChecker and RateLimiter (with a nil keyFunc) use. An empty tp trusts nobody, unlike SetTrustedProxies.
It is not safe to call concurrently with requests. Call it once at startup.
func SetTrustedProxies ¶
func SetTrustedProxies(cidrs []string)
SetTrustedProxies configures the default (package-level) extractor with NewClientIPExtractor's rules, including its deprecated trust-everyone default for an empty list. Prefer SetDefaultTrustedProxies.
Like SetDefaultTrustedProxies, it is not safe to call concurrently with requests. Call it once at startup.
Types ¶
type BodyLimiter ¶ added in v0.0.7
type BodyLimiter struct {
// contains filtered or unexported fields
}
BodyLimiter limits the size of incoming request bodies using http.MaxBytesReader. When the handler reads past the limit, MaxBytesReader returns an error and the request fails.
Nil-safe: a nil BodyLimiter passes requests through unchanged.
func NewBodyLimiter ¶ added in v0.0.7
func NewBodyLimiter(maxBytes int64) *BodyLimiter
NewBodyLimiter creates a limiter with the given max body size in bytes. Returns nil if maxBytes <= 0 (caller should skip the middleware).
func (*BodyLimiter) Middleware ¶ added in v0.0.7
func (b *BodyLimiter) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware that limits request body size. On a nil receiver, returns the handler unchanged.
type CORSOption ¶ added in v0.0.26
type CORSOption func(*corsConfig)
CORSOption configures the CORS middleware.
func CORSAllowHeaders ¶ added in v0.0.26
func CORSAllowHeaders(headers ...string) CORSOption
CORSAllowHeaders overrides the default allowed headers (Content-Type, Authorization).
func CORSAllowMethods ¶ added in v0.0.26
func CORSAllowMethods(methods ...string) CORSOption
CORSAllowMethods overrides the default allowed methods (GET, POST, OPTIONS).
func CORSExposeHeaders ¶ added in v0.0.26
func CORSExposeHeaders(headers ...string) CORSOption
CORSExposeHeaders sets the Access-Control-Expose-Headers value. By default no headers are exposed.
type ClientIPExtractor ¶
type ClientIPExtractor struct {
// contains filtered or unexported fields
}
ClientIPExtractor extracts the real client IP from requests. It wraps a TrustedProxies and answers with TrustedProxies.ClientIP.
Usage:
// Trust Caddy on localhost and the Docker bridge network
extractor := NewClientIPExtractor([]string{"127.0.0.1/32", "172.17.0.0/16", "::1/128"})
ip := extractor.ExtractClientIP(r)
New code that makes security decisions should use TrustedProxies directly, where an empty list trusts nobody and bad entries are errors.
func NewClientIPExtractor ¶
func NewClientIPExtractor(cidrs []string) *ClientIPExtractor
NewClientIPExtractor creates an extractor with the given trusted proxy CIDRs or bare addresses. Entries that fail to parse are dropped.
Deprecated behavior: when cidrs is nil, empty, or holds no valid entry, every peer is trusted, so any client can set its own X-Forwarded-For. That default is kept for compatibility and will change to trust nobody in a later release. Use ParseTrustedProxies, which trusts nobody when empty and reports bad entries, and SetDefaultTrustedProxies for the package-level ClientIP. See UPGRADING.md.
func (*ClientIPExtractor) ExtractClientIP ¶
func (e *ClientIPExtractor) ExtractClientIP(r *http.Request) string
ExtractClientIP returns TrustedProxies.ClientIP for the extractor's list. X-Forwarded-For and X-Real-IP count only when RemoteAddr is a trusted proxy, and X-Forwarded-For is walked right to left, skipping trusted hops. With the trust-everyone default every hop is trusted, so the leftmost X-Forwarded-For entry wins.
type ConnLimiter ¶
type ConnLimiter struct {
// contains filtered or unexported fields
}
ConnLimiter limits the number of concurrent active requests to a handler. Designed for WebSocket endpoints where each connection holds resources for the lifetime of the session.
When the limit is reached, new requests receive 503 Service Unavailable. The counter decrements when the request handler returns (connection closes).
func NewConnLimiter ¶
func NewConnLimiter(max int64) *ConnLimiter
NewConnLimiter creates a limiter with the given max concurrent connections. Pass 0 for unlimited (returns nil — caller should skip the middleware).
func (*ConnLimiter) Active ¶
func (c *ConnLimiter) Active() int64
Active returns the current number of active connections.
func (*ConnLimiter) Middleware ¶
func (c *ConnLimiter) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware that enforces the connection limit.
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard composes multiple middleware into a single wrapper. Middleware are applied in the order they are added via Use — the first middleware added is the outermost (runs first on request, last on response).
Usage:
g := &Guard{}
g.Use(originChecker.Middleware, rateLimiter.Middleware(nil), auth.Middleware, connLimiter.Middleware)
http.Handle("/ws", g.Wrap(wsHandler))
Example ¶
ExampleGuard demonstrates composing middleware into a chain using Guard. Middleware are applied in Use() order — the first added is outermost (runs first on request, last on response). Nil middleware are silently skipped.
package main
import (
"fmt"
"net/http"
mw "github.com/panyam/servicekit/middleware"
)
func main() {
// Create middleware components
rl := mw.NewRateLimiter(mw.RateLimitConfig{
GlobalPerSec: 100,
PerKeyPerSec: 10,
})
oc := mw.NewOriginChecker([]string{
"https://example.com",
"https://*.example.com",
})
// Compose into a Guard chain
g := &mw.Guard{}
g.Use(
oc.Middleware, // Check origin first
rl.Middleware(nil), // Then rate limit (nil key = use ClientIP)
mw.Recovery, // Catch panics
)
// Wrap your handler
handler := g.Wrap(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}))
http.Handle("/api", handler)
_ = handler
fmt.Println("Guard chain configured")
}
Output: Guard chain configured
type HealthCheck ¶ added in v0.0.7
type HealthCheck struct {
// contains filtered or unexported fields
}
HealthCheck is an HTTP handler that serves health/readiness endpoints for load balancers and Kubernetes probes. It implements http.Handler and should be mounted directly on a mux, not used as middleware.
Nil-safe: a nil *HealthCheck returns 404.
func NewHealthCheck ¶ added in v0.0.7
func NewHealthCheck(opts ...HealthOption) *HealthCheck
NewHealthCheck creates a health check handler with the given options. Default path is "/healthz".
func (*HealthCheck) Path ¶ added in v0.0.7
func (h *HealthCheck) Path() string
Path returns the configured endpoint path for mux registration.
func (*HealthCheck) ServeHTTP ¶ added in v0.0.7
func (h *HealthCheck) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler. On a nil receiver, returns 404.
type HealthOption ¶ added in v0.0.7
type HealthOption func(*HealthCheck)
HealthOption configures the health check handler.
func WithPath ¶ added in v0.0.7
func WithPath(path string) HealthOption
WithPath sets the health endpoint path (default "/healthz").
func WithReadyFunc ¶ added in v0.0.7
func WithReadyFunc(fn func() bool) HealthOption
WithReadyFunc sets an optional readiness callback. When set and returning false, the endpoint returns 503 with {"status":"not ready"}.
type OriginChecker ¶
type OriginChecker struct {
// contains filtered or unexported fields
}
OriginChecker rejects requests whose Origin header doesn't match an allowlist. Designed for WebSocket endpoints where CORS headers alone don't prevent cross-origin connections.
Matching rules:
- Exact match on scheme+host (port-insensitive for 80/443)
- Wildcard subdomain: "*.example.com" matches "foo.example.com"
- "localhost" matches any localhost origin regardless of port
- Empty allowlist = allow all (no-op)
- Missing Origin header = blocked (unless allowlist is empty)
func NewLocalhostOriginChecker ¶ added in v0.0.18
func NewLocalhostOriginChecker() *OriginChecker
NewLocalhostOriginChecker creates an OriginChecker that only allows localhost origins (localhost, 127.0.0.1, ::1). This is the secure default for local development servers that don't have an explicit allowlist.
Unlike NewOriginChecker(nil) which returns nil (allow-all), this returns a restrictive checker that blocks remote origins.
func NewOriginChecker ¶
func NewOriginChecker(origins []string) *OriginChecker
NewOriginChecker creates a checker from a list of allowed origins. Accepts formats: "https://example.com", "*.example.com", "localhost", "*". Returns nil if the list is empty or contains "*" (allow all origins).
Example ¶
ExampleNewOriginChecker demonstrates WebSocket origin validation with exact matches, wildcard subdomains, and localhost support. The checker is typically used via Guard middleware, but Check() can be called directly.
package main
import (
"fmt"
mw "github.com/panyam/servicekit/middleware"
)
func main() {
oc := mw.NewOriginChecker([]string{
"https://example.com", // exact match
"*.example.com", // wildcard subdomain
"localhost", // any localhost port
})
fmt.Println(oc.Check("https://example.com")) // true
fmt.Println(oc.Check("https://app.example.com")) // true
fmt.Println(oc.Check("http://localhost:3000")) // true
fmt.Println(oc.Check("https://evil.com")) // false
}
Output: true true true false
func (*OriginChecker) Check ¶
func (c *OriginChecker) Check(origin string) bool
Check returns true if the origin is allowed.
func (*OriginChecker) CheckRequest ¶ added in v0.0.18
func (c *OriginChecker) CheckRequest(r *http.Request) bool
CheckRequest validates an HTTP request's origin using both Origin and Host headers. This implements the full DNS rebinding protection pattern:
- Origin header present → delegates to Check(origin)
- Origin absent, Host is localhost → allow (local dev tools like curl)
- Origin absent, Host matches the allowlist → allow (e.g. a LAN address listed so a phone can reach a dev server)
- Origin absent, any other Host → reject (potential DNS rebinding)
- No Origin or Host info → allow (same-origin or non-browser client)
Nil-safe: calling on a nil *OriginChecker allows all requests.
func (*OriginChecker) Middleware ¶
func (c *OriginChecker) Middleware(next http.Handler) http.Handler
Middleware returns an HTTP middleware that rejects disallowed origins. Only applies to WebSocket upgrade requests (Connection: Upgrade). Non-upgrade requests pass through unchanged.
type RateLimitConfig ¶
type RateLimitConfig struct {
GlobalPerSec float64 // max requests/sec globally (0 = unlimited)
PerKeyPerSec float64 // max requests/sec per key (0 = unlimited)
PerKeyBurst int // burst allowance per key
KeyLimiterTTL time.Duration // cleanup interval for stale per-key limiters
}
RateLimitConfig controls rate limiting.
func DefaultRateLimitConfig ¶
func DefaultRateLimitConfig() RateLimitConfig
DefaultRateLimitConfig returns sensible defaults.
type RateLimiter ¶
type RateLimiter struct {
Config RateLimitConfig
// OnRejected is called when a request is rate-limited.
// The key argument is the rate limit key (e.g., IP address, subject ID).
OnRejected func(key string)
// contains filtered or unexported fields
}
RateLimiter enforces global and per-key rate limits.
func NewRateLimiter ¶
func NewRateLimiter(cfg RateLimitConfig) *RateLimiter
NewRateLimiter creates a rate limiter. Returns nil if both limits are 0.
Example ¶
ExampleNewRateLimiter demonstrates per-key rate limiting with a custom key function. The default key is client IP; override it to rate limit per user, per API key, or per any request attribute.
package main
import (
"fmt"
"net/http"
mw "github.com/panyam/servicekit/middleware"
)
func main() {
rl := mw.NewRateLimiter(mw.RateLimitConfig{
GlobalPerSec: 100,
PerKeyPerSec: 5,
PerKeyBurst: 3,
})
// Rate limit by API key header instead of IP
apiKeyFunc := func(r *http.Request) string {
return r.Header.Get("X-API-Key")
}
handler := rl.Middleware(apiKeyFunc)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
}))
_ = handler
fmt.Println("Rate limiter configured")
}
Output: Rate limiter configured
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string) bool
Allow checks both global and per-key rate limits. Returns false if rejected.
func (*RateLimiter) Middleware ¶
func (rl *RateLimiter) Middleware(keyFunc func(*http.Request) string) func(http.Handler) http.Handler
Middleware returns an HTTP middleware that enforces rate limits. keyFunc extracts the rate limit key from the request. If nil, defaults to ClientIP.
type RequestID ¶ added in v0.0.7
type RequestID struct{}
RequestID generates or propagates request IDs via the X-Request-Id header. If the incoming request has an X-Request-Id header, it is preserved. Otherwise, a new 32-character hex string (16 random bytes) is generated. The ID is stored in the request context and set on the response header.
func NewRequestID ¶ added in v0.0.7
func NewRequestID() *RequestID
NewRequestID creates a RequestID middleware instance.
type TrustedProxies ¶ added in v0.2.5
TrustedProxies lists the reverse proxies and load balancers in front of this process. Forwarding headers (X-Forwarded-For, X-Real-IP, X-Forwarded-Proto, Forwarded) are client-supplied, so they count only when the TCP peer is in this list (CWE-348).
An empty or nil list trusts nobody. Every request then reports its TCP peer as the client, and IsHTTPS reports only whether this process ended TLS itself. To trust every peer, list 0.0.0.0/0 and ::/0, and only do that when the network guarantees nothing but the proxy can reach this port.
The zero value is ready to use. A TrustedProxies is read-only after parsing and safe for concurrent use.
func ParseTrustedProxies ¶ added in v0.2.5
func ParseTrustedProxies(entries []string) (TrustedProxies, error)
ParseTrustedProxies parses CIDRs ("10.0.0.0/8") and single addresses ("192.0.2.10", "::1") into TrustedProxies. Blank entries are skipped. Any other entry that fails to parse returns an error naming it, so a typo in operator config fails at startup instead of trusting less than intended.
func (TrustedProxies) ClientIP ¶ added in v0.2.5
func (tp TrustedProxies) ClientIP(r *http.Request) string
ClientIP returns the address a request came from, for rate limiting and logging. Its signature fits RateLimiter.Middleware's keyFunc, so rl.Middleware(tp.ClientIP) keys buckets by it.
When the TCP peer is not trusted, the answer is the peer, whatever the headers say. Otherwise anyone could send a fresh X-Forwarded-For with every request and get a fresh rate-limit bucket each time.
When the peer is trusted, X-Forwarded-For is walked right to left. Each trusted hop vouches for the entry to its left, so the first untrusted entry is the client. Entries to its left were written by the client and are ignored. When every entry is trusted, the leftmost one is the client. An entry that does not parse as an address stops the walk and returns the peer. X-Real-IP is read only when a trusted peer sent no X-Forwarded-For.
func (TrustedProxies) Contains ¶ added in v0.2.5
func (tp TrustedProxies) Contains(addr netip.Addr) bool
Contains reports whether addr is one of the trusted proxies. An IPv4-mapped IPv6 address ("::ffff:10.0.0.1") matches its IPv4 form.
func (TrustedProxies) IsHTTPS ¶ added in v0.2.5
func (tp TrustedProxies) IsHTTPS(r *http.Request) bool
IsHTTPS reports whether the client reached this server over HTTPS, for decisions like marking a cookie Secure. It is true when this process ended TLS itself (r.TLS is set). Behind a proxy that ends TLS the request arrives as plain HTTP, so it is also true when the TCP peer is trusted and the proxy says https. The proxy says so in the first X-Forwarded-Proto value, or, when that header is absent, in the proto of the first Forwarded element (RFC 7239). Only the first value counts, because the proxy nearest the client writes it.
From an untrusted peer both headers are ignored and the answer is r.TLS != nil. An empty list therefore never reads them.