middleware

package
v0.0.124 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: GPL-3.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Auth

func Auth(jwtMgr *auth.JWTManager) func(http.Handler) http.Handler

Auth returns middleware that validates a JWT from the Authorization header (Bearer scheme) or the "token" query parameter, and stores the claims in context.

func AuthRunner added in v0.0.89

func AuthRunner(jwtMgr *auth.JWTManager, checker RunnerTokenChecker) func(http.Handler) http.Handler

AuthRunner is AuthScope(runner) plus the revocation check. A revoked token is a 401 — the runner stops and asks for a fresh `ex-runner login`. A failed check is a 503 instead, so a store blip makes the runner back off and retry rather than give up on a credential that is probably fine. A nil checker fails closed: no runner token is accepted at all.

func AuthScope added in v0.0.72

func AuthScope(jwtMgr *auth.JWTManager, scope string) func(http.Handler) http.Handler

AuthScope validates a JWT and requires it to carry exactly the given scope. Session tokens (empty scope) and other scopes are rejected: the runner API takes runner tokens only, the run-tool API run tokens only.

func AuthScopeWithUserStatus added in v0.0.97

func AuthScopeWithUserStatus(jwtMgr *auth.JWTManager, scope string, users authUserStore) func(http.Handler) http.Handler

AuthScopeWithUserStatus is AuthScope plus the deactivation check the session middleware already makes: a machine token acts with its user's access (a run token's UserID is the run's INVOKER), so it must stop working the moment that account is deactivated, not when the token expires. An unreadable status fails closed. A nil store skips the check.

func AuthWithUserStatus added in v0.0.29

func AuthWithUserStatus(jwtMgr *auth.JWTManager, users authUserStore) func(http.Handler) http.Handler

AuthWithUserStatus validates a JWT and, when a user store is supplied, rejects tokens for accounts that have since been deactivated and replaces the token's role claim with the STORED role. An access token lives 15 minutes; without this, an admin demoted (or a member promoted) in the meantime kept the old powers until it expired — every role gate (RequireSystemRole, the handlers' requireAdmin and guest checks) reads the claims this puts in context.

func CORS

func CORS(allowOrigins ...string) func(http.Handler) http.Handler

CORS returns middleware that sets Cross-Origin Resource Sharing headers. Multiple origins may be passed; the request Origin is echoed back when it matches one of them (required when Allow-Credentials is true).

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) *model.TokenClaims

ClaimsFromContext extracts the TokenClaims stored in context by the Auth middleware.

func Compress added in v0.0.97

func Compress(skipPrefixes ...string) func(http.Handler) http.Handler

Compress gzip-encodes responses (API JSON, the SPA's static assets) for clients that accept it, via klauspost/compress's gzhttp — small bodies and already-compressed content types pass through untouched. Paths under one of skipPrefixes are never wrapped (media streams: already-compressed bytes, Range requests), nor is a WebSocket upgrade. Caching headers are the handlers' own and are left as they are.

func ContextWithClaims

func ContextWithClaims(ctx context.Context, claims *model.TokenClaims) context.Context

ContextWithClaims returns a new context with the given claims attached so downstream code (e.g. service-layer permission checks) can read them via ClaimsFromContext. This is primarily useful in tests that exercise code paths gated on the authenticated user's role.

func LogHandler added in v0.0.97

func LogHandler(h slog.Handler) slog.Handler

LogHandler wraps h so a record logged with a request's context (the slog *Context functions) carries that request's ID under "requestID" — the access log's key — plus the Datadog trace and span IDs (dd.trace_id, dd.span_id) when the context holds a span, which ties the line to its APM trace. Records logged without such a context pass through unchanged.

func Logging

func Logging(logAll bool) func(http.Handler) http.Handler

Logging returns access-log middleware that records method, path, status, and duration for each request.

logAll=true logs every request, except /healthz when it returns 2xx — orchestrators (Docker, k8s) hit it every few seconds and the noise drowns out signal in the access log; a non-2xx healthcheck still logs so a flapping probe stays visible.

logAll=false (ACCESS_LOG_ENABLED=false) silences the access log EXCEPT for 5xx responses: server faults must stay visible even with access logging switched off.

func ProgressDeadline added in v0.0.97

func ProgressDeadline(idle time.Duration) func(http.Handler) http.Handler

ProgressDeadline replaces the server's fixed write timeout with a progress-based one for streaming responses (downloads, video): every write pushes the connection's write deadline idle into the future, so a body of any size streams for as long as the client keeps reading, while a client that stops reading is cut off idle after its last progress. Pair it with a RequestTimeout exemption for the same route — the request-context budget would otherwise still end the stream.

func RateLimit added in v0.0.50

func RateLimit(counter RateLimitCounter, limit Limit) func(http.Handler) http.Handler

RateLimit throttles per client IP and route. The route enters the key as a digest, not verbatim: some paths carry a secret (an incoming webhook's URL is its credential), and Redis keys are not where secrets belong.

func RateLimitPerUser added in v0.0.53

func RateLimitPerUser(counter RateLimitCounter, limit Limit) func(http.Handler) http.Handler

RateLimitPerUser keys on the authenticated caller instead of the IP, so a single account can't flood write endpoints — message sends fan out notifications to every member, so an unbounded write rate is an amplification vector. One counter per (limiter, caller) across every route it wraps. A run-scoped token is keyed by its RUN: run tokens carry the invoking human's user ID, and an agent's tool calls must not spend the human's own budget. Unauthenticated requests fall back to the client IP. Must run AFTER the auth middleware so the caller is in context.

func RedactPath added in v0.0.97

func RedactPath(path string) string

RedactPath masks credentials that ride in a URL path before the path reaches a log line: an incoming webhook's URL (/hooks/{id}) is that webhook's only credential, and a media URL's token is a bearer capability for the file.

func RequestID

func RequestID(next http.Handler) http.Handler

RequestID is middleware that generates a unique request ID, stores it in context, and sets the X-Request-ID response header.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext returns the request ID stored in context.

func RequestTimeout added in v0.0.53

func RequestTimeout(d time.Duration, streamingPrefixes ...string) func(http.Handler) http.Handler

RequestTimeout attaches a context deadline to each request so a slow or black-holed dependency (DynamoDB/OpenSearch have no default per-call deadline) can't pin a handler goroutine indefinitely — the deadline propagates through r.Context() to every downstream call. Long-lived connections (the WebSocket upgrade) are exempt, or the socket would be torn down after the deadline, and so is every path under one of streamingPrefixes: a download or a video read legitimately outlasts any fixed budget (a 30s cap truncated them mid-body). Those routes bound a stalled client with ProgressDeadline instead.

func RequireSystemRole

func RequireSystemRole(roles ...model.SystemRole) func(http.Handler) http.Handler

RequireSystemRole returns middleware that checks whether the authenticated user has one of the specified system roles.

func SecretFingerprint added in v0.0.97

func SecretFingerprint(secret string) string

SecretFingerprint is a short, non-reversible stand-in for a secret identifier in logs (e.g. a webhook ID), stable enough to correlate lines.

func SecurityHeaders added in v0.0.53

func SecurityHeaders(next http.Handler) http.Handler

SecurityHeaders sets defense-in-depth response headers on every response: a CSP (incl. frame-ancestors), X-Frame-Options (clickjacking belt-and-braces for older browsers), nosniff, a no-referrer policy (so an access token that rides in a URL can't leak via Referer), and HSTS (ignored by browsers over plain HTTP, so safe to always send).

func SecurityHeadersWith added in v0.0.61

func SecurityHeadersWith(extraConnectSrc ...string) func(http.Handler) http.Handler

SecurityHeadersWith is SecurityHeaders with extra connect-src origins appended to the CSP. Direct-to-storage browser uploads PUT presigned URLs straight at the S3 endpoint; the base policy's `https:` covers production object stores, but a plain-http endpoint (local MinIO) must be allow-listed explicitly or the browser refuses the upload with a CSP violation.

func SecurityHeadersWithOptions added in v0.0.97

func SecurityHeadersWithOptions(o CSPOptions) func(http.Handler) http.Handler

SecurityHeadersWithOptions is SecurityHeaders with the given additions to the CSP.

func SetTrustedProxyCount added in v0.0.53

func SetTrustedProxyCount(n int)

SetTrustedProxyCount configures how many trusted proxies prepend to X-Forwarded-For. Called from the app wiring (internal/app) with the deployment's topology.

func UserIDFromContext

func UserIDFromContext(ctx context.Context) string

UserIDFromContext returns the authenticated user's ID from context.

func Wrap

func Wrap(h http.Handler, mws ...func(http.Handler) http.Handler) http.Handler

Wrap applies a chain of middleware to a handler in the order provided, so the first middleware in the list is the outermost.

func WrapFunc

func WrapFunc(h http.HandlerFunc, mws ...func(http.Handler) http.Handler) http.Handler

WrapFunc is a convenience wrapper for http.HandlerFunc.

Types

type CSPOptions added in v0.0.97

type CSPOptions struct {
	// ConnectSrc is appended to connect-src (see SecurityHeadersWith).
	ConnectSrc []string
	// ScriptSrc is appended to script-src: the hashes of the served page's
	// inline scripts, and e.g. Sentry's CDN, which serves the lazily loaded
	// Session Replay bundle when a deployment samples it.
	ScriptSrc []string
	// WorkerSrc, when set, adds a worker-src of 'self' plus these sources
	// (Session Replay compresses in a blob: worker). 'self' stays because
	// pdf.js runs its worker from the app's own origin; without WorkerSrc
	// the directive is omitted and workers fall back to script-src.
	WorkerSrc []string
	// FramePath is the one same-origin path prefix the page may frame (the
	// HTML-attachment preview route). Empty keeps frame-src 'none'.
	FramePath string
	// FrameHosts are the deployment's public hosts (host[:port]) that
	// FramePath is allowed under, besides the host each request names.
	FrameHosts []string
	// FrameSrc are https origins the page may frame besides that route:
	// the SharePoint hosts a file preview loads from ("https://host" or
	// "https://*.domain"). Anything else is dropped.
	FrameSrc []string
}

CSPOptions are the per-deployment additions to the base policy. The zero value serves securityHeaderCSP unchanged.

type Limit added in v0.0.97

type Limit struct {
	Name   string
	Rate   int
	Burst  int
	Period time.Duration
}

Limit is one limiter's budget: Rate requests per Period, with up to Burst requests admitted back to back (GCRA — a client that has been quiet can spend a burst at once, then refills at Rate/Period).

Name namespaces the limiter's counters: two limiters with different names never share a budget, even when they key on the same user. (They used to: every per-user limiter spent one `rlu:write:<id>` counter, so a burst of message sends locked a user out of minting a WebSocket ticket — and a user without a socket gets no desktop alerts.)

func PerMinute added in v0.0.97

func PerMinute(name string, rate, burst int) Limit

PerMinute is a Limit of rate requests a minute with the given burst.

type RateLimitCounter added in v0.0.50

type RateLimitCounter interface {
	Allow(ctx context.Context, key string, limit Limit) (allowed bool, retryAfter time.Duration, err error)
}

RateLimitCounter decides whether one more request under key fits the limit. retryAfter is how long until the next request would be admitted (only meaningful when allowed is false).

type RedisRateLimiter added in v0.0.97

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

RedisRateLimiter is the production RateLimitCounter: go-redis/redis_rate's GCRA limiter, one atomic Lua call per request, shared by every instance.

func NewRedisRateLimiter added in v0.0.97

func NewRedisRateLimiter(client *redis.Client) *RedisRateLimiter

NewRedisRateLimiter builds the limiter over an existing Redis client.

func (*RedisRateLimiter) Allow added in v0.0.97

func (l *RedisRateLimiter) Allow(ctx context.Context, key string, limit Limit) (bool, time.Duration, error)

Allow implements RateLimitCounter.

type RunnerTokenChecker added in v0.0.89

type RunnerTokenChecker interface {
	RunnerTokenActive(ctx context.Context, claims *model.TokenClaims) (bool, error)
}

RunnerTokenChecker reports whether a runner token's record still exists — the per-install revocation check behind every runner request. false means the install was revoked (Runners page, `ex-runner logout`, account deactivation) or has expired; an error means the check itself failed.

Jump to

Keyboard shortcuts

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