Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for Go services: authentication (API key, HMAC signatures, mTLS client certificates), rate limiting, an IP allowlist, security headers, request logging, gzip compression and request body limiting.
Every middleware here serves net/http and is named XxxStd. The Fiber half of each pair lives in the fiberadapter subpackage, so importing this package does not link Fiber -- and with it fasthttp -- into a binary that never serves a Fiber route. The two halves share their configuration structs and the rules they enforce; see fiberadapter's package documentation.
The exported helpers that carry those shared rules -- AuthenticateMTLS, ConstantTimeEqual, HMACConfig.ExpectedSignature and the rest -- exist so a framework adapter runs the same check the net/http middleware runs rather than a second copy of it.
Index ¶
- Variables
- func APIKeyAuthStd(cfg APIKeyConfig) func(http.Handler) http.Handler
- func AuthenticateMTLS(state *tls.ConnectionState, cfg MTLSConfig, lists CertAllowLists) (*x509.Certificate, error)
- func BodyLimitStd(cfg BodyLimitConfig) func(http.Handler) http.Handler
- func CertificateAbsent(err error) bool
- func CompressStd(cfg CompressConfig) func(http.Handler) http.Handler
- func ComputeHMAC(timestamp, service, body, secret string) string
- func ComputeHMACBound(in SignatureInput) string
- func ConstantTimeEqual(a, b string) bool
- func GetClientIP(r *http.Request, trustedConfig *TrustedProxyConfig) string
- func HMACAuthStd(cfg HMACConfig) func(http.Handler) http.Handler
- func HeaderOrDefault(header, defaultValue string) string
- func IPAllowlistMiddleware(allowlist string) func(http.Handler) http.Handler
- func IPAllowlistMiddlewareFromConfig(cfg IPAllowlistConfig) func(http.Handler) http.Handler
- func IsPrivateIP(ip net.IP) bool
- func IsTimestampValid(timestamp, maxDriftSeconds int64) bool
- func JoinForwarded(values []string) string
- func LastHeaderValue(values []string) string
- func MTLSAuthStd(cfg MTLSConfig) func(http.Handler) http.Handler
- func MaskEmail(email string) string
- func MaskPhone(phone string) string
- func NoCacheHeadersStd() func(http.Handler) http.Handler
- func ParseTimestamp(timestamp string) (int64, error)
- func RateLimitStd(cfg RateLimitConfig) func(http.Handler) http.Handler
- func ReplayRetention(maxDrift time.Duration) time.Duration
- func RequestLoggingStd(cfg LoggingConfig) func(http.Handler) http.Handler
- func SecurityHeadersStd(cfg SecurityHeadersConfig) func(http.Handler) http.Handler
- type APIKeyConfig
- type AuthConfig
- type BodyLimitConfig
- type CertAllowLists
- type CompressConfig
- type HMACConfig
- func (cfg HMACConfig) CheckTimestamp(timestamp string) error
- func (cfg HMACConfig) ExpectedSignature(in SignatureInput) string
- func (cfg HMACConfig) ResolveSecret(keyID string) (secret string, disabled bool, err error)
- func (cfg HMACConfig) ServiceAllowed(service string) bool
- func (cfg HMACConfig) WithDefaults() HMACConfig
- type IPAllowlistConfig
- type LoggingConfig
- type MTLSConfig
- type MemoryReplayGuard
- type RateLimitConfig
- type RateLimiter
- type RateLimiterConfig
- type ReplayGuard
- type RequestSignatureFunc
- type SecurityHeadersConfig
- type SignatureInput
- type TrustedProxyConfig
Constants ¶
This section is empty.
Variables ¶
var ( // ErrAPIKeyNotConfigured indicates no API key was configured on the server. ErrAPIKeyNotConfigured = errors.New("API key not configured") // ErrAPIKeyMissing indicates no API key was provided in the request. ErrAPIKeyMissing = errors.New("API key missing") // ErrAPIKeyInvalid indicates the provided API key is invalid. ErrAPIKeyInvalid = errors.New("API key invalid") // ErrHMACSecretNotConfigured indicates no HMAC secret was configured. ErrHMACSecretNotConfigured = errors.New("HMAC secret not configured") // ErrHMACSignatureMissing indicates no HMAC signature was provided. ErrHMACSignatureMissing = errors.New("HMAC signature missing") // ErrHMACSignatureInvalid indicates the HMAC signature is invalid. ErrHMACSignatureInvalid = errors.New("HMAC signature invalid") // ErrHMACTimestampMissing indicates no timestamp was provided for HMAC. ErrHMACTimestampMissing = errors.New("HMAC timestamp missing") // ErrHMACTimestampInvalid indicates the timestamp format is invalid. ErrHMACTimestampInvalid = errors.New("HMAC timestamp invalid") // ErrHMACTimestampExpired indicates the timestamp has expired. ErrHMACTimestampExpired = errors.New("HMAC timestamp expired") // ErrHMACKeyIDInvalid indicates the key ID is invalid or not found. ErrHMACKeyIDInvalid = errors.New("HMAC key ID invalid") // ErrMTLSCertificateMissing indicates no client certificate was provided. ErrMTLSCertificateMissing = errors.New("mTLS client certificate missing") // ErrMTLSCertificateInvalid indicates the client certificate is invalid. ErrMTLSCertificateInvalid = errors.New("mTLS client certificate invalid") // ErrMTLSCertificateUnverified indicates the peer presented a certificate // that the TLS layer did not verify against the server's ClientCAs. This // happens when the server is configured with tls.RequestClientCert or // tls.RequireAnyClientCert instead of tls.RequireAndVerifyClientCert. ErrMTLSCertificateUnverified = errors.New("mTLS client certificate not verified by the TLS layer") ErrUnauthorized = errors.New("unauthorized") )
Authentication errors
var ( // ErrRateLimitExceeded indicates the rate limit has been exceeded. ErrRateLimitExceeded = errors.New("rate limit exceeded") )
Rate limiting errors
var ( // ErrRequestBodyTooLarge indicates the request body exceeds the size limit. ErrRequestBodyTooLarge = errors.New("request body too large") )
Request errors
Functions ¶
func APIKeyAuthStd ¶
func APIKeyAuthStd(cfg APIKeyConfig) func(http.Handler) http.Handler
APIKeyAuthStd creates a standard net/http middleware for API key authentication.
func AuthenticateMTLS ¶
func AuthenticateMTLS(state *tls.ConnectionState, cfg MTLSConfig, lists CertAllowLists) (*x509.Certificate, error)
AuthenticateMTLS runs the complete mTLS check for a connection state: the certificate must be verified by the TLS layer AND satisfy every restriction in cfg -- chain presence, then the CN, OU and DNS SAN allow lists, then CertValidator.
This is the single entry point for every middleware that authenticates a client certificate, net/http and Fiber alike, so no combined middleware can accept a certificate that a dedicated one would reject. Two copies of a certificate check is how one framework ends up accepting what the other rejects; that is also why it is exported rather than reimplemented in the adapter.
func BodyLimitStd ¶
func BodyLimitStd(cfg BodyLimitConfig) func(http.Handler) http.Handler
BodyLimitStd creates a standard net/http middleware that limits request body size.
func CertificateAbsent ¶
CertificateAbsent reports whether err says the client presented no certificate at all -- the one condition RequireCert=false is meant to wave through.
Deliberately NOT errors.Is(err, ErrMTLSCertificateMissing). A CertValidator is caller-supplied code, and one that returns or wraps that exported sentinel made a certificate which explicitly FAILED validation read as an absent one, so the request was let through whenever RequireCert was false. This type is unexported, so only the presence check above can produce it.
func CompressStd ¶
func CompressStd(cfg CompressConfig) func(http.Handler) http.Handler
CompressStd creates a standard net/http middleware for gzip compression.
func ComputeHMAC ¶
ComputeHMAC computes an HMAC-SHA256 signature. The message format is: timestamp:service:body
func ComputeHMACBound ¶
func ComputeHMACBound(in SignatureInput) string
ComputeHMACBound computes HMAC-SHA256 over a canonical, unambiguous encoding of the request:
len(method) "\n" method "\n" len(path) "\n" path "\n" ... and so on for query, timestamp, service, body
Two properties matter here:
- The method, path and query are covered, so a signature minted for POST /transfer cannot be replayed against POST /delete-account.
- Every field is length-prefixed, so no combination of field values can produce the same byte string as a different combination. The legacy "timestamp:service:body" form has no such property: service is taken from a client-supplied header, so ("a", "b:c") and ("a:b", "c") sign identically and a valid signature can be presented with a different service than the one it was issued for.
func ConstantTimeEqual ¶
ConstantTimeEqual compares two strings in constant time, without leaking how much of them matched or how long the expected value is.
subtle.ConstantTimeCompare returns early when the lengths differ, so calling it directly on a secret and an attacker-supplied value leaks the secret's length through timing. Both inputs are padded to the same size first, and the length check is folded into the result.
func GetClientIP ¶
func GetClientIP(r *http.Request, trustedConfig *TrustedProxyConfig) string
GetClientIP extracts the real client IP address from an HTTP request. It honours X-Forwarded-For and X-Real-IP only when the direct peer is a trusted proxy, and resolves the chain from the right so a client cannot prepend an address of its choosing.
func HMACAuthStd ¶
func HMACAuthStd(cfg HMACConfig) func(http.Handler) http.Handler
func HeaderOrDefault ¶
HeaderOrDefault returns header when non-empty, otherwise defaultValue.
Exported so a framework adapter resolves a configured header name to the same default the net/http middlewares use.
func IPAllowlistMiddleware ¶
IPAllowlistMiddleware returns an http.Handler that allows only requests from IPs or CIDR ranges in allowlist. allowlist is comma-separated (e.g. "127.0.0.1,10.0.0.0/8,192.168.1.1"). If allowlist is empty, the returned handler is a pass-through (all requests allowed). Client IP is resolved via GetClientIP(r, nil); use IPAllowlistMiddlewareFromConfig when you need OnDenied or TrustedProxyConfig.
func IPAllowlistMiddlewareFromConfig ¶
func IPAllowlistMiddlewareFromConfig(cfg IPAllowlistConfig) func(http.Handler) http.Handler
IPAllowlistMiddlewareFromConfig returns an http.Handler that allows only requests from IPs or CIDR ranges in cfg.Allowlist. If cfg.Allowlist is empty, the returned handler is a pass-through. When access is denied, cfg.OnDenied is called if set, otherwise http.Error(w, "Forbidden", 403) is used. Client IP is resolved via GetClientIP(r, cfg.TrustedProxyConfig).
func IsPrivateIP ¶
IsPrivateIP checks if an IP address is a private IP address.
func IsTimestampValid ¶
IsTimestampValid checks if a timestamp is within the allowed drift.
func JoinForwarded ¶
JoinForwarded splices every X-Forwarded-For field into one chain, in wire order.
The header may legitimately appear more than once: a proxy that APPENDS its own line instead of coalescing into the client's is compliant, and RFC 9110 says the two forms are equivalent. Header.Get returns only the FIRST line, so in that deployment the resolver walked a chain consisting of nothing but the client's own fabrication -- the proxy-added address was never in it, and the right-to-left rule that makes this function spoof-resistant had nothing to work with. Every control keyed on it (allow-lists, per-IP rate limits) was bypassable by sending a single X-Forwarded-For header.
func LastHeaderValue ¶
LastHeaderValue returns the last non-empty value of a single-valued header.
The LAST, for the same reason: a proxy that appends rather than overwrites puts its own value after whatever the client sent, so the final line is the one attributable to the trusted hop. Where the proxy overwrites, there is only one and this is the same value Get would return.
func MTLSAuthStd ¶
func MTLSAuthStd(cfg MTLSConfig) func(http.Handler) http.Handler
MTLSAuthStd creates a standard net/http middleware for mTLS authentication. It requires TLS to be configured with ClientAuth; the Fiber equivalent is fiberadapter.MTLSAuth.
func MaskEmail ¶
MaskEmail masks an email address for logging. Example: john.doe@example.com -> jo***@example.com
func NoCacheHeadersStd ¶
NoCacheHeadersStd creates a standard net/http middleware that prevents caching.
func ParseTimestamp ¶
ParseTimestamp parses a Unix timestamp string.
func RateLimitStd ¶
func RateLimitStd(cfg RateLimitConfig) func(http.Handler) http.Handler
RateLimitStd creates a standard net/http middleware for rate limiting.
func ReplayRetention ¶
ReplayRetention is how long a ReplayGuard must remember a signature.
It has to cover the whole span over which one timestamp stays acceptable. Timestamps are validated as integer seconds, inclusively, against time.Now().Unix(): a request stamped ts is accepted while ts-drift <= floor(now) <= ts+drift, so the first acceptance can be as early as ts-drift and the last as late as ts+drift+1 (a whole second past ts+drift, because floor(now) does not tick until then).
Hence 2*drift + 1s. Retaining for one drift let a captured request through again as soon as the first retention elapsed; retaining for exactly two left the final fractional second of validity uncovered -- with the 5 minute default, a 0.9s window in which the same request replayed successfully.
func RequestLoggingStd ¶
func RequestLoggingStd(cfg LoggingConfig) func(http.Handler) http.Handler
RequestLoggingStd creates a standard net/http middleware for request logging.
func SecurityHeadersStd ¶
func SecurityHeadersStd(cfg SecurityHeadersConfig) func(http.Handler) http.Handler
SecurityHeadersStd creates a standard net/http middleware that adds security headers.
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
// APIKey is the expected API key value.
// If empty, authentication will fail for all requests (secure by default).
APIKey string
// HeaderName is the header name to look for the API key.
// Default: "X-API-Key"
HeaderName string
// QueryParamName is the query parameter name to look for the API key.
// If set, the middleware will also check query parameters.
// Default: "" (disabled)
//
// Enable this only when a client genuinely cannot set headers. A key in
// the query string is recorded by access logs, proxy logs, browser
// history, and is sent onwards in the Referer header of any outbound link.
QueryParamName string
// AuthScheme is the Authorization header scheme (e.g., "Bearer", "ApiKey").
// If set, the middleware will also check Authorization header.
// Default: "" (disabled)
AuthScheme string
// AllowEmptyKey allows requests when no API key is configured.
// This is useful for development mode but NOT recommended for production.
// Default: false
AllowEmptyKey bool
// Logger for logging authentication events.
// If nil, no logging is performed.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
APIKeyConfig configures the API Key authentication middleware.
func DefaultAPIKeyConfig ¶
func DefaultAPIKeyConfig() APIKeyConfig
DefaultAPIKeyConfig returns the default API key configuration.
type AuthConfig ¶
type AuthConfig struct {
// MTLSConfig for mTLS authentication (highest priority)
MTLSConfig *MTLSConfig
// HMACConfig for HMAC signature authentication
HMACConfig *HMACConfig
// APIKeyConfig for API key authentication (lowest priority)
APIKeyConfig *APIKeyConfig
// AllowNoAuth allows requests when no authentication method is configured.
// This is useful for development mode but NOT recommended for production.
// Default: false
AllowNoAuth bool
// Logger for logging authentication events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection.
TrustedProxyConfig *TrustedProxyConfig
}
AuthConfig configures the combined authentication middleware. It supports multiple authentication methods with priority: mTLS > HMAC > API Key
type BodyLimitConfig ¶
type BodyLimitConfig struct {
// MaxSize is the maximum allowed request body size in bytes.
// Default: 4MB (4 * 1024 * 1024)
MaxSize int64
// SkipMethods is a list of HTTP methods to skip body limit check.
// Default: ["GET", "HEAD", "OPTIONS"]
SkipMethods []string
// SkipPaths is a list of paths to skip body limit check.
SkipPaths []string
// Logger for logging body limit events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
BodyLimitConfig configures the body limit middleware.
func DefaultBodyLimitConfig ¶
func DefaultBodyLimitConfig() BodyLimitConfig
DefaultBodyLimitConfig returns the default body limit configuration.
type CertAllowLists ¶
type CertAllowLists struct {
// contains filtered or unexported fields
}
CertAllowLists holds the CN/OU/SAN allow lists of an MTLSConfig in lookup form, so the per-request path does not rebuild them.
Exported so a framework adapter builds them once, as the net/http middleware does.
func NewCertAllowLists ¶
func NewCertAllowLists(cfg MTLSConfig) CertAllowLists
NewCertAllowLists builds the lookup sets AuthenticateMTLS matches against.
Exported for framework adapters.
type CompressConfig ¶
type CompressConfig struct {
// Level is the gzip compression level.
// Valid values: gzip.NoCompression (0) to gzip.BestCompression (9)
// Default: gzip.DefaultCompression (-1)
Level int
// MinSize is the minimum response size to trigger compression.
// Responses smaller than this are not compressed.
// Default: 1024 (1KB)
MinSize int
// SkipPaths is a list of paths to skip compression.
SkipPaths []string
// ContentTypes is a list of content types to compress.
// If empty, all text-based content types are compressed.
// Example: ["application/json", "text/html", "text/plain"]
ContentTypes []string
}
CompressConfig configures the compression middleware.
func DefaultCompressConfig ¶
func DefaultCompressConfig() CompressConfig
DefaultCompressConfig returns the default compression configuration.
type HMACConfig ¶
type HMACConfig struct {
// Secret is the shared secret for HMAC signature verification.
// Required if KeyProvider is not set.
Secret string
// KeyProvider provides HMAC secrets by key ID.
// This allows for key rotation support.
// If set, takes precedence over Secret.
KeyProvider func(keyID string) string
// SignatureHeader is the header name for the HMAC signature.
// Default: "X-Signature"
SignatureHeader string
// TimestampHeader is the header name for the request timestamp.
// Default: "X-Timestamp"
TimestampHeader string
// KeyIDHeader is the header name for the key ID (for key rotation).
// Default: "X-Key-Id"
KeyIDHeader string
// ServiceHeader is the header name for the service identifier.
// Default: "X-Service"
ServiceHeader string
// MaxTimeDrift is the maximum allowed time difference between
// the request timestamp and server time.
// Default: 5 minutes
MaxTimeDrift time.Duration
// AllowEmptySecret allows requests when no secret is configured.
// This is useful for development mode but NOT recommended for production.
// Default: false
AllowEmptySecret bool
// SignatureFunc is a custom function to compute the expected signature.
// If nil, the default signature function is used:
// HMAC-SHA256(secret, timestamp:service:body)
//
// Note what this form does NOT cover: the request method, path and query.
// A signature minted for POST /transfer is equally valid on POST
// /delete-account with the same body. Set RequestSignatureFunc to bind the
// signature to the request target.
SignatureFunc func(timestamp, service, body, secret string) string
// AllowDelimitersInService permits ':' in the service identifier.
//
// ':' is rejected by default because ComputeHMAC -- the signer used when
// neither function below is set -- signs "timestamp:service:body", which
// has no field boundaries: (service "a", body "b:c") and (service "a:b",
// body "c") produce the same bytes, so one signature stands for two
// different requests.
//
// Whether a signer is safe from that cannot be inferred from the config:
// SignatureFunc may be ComputeHMAC itself, or a wrapper around it, and a
// custom RequestSignatureFunc may concatenate just as ambiguously. So the
// guard stays on unless you turn it off here, having checked that your
// signer frames its fields unambiguously. This package's own
// ComputeHMACBound is length-prefixed and is recognised without the flag.
AllowDelimitersInService bool
// RequestSignatureFunc computes the expected signature over the full
// request, including its method, path and query. When set it takes
// precedence over SignatureFunc.
//
// ComputeHMACBound is the recommended implementation. Switching to it
// changes the bytes being signed, so every signer has to be updated at the
// same time; that is why it is opt-in rather than the default.
RequestSignatureFunc RequestSignatureFunc
// ReplayGuard, when set, rejects a signature that has already been
// accepted. Without it a captured request can be replayed freely for the
// whole MaxTimeDrift window (5 minutes by default).
//
// Use NewMemoryReplayGuard for a single instance, or a shared store for a
// multi-instance deployment.
ReplayGuard ReplayGuard
// Logger for logging authentication events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
HMACConfig configures the HMAC signature authentication middleware.
func DefaultHMACConfig ¶
func DefaultHMACConfig() HMACConfig
DefaultHMACConfig returns the default HMAC configuration.
func (HMACConfig) CheckTimestamp ¶
func (cfg HMACConfig) CheckTimestamp(timestamp string) error
CheckTimestamp validates a request timestamp against MaxTimeDrift, and logs the rejection when it is outside the window.
The drift is an absolute value, so a timestamp far in the FUTURE is refused just as one far in the past is.
Exported so a framework adapter applies exactly the window the net/http middleware applies.
func (HMACConfig) ExpectedSignature ¶
func (cfg HMACConfig) ExpectedSignature(in SignatureInput) string
ExpectedSignature picks the signature function configured on cfg.
RequestSignatureFunc wins when set; otherwise the legacy SignatureFunc (or ComputeHMAC) is used with only timestamp, service and body.
func (HMACConfig) ResolveSecret ¶
func (cfg HMACConfig) ResolveSecret(keyID string) (secret string, disabled bool, err error)
ResolveSecret picks the HMAC secret to verify a request against.
KeyProvider wins when set. A provider that returns nothing for a NON-EMPTY key ID means that key ID is invalid, which is a different answer from "no secret is configured at all" and must not be reported as one.
disabled is true when no secret is configured and AllowEmptySecret permits the request through unauthenticated; the caller should let it pass.
Exported so a framework adapter resolves the secret exactly as the net/http middleware does.
func (HMACConfig) ServiceAllowed ¶
func (cfg HMACConfig) ServiceAllowed(service string) bool
ServiceAllowed reports whether service may be used with cfg's signature function.
The guard is ON unless the configuration positively establishes that the signer is unambiguous. Only two things establish that: the caller setting AllowDelimitersInService, and this package's own length-prefixed ComputeHMACBound.
Non-nilness does not establish it, which is what an earlier version got wrong. "SignatureFunc != nil means a custom signer, so the legacy encoding is not in use" is false for the one assignment most likely to be written by hand -- SignatureFunc: ComputeHMAC, the exported default -- and equally false for any wrapper around it, or for a custom RequestSignatureFunc that concatenates its fields. Each of those turned the guard off while signing exactly the ambiguous bytes it exists to defend.
func (HMACConfig) WithDefaults ¶
func (cfg HMACConfig) WithDefaults() HMACConfig
HMACAuthStd creates a standard net/http middleware for HMAC signature authentication. WithDefaults returns cfg with the header names and MaxTimeDrift filled in.
SignatureFunc is deliberately NOT defaulted to ComputeHMAC. ExpectedSignature already falls back to it, and materializing the default made ServiceAllowed see a non-nil function and mistake the legacy delimiter-based signer for a caller-supplied custom one -- which re-allowed ':' in the service header and reopened the collision that check exists to close.
Exported so a framework adapter defaults a config exactly as the net/http middleware does.
type IPAllowlistConfig ¶
type IPAllowlistConfig struct {
// Allowlist is a comma-separated list of IP addresses and/or CIDR networks (e.g. "127.0.0.1,10.0.0.0/8").
// If empty, all requests are allowed (pass-through).
Allowlist string
// OnDenied is called when the client IP is not in the allowlist. If nil, http.Error(w, "Forbidden", 403) is used.
// Use this to log and then respond (e.g. log and http.Error).
OnDenied func(w http.ResponseWriter, r *http.Request)
// TrustedProxyConfig for client IP resolution. If nil, DefaultTrustedProxyConfig() is used.
TrustedProxyConfig *TrustedProxyConfig
}
IPAllowlistConfig configures IP allowlist middleware.
type LoggingConfig ¶
type LoggingConfig struct {
// Logger is the zerolog logger to use.
// If nil, logging is disabled.
Logger *zerolog.Logger
// SkipPaths is a list of paths to skip logging.
// Useful for health check endpoints.
SkipPaths []string
// LogRequestBody enables logging of request body.
// Warning: This may log sensitive data.
// Default: false
LogRequestBody bool
// LogResponseBody enables logging of response body.
// Warning: This may log sensitive data and impact performance.
// Default: false
LogResponseBody bool
// MaxBodyLogSize is the maximum body size to log (in bytes).
// Bodies larger than this are truncated.
// Default: 1024
MaxBodyLogSize int
// LogHeaders enables logging of request headers.
// Default: false
LogHeaders bool
// SensitiveHeaders is a list of header names to mask in logs.
// Default: ["Authorization", "X-API-Key", "Cookie", "Set-Cookie"]
SensitiveHeaders []string
// LogLevel is the log level for successful requests.
// Default: zerolog.InfoLevel
LogLevel zerolog.Level
// ErrorLogLevel is the log level for failed requests (status >= 400).
// Default: zerolog.WarnLevel
ErrorLogLevel zerolog.Level
// IncludeLatency includes request latency in logs.
// Default: true
IncludeLatency bool
// TrustedProxyConfig for client IP detection.
TrustedProxyConfig *TrustedProxyConfig
}
LoggingConfig configures the request logging middleware.
func DefaultLoggingConfig ¶
func DefaultLoggingConfig() LoggingConfig
DefaultLoggingConfig returns the default logging configuration.
type MTLSConfig ¶
type MTLSConfig struct {
// RequireCert requires a valid client certificate.
// If false, requests without certificates are allowed through.
// Default: true
RequireCert bool
// AllowedCNs is a list of allowed Common Names.
// If empty, any valid certificate is accepted.
AllowedCNs []string
// AllowedOUs is a list of allowed Organizational Units.
// If empty, any valid certificate is accepted.
AllowedOUs []string
// AllowedDNSSANs is a list of allowed DNS Subject Alternative Names.
// If empty, any valid certificate is accepted.
AllowedDNSSANs []string
// CertValidator is a custom function to validate the client certificate.
// If set, it's called after the built-in validation.
// Return nil to accept the certificate, or an error to reject it.
CertValidator func(cert *x509.Certificate) error
// Logger for logging authentication events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection in logs.
TrustedProxyConfig *TrustedProxyConfig
}
MTLSConfig configures the mTLS (mutual TLS) authentication middleware.
func DefaultMTLSConfig ¶
func DefaultMTLSConfig() MTLSConfig
DefaultMTLSConfig returns the default mTLS configuration.
type MemoryReplayGuard ¶
type MemoryReplayGuard struct {
// contains filtered or unexported fields
}
MemoryReplayGuard is a single-process ReplayGuard.
It is suitable for a single instance. A deployment behind a load balancer needs a shared store (Redis SET NX with a TTL, for example), otherwise a request replayed to a different instance is not detected.
func NewMemoryReplayGuard ¶
func NewMemoryReplayGuard() *MemoryReplayGuard
NewMemoryReplayGuard returns an empty in-process replay guard.
func (*MemoryReplayGuard) Seen ¶
func (g *MemoryReplayGuard) Seen(id string, ttl time.Duration) bool
Seen records id and reports whether it had been seen before.
ttl is the full retention the caller asks for -- see ReplayRetention, which doubles MaxTimeDrift to cover a signature's whole validity period rather than just the drift. It applies to THIS id only.
type RateLimitConfig ¶
type RateLimitConfig struct {
// Limiter is the rate limiter to use.
// If nil, a new one is created with default settings.
Limiter *RateLimiter
// SkipPaths is a list of paths to skip rate limiting.
SkipPaths []string
// Logger for logging rate limit events.
Logger *zerolog.Logger
// TrustedProxyConfig for client IP detection.
TrustedProxyConfig *TrustedProxyConfig
// OnLimitReached is called when the rate limit is reached.
// Useful for recording metrics.
OnLimitReached func(key string)
}
RateLimitConfig configures the rate limit middleware.
type RateLimiter ¶
type RateLimiter struct {
// contains filtered or unexported fields
}
RateLimiter implements an in-memory rate limiter with sliding window.
func NewRateLimiter ¶
func NewRateLimiter(cfg RateLimiterConfig) *RateLimiter
NewRateLimiter creates a new rate limiter with the given configuration.
func (*RateLimiter) AddToWhitelist ¶
func (rl *RateLimiter) AddToWhitelist(key string) bool
AddToWhitelist adds a key to the whitelist.
func (*RateLimiter) Allow ¶
func (rl *RateLimiter) Allow(key string) bool
Allow checks if a request from the given key should be allowed.
func (*RateLimiter) IsWhitelisted ¶
func (rl *RateLimiter) IsWhitelisted(key string) bool
IsWhitelisted checks if a key is in the whitelist.
func (*RateLimiter) RemoveFromWhitelist ¶
func (rl *RateLimiter) RemoveFromWhitelist(key string)
RemoveFromWhitelist removes a key from the whitelist.
func (*RateLimiter) Reset ¶
func (rl *RateLimiter) Reset()
Reset clears all visitor data and whitelist.
func (*RateLimiter) Stop ¶
func (rl *RateLimiter) Stop()
Stop stops the rate limiter and its cleanup goroutine.
type RateLimiterConfig ¶
type RateLimiterConfig struct {
// Rate is the maximum number of requests allowed per window.
// Default: 100
Rate int
// Window is the time window for rate limiting.
// Default: 1 minute
Window time.Duration
// MaxVisitors is the maximum number of unique visitors to track.
// Oldest entries are evicted when this limit is reached.
// Default: 10000
MaxVisitors int
// MaxWhitelist is the maximum number of whitelisted IPs.
// Default: 100
MaxWhitelist int
// CleanupInterval is how often to clean up expired entries.
// Default: 1 minute
CleanupInterval time.Duration
}
RateLimiterConfig configures the rate limiter.
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig() RateLimiterConfig
DefaultRateLimiterConfig returns the default rate limiter configuration.
type ReplayGuard ¶
type ReplayGuard interface {
// Seen atomically records id and reports whether it was already present.
// Implementations must expire entries after ttl.
Seen(id string, ttl time.Duration) bool
}
ReplayGuard records request identities that have already been accepted, so a captured request cannot be replayed within the timestamp window.
A timestamp window alone does not prevent replay: it only bounds how long a captured request stays useful. With MaxTimeDrift at its 5 minute default, every signed request is replayable an unlimited number of times for five minutes.
type RequestSignatureFunc ¶
type RequestSignatureFunc func(in SignatureInput) string
RequestSignatureFunc computes the expected signature for a request.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
// XContentTypeOptions sets X-Content-Type-Options header.
// Prevents MIME type sniffing.
// Default: "nosniff"
XContentTypeOptions string
// XFrameOptions sets X-Frame-Options header.
// Prevents clickjacking.
// Default: "DENY"
XFrameOptions string
// XXSSProtection sets the X-XSS-Protection header.
//
// Default: "0". The header is deprecated and the legacy filter it enabled
// ("1; mode=block") introduced XSS and cross-site info-leak bugs of its own
// in the browsers that shipped it, so current guidance is to disable it
// explicitly and rely on Content-Security-Policy instead.
// Enables browser XSS filter.
// Default: "1; mode=block"
XXSSProtection string
// ReferrerPolicy sets Referrer-Policy header.
// Controls referrer information.
// Default: "strict-origin-when-cross-origin"
ReferrerPolicy string
// ContentSecurityPolicy sets Content-Security-Policy header.
// Controls resource loading policy.
// Default: "" (not set)
ContentSecurityPolicy string
// StrictTransportSecurity sets Strict-Transport-Security header.
// Enforces HTTPS connections.
// Default: "" (not set, set to "max-age=31536000; includeSubDomains" for production)
StrictTransportSecurity string
// PermissionsPolicy sets Permissions-Policy header.
// Controls browser features.
// Default: "" (not set)
PermissionsPolicy string
// CrossOriginOpenerPolicy sets Cross-Origin-Opener-Policy header.
// Default: "" (not set)
CrossOriginOpenerPolicy string
// CrossOriginResourcePolicy sets Cross-Origin-Resource-Policy header.
// Default: "" (not set)
CrossOriginResourcePolicy string
// CrossOriginEmbedderPolicy sets Cross-Origin-Embedder-Policy header.
// Default: "" (not set)
CrossOriginEmbedderPolicy string
// CacheControl sets Cache-Control header.
// Default: "" (not set)
CacheControl string
// Pragma sets Pragma header.
// Default: "" (not set)
Pragma string
// CustomHeaders allows setting additional custom headers.
CustomHeaders map[string]string
}
SecurityHeadersConfig configures security headers middleware.
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns the default security headers configuration.
func StrictSecurityHeadersConfig ¶
func StrictSecurityHeadersConfig() SecurityHeadersConfig
StrictSecurityHeadersConfig returns a stricter security headers configuration. Suitable for production API servers.
type SignatureInput ¶
type SignatureInput struct {
Method string
// Path is the request target's ESCAPED path, not the decoded one.
//
// Decoding first collapses distinct targets: "/a/b" and "/a%2Fb" both
// decode to "/a/b" and would sign identically, while net/http's ServeMux
// routes the first to "/a/b" and the second to a single-segment
// "/{x}" handler -- so a signature authorized for one route would
// authenticate a different one.
Path string
RawQuery string
Timestamp string
Service string
Body string
Secret string
}
SignatureInput carries everything a request signature may be computed over.
The legacy SignatureFunc only receives timestamp, service, body and secret, which is why a signature produced for one endpoint is equally valid on any other endpoint that accepts the same body. RequestSignatureFunc receives the request target as well so the signature can be bound to it.
type TrustedProxyConfig ¶
type TrustedProxyConfig struct {
// TrustedProxies is a list of trusted proxy IP addresses or CIDR ranges.
// If empty, private IP addresses are trusted by default.
TrustedProxies []string
// TrustAllProxies trusts all proxies (not recommended for production).
TrustAllProxies bool
// contains filtered or unexported fields
}
TrustedProxyConfig configures trusted proxy settings for client IP detection.
A zero value, or one built as a struct literal, is safe to use: the proxy list is parsed lazily on first use. Previously only NewTrustedProxyConfig populated the parsed fields, so a literal such as
&TrustedProxyConfig{TrustedProxies: []string{"10.0.0.1"}}
left them empty and IsTrusted fell through to its "nothing configured" branch -- trusting every private address instead of the single one asked for. A tightened policy silently became a looser one.
func DefaultTrustedProxyConfig ¶
func DefaultTrustedProxyConfig() *TrustedProxyConfig
DefaultTrustedProxyConfig returns a default configuration that trusts private IPs.
func NewTrustedProxyConfig ¶
func NewTrustedProxyConfig(proxies []string) *TrustedProxyConfig
NewTrustedProxyConfig creates a TrustedProxyConfig from a list of IP addresses or CIDR ranges.
func (*TrustedProxyConfig) ClientIPFromForwarded ¶
func (c *TrustedProxyConfig) ClientIPFromForwarded(forwarded, realIP string, peer net.IP) string
ClientIPFromForwarded resolves the client address from a forwarded chain, assuming the direct peer has already been established as a trusted proxy.
The chain is walked from the RIGHT: every well-behaved hop appends the address it received the request from, so the rightmost entries are the proxies nearest to us. Entries that are themselves trusted proxies are skipped; the first untrusted address is the client.
Taking the leftmost entry instead -- the previous behaviour -- is spoofable by design. A client sends "X-Forwarded-For: 1.2.3.4"; the proxy appends the real address to the right of it; the forged value is still first. That made every control keyed on this function (IP allow-list, per-IP rate limiting, audit logs) trivially bypassable even behind a correctly configured proxy.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package fiberadapter exposes middleware-kit over Fiber v3.
|
Package fiberadapter exposes middleware-kit over Fiber v3. |