Documentation
¶
Index ¶
- Constants
- func AccessLog(log *slog.Logger, trustedProxies ...*net.IPNet) func(http.Handler) http.Handler
- func AssetCache(next http.Handler) http.Handler
- func AssetCacheManifest(next http.Handler, files []string) http.Handler
- func AssetCacheManifestWithTTL(next http.Handler, files []string, ttl time.Duration) http.Handler
- func AssetCacheWithTTL(next http.Handler, ttl time.Duration) http.Handler
- func Authenticate(cfg *AuthConfig, sessions SessionStore, pats PATLookup) func(http.Handler) http.Handler
- func BodyLimit(n int64) func(http.Handler) http.Handler
- func BodyLimitExcept(n int64, exemptPrefixes ...string) func(http.Handler) http.Handler
- func CORS(allowedOrigins []string, allowCredentials bool) func(http.Handler) http.Handler
- func CSRFConditional(cfg *CSRFConfig, secure bool) func(http.Handler) http.Handler
- func CSRFMaskedToken(r *http.Request) string
- func CachePrefix(rules map[string]string) func(http.Handler) http.Handler
- func CachePrefixTTL(paths []string, ttl time.Duration) func(http.Handler) http.Handler
- func ClientIP(r *http.Request, trustedProxies ...*net.IPNet) string
- func ClientMetadata(next http.Handler) http.Handler
- func ClientMetadataFrom(ctx context.Context) (platform, version, os string)
- func ConfigHandler(d ConfigDeps) http.HandlerFunc
- func DecodeJSON(w http.ResponseWriter, r *http.Request, dst any) bool
- func DecodeJSONKnown(w http.ResponseWriter, r *http.Request, dst any) (unknown []string, ok bool)
- func DeriveCSRFKey(signingSecret []byte) []byte
- func ErrConflict(w http.ResponseWriter, msg string)
- func ErrForbidden(w http.ResponseWriter, msg string)
- func ErrInternal(w http.ResponseWriter)
- func ErrNotFound(w http.ResponseWriter, msg string)
- func ErrPayloadTooLarge(w http.ResponseWriter, msg string)
- func ErrReauthRequired(w http.ResponseWriter, maxAge time.Duration, confirmedAt time.Time)
- func ErrReauthRequiredFactor(w http.ResponseWriter, maxAge time.Duration, confirmedAt time.Time, ...)
- func ErrTimeout(w http.ResponseWriter)
- func ErrUnauthenticated(w http.ResponseWriter, msg string)
- func ErrUnavailable(w http.ResponseWriter, msg string)
- func ErrValidation(w http.ResponseWriter, msg string)
- func FrameworkVersion() string
- func Gzip(next http.Handler) http.Handler
- func HashIP(ip, secret string) string
- func HashToken(token string) string
- func MintToken() (string, error)
- func P(fn func(w http.ResponseWriter, r *http.Request, p *Principal)) http.HandlerFunc
- func ParseOrigins(raw string) []string
- func ParseTrustedProxies(raw string) []*net.IPNet
- func PoolStats(pool *pgxpool.Pool) (acquired, idle, total int32)
- func Precompressed(fsys fs.FS) func(http.Handler) http.Handler
- func PrincipalHolder() func(http.Handler) http.Handler
- func RateLimit(l Limiter, dimension string, perMinute int, keyFn func(r *http.Request) string) func(http.Handler) http.Handler
- func Recover(log *slog.Logger) func(http.Handler) http.Handler
- func RequestID(r *http.Request) string
- func RequestIDFromCtx(ctx context.Context) string
- func RequestIDMiddleware(next http.Handler) http.Handler
- func RequireAuth(next http.Handler) http.Handler
- func RequireHuman(next http.HandlerFunc) http.HandlerFunc
- func RequireRecentAuth(maxAge time.Duration) func(http.Handler) http.Handler
- func RequireRecentMFA(maxAge time.Duration) func(http.Handler) http.Handler
- func RequireScope(required ...string) func(http.Handler) http.Handler
- func RequireTransportKind(cfg *AuthConfig, kinds ...TransportKind) func(http.Handler) http.Handler
- func RequireWorkspaceScope() func(http.Handler) http.Handler
- func SecurityHeaders(next http.Handler) http.Handler
- func SvixHeaders(r *http.Request) (msgID, timestamp, signature string)
- func SvixVerify(secret, msgID, timestamp, signature string, body []byte) bool
- func Timeout(d time.Duration) func(http.Handler) http.Handler
- func TimeoutExcept(d time.Duration, exemptPrefixes ...string) func(http.Handler) http.Handler
- func WithPrincipal(ctx context.Context, p *Principal) context.Context
- func WriteErr(w http.ResponseWriter, err error)
- func WriteError(w http.ResponseWriter, status int, code, message string, details any)
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type AuthConfig
- type CSRFConfig
- type CheckFunc
- type ConfigDeps
- type CredentialScope
- type Error
- func NewConflict(msg string) *Error
- func NewError(status int, code, message string) *Error
- func NewForbidden(msg string) *Error
- func NewNotFound(msg string) *Error
- func NewQuotaExceeded(msg string) *Error
- func NewRateLimited(msg string) *Error
- func NewRateLimitedRetry(msg string, after time.Duration) *Error
- func NewUnauthenticated(msg string) *Error
- func NewValidation(msg string) *Error
- type ErrorBody
- type Factor
- type FailOpenLimiter
- type Health
- type Limiter
- type MemoryLimiter
- type Mux
- type PATLookup
- type Pagination
- type Principal
- type PrincipalCell
- type ProjectScope
- type RouteInfo
- type Router
- type SessionCreate
- type SessionStore
- type Source
- type TransportKind
Constants ¶
const ( HeaderClientPlatform = "X-Client-Platform" HeaderClientVersion = "X-Client-Version" HeaderClientOS = "X-Client-OS" )
const ( DefaultPageNum = 1 DefaultPageSize = 20 MaxPageSize = 100 )
Pagination defaults shared by every list endpoint. They mirror the convention the HTTP API documents (`pageNum` 1-based, `pageSize` capped) so a product does not have to re-derive the numbers.
const ( CodeUnauthenticated = "E_UNAUTHENTICATED" CodeForbidden = "E_FORBIDDEN" CodeNotFound = "E_NOT_FOUND" CodeValidation = "E_VALIDATION" CodeConflict = "E_CONFLICT" CodeRateLimited = "E_RATE_LIMITED" CodeQuotaExceeded = "E_QUOTA_EXCEEDED" CodeInternal = "E_INTERNAL" CodeTimeout = "E_TIMEOUT" CodePayloadTooLarge = "E_PAYLOAD_TOO_LARGE" // CodeReauthRequired is the step-up challenge (RequireRecentAuth): the // caller is authenticated but the password confirmation is stale — confirm // via POST /auth/confirm-password, then retry. 403, never 401. CodeReauthRequired = "E_REAUTH_REQUIRED" // CodeAuthTransportConflict rejects mixed-transport requests (session // cookie AND bearer credential on one request — or an ambiguous duplicate // of either): which credential authenticated and which transport the // gates inspected must never diverge (GitLab #22435 class). 401, and // logged as a security signal, never silently disambiguated. CodeAuthTransportConflict = "E_AUTH_TRANSPORT_CONFLICT" )
const ClientUnknown = "unknown"
const DefaultPATPrefix = "tk_"
DefaultPATPrefix is the canonical PAT token prefix: webx parses the Bearer token with it, wsx.DefaultPATPrefix aliases it for WebSocket first-frame auth, and identity/domain keeps a mirrored constant (domain purity — pure stdlib, no framework import). internal/arch's parity test pins the three together; changing the prefix means changing them in lockstep and handling already-stored tokens.
const HeaderRequestID = "X-Request-Id"
const SvixTolerance = 5 * time.Minute
SvixTolerance is the allowed clock skew between the svix-timestamp header and the receiver's clock. The Svix standard is five minutes.
Variables ¶
This section is empty.
Functions ¶
func AssetCache ¶ added in v0.12.0
AssetCache adds strong caching to content-addressed static assets and passes every other request through untouched.
Why it is needed: `http.FileServer` sets no Cache-Control / ETag / Last- Modified at all, leaving the browser to heuristic caching. Measured consequence: every in-site navigation re-downloaded the entry chunk — the same 178KB (gzip) file was fetched twice across a single /login -> /register navigation. The bytes saved on first load were paid back on every click.
Why immutable is safe: Vite derives the file name from the content hash, so content changes rotate the URL. The bytes behind a given URL never change, which means "one year + immutable" cannot serve stale code; a release simply stops referencing the old URL and the cache entry becomes unreachable. This mirrors what renderx already does by mixing buildID into its cache keys.
Why HTML and unhashed files are left alone: HTML must revalidate, or a release strands users on an old document that references deleted assets. Paths without a fingerprint (`/favicon.png`, `/brand/logo.png`) can be replaced in place, so any policy for them belongs to the product.
func AssetCacheManifest ¶ added in v0.12.0
AssetCacheManifest is the exact variant: `files` is the set of paths the build actually emitted (leading slash optional), typically extracted from Vite's `manifest.json`.
Why it exists: every other form of this middleware has to GUESS whether a URL is content-addressed, and the guess has a false-positive class that breaks in-place replacement — a hand-written `Some-Page-Banner.png` looks exactly like a fingerprint, gets `immutable, max-age=1y`, and then keeps serving old bytes to returning visitors after the product replaces the file. The manifest removes the guess: a path is immutable iff the build listed it.
Wiring: build the set once at startup (it is read-only afterwards) and mount this instead of AssetCache. Products that cannot reach their manifest keep using AssetCache and accept the documented false positives.
`files` keys are matched against r.URL.Path after prepending "/" when absent, so both `assets/app-abc123.js` and `/assets/app-abc123.js` are accepted. Non-content-addressed files (HTML, favicons, uploads) must simply be left out of the set — anything absent passes through untouched.
func AssetCacheManifestWithTTL ¶ added in v0.12.0
AssetCacheManifestWithTTL is the configurable-TTL variant.
func AssetCacheWithTTL ¶ added in v0.12.0
AssetCacheWithTTL is the configurable variant; ttl <= 0 falls back to a year.
Content addressing is inferred from the filename (see looksContentAddressed). When the build's manifest is available, use AssetCacheManifest instead: the inference has false positives that no name rule can eliminate.
func Authenticate ¶
func Authenticate(cfg *AuthConfig, sessions SessionStore, pats PATLookup) func(http.Handler) http.Handler
func BodyLimitExcept ¶ added in v0.7.1
BodyLimitExcept is the prefix-exemption variant (storage-walk #11): exempt prefixes BYPASS the limit reader entirely instead of getting a second, larger MaxBytesReader layered on top. Layering two MaxBytesReaders nests the constraints — the effective limit is the MINIMUM, so the common product wiring of pathGate(BodyLimit(6MB), "/api/upload/") over a global 1MB BodyLimit silently kept 1MB in charge (field-report verified).
Pairing rule (#12): a prefix whose body limit you raise almost always also needs TimeoutExcept — reading a large (possibly slow) body consumes the request-timeout budget, and a 5s global timeout bisects slow uploads no matter how generous the body limit is.
func CSRFConditional ¶
func CSRFMaskedToken ¶
func CachePrefix ¶ added in v0.16.0
CachePrefix returns middleware that sets Cache-Control on responses whose URL path starts with one of the declared prefixes — for the non-hashed static files AssetCache deliberately leaves alone.
Why it exists: AssetCache/AssetCacheManifest cache only content-addressed files, and the ruling there is that files which can be replaced in place (`/favicon.png`, `/brand/logo.png`, product image directories like `/shots/*`) get their policy from the product. The practical outcome of that ruling was consumers hand-writing per-prefix `Set("Cache-Control", ...)` branches inside their SPA handler, with the failure a hand-written whitelist invites: one missing prefix silently serves a whole image directory with zero cache headers (product field report: 838 KiB re-downloaded per returning visit). This helper lets the product declare the prefixes instead of implementing the branch.
Matching semantics:
- **Longest prefix wins.** A map has no iteration order, so "first match" would be non-deterministic; longest match is deterministic and makes the more specific declaration win (`/shots/thumbs/` over `/shots/`).
- Prefixes match with strings.HasPrefix against r.URL.Path, the same convention as TimeoutExcept/BodyLimitExcept. Directory prefixes should end in "/": `/shots` also matches `/shots-extra/` — usually not what a directory declaration means.
- A missing leading slash is prepended at construction (`shots/` behaves like `/shots/`); an empty prefix or an empty value is ignored (an empty value would set an empty header).
- GET/HEAD only; other methods pass through untouched.
- No prefix matches → the request passes through with no header, keeping the caller's default.
- A matched response carries the declared value only when it is a 2xx (206 excluded) and Cache-Control is not already set. Error responses are never decorated — same ruling as AssetCache: a 404 under a cached prefix must not be pinned, or the browser is entitled to cache the error for the full max-age. A Cache-Control set by the inner handler wins: the inner decision is more specific than a prefix declaration.
Values are used verbatim; the caller controls public/private, must-revalidate and friends. For a plain shared-cache TTL see CachePrefixTTL.
func CachePrefixTTL ¶ added in v0.16.0
CachePrefixTTL is the convenience form of CachePrefix: one shared-cache TTL (`public, max-age=<seconds>`) for every listed prefix.
Deliberately NO `immutable`: these files are exactly the ones that can be replaced in place, which is why AssetCache excludes them. `immutable` on a replaceable file strands returning visitors on old bytes until the max-age expires — declare a TTL short enough to tolerate replacement instead. ttl is truncated to whole seconds; ttl <= 0 yields `max-age=0` (revalidate every time), never a silently longer fallback.
func ClientMetadataFrom ¶
func ConfigHandler ¶
func ConfigHandler(d ConfigDeps) http.HandlerFunc
func DecodeJSON ¶
func DecodeJSONKnown ¶ added in v0.6.1
DecodeJSONKnown is the evolution-friendly counterpart of DecodeJSON (aifengkong #3): valid JSON is decoded into dst leniently — type mismatches still fail with 400 — but UNKNOWN field names are captured into the returned slice instead of rejected, so a handler can accept a client that started sending extra data (shadow-field rollout) while still seeing exactly what it ignored. Handlers wanting unknown = 400 keep DecodeJSON.
func DeriveCSRFKey ¶
func ErrConflict ¶
func ErrConflict(w http.ResponseWriter, msg string)
func ErrForbidden ¶
func ErrForbidden(w http.ResponseWriter, msg string)
func ErrInternal ¶
func ErrInternal(w http.ResponseWriter)
func ErrNotFound ¶
func ErrNotFound(w http.ResponseWriter, msg string)
func ErrPayloadTooLarge ¶
func ErrPayloadTooLarge(w http.ResponseWriter, msg string)
func ErrReauthRequired ¶ added in v0.4.0
ErrReauthRequired writes the step-up challenge: RFC 9470's insufficient_user_authentication semantics adapted to ploykit's cookie + error-envelope shape. 403 (not 401): the caller IS authenticated, only the assurance is stale, and a 401 would wrongly steer SPAs to full re-login.
func ErrReauthRequiredFactor ¶ added in v0.5.0
func ErrReauthRequiredFactor(w http.ResponseWriter, maxAge time.Duration, confirmedAt time.Time, factor Factor)
ErrReauthRequiredFactor is ErrReauthRequired with the stale factor named in the details: same 403 E_REAUTH_REQUIRED envelope, details.factor tells the client which proof to present.
func ErrTimeout ¶
func ErrTimeout(w http.ResponseWriter)
func ErrUnauthenticated ¶
func ErrUnauthenticated(w http.ResponseWriter, msg string)
func ErrUnavailable ¶
func ErrUnavailable(w http.ResponseWriter, msg string)
func ErrValidation ¶
func ErrValidation(w http.ResponseWriter, msg string)
func FrameworkVersion ¶ added in v0.7.0
func FrameworkVersion() string
FrameworkVersion reports the ploykit version this binary was compiled against, via the module build graph. Empty string when unavailable (go run without module metadata) — consumers must treat "" as "unknown", not as a version.
func Gzip ¶ added in v0.13.0
Gzip compresses text responses when the client accepts gzip.
The runtime lane of the framework's compression design: brotli is a build-time sidecar (webx.Precompressed — Go ships no brotli encoder, and -q 11 at build time beats anything runtime could afford), while gzip runs here because compress/gzip is stdlib and level-5 CPU cost is microseconds per KB. What each layer compresses barely overlaps: Precompressed answers for the static asset surface before the file server runs; this layer covers everything dynamic (renderx HTML, API JSON, SSE-less streaming responses).
Positioning: OUTERMost of the response-shaping middlewares, wrapping Precompressed/AssetCache and the handlers. It skips bodies that already carry a Content-Encoding, which is exactly how Precompressed's brotli responses pass through untouched.
Deliberate pass-throughs, each with a reason:
Range requests: the client asked for specific bytes of the identity body; re-encoding would desynchronize offsets.
HEAD: no body to compress, and advertising a Content-Encoding for an empty response misleads caches.
Non-compressible Content-Type: see gzipCompressible.
Responses that set their own Content-Encoding (Precompressed already did).
A preset Content-Length is NOT a skip: http.FileServer sets it for every small file, and dropping compression there would gut the middleware's purpose. `start` deletes the header and the compressed length takes over.
Vary: Accept-Encoding is stamped on every response this layer touches, compressed or not — a shared cache must never pair an identity variant with a gzip-accepting client or vice versa (deduped via hasVaryToken, shared with Precompressed).
Content-Type is decided either by the handler's header (WriteHeader path) or by sniffing the first Write (http.DetectContentType) when the handler set none — same fallback the net/http file server uses.
func P ¶
func P(fn func(w http.ResponseWriter, r *http.Request, p *Principal)) http.HandlerFunc
func ParseOrigins ¶
func ParseTrustedProxies ¶
func Precompressed ¶ added in v0.12.0
Precompressed serves a brotli sidecar file (`app.js.br`) when the client accepts it and the sidecar exists, falling back to the identity file otherwise.
Why precompressed instead of compressing on the fly: Go's standard library ships a brotli *decoder* but no encoder, so runtime brotli would mean a third party dependency plus per-request CPU. The build already knows the bytes and can afford `-q 11`, which is ~14% smaller than gzip -9 on the framework chunk (measured: 171KB → 144KB for the example's entry bundle). Lazy route chunks are a few KB, where the difference is noise — this pays on the entry bundle and on CSS.
Wiring contract: the caller must mount whatever produces `.br` files into the same fs.FS as the originals, and must set `Vary: Accept-Encoding` on every response that could differ — including the identity one, or a shared cache will hand a brotli body to a client that never advertised support.
func RequestIDFromCtx ¶
func RequireHuman ¶
func RequireHuman(next http.HandlerFunc) http.HandlerFunc
func RequireRecentAuth ¶ added in v0.4.0
RequireRecentAuth guards sensitive operations behind a fresh password confirmation (step-up / sudo mode, the Laravel password.confirm / GitHub sudo-mode pattern). Mount it after Authenticate. Only interactive sessions pass: a session whose PasswordConfirmedAt is older than maxAge — or never set — fails with the two-phase reauthentication protocol (403 E_REAUTH_REQUIRED + details.max_age_seconds): the client re-verifies the password via POST /auth/confirm-password and retries the original request (docs/api-conventions.md §step-up). Machine callers (PAT / system) can never satisfy step-up and get a plain 403 — they cannot reauthenticate interactively, so a scoped PAT must not reach actions reserved for a present human.
The window is a product policy decision (GitHub uses 2h, Laravel 3h defaults): pick it per mount site, there is deliberately no package default.
This is the static, route-level policy path. authorization/'s Challenge outcome covers the computed, catalog-driven escalation for strong-profile consumers — do not mount both on the same operation (see the step-up section of authorization/README.md).
func RequireRecentMFA ¶ added in v0.5.0
RequireRecentMFA is RequireRecentAuth's second-factor twin: it guards AAL2-grade operations behind a fresh MFA proof (TOTP / backup code via POST /auth/verify-mfa). Mount it after Authenticate. Only interactive sessions pass: a session whose MFAConfirmedAt is older than maxAge — or never set — fails with the two-phase challenge (403 E_REAUTH_REQUIRED + details.max_age_seconds + details.factor="mfa"); machine callers (PAT / system) get a plain 403 — they can never complete an interactive MFA proof (ADR 0011 semantics extended to MFA, ADR 0013 batch 2).
The window is product policy — pick it per mount site, there is no package default. This is the static road; the computed, catalog-driven form is authorization/'s recent_auth: password_and_mfa — do not mount both on the same operation.
func RequireScope ¶ added in v0.4.0
RequireScope closes the PAT scope-enforcement gap on endpoints that do NOT go through authz (machine-to-machine mounts such as MCP tools, OpenAPI servers, webhook receivers). authz.CanIn already enforces CredentialScope.Permissions when the product calls it; this middleware is the equivalent default for handlers that build their own actor straight from the Principal — without it, any PAT passes regardless of its declared scope (field report: risk-engine-server issue #12, a scoped PAT invoking an unrestricted MCP tool succeeded where it should have been rejected).
Semantics:
- Non-PAT principals (sessions) pass untouched — browser sessions are not scope-bounded; authorization stays with authz/role checks.
- PATs whose scope carries no Permissions list are unrestricted by design (AllowsPermission: nil = allow-all) and pass.
- A PAT with a Permissions list passes only if some declared permission shares the domain of at least one required permission (permDomain: "post:submit" and "post:*" both cover domain "post").
Mount it right after Authenticate on machine-facing routes:
mux.Handle("POST /mcp", Authenticate(...)(RequireScope("post:submit", "post:publish")(h)))
Workspace bounding (Scope.WorkspaceIDs) is checked by RequireWorkspaceScope when the workspace id is known at mount time; for request-derived workspace ids keep using authz.CanIn inside the handler.
func RequireTransportKind ¶ added in v0.5.0
func RequireTransportKind(cfg *AuthConfig, kinds ...TransportKind) func(http.Handler) http.Handler
RequireTransportKind rejects requests whose transport is not one of kinds. Mount it before any handler logic runs — a transport violation terminates the request before authentication, authorization, or CSRF can form an opinion on the "wrong" credential (that ordering is the GitLab-#22435 lesson).
- mixed transport → 401 E_AUTH_TRANSPORT_CONFLICT always (a security signal worth its own log line, never silently disambiguated);
- no credential → 401 E_UNAUTHENTICATED;
- a present-but-not-allowed transport → 403 E_FORBIDDEN (the caller authenticated, this transport may not perform the operation).
Typical mount: RequireTransportKind(&cfg, TransportBearer) in front of a machine-only endpoint. Session-only and multi-transport routes keep their ordinary auth middleware — this matcher is opt-in per operation class.
func RequireWorkspaceScope ¶ added in v0.4.0
RequireWorkspaceScope bounds a PAT to its declared workspace list when the endpoint serves exactly one fixed workspace context (request-derived contexts belong in the handler via authz.CanIn, which also checks WorkspaceIDs). Non-PAT principals pass untouched.
func SvixHeaders ¶ added in v0.15.0
SvixHeaders extracts the Svix signing triple from a request. Missing headers come back as empty strings; SvixVerify then fails.
func SvixVerify ¶ added in v0.15.0
SvixVerify reports whether the Svix signature triple authenticates body at the current time. secret is the endpoint's signing secret in the usual "whsec_<base64>" form (raw base64 without the prefix is accepted too).
func TimeoutExcept ¶
func WriteErr ¶
func WriteErr(w http.ResponseWriter, err error)
WriteErr writes the canonical error body, plus the retry metadata when the error carries a RetryAfter hint.
func WriteError ¶
func WriteError(w http.ResponseWriter, status int, code, message string, details any)
Types ¶
type AuthConfig ¶
type AuthConfig struct {
CookieName string
CookieDomain string
Secure bool
SessionTTL time.Duration
AbsoluteTTL time.Duration
IPHashSecret string
PATPrefix string
}
func DefaultAuthConfig ¶
func DefaultAuthConfig() AuthConfig
DefaultAuthConfig returns the shared defaults. Secure defaults to **false**: a production-true default made every local-HTTP / intranet deployment fail login with an opaque CSRF error (the Secure cookie is never sent back over plain HTTP — two layers away from the root cause, see aiblog/risk-engine field reports). Production deployments must opt in explicitly:
cfg := webx.DefaultAuthConfig() cfg.Secure = env == "production"
IPHashSecret is deliberately left empty here (local development needs no salt) and MUST be set in production: it keys the IP fingerprint used by login throttling and step-up re-authentication, and an empty salt makes those fingerprints enumerable. HashIP logs a one-time warning when it sees an empty salt, but a warning is easy to miss in a busy boot log — wire devx.IPHashSaltCheck into the product's doctor so the gap shows up as a failed startup diagnostic instead.
example wires it to SECURE_COOKIE / AUTH_IP_HASH_SECRET the same way.
func (*AuthConfig) ClassifyTransport ¶ added in v0.5.0
func (c *AuthConfig) ClassifyTransport(r *http.Request) TransportKind
ClassifyTransport inspects the raw request (no store lookups) and names its auth transport. Strictness is the point:
- exactly one session cookie → session_cookie; more than one cookie with the configured name (domain/path shadowing) is ambiguous → mixed;
- exactly one `Authorization: Bearer <prefix…>` header (the configured PAT prefix — foreign bearer schemes are not our credentials) → bearer; several Authorization headers → mixed;
- cookie AND bearer present → mixed.
Authenticate resolves sessions and PATs through this single classification, so "which credential authenticated" and "which transport the gate saw" can never diverge.
func (*AuthConfig) ClearSessionCookie ¶
func (c *AuthConfig) ClearSessionCookie(w http.ResponseWriter)
func (*AuthConfig) SetSessionCookie ¶
func (c *AuthConfig) SetSessionCookie(w http.ResponseWriter, token string, exp time.Time)
type CSRFConfig ¶
type CSRFConfig struct {
Key []byte
// TrustedOrigins lists host[:port] entries gorilla/csrf accepts as
// cross-origin submitters. Matching is exact, port included.
TrustedOrigins []string
// TrustLocalhostAnyPort is a development convenience: when set, the
// loopback family (localhost, 127.0.0.1, [::1]) is trusted on ANY port,
// so a dev server drifting off its default port (vite 5173 -> 5176 when
// 5173 is taken) does not turn every write into an opaque 403. Leave it
// off in production; production must enumerate exact origins.
TrustLocalhostAnyPort bool
ExemptPrefixes []string
// MaxAge is the CSRF cookie lifetime in seconds, passed through to
// gorilla/csrf verbatim (orkome pack-rollout addendum). Zero value keeps the framework's
// historical behavior (gorilla's 12h default); a product whose session
// TTL exceeds 12h must raise this or long-idle users hit "every write
// 403s" until the next /config refetch (the cookie dies before the
// session does) — align it with AuthConfig.SessionTTL. Negative means a
// session cookie (gorilla semantics). The zero-value-defaults-to-12h
// reading is deliberate: an unset config must not change existing
// deployments' cookie behavior.
MaxAge int
PATPrefix string
// SessionCookieName is the auth session cookie's name — the CSRF skip is
// a clean bearer transport only; a request that also carries this cookie
// is mixed and falls through to the CSRF check. Wire it to
// AuthConfig.CookieName (empty = never treat requests as cookie-carrying).
SessionCookieName string
}
type ConfigDeps ¶
type CredentialScope ¶
type CredentialScope struct {
WorkspaceIDs []string `json:"workspace_ids,omitempty"`
Permissions []string `json:"permissions,omitempty"`
}
func (*CredentialScope) Allows ¶ added in v0.4.0
func (s *CredentialScope) Allows(required ...string) bool
Allows reports whether the scope covers ALL of the required permissions (same per-permission semantics as AllowsPermission; nil Permissions = unrestricted). The default enforcement gate for machine-facing mounts: webx.RequireScope(required...) is exactly `p.Scope.Allows(required...)`.
func (*CredentialScope) AllowsPermission ¶
func (s *CredentialScope) AllowsPermission(perm string) bool
func (*CredentialScope) AllowsWorkspace ¶
func (s *CredentialScope) AllowsWorkspace(workspaceID string) bool
type Error ¶
type Error struct {
Status int
Code string
Message string
// RetryAfter, when non-zero, is emitted as the standard `Retry-After`
// header by WriteErr and mirrored into the JSON body. Rate-limit errors
// set it so clients can wait the right amount instead of guessing (a bare
// 429 carrying only prose is the shape that produces blind retry storms
// and "how long do I wait?" support tickets).
RetryAfter time.Duration
}
func NewConflict ¶
func NewForbidden ¶
func NewNotFound ¶
func NewQuotaExceeded ¶
func NewRateLimited ¶
func NewRateLimitedRetry ¶ added in v0.11.3
NewRateLimitedRetry is NewRateLimited plus the wait hint. The response then carries `Retry-After` (whole seconds, rounded up) AND the same value in the JSON body as details.retry_after_seconds — the body copy exists because browser JS cannot read response headers on a cross-origin request without explicit CORS exposure, and the body is always readable.
func NewUnauthenticated ¶
func NewValidation ¶
type Factor ¶ added in v0.5.0
type Factor string
Factor names the stale step-up fact, so clients know which confirmation endpoint clears the challenge (confirm-password vs verify-mfa).
type FailOpenLimiter ¶
type FailOpenLimiter struct{}
type Health ¶
type Health struct {
// contains filtered or unexported fields
}
func (*Health) Liveness ¶
func (h *Health) Liveness() http.HandlerFunc
func (*Health) Readiness ¶
func (h *Health) Readiness() http.HandlerFunc
type MemoryLimiter ¶ added in v0.7.0
type MemoryLimiter struct {
// contains filtered or unexported fields
}
MemoryLimiter is an in-process sliding-window Limiter (renderx-walk #6): single-binary deployments without Redis previously fell back to FailOpenLimiter — rate limiting silently off, brute-force surfaces wide open. This implementation is standard-library only and per-process (each replica limits independently), which is the correct trade for small deployments; multi-instance products move to redisx.NewGCRALimiter.
func NewMemoryLimiter ¶ added in v0.7.0
func NewMemoryLimiter() *MemoryLimiter
NewMemoryLimiter returns an in-process sliding-window limiter. The window is one minute (the Limiter contract's perMinute semantics).
type Mux ¶ added in v0.4.0
type Mux struct {
// contains filtered or unexported fields
}
Mux wraps *http.ServeMux and records every registered pattern, giving products route introspection the std mux lacks (the chi.Walk equivalent): Routes() returns a sorted, immutable snapshot for diagnostics, route listings, and runtime↔OpenAPI contract tests. Serving behavior is the delegated std mux, unchanged.
func (*Mux) Handle ¶ added in v0.4.0
Handle records the pattern and delegates to the wrapped *http.ServeMux.
func (*Mux) HandleFunc ¶ added in v0.4.0
HandleFunc records the pattern and delegates to the wrapped *http.ServeMux.
type Pagination ¶ added in v0.11.3
Pagination is a parsed and clamped `?pageNum=&pageSize=` pair.
func ParsePagination ¶ added in v0.11.3
func ParsePagination(r *http.Request, defaultSize, maxSize int) Pagination
ParsePagination reads `pageNum` / `pageSize` from the request and clamps them into a usable range:
- a missing, non-numeric, or < 1 pageNum becomes 1
- a missing, non-numeric, or < 1 pageSize becomes defaultSize
- a pageSize above maxSize becomes maxSize
Clamping (rather than rejecting) is deliberate: a pagination parameter is never the reason a read should fail, and the alternative — each handler inventing its own rule — produces the observable mess this helper replaces (one endpoint clamping pageSize=999 to 100, another honoring it verbatim, a third silently returning the default).
Pass 0 for defaultSize/maxSize to use DefaultPageSize/MaxPageSize.
func (Pagination) Offset ¶ added in v0.11.3
func (p Pagination) Offset() int
Offset is the SQL OFFSET for this page.
type Principal ¶
type Principal struct {
UserID string
Email string
Name string
Source Source
SessionID string
PATID string
WorkspaceID string
Role string
Project *ProjectScope
Scope *CredentialScope
AgentID string
IsPlatformAdmin bool
ImpersonatedBy string
// PasswordConfirmedAt records when the caller last proved the password for
// this session: a password login / registration / password change births
// the session already confirmed, and POST /auth/confirm-password (step-up)
// re-stamps it later. Zero = never proved (code login, third-party login,
// impersonation, PAT). Consumed by RequireRecentAuth.
PasswordConfirmedAt time.Time
// MFAConfirmedAt records when the caller last proved a second factor for
// this session (TOTP / backup code via POST /auth/verify-mfa). Sessions
// born from a login that completed MFA start confirmed
// (SessionCreate.MFAConfirmed); password-only logins stay unconfirmed.
// Zero = no MFA proof on this session. Consumed by RequireRecentMFA.
MFAConfirmedAt time.Time
}
func PrincipalFrom ¶
func PrincipalFromRequest ¶
func (*Principal) MFAConfirmedWithin ¶ added in v0.5.0
MFAConfirmedWithin is MFAConfirmedWithin's second factor twin: it reports whether the MFA proof on this session is fresh enough for a RequireRecentMFA window of maxAge.
func (*Principal) PasswordConfirmedWithin ¶ added in v0.4.0
PasswordConfirmedWithin reports whether the password confirmation is fresh enough for a step-up window of maxAge (never-confirmed and future-dated stamps both fail).
type PrincipalCell ¶
type PrincipalCell struct {
// contains filtered or unexported fields
}
func (*PrincipalCell) Get ¶
func (c *PrincipalCell) Get() *Principal
func (*PrincipalCell) Set ¶
func (c *PrincipalCell) Set(p *Principal)
type ProjectScope ¶
type RouteInfo ¶ added in v0.4.0
type RouteInfo struct {
// Method is the leading HTTP method of the pattern ("GET", "POST", ...).
// It is "" when the pattern carries no method prefix (mounts, catch-alls,
// subtree handlers) — by convention those are not endpoints.
Method string
// Path is the pattern minus the method prefix, kept literal: wildcards
// like {id} are preserved exactly as registered.
Path string
// Pattern is the raw pattern as registered (method prefix included).
Pattern string
}
RouteInfo describes one registered route pattern.
type Router ¶ added in v0.4.0
type Router interface {
Handle(pattern string, h http.Handler)
HandleFunc(pattern string, f func(http.ResponseWriter, *http.Request))
}
Router is the route-registration surface every framework Mount function accepts. *http.ServeMux satisfies it, so products keeping a std mux keep compiling unchanged; passing a *Mux additionally records the route set for runtime introspection (see Mux).
type SessionCreate ¶ added in v0.4.0
type SessionCreate struct {
UserID string
IPHash string
UserAgent string
// PasswordConfirmed marks a session born right after an explicit password
// proof (password login, registration, password change). Such sessions
// start with PasswordConfirmedAt set and satisfy RequireRecentAuth
// immediately; code/third-party logins stay unconfirmed until the caller
// completes a step-up (POST /auth/confirm-password).
PasswordConfirmed bool
// MFAConfirmed marks a session born from a login that completed the
// second factor (TOTP / backup code). Such sessions start with
// MFAConfirmedAt set and satisfy RequireRecentMFA immediately;
// password-only logins stay MFA-unconfirmed until the caller completes
// POST /auth/verify-mfa. Password-only and MFA-only births are both
// expressible — the two stamps are independent facts (ADR 0013 batch 2:
// a login completing MFA stamps both, a password-only login only the
// password fact).
MFAConfirmed bool
Now time.Time
}
SessionCreate carries the inputs of SessionStore.CreateSession.
type SessionStore ¶
type SessionStore interface {
CreateSession(ctx context.Context, in SessionCreate) (token string, exp time.Time, err error)
VerifySession(ctx context.Context, token string, now time.Time) (*Principal, error)
RenewSession(ctx context.Context, token string, now time.Time) (exp time.Time, renewed bool, err error)
RevokeSession(ctx context.Context, token string) error
}
type TransportKind ¶ added in v0.5.0
type TransportKind string
TransportKind is the authentication transport a request arrived on — the per-operation transport contract of ADR 0013 batch 3 (G4): the operation's declared auth_method is only as strong as the transport it accepts, and a request carrying TWO credentials must never be resolved by picking one silently (GitLab #22435 class: CSRF decisions keyed off one credential while the other authenticates).
The kinds are deliberately neutral — webx never imports authorization/ (arch A6 cuts both ways); the catalog auth_method → kind mapping is five lines at the composition root.
const ( // TransportNone: no credential on the wire. TransportNone TransportKind = "none" // TransportSessionCookie: exactly one session cookie, no bearer header. TransportSessionCookie TransportKind = "session_cookie" // TransportBearer: exactly one well-formed Authorization: Bearer header, // no session cookie. TransportBearer TransportKind = "bearer" // TransportMixed: both credentials (or an ambiguous duplicate of one) on // the same request — always a rejection, never resolved by precedence. TransportMixed TransportKind = "mixed" )