middleware

package module
v3.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: Apache-2.0 Imports: 20 Imported by: 2

README

middleware-kit

Go Reference License Go Test Coverage Go Report Card

中文文档

A comprehensive HTTP middleware toolkit for Go services. This package provides authentication (API Key, HMAC, mTLS), rate limiting, security headers, request logging, compression, and body limiting middleware for both Fiber and standard net/http.

Breaking in v3.0.0 — Fiber support moved to a subpackage, and the Fiber mTLS check now runs. The import path is now github.com/soulteary/middleware-kit/v3, and the Fiber middleware is github.com/soulteary/middleware-kit/v3/fiberadapter, so importing the root package no longer links Fiber (and fasthttp) into binaries that never use it. In a net/http service that means 25 fewer linked packages, 11 fewer modules and a 14% smaller binary.

If you use the Fiber MTLSAuth or CombinedAuth, read Upgrade Notes (v3.0.0) before deploying — the certificate check they were supposed to run never ran under Fiber v3, and now does.

Every middleware was already a pair — XxxAuth (Fiber) and XxxAuthStd (net/http). The Std names are unchanged. Drop the middleware. prefix from the Fiber half and use fiberadapter.:

Before After
middleware.APIKeyAuth(cfg) fiberadapter.APIKeyAuth(cfg)
middleware.HMACAuth(cfg) fiberadapter.HMACAuth(cfg)
middleware.MTLSAuth(cfg) fiberadapter.MTLSAuth(cfg)
middleware.CombinedAuth(cfg) fiberadapter.CombinedAuth(cfg)
middleware.RateLimit(cfg) fiberadapter.RateLimit(cfg)
middleware.BodyLimit(cfg) fiberadapter.BodyLimit(cfg)
middleware.SecurityHeaders(cfg) fiberadapter.SecurityHeaders(cfg)
middleware.NoCacheHeaders() fiberadapter.NoCacheHeaders()
middleware.RequestLogging(cfg) fiberadapter.RequestLogging(cfg)
middleware.GetClientIPFiber(c, cfg) fiberadapter.GetClientIPFiber(c, cfg)

The Fiber-typed hooks moved with them. ErrorHandler, SuccessHandler, KeyFunc and CustomFields were typed func(fiber.Ctx) ..., which is what pulled Fiber into the root package, so they now live on fiberadapter.APIKeyConfig, fiberadapter.HMACConfig, fiberadapter.MTLSConfig, fiberadapter.AuthConfig, fiberadapter.BodyLimitConfig, fiberadapter.LoggingConfig and fiberadapter.RateLimitConfig — each of which embeds the root config, so every other field is unchanged and shared with the Std half:

fiberadapter.APIKeyAuth(fiberadapter.APIKeyConfig{
    APIKeyConfig: middleware.APIKeyConfig{APIKey: "..."},
    ErrorHandler: func(c fiber.Ctx, err error) error { ... },
})

Features

  • Authentication Middleware

    • API Key authentication with multiple sources (header, query, Authorization)
    • HMAC signature verification with key rotation support
    • mTLS client certificate authentication with CN/OU/SAN filtering
    • Combined authentication with priority: mTLS > HMAC > API Key
  • Security Middleware

    • Security headers (XSS, clickjacking, MIME sniffing protection)
    • Configurable Content-Security-Policy
    • HSTS support
  • Traffic Control

    • In-memory rate limiting with sliding window
    • IP whitelist support
    • Configurable limits per client
  • Request Processing

    • Request body size limiting
    • Gzip compression with configurable thresholds
    • Request/response logging with sensitive data masking
  • Utilities

    • Client IP detection with trusted proxy support
    • Sensitive data masking (email, phone)

Installation

go get github.com/soulteary/middleware-kit/v3

Usage

API Key Authentication
import (
    "github.com/gofiber/fiber/v3"
    middleware "github.com/soulteary/middleware-kit/v3"
    "github.com/soulteary/middleware-kit/v3/fiberadapter"
)

app := fiber.New()

// Simple API key authentication
app.Use(fiberadapter.APIKeyAuth(fiberadapter.APIKeyConfig{
    APIKeyConfig: middleware.APIKeyConfig{
        APIKey: "your-secret-api-key",
    },
}))

// With multiple sources
app.Use(fiberadapter.APIKeyAuth(fiberadapter.APIKeyConfig{
    APIKeyConfig: middleware.APIKeyConfig{
        APIKey:         "your-secret-api-key",
        HeaderName:     "X-API-Key",           // Check this header
        AuthScheme:     "Bearer",               // Also check Authorization: Bearer <key>
        QueryParamName: "api_key",              // Also check ?api_key=<key>
    },
}))
HMAC Signature Authentication
// Basic HMAC authentication
app.Use(fiberadapter.HMACAuth(fiberadapter.HMACConfig{
    HMACConfig: middleware.HMACConfig{
        Secret: "your-hmac-secret",
    },
}))

// With key rotation support
keys := map[string]string{
    "key-v1": "secret-v1",
    "key-v2": "secret-v2",
}
app.Use(fiberadapter.HMACAuth(fiberadapter.HMACConfig{
    HMACConfig: middleware.HMACConfig{
        KeyProvider: func(keyID string) string {
            return keys[keyID]
        },
        MaxTimeDrift: 5 * time.Minute,
    },
}))

// Computing the signature on the client side
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
signature := middleware.ComputeHMAC(timestamp, "service-name", requestBody, secret)
// Headers: X-Signature, X-Timestamp, X-Service, X-Key-Id (optional)
Binding the signature to the request

The default signed message is timestamp:service:body. It covers neither the method nor the path, so a signature minted for POST /transfer is equally valid on POST /delete-account with the same body.

ComputeHMACBound signs the method, path and query as well, and length-prefixes every field so the encoding is injective. Changing the signed bytes breaks every deployed signer at once, so it is opt-in:

app.Use(fiberadapter.HMACAuth(fiberadapter.HMACConfig{
    HMACConfig: middleware.HMACConfig{
        Secret:               "your-hmac-secret",
        RequestSignatureFunc: middleware.ComputeHMACBound,
    },
}))

Clients sign the same way:

signature := middleware.ComputeHMACBound(middleware.SignatureInput{
    Timestamp: timestamp,
    Service:   "service-name",
    Method:    req.Method,
    Path:      req.URL.Path,
    RawQuery:  req.URL.RawQuery,
    Body:      string(body),
    Secret:    secret,
})

The legacy encoding is made safe in place: because service comes from a client-supplied header and the old format is not injective, a signature for (service "a", body "b:c") could be presented as (service "a:b", body "c"). A service identifier containing the delimiter is now rejected. Set AllowDelimitersInService only if you have a deployed signer that needs it.

Replay protection

The timestamp window bounds how long a captured request stays useful — it does not stop the request being replayed inside that window. Without a guard, every signed request is replayable for MaxTimeDrift:

app.Use(fiberadapter.HMACAuth(fiberadapter.HMACConfig{
    HMACConfig: middleware.HMACConfig{
        Secret:      "your-hmac-secret",
        ReplayGuard: middleware.NewMemoryReplayGuard(), // single instance
    },
}))

ReplayGuard is an interface, so a multi-instance deployment can back it with shared storage:

type ReplayGuard interface {
    // Seen reports whether id has been accepted before, and records it for ttl.
    Seen(id string, ttl time.Duration) bool
}
mTLS Client Certificate Authentication
mTLS Client Certificate Authentication
// Basic mTLS
app.Use(fiberadapter.MTLSAuth(fiberadapter.MTLSConfig{
    MTLSConfig: middleware.MTLSConfig{
        RequireCert: true,
    },
}))

// With CN/OU restrictions
app.Use(fiberadapter.MTLSAuth(fiberadapter.MTLSConfig{
    MTLSConfig: middleware.MTLSConfig{
        RequireCert: true,
        AllowedCNs:  []string{"service-a", "service-b"},
        AllowedOUs:  []string{"engineering"},
    },
}))

// With custom validator
app.Use(fiberadapter.MTLSAuth(fiberadapter.MTLSConfig{
    MTLSConfig: middleware.MTLSConfig{
        RequireCert: true,
        CertValidator: func(cert *x509.Certificate) error {
            // Custom validation logic
            if cert.NotAfter.Before(time.Now().Add(24 * time.Hour)) {
                return errors.New("certificate expires too soon")
            }
            return nil
        },
    },
}))

A certificate must have been verified by the TLS layer. tls.ConnectionState.PeerCertificates is populated whenever the peer sends a certificate, and with tls.RequestClientCert or tls.RequireAnyClientCert the server verifies nothing — so a self-signed certificate would pass, and since its Subject is chosen by whoever generated it, a CN allow-list on top gives no protection either. Authentication requires a non-empty VerifiedChains; configure your tls.Config with ClientAuth: tls.RequireAndVerifyClientCert and a ClientCAs pool.

An unverified certificate is rejected with ErrMTLSCertificateUnverified. Failure reasons are wrapped, so logs keep naming the specific cause.

Combined Authentication
// Try multiple authentication methods in order: mTLS > HMAC > API Key
app.Use(fiberadapter.CombinedAuth(fiberadapter.AuthConfig{
    AuthConfig: middleware.AuthConfig{
        MTLSConfig: &middleware.MTLSConfig{
            RequireCert: false, // Optional mTLS
        },
        HMACConfig: &middleware.HMACConfig{
            Secret: "hmac-secret",
        },
        APIKeyConfig: &middleware.APIKeyConfig{
            APIKey: "api-key",
        },
    },
}))

CombinedAuth's mTLS branch runs the same check as the dedicated MTLSAuth middleware, including AllowedCNs, AllowedOUs, AllowedDNSSANs and CertValidator, so the combined middleware cannot accept what the dedicated one rejects.

Rate Limiting
// Create rate limiter
limiter := middleware.NewRateLimiter(middleware.RateLimiterConfig{
    Rate:   100,              // 100 requests
    Window: time.Minute,      // per minute
})
defer limiter.Stop()

// Add to middleware
app.Use(fiberadapter.RateLimit(fiberadapter.RateLimitConfig{
    RateLimitConfig: middleware.RateLimitConfig{
        Limiter:   limiter,
        SkipPaths: []string{"/health", "/metrics"},
    },
}))

// Whitelist IPs
limiter.AddToWhitelist("10.0.0.1")

// Custom key function (e.g., rate limit by user ID)
app.Use(fiberadapter.RateLimit(fiberadapter.RateLimitConfig{
    RateLimitConfig: middleware.RateLimitConfig{
        Limiter: limiter,
        KeyFunc: func(c fiber.Ctx) string {
            return c.Get("X-User-ID")
        },
    },
}))

The in-memory limiter tracks the window start separately from the eviction timestamp, so an active client rolls over on schedule: "100 per minute" means 100 requests in any minute, not "100 requests then a full minute of silence".

Security Headers
// Default security headers
app.Use(fiberadapter.SecurityHeaders(middleware.DefaultSecurityHeadersConfig()))

// Strict security headers (recommended for production)
app.Use(fiberadapter.SecurityHeaders(middleware.StrictSecurityHeadersConfig()))

// Custom configuration
app.Use(fiberadapter.SecurityHeaders(middleware.SecurityHeadersConfig{
    XContentTypeOptions:     "nosniff",
    XFrameOptions:           "DENY",
    ContentSecurityPolicy:   "default-src 'self'",
    StrictTransportSecurity: "max-age=31536000; includeSubDomains",
}))

// No-cache headers for sensitive endpoints
app.Use("/api/sensitive", fiberadapter.NoCacheHeaders())
Request Body Limiting
app.Use(fiberadapter.BodyLimit(fiberadapter.BodyLimitConfig{
    BodyLimitConfig: middleware.BodyLimitConfig{
        MaxSize:     4 * 1024 * 1024, // 4MB
        SkipMethods: []string{"GET", "HEAD"},
        SkipPaths:   []string{"/upload"}, // Allow larger uploads
    },
}))
Gzip Compression (Standard HTTP)
import "net/http"

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Hello, World!"))
})

compressed := middleware.CompressStd(middleware.DefaultCompressConfig())(handler)
http.ListenAndServe(":8080", compressed)
Request Logging
import "github.com/rs/zerolog"

logger := zerolog.New(os.Stdout)

app.Use(fiberadapter.RequestLogging(fiberadapter.LoggingConfig{
    LoggingConfig: middleware.LoggingConfig{
        Logger:     &logger,
        SkipPaths:  []string{"/health", "/metrics"},
        LogHeaders: true,
        SensitiveHeaders: []string{
            "Authorization",
            "X-API-Key",
            "Cookie",
        },
    },
}))
Client IP Detection
// Always build the config with the constructor
trustedProxies := middleware.NewTrustedProxyConfig([]string{
    "10.0.0.0/8",
    "192.168.1.1",
})

// In a Fiber handler
app.Get("/", func(c fiber.Ctx) error {
    clientIP := fiberadapter.GetClientIPFiber(c, trustedProxies)
    return c.SendString("Your IP: " + clientIP)
})

// In a standard HTTP handler
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    clientIP := middleware.GetClientIP(r, trustedProxies)
    fmt.Fprintf(w, "Your IP: %s", clientIP)
})

X-Forwarded-For is walked from the right, skipping hops that are themselves trusted proxies, and stops at the first untrusted address. That is the only reading that is not spoofable: a client sends X-Forwarded-For: 1.2.3.4, the proxy appends the real address to the right of it, and the forged value stays leftmost. X-Real-IP is used only when no usable chain is present.

Every control keyed on this function — the IP allow-list, per-IP rate limiting, audit logs — is only as trustworthy as TrustedProxies, so set it to your actual proxies. With nothing configured, private addresses are trusted.

IPv6 unique local addresses (fc00::/7) count as private, so an all-IPv6 deployment trusts its own proxies.

Data Masking Utilities
Data Masking Utilities
// Mask email for logging
masked := middleware.MaskEmail("john.doe@example.com")
// Output: jo***@example.com

// Mask phone for logging
masked := middleware.MaskPhone("+1234567890")
// Output: +12***7890

Standard net/http Support

All middleware support both Fiber and standard net/http:

import (
    "net/http"
    middleware "github.com/soulteary/middleware-kit/v3"
)

// API Key authentication
handler := middleware.APIKeyAuthStd(middleware.APIKeyConfig{
    APIKey: "your-api-key",
})(yourHandler)

// HMAC authentication
handler = middleware.HMACAuthStd(middleware.HMACConfig{
    Secret: "your-secret",
})(handler)

// Rate limiting
limiter := middleware.NewRateLimiter(middleware.DefaultRateLimiterConfig())
handler = middleware.RateLimitStd(middleware.RateLimitConfig{
    Limiter: limiter,
})(handler)

// Security headers
handler = middleware.SecurityHeadersStd(middleware.DefaultSecurityHeadersConfig())(handler)

// Body limit
handler = middleware.BodyLimitStd(middleware.BodyLimitConfig{
    MaxSize: 4 * 1024 * 1024,
})(handler)

// Compression
handler = middleware.CompressStd(middleware.DefaultCompressConfig())(handler)

// Logging
handler = middleware.RequestLoggingStd(middleware.LoggingConfig{
    Logger: &logger,
})(handler)

http.ListenAndServe(":8080", handler)

Project Structure

middleware-kit/
├── apikey.go           # API Key authentication
├── hmac.go             # HMAC signature authentication
├── mtls.go             # mTLS client certificate authentication
├── auth.go             # Combined authentication middleware
├── ratelimit.go        # Rate limiting
├── security.go         # Security headers
├── bodylimit.go        # Request body size limiting
├── compress.go         # Gzip compression
├── logging.go          # Request logging
├── clientip.go         # Client IP detection
├── helpers.go          # Utility functions
├── errors.go           # Error definitions
└── *_test.go           # Comprehensive tests

Upgrade Notes (v3.0.0)

The import path changed and one Fiber security check starts working. Read the mTLS item before upgrading a live deployment.

  • The module path is now /v3. Update every import: github.com/soulteary/middleware-kit/v2 → github.com/soulteary/middleware-kit/v3. Go treats a major version as a separate module, so nothing upgrades on its own and the v2 line keeps working until you move.

  • Fiber middleware moved to the fiberadapter subpackage. See the table at the top of this file. The Std (net/http) names and behaviour are unchanged — every one of them is byte-identical to its v2 implementation.

  • ⚠️ The Fiber mTLS check never ran, and now does. MTLSAuth and CombinedAuth gated their certificate check on c.Protocol() == "https". In Fiber v3, Protocol() reports the HTTP version — it returns "HTTP/1.1" — so that test was never true and everything behind it was skipped:

    Config Should be Was, in v2.0.0–v2.2.0
    MTLSAuth, RequireCert: true, verified cert matching AllowedCNs 200 401 — deny-all
    MTLSAuth, RequireCert: false, verified cert failing AllowedCNs 401 200 — fail-open
    CombinedAuth, mTLS the only scheme, verified cert 200 401

    What this means for you:

    • If you set RequireCert: false expecting "verify a certificate when one is presented, allow anonymous otherwise", nothing was being verified. AllowedCNs, AllowedOUs, AllowedDNSSANs and CertValidator now actually run, so a certificate outside your allow-list starts being rejected where it used to pass. Check that the certificates your clients present really do match the lists you configured.
    • If you use CombinedAuth with an MTLSConfig, the mTLS scheme was never attempted: an mTLS-only AuthConfig refused everything, and a mixed one silently demanded HMAC or an API key from clients that had already presented a certificate. mTLS now authenticates, so those clients stop being asked for the other credentials.
    • Plaintext requests are unaffected in both directions: 401 with reason certificate_required when RequireCert is set, pass-through when it is not.

    The scheme pre-check was removed rather than repaired. AuthenticateMTLS reads the TLS connection state itself and reports a plaintext connection as an absent certificate — the one condition RequireCert: false is meant to wave through — so the Fiber middleware now has the same shape as MTLSAuthStd, which consults r.TLS and nothing else. c.Scheme() would not be a safe replacement: it answers "https" for a plaintext request carrying X-Forwarded-Proto from a trusted proxy, and a forwarded header cannot establish that a client certificate was presented to this process.

  • New API: the checks both halves share are exported so an adapter runs the same code the net/http middleware runs — AuthenticateMTLS, NewCertAllowLists, CertAllowLists, CertificateAbsent, ConstantTimeEqual, HMACConfig.ExpectedSignature, HMACConfig.ServiceAllowed, ParseTimestamp, IsTimestampValid, ReplayRetention, TrustedProxyConfig.ClientIPFromForwarded, JoinForwarded, LastHeaderValue and HeaderOrDefault. All additive.

Upgrade Notes (v2.2.0)

Three of these reject requests that previously authenticated. Read the mTLS and HMAC items before upgrading a live deployment.

  • mTLS requires a TLS-verified certificate. Both MTLSAuth and CombinedAuth accepted any certificate the peer sent, because PeerCertificates is populated regardless of verification — with tls.RequestClientCert or tls.RequireAnyClientCert the server verifies nothing, so a self-signed certificate passed and the CN allow-list on top gave no protection. A non-empty VerifiedChains is now required. If your tls.Config does not use RequireAndVerifyClientCert with a ClientCAs pool, mTLS clients will start failing with ErrMTLSCertificateUnverified.
  • CombinedAuth now enforces the mTLS allow-lists. Its mTLS branch tested only len(PeerCertificates) > 0 and returned c.Next(), so AllowedCNs, AllowedOUs, AllowedDNSSANs and CertValidator were never consulted — configuring them there had no effect and any client certificate authenticated.
  • An HMAC service containing the delimiter is rejected. The legacy signed message timestamp:service:body is not injective and service comes from a client-supplied header, so a signature for ("a", "b:c") could be presented as ("a:b", "c"). Set AllowDelimitersInService if a deployed signer needs the old behaviour.
  • X-Forwarded-For is read from the right, and X-Real-IP no longer wins. Taking the leftmost entry is spoofable by design — the proxy appends the real address to the right of whatever the client sent — so every control keyed on GetClientIP was bypassable even behind a correctly configured proxy. Client IPs in your logs and rate-limit buckets will change, to the correct values.
  • TrustedProxyConfig parses its lists lazily. Parsing happened only in NewTrustedProxyConfig, while TrustedProxies is an exported field and DefaultTrustedProxyConfig returns a literal — so a config built as a struct literal had empty parsed lists and fell through to "nothing configured", trusting every private address instead of the one asked for. Tightening the policy silently loosened it.
  • IPv6 unique local addresses (fc00::/7) count as private. An all-IPv6 deployment never trusted its own proxies.
  • The rate-limit window rolls over for active clients. The in-memory limiter compared the window against lastSeen, refreshed on every allowed request, so the counter only grew: "100 per minute" meant "100 requests, then a full minute of silence", and a steady 1 req/s client was blocked at the 100th second. Some clients you were blocking will now be allowed — correctly.
  • X-XSS-Protection defaults to "0". The header is deprecated, and the filter that "1; mode=block" enabled introduced XSS and info-leak bugs of its own.
  • Secret comparison no longer leaks length. constantTimeEqual called subtle.ConstantTimeCompare directly, which returns early on a length mismatch.
  • New API: ReplayGuard and NewMemoryReplayGuard for HMAC replay protection; ComputeHMACBound, SignatureInput and RequestSignatureFunc for signatures that cover the method, path and query; HMACConfig.AllowDelimitersInService; ErrMTLSCertificateUnverified.

Requirements

  • Go 1.27.4+ (go.mod declares go 1.27.4)
  • github.com/gofiber/fiber/v3 v3.5.0+ (for the fiberadapter subpackage only)
  • github.com/rs/zerolog v1.35.0+ (for logging)

This v3 module line targets Fiber v3. Applications that still use Fiber v2 should remain on github.com/soulteary/middleware-kit v1.

Test Coverage

Run tests:

go test ./... -v

# With coverage
go test ./... -coverprofile=coverage.out -covermode=atomic
go tool cover -html=coverage.out -o coverage.html
go tool cover -func=coverage.out

Changelog

Release history and upgrade notes: CHANGELOG.md.

Security

To report a vulnerability, see SECURITY.md — please report privately rather than in a public issue. That file also records a client-certificate check that does not execute in v2.0.0–v2.2.0 and is fixed in v3.0.0.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

See LICENSE file for details.

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

Constants

This section is empty.

Variables

View Source
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 is a generic unauthorized error.
	ErrUnauthorized = errors.New("unauthorized")
)

Authentication errors

View Source
var (
	// ErrRateLimitExceeded indicates the rate limit has been exceeded.
	ErrRateLimitExceeded = errors.New("rate limit exceeded")
)

Rate limiting errors

View Source
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

func CertificateAbsent(err error) bool

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

func ComputeHMAC(timestamp, service, body, secret string) string

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

func ConstantTimeEqual(a, b string) bool

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

func HeaderOrDefault(header, defaultValue string) string

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

func IPAllowlistMiddleware(allowlist string) func(http.Handler) http.Handler

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

func IsPrivateIP(ip net.IP) bool

IsPrivateIP checks if an IP address is a private IP address.

func IsTimestampValid

func IsTimestampValid(timestamp, maxDriftSeconds int64) bool

IsTimestampValid checks if a timestamp is within the allowed drift.

func JoinForwarded

func JoinForwarded(values []string) string

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

func LastHeaderValue(values []string) string

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

func MaskEmail(email string) string

MaskEmail masks an email address for logging. Example: john.doe@example.com -> jo***@example.com

func MaskPhone

func MaskPhone(phone string) string

MaskPhone masks a phone number for logging. Example: +1234567890 -> +123***7890

func NoCacheHeadersStd

func NoCacheHeadersStd() func(http.Handler) http.Handler

NoCacheHeadersStd creates a standard net/http middleware that prevents caching.

func ParseTimestamp

func ParseTimestamp(timestamp string) (int64, error)

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

func ReplayRetention(maxDrift time.Duration) time.Duration

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.

func (*TrustedProxyConfig) IsTrusted

func (c *TrustedProxyConfig) IsTrusted(ip net.IP) bool

IsTrusted checks if an IP address is from a trusted proxy.

Directories

Path Synopsis
Package fiberadapter exposes middleware-kit over Fiber v3.
Package fiberadapter exposes middleware-kit over Fiber v3.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL