middleware

package
v0.23.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const RequestIDHeader = "X-Request-Id"

RequestIDHeader is the header RequestID writes the server request ID to, and the header a client's own correlation ID is read from.

Variables

This section is empty.

Functions

func Authenticate

func Authenticate(a auth.Authenticator, logger *slog.Logger, opts ...AuthOption) func(http.Handler) http.Handler

Authenticate returns a middleware that extracts a bearer token from the request's "Authorization" header, authenticates it via a, and stores the resulting Principal in the request context (auth.WithPrincipal), so a later handler or middleware (e.g. RequirePermission) can read it via auth.FromContext.

On success it also records principal.UserID — only the opaque ID, never the username, roles or token — in the reqctx user slot (reqctx.SetUserID), so StructuredLogger, which wraps this middleware and therefore never sees the derived request carrying the Principal, can log who made the request. The slot is installed by RequestContext; without it the call is a no-op and authentication works unchanged. A failed authentication leaves the slot empty.

Extraction (see extractBearerToken) happens before a.Authenticate is ever called: a missing header, an empty header, a scheme other than "Bearer" (checked case-insensitively per RFC 6750), or a "Bearer" scheme with no token after it is rejected as auth.ErrUnauthenticated without invoking the Authenticator at all, since there is no credential yet worth asking an identity provider about.

Fail-closed: on any error from extraction or from a.Authenticate, this middleware writes an error response and returns without calling next.ServeHTTP.

Status mapping:

  • auth.ErrServiceUnavailable -> 503. The identity provider is unreachable or failing; this must never collapse into 401 or 500. All three source systems this package was ported from made that mistake — go-crucible and go-licencias returned 403, and the base returned 403 too, for a Zitadel outage. A 503 tells the client the failure is transient and retryable and tells monitoring "infrastructure incident", where a 401 or 403 reads as "your credentials/permissions are the problem".
  • auth.ErrForbidden -> 403
  • anything else, including auth.ErrUnauthenticated -> 401

The underlying error is always logged server-side at error level, with the request method, path, client IP and request ID (the last two from reqctx, empty when RequestContext is not mounted upstream); the token is never logged, and the error detail is never included in the response body. Mount RequestContext before this middleware so those fields are filled in.

func DefaultDurationBuckets added in v0.11.0

func DefaultDurationBuckets() []float64

DefaultDurationBuckets returns the http_request_duration_seconds buckets NewMetrics uses when WithDurationBuckets is not given: 5 ms to 10 s.

func ParseTrustedProxies added in v0.9.0

func ParseTrustedProxies(s string) ([]netip.Prefix, error)

ParseTrustedProxies parses a comma-separated list of CIDR prefixes and/or single IPs (for example the value of a TRUSTED_PROXIES environment variable) into prefixes for RealIP. A single IP becomes a /32 (IPv4) or /128 (IPv6) prefix; host bits are masked and IPv4-mapped IPv6 values are converted to IPv4. Empty items are skipped, so an empty string yields no prefixes — the safe default under which RealIP trusts no header. Any invalid item, including one with an IPv6 zone, is an error naming it.

func RateLimitJSON

func RateLimitJSON() http.HandlerFunc

RateLimitJSON returns an http.HandlerFunc that writes a JSON 429 response. Use with httprate.WithLimitHandler(middleware.RateLimitJSON()).

func RealIP added in v0.9.0

func RealIP(trusted ...netip.Prefix) func(http.Handler) http.Handler

RealIP rewrites r.RemoteAddr to the originating client IP, but only when the request arrived through one of the trusted proxies.

Unlike chi's middleware.RealIP, which believes X-Forwarded-For, X-Real-IP and True-Client-IP from any peer, this middleware first checks the direct peer (the host part of r.RemoteAddr). If that peer is not inside one of the trusted prefixes the request is passed through untouched, so a client that connects directly cannot forge its own IP — and with it the reqctx client IP, audit_log.ip and any IP-keyed rate limit downstream. With no trusted prefixes at all, forwarding headers are never consulted.

For a trusted peer, the client IP is resolved as follows:

  • X-Forwarded-For (every header line, joined in order) is walked right to left. Entries inside a trusted prefix are proxies and are skipped; the first entry that is not trusted is the client. If every entry is trusted, the leftmost one is used (nginx real_ip_recursive semantics). An empty or unparseable entry reached during the walk stops it and leaves r.RemoteAddr unchanged: nothing to its left can be attributed to a trusted hop.
  • Only when no X-Forwarded-For header is present is X-Real-IP consulted; an unparseable value leaves r.RemoteAddr unchanged.
  • True-Client-IP is never consulted: it is a CDN-specific header that a generic reverse proxy passes through verbatim from the client.

Entries may carry a port ("1.2.3.4:80", "[2001:db8::1]:443") and an IPv6 zone; both are stripped. IPv4-mapped IPv6 addresses are unmapped before matching, so "::ffff:10.0.0.1" matches 10.0.0.0/8. The rewritten r.RemoteAddr is the bare IP with no port, like chi's middleware.RealIP; RequestContext and net.SplitHostPort-with-fallback consumers handle both forms.

Mount it before RequestContext and before any rate limiter keyed on r.RemoteAddr. Build the prefixes with ParseTrustedProxies.

func Recovery

func Recovery(logger *slog.Logger) func(next http.Handler) http.Handler

Recovery recovers from panics in the handler chain and returns a 500 error.

The log line carries the panic value's Go type under "panic_type", the path, the method and the stack trace. "error" holds the value as text, bounded by maxLoggedPanicBytes, only when the value is an error (its Error() text) or of a string, bool or numeric kind with no methods, named types included: for any other value only the type is logged. A struct would print its unexported fields; a scalar type with methods (a String that redacts a secret, say) may hold something its author did not mean to print, and logging either its raw value or its String output could be wrong.

func RequestContext

func RequestContext(next http.Handler) http.Handler

RequestContext populates vogel/reqctx with the three pieces of request-scoped metadata every downstream layer needs: the request ID, the client IP, and the User-Agent. It also installs the empty user slot (reqctx.WithUserSlot) that Authenticate fills with the principal's UserID.

It is the single writer for this metadata (replacing what used to be two separate middlewares — one bridging chi's request ID into logger's own context key, one extracting IP/User-Agent into a middleware-local key). Consolidating into one middleware over one neutral package (reqctx) means:

  • logger.Logger.WithContext and audit.Recorder.Record read the exact same request ID, from the exact same context key, so a log line and an audit_log row for the same request are provably linked.
  • neither logger nor audit needs to import httpx or chi to get at it.

Mount vogel's RequestID upstream of this middleware: RequestContext does not generate an ID itself. It prefers the ID RequestID stored in reqctx and, only when there is none, falls back to chi's middleware.GetReqID, so a consumer that still mounts chi's middleware.RequestID keeps working unchanged. Prefer vogel's RequestID: chi's honors a client-supplied X-Request-Id header verbatim, so with it a client chooses the request_id that reaches logs, audit_log rows and error responses.

Mount it before Authenticate: the auth-failure log reads the client IP and request ID from reqctx, so with RequestContext mounted after it a rejected request is logged with an empty ip and request_id (RequirePermission and RequireAccess read the request ID the same way). docs/WIRING.md gives the full middleware order.

The user slot is installed here rather than in StructuredLogger or Authenticate because this is the one middleware the documented order already places upstream of both: StructuredLogger reads reqctx from the request it receives, so it must sit inside RequestContext, and Authenticate sits inside StructuredLogger. A slot installed by StructuredLogger would work for the access log alone, but would make the user ID's availability to logger.Logger.WithContext depend on whether an access logger happens to be mounted; keeping every reqctx value under this single writer keeps one rule for all of them. With RequestContext missing there is no slot, SetUserID is a no-op and no user_id is logged — the same degradation as the empty request_id.

func RequestID added in v0.9.0

func RequestID(next http.Handler) http.Handler

RequestID assigns every request a fresh server-generated ID: 16 bytes from crypto/rand, hex-encoded (32 lowercase hex characters). It stores the ID in reqctx (read by RequestContext, logger and audit) and under chi's middleware.RequestIDKey (read by chi's GetReqID, e.g. the trace_id of httpx/response errors), and sets it on the response's X-Request-Id header.

Unlike chi's middleware.RequestID, it never adopts an incoming X-Request-Id: a client could otherwise choose the request_id stamped on logs and audit rows, collide with another request's ID, or inject log content. A client-supplied value is instead kept, for correlation only, via reqctx.WithClientRequestID, after stripping every byte outside visible ASCII (0x21-0x7E, so no spaces or control characters) and truncating it to 128 bytes; an empty result is not stored.

If crypto/rand fails, RequestID panics: rand.Read never returns an error on supported platforms (see its documentation), and an unidentifiable request is not a state worth limping along in.

Mount it first, upstream of RequestContext and every middleware that logs.

func RequireAccess added in v0.3.0

func RequireAccess(guard *access.Guard, resourceKind, action string, logger *slog.Logger, opts ...AuthOption) func(http.Handler) http.Handler

RequireAccess returns a middleware that performs the same coarse authorization check as RequirePermission (principal + resource kind + an ID taken from the URL, with no entity-specific attributes), but through an access.Guard instead of a bare authz.Checker.

Use this instead of RequirePermission when the same Checker also backs a per-instance check made later in the handler (via guard.Check, after the entity is loaded, with its data folded into authz.Resource.Attr) -- see the access package doc for why that second check cannot happen here, in the middleware, instead. When guard was built with access.WithPrincipalAttributes, this middleware installs access.WithRequestScope on the request context BEFORE running its own check, so the principal-attribute resolver runs at most once for the request no matter how many of the middleware's own check and the handler's later guard.Check end up needing it. When guard has no resolver configured, the request is passed to next completely unchanged -- byte for byte the same behavior as before this middleware existed.

Fail-closed: on any error, this middleware writes a response (via WriteAccessError) and returns without calling next.ServeHTTP.

Log volume: every denial (403) writes one Warn line to logger, with no sampling or rate limiting of its own. A client that probes many resources it may not see -- an enumeration attempt, or a broken client retrying in a loop -- therefore produces one Warn line per request, and the log volume grows with the attacker's request rate. That is deliberate (the denials are the signal), but a service exposed to untrusted clients should bound it at the logger, not here: pass a *slog.Logger whose slog.Handler wraps the real one with a sampling or rate-limiting handler (keyed, for example, on the "user_id" or "path" attribute, so one noisy client cannot drown out the others), or pass a logger whose handler level is above slog.LevelWarn to drop the denial lines entirely while still keeping the 503 Error lines. A request rate limiter mounted in front of the router (vogel ships none; httprate is a common choice) bounds the log volume as a side effect. The same applies to WriteAccessError, which logs through the same path.

func RequirePermission

func RequirePermission(checker authz.Checker, resourceKind, action string, logger *slog.Logger, opts ...AuthOption) func(http.Handler) http.Handler

RequirePermission returns a middleware that checks whether the Principal authenticated by an earlier Authenticate middleware is allowed to perform action on a resource of kind resourceKind.

Use this when the authorization decision depends only on the principal and the resource kind — i.e. no resource-level attributes are needed. The resource ID is taken from the URL parameter "id" if present, and falls back to the wildcard otherwise.

For attribute-based checks (e.g. status == "DRAFT"), or when the same Checker needs principal attributes resolved from another system (e.g. the user's current assignments), build an access.Guard and use RequireAccess here instead, then call access.Guard.Check + WriteAccessError in the handler after loading the entity.

Fail-closed: on any error, this middleware writes an error response and returns without calling next.ServeHTTP.

Status mapping — this deliberately supersedes go-licencias' DEC-08, which mapped a Cerbos check error to 403 "to avoid an oracle" (i.e. to keep a caller from telling a PDP outage apart from a real deny). That reasoning trades away more than it buys: a PDP outage reported as 403 tells the client "you lack permission" and tells monitoring "permissions bug" instead of "infrastructure incident", and unlike 403, 503 is retryable. go-crucible independently made the same mistake by returning 500 instead:

  • checker.IsAllowed returns a non-nil error (PDP unreachable/failing) -> 503
  • checker.IsAllowed returns (false, nil) (genuine denial) -> 403
  • no Principal in the request context (missing/invalid credentials) -> 401

The underlying error is always logged server-side at error level; its detail is never included in the response body.

This is now a thin wrapper around RequireAccess, backed by an access.Guard with no PrincipalAttributes resolver configured — the status mapping and wildcard-ID logic live there once, instead of twice. One consequence of that: access.New panics on a nil checker, so a nil checker now surfaces immediately when RequirePermission is called (at router-construction time) rather than on the first request that hits the route it guards. That is a strictly earlier failure for what was already a wiring mistake, not a new way for this function to fail.

func SecurityHeaders

func SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders adds common HTTP security headers to every response.

It also sets Cache-Control: private, no-store (and Pragma: no-cache for HTTP/1.0 intermediaries) so that API responses, which are authenticated and per-user by default, are never retained by a browser and never by a shared cache.

Cross-Origin-Opener-Policy: same-origin isolates the browsing context from cross-origin windows, and Cross-Origin-Resource-Policy: same-origin stops other origins from embedding a response (an <img>, <script> or no-cors fetch from a foreign page is blocked by the browser).

Every header is set BEFORE next.ServeHTTP runs, so a handler that serves genuinely cacheable or embeddable content (a public asset, a versioned schema) can override the defaults by setting its own Cache-Control (and deleting Pragma) or its own Cross-Origin-Resource-Policy (for example "cross-origin") before writing its response.

func StructuredLogger

func StructuredLogger(logger *slog.Logger, opts ...LoggerOption) func(next http.Handler) http.Handler

StructuredLogger returns a structured access-log middleware.

The request ID comes from reqctx, which RequestContext populates — mount RequestContext upstream of this middleware. Reading chi's GetReqID directly here instead would agree with what logger.Logger.WithContext and audit.Recorder.Record report only by coincidence, since both of those read reqctx: a request ID reaching the context by any other route would land in an audit_log row while this access log printed an empty one.

When the client sent its own correlation ID (see RequestID), it is logged under "client_request_id", apart from the server-generated "request_id", so a client-chosen value is never mistaken for the server's; the key is left out when there is none.

The authenticated user's ID is logged under "user_id", read from the reqctx user slot that RequestContext installs and Authenticate fills on success. A slot is needed because this middleware wraps Authenticate: the Principal Authenticate stores lives on a derived request this middleware never sees, while the slot is a pointer shared by both. The slot is read in the deferred log line, after next has returned, so the write has already happened on the same goroutine. The key is left out for an unauthenticated request or when RequestContext is not mounted.

The client's address ("remote_addr", r.RemoteAddr) and "user_agent" are personal data under GDPR-style rules. Both are logged by default; WithRemoteAddr truncates or omits the address and WithoutUserAgent omits the user agent.

func WriteAccessError added in v0.3.0

func WriteAccessError(w http.ResponseWriter, r *http.Request, err error, logger *slog.Logger, opts ...AuthOption) bool

WriteAccessError maps an error returned by access.Guard.Check (or access.Guard.Principal) to the appropriate HTTP status and writes it, returning true. It writes nothing and returns false for nil or for any error that is not one of access.ErrUnauthenticated, access.ErrForbidden, or access.ErrUnavailable, so a handler can fall through to its own domain-specific error mapping (e.g. errors.Is against a not-found or conflict sentinel) instead of this helper claiming an error it does not recognize.

This is the counterpart, inside a handler, of what RequireAccess does in the router: a handler that calls guard.Check after loading an entity uses WriteAccessError to get the exact same 401/403/503 mapping and logging the middleware gives every route, without duplicating the switch itself. It logs the denial with an empty resource and action; prefer WriteAccessErrorFor, which carries the checked resource and action.

Like RequireAccess, it logs every 403 at Warn with no sampling of its own; see the "Log volume" paragraph on RequireAccess for how to bound that with a sampling or rate-limiting slog.Handler.

func WriteAccessErrorFor added in v0.9.0

func WriteAccessErrorFor(w http.ResponseWriter, r *http.Request, err error, logger *slog.Logger, res authz.Resource, action string, opts ...AuthOption) bool

WriteAccessErrorFor is WriteAccessError for a handler that knows which instance it checked: it maps err exactly as WriteAccessError does, and carries res.Kind, res.ID and action into the 401/403/503 log line instead of leaving them empty. Pass the same resource and action given to guard.Check, so a per-instance denial is as traceable in the logs as one made by RequireAccess. res.Attr (the entity data folded into the check) is never logged.

Like WriteAccessError, it writes nothing and returns false for nil or for any error that is not one of the three access sentinels.

Types

type AuthMessages

type AuthMessages struct {
	// Unauthorized is returned on HTTP 401: missing, malformed, or expired
	// credentials.
	Unauthorized string

	// Forbidden is returned on HTTP 403: valid credentials, but the action is
	// not permitted (insufficient role, or a policy denial).
	Forbidden string

	// ServiceUnavailable is returned on HTTP 503: the identity provider or
	// policy decision point could not be reached.
	ServiceUnavailable string
}

AuthMessages holds the user-facing strings returned by Authenticate and RequirePermission.

A library must not bake user-facing copy in one language: the source systems this package was ported from returned hardcoded Spanish literals (in one case, Rioplatense voseo inside a Chilean product — an existing inconsistency, not something worth reproducing). DefaultAuthMessages provides neutral English defaults; each consuming application overrides them via WithAuthMessages to localize.

func DefaultAuthMessages

func DefaultAuthMessages() AuthMessages

DefaultAuthMessages returns neutral English defaults for AuthMessages.

type AuthOption

type AuthOption func(*AuthMessages)

AuthOption customizes Authenticate or RequirePermission.

func WithAuthMessages

func WithAuthMessages(m AuthMessages) AuthOption

WithAuthMessages overrides the default user-facing messages. Any field left as the empty string keeps its default.

type ExemplarFunc added in v0.12.0

type ExemplarFunc func(ctx context.Context) (traceID, spanID string)

ExemplarFunc returns the trace and span IDs of the span carried by ctx, or empty strings when there is none (or it was not sampled). It has the shape of logger.TraceIDsFunc; otel.SampledTraceIDs implements it.

type LoggerOption added in v0.11.0

type LoggerOption func(*loggerConfig)

LoggerOption configures StructuredLogger.

func WithRemoteAddr added in v0.11.0

func WithRemoteAddr(mode RemoteAddrMode) LoggerOption

WithRemoteAddr sets how the client address is logged.

func WithoutUserAgent added in v0.11.0

func WithoutUserAgent() LoggerOption

WithoutUserAgent leaves user_agent out of the line.

type Metrics

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics is an HTTP middleware that records Prometheus metrics (request count, latency, and response size) for every request.

Unlike a package-level prometheus.MustRegister in an init() function, Metrics is safe to construct more than once against the same Registerer: a prometheus.AlreadyRegisteredError is handled by reusing the already registered collector instead of panicking. This matters for a library — a consumer may build two server instances, or a test may construct a Metrics per test case.

func NewMetrics

func NewMetrics(reg prometheus.Registerer, opts ...MetricsOption) (*Metrics, error)

NewMetrics creates a Metrics middleware, registering its collectors on reg. If reg is nil, prometheus.DefaultRegisterer is used.

func (*Metrics) Middleware

func (m *Metrics) Middleware(next http.Handler) http.Handler

Middleware wraps next, recording request count, latency, and response size labeled by method and chi route pattern.

The request is recorded in a deferred call, so a handler that panics is still counted, as a 500, before the panic continues to an outer Recovery (the order the examples use). Outside a chi router, or for a request no route matched, the path label is "unknown".

type MetricsOption added in v0.11.0

type MetricsOption func(*metricsConfig)

MetricsOption configures NewMetrics.

func WithDurationBuckets added in v0.11.0

func WithDurationBuckets(buckets ...float64) MetricsOption

WithDurationBuckets sets the http_request_duration_seconds bucket upper bounds, in seconds. They must be non-empty and strictly increasing, or NewMetrics fails. Use it when the defaults do not bracket the service's latency objective, so the SLO threshold falls on a bucket boundary.

Buckets are fixed when the collector is first registered: a later NewMetrics on the same Registerer reuses that collector and its buckets.

func WithExemplars added in v0.12.0

func WithExemplars(fn ExemplarFunc) MetricsOption

WithExemplars attaches the request's trace_id and span_id, read with fn, as an exemplar to each http_request_duration_seconds observation, so a slow bucket links to a trace. A request fn finds no trace for records no exemplar. Prometheus reads exemplars only in the OpenMetrics format: serve the registry with promhttp.HandlerOpts{EnableOpenMetrics: true}.

type RemoteAddrMode added in v0.11.0

type RemoteAddrMode int

RemoteAddrMode selects how StructuredLogger logs the client address.

const (
	// RemoteAddrFull logs r.RemoteAddr as is (the default).
	RemoteAddrFull RemoteAddrMode = iota
	// RemoteAddrTruncated logs only the network part of the address: the
	// first 24 bits of an IPv4 address and the first 48 of an IPv6 one, with
	// no port, so the line still shows where traffic comes from without
	// identifying one host. An address that does not parse is left out.
	RemoteAddrTruncated
	// RemoteAddrOmitted leaves remote_addr out of the line.
	RemoteAddrOmitted
)

Jump to

Keyboard shortcuts

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