middleware

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 44 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

View Source
const AuthRealm = "openartifact"

AuthRealm is the realm of the Basic and Bearer challenges. It is a protocol identifier: clients that select credentials by realm (sbt's Credentials, for one) must be given exactly this value, so client snippets quote it.

View Source
const CSRFTokenCookieName = "oa_csrf"
View Source
const TraceIDKey contextKey = "trace_id"

Variables

This section is empty.

Functions

func AuditMiddleware

func AuditMiddleware(auditLogger *audit.Logger, trusted ...*TrustedProxies) func(http.Handler) http.Handler

func AuthAuditMiddleware added in v0.2.0

func AuthAuditMiddleware(
	auditLogger *audit.Logger,
	db AuthAuditMiddlewareStore,
	trusted ...*TrustedProxies,
) func(http.Handler) http.Handler

AuthAuditMiddleware audits auth.login, auth.login_failed, auth.logout and auth.sso_login. Success is decided from what the handler did to the session cookie (a Set-Cookie carrying a fresh oa_session value), not from the status code, because the SSO callbacks redirect on both success and failure.

func CORSMiddleware

func CORSMiddleware(allowedOrigins []string) func(http.Handler) http.Handler

CORSMiddleware handles CORS headers.

The browser refuses to deliver a credentialed response when the server returns Access-Control-Allow-Origin: * — credentials require an exact origin echo plus Access-Control-Allow-Credentials: true. The SPA always uses fetch with credentials: 'include' (for the session cookie), so for an explicitly listed origin we echo it and advertise credentials.

A "*" entry must never be combined with credentials: reflecting an arbitrary Origin together with Allow-Credentials would let any website read authenticated responses with the visitor's session cookie. With a wildcard the middleware answers a literal "*" without credentials (token-header clients still work; cookie-session browsers cross-origin do not), unless the origin is also listed explicitly.

func CSRFMiddleware

func CSRFMiddleware(baseURL string, trusted *TrustedProxies) func(http.Handler) http.Handler

CSRFMiddleware enforces CSRF protection for browser sessions. baseURL is the public base URL: an https value forces Secure on the CSRF cookie and its origin is accepted as the origin of Basic-authenticated browser requests. trusted lists the reverse proxies whose X-Forwarded-Proto / X-Forwarded-Host may be believed (nil trusts nobody).

A state-changing request authenticated by the session cookie must echo the token bound to that session in X-CSRF-Token, on every path (the API, /repos, /v2, ...). Requests authenticated by an explicit header credential cannot be forged cross-site and are unaffected, except Basic requests that are visibly cross-site: on /api/v1 they need the double-submit token, elsewhere they are refused.

func CSRFTokenForSession added in v0.15.0

func CSRFTokenForSession(sessionCookieValue string) string

CSRFTokenForSession derives the CSRF token of a browser session from its session cookie value: HMAC-SHA256 keyed with that (256-bit random, HttpOnly) secret. Only a holder of the session cookie can compute it, so a token planted from a sibling subdomain, or kept from an earlier session, never validates for another session. The session cookie value is rotated on every login, which rotates the token with it.

func ClientIP

func ClientIP(r *http.Request, trusted *TrustedProxies) string

ClientIP returns the request's client IP. X-Forwarded-For / X-Real-IP are honored ONLY when the immediate TCP peer (r.RemoteAddr) is a configured trusted proxy; otherwise the peer address itself is returned. This means a direct, non-proxied client can never spoof its own IP by setting either header — the classic bypass this replaces.

func CompressAPI added in v0.19.0

func CompressAPI(next http.Handler) http.Handler

CompressAPI zstd- or gzip-encodes the JSON documents of the control-plane API (/api/v1/**) for clients that accept it; see httpcompress.Middleware for the rules. Everything else passes through untouched. Repository routes (/repos, /v2) serve artifacts and are never compressed here: the formats' metadata handlers opt in one by one (base.Compress). Downloads under /api/v1 (a Content-Disposition response: artifact and export downloads) are left alone by the middleware itself.

Mount it innermost on the authenticated router, so the status-recording writer of the outer layers stays the one the handlers see.

func CountUploads added in v0.9.0

func CountUploads(reg *metrics.Registry, format string, next http.HandlerFunc) http.HandlerFunc

CountUploads wraps a handler that serves one hosted-upload format on a route it shares with other formats (so MetricsMiddleware cannot tell the format from the route), counting every request it serves in openartifact_uploads_total by response status.

func DenialAuditMiddleware added in v0.22.0

func DenialAuditMiddleware(auditLogger *audit.Logger, trusted ...*TrustedProxies) func(http.Handler) http.Handler

DenialAuditMiddleware records a mutating request refused with 401 or 403 before AuditMiddleware ran (RBAC denial, CSRF failure), which that middleware sits too deep in the chain to see. Install it outside RBAC.

func GroupDeployFromContext added in v0.26.0

func GroupDeployFromContext(ctx context.Context, group string) string

GroupDeployFromContext returns the deploy target RBAC authorized a write to group against, "" when it authorized none (the write to a group is then refused).

func IPAllowlistMiddleware

func IPAllowlistMiddleware(allowedCIDRs []string, trusted *TrustedProxies) func(http.Handler) http.Handler

IPAllowlistMiddleware blocks requests not from allowed CIDRs. If allowlist is empty, all IPs are allowed. trusted controls which reverse proxies' X-Forwarded-For/X-Real-IP are honored when resolving the client IP — see ClientIP.

func LimiterKey added in v0.6.0

func LimiterKey(ip string) string

LimiterKey normalizes a client IP string into a rate-limiter key: IPv4-mapped IPv6 addresses collapse to IPv4 and IPv6 addresses collapse to their /64, so a single subscriber cannot mint 2^64 distinct keys. Unparseable input is returned unchanged.

func LoggingMiddleware

func LoggingMiddleware(log *logger.Logger) func(http.Handler) http.Handler

LoggingMiddleware logs HTTP requests.

func MCPResourceURL added in v0.8.0

func MCPResourceURL(baseURL, mcpPath string) string

MCPResourceURL is the canonical resource identifier (RFC 8707) of the MCP endpoint: the base URL plus its mount path. OIDC access tokens must name it in their aud claim.

func MaxBodyMiddleware added in v0.6.0

func MaxBodyMiddleware(limit int64) func(http.Handler) http.Handler

MaxBodyMiddleware caps every request body at limit bytes. Reads past the cap fail with *http.MaxBytesError (handlers answer 413) and the connection is closed. A non-positive limit disables the cap. It is the backstop behind the per-handler limits, so no endpoint can be made to buffer or spool an unbounded body.

func MetricsMiddleware

func MetricsMiddleware(reg *metrics.Registry) func(http.Handler) http.Handler

func PathLabel added in v0.9.0

func PathLabel(pattern string, r *http.Request) string

PathLabel is the value of the path label of the HTTP metrics: the route template that served the request, never the raw URL.

pattern is the chi route pattern ("" when no route matched). Templates ("/repos/{name}/{pkg}", "/repos/maven/{name}/*") are bounded by the route table, so repository names, package names, versions and digests never reach a label; a wildcard keeps its "/*" so every catch-all is one fixed bucket. The one exception is the OCI registry, whose single "/v2/*" route is split into the registry endpoints (see ociPathLabel). A request that matched no route is "unmatched".

func PrincipalFromContext

func PrincipalFromContext(ctx context.Context) *auth.Principal

func ProtectedResourceMetadataURL added in v0.8.0

func ProtectedResourceMetadataURL(baseURL, mcpPath string) string

ProtectedResourceMetadataURL is where the RFC 9728 metadata of the MCP endpoint at mcpPath is served: the well-known segment is inserted between the host and the path (RFC 9728 section 3.1). baseURL is the public URL of the server without a path.

func RBACMiddleware

func RBACMiddleware(cfg RBACConfig, db RBACMiddlewareStore, evaluator *auth.Evaluator, log *logger.Logger) func(http.Handler) http.Handler

func RateLimitMiddleware

func RateLimitMiddleware(ctx context.Context, limit int, window time.Duration, trusted *TrustedProxies) func(http.Handler) http.Handler

RateLimitMiddleware limits requests per IP using a token bucket algorithm. limit: max requests per window window: time window duration trusted: which reverse proxies' X-Forwarded-For/X-Real-IP are honored when resolving the client IP — see ClientIP.

The janitor goroutine that drops idle buckets runs until ctx is cancelled.

func RecoveryMiddleware

func RecoveryMiddleware(log *logger.Logger) func(http.Handler) http.Handler

RecoveryMiddleware recovers from panics.

func RejectNULBytes added in v0.11.0

func RejectNULBytes(next http.Handler) http.Handler

RejectNULBytes answers 400 to a request whose path or query string carries a NUL byte. NUL is never meaningful in a URL, and Postgres text cannot store it: reaching a query it surfaces as a database error (500) from whichever endpoint happens to bind the value.

func RepoAndPath added in v0.4.0

func RepoAndPath(urlPath string) (string, string)

RepoAndPath maps a request path to the (repository, artifact path) pair the permission evaluator scopes against, so code serving a repository on behalf of the router sees exactly what RBAC authorized.

func RequestIDMiddleware

func RequestIDMiddleware(next http.Handler) http.Handler

RequestIDMiddleware adds a unique request ID to each request.

func SecurityHeadersMiddleware added in v0.2.0

func SecurityHeadersMiddleware(hsts bool) func(http.Handler) http.Handler

SecurityHeadersMiddleware sets baseline hardening headers on every response. hsts enables Strict-Transport-Security and should only be set when the server is reachable over HTTPS. Existing handler-set values are preserved (headers are added before the handler runs, handlers may override).

func SessionCSRFCookie added in v0.15.0

func SessionCSRFCookie(sessionCookieValue string, secure bool) *http.Cookie

SessionCSRFCookie is the readable (not HttpOnly) cookie that hands the CSRF token of the session sessionCookieValue to the SPA, which echoes it in X-CSRF-Token.

func TracingMiddleware

func TracingMiddleware(next http.Handler) http.Handler

TracingMiddleware generates a trace ID per request if not present in headers (only a 32-character lowercase hex one is accepted from the client, anything else is replaced: the value is echoed in a response header and written to the logs) and propagates it via X-Trace-ID response header. When OpenTelemetry is enabled the request has a W3C trace (telemetry.HTTPMiddleware runs first) and its trace id is used instead, so the header, the logs and the exported spans agree.

func TrackBlobAccess added in v0.7.0

func TrackBlobAccess(next http.Handler) http.Handler

TrackBlobAccess marks client downloads (GET and HEAD of repository content: the /repos/ format routes and the /v2/ registry) so that the tiered blob store records the blobs they read as accessed. Reads by background workers and admin endpoints carry no mark and never count as a download, which keeps "not downloaded for N days" policies and promote-on-read honest.

func WithGroupDeploy added in v0.26.0

func WithGroupDeploy(ctx context.Context, group, target string) context.Context

WithGroupDeploy returns ctx recording that a write to group was authorized as a write to target, its deploy target. The dispatcher serves the write from exactly that repository, so what RBAC authorized is what is written.

func WithPrincipal

func WithPrincipal(ctx context.Context, p *auth.Principal) context.Context

Types

type AuthAuditMiddlewareStore added in v0.15.0

type AuthAuditMiddlewareStore interface {
	// contains filtered or unexported methods
}

AuthAuditMiddlewareStore is the part of the database AuthAuditMiddleware needs.

type MCPBearerVerifier added in v0.8.0

type MCPBearerVerifier func(ctx context.Context, token string) (*models.User, error)

MCPBearerVerifier maps a bearer credential that is not an API token (an OIDC access token) to the local user it identifies. It returns auth.ErrAccessTokenNotAccepted (or any error) for credentials it does not accept.

type RBACConfig

type RBACConfig struct {
	LegacyAPIKey        string
	LegacyAPIKeyEnabled bool
	AllowAnonymousRead  bool
	// MCPPath is the mount path for the MCP HTTP endpoint (e.g. "/mcp").
	// It lives outside /api/, /v2/, and /repos/ but must never fall through
	// the SPA/static bypass below — MCP tools require auth like the REST API.
	MCPPath string
	// QuayAPIPath is the mount path of the Quay-compatible API facade
	// (internal/quayapi), "" while it is disabled. Like the MCP path it is
	// outside /api/, /v2/ and /repos/ yet must never fall through the static
	// bypass; every request to it needs the global manage permission.
	QuayAPIPath string
	// SPAHandler serves the web UI. Browser navigations to Vue-router page
	// shapes under /repos/ (which collide with format-handler routes such as
	// the npm packument GET /repos/{name}/{pkg}) are answered by it directly,
	// never by the format handler and never without going through RBAC for
	// any non-navigation request. When nil, those paths get full RBAC
	// evaluation like every other /repos/ path.
	SPAHandler http.Handler
	// ClientBaseURL is BASE_URL as an explicit override of the origin handed to
	// package clients, "" when it was not set. Cargo's WWW-Authenticate login_url
	// is built on it, else on the request's origin (see internal/publicurl); the
	// MCP challenge's resource_metadata points at it and is omitted when empty.
	ClientBaseURL string
	// MCPBearerVerifier accepts OIDC access tokens on the MCP endpoint in
	// addition to API tokens; nil accepts API tokens only.
	MCPBearerVerifier MCPBearerVerifier
	// ProjectSettings decides whether non-admin users may create projects
	// (POST /api/v1/projects); nil means only global admins may.
	ProjectSettings *auth.ProjectSettings
}

type RBACMiddlewareStore added in v0.15.0

type RBACMiddlewareStore interface {
	// contains filtered or unexported methods
}

RBACMiddlewareStore is the part of the database RBACMiddleware needs.

type TrustedProxies

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

TrustedProxies holds the parsed CIDR blocks of reverse proxies allowed to set X-Forwarded-For / X-Real-IP. Build one with NewTrustedProxies at startup and share it across IPAllowlistMiddleware, RateLimitMiddleware, and any other code that needs the caller's real IP (e.g. login rate limiting).

func NewTrustedProxies

func NewTrustedProxies(cidrs []string) *TrustedProxies

NewTrustedProxies parses cidrs into a TrustedProxies set. Invalid or blank entries are skipped. A nil/empty result still behaves correctly: no proxy is trusted, so ClientIP always falls back to the TCP peer address.

func (*TrustedProxies) Configured added in v0.2.0

func (t *TrustedProxies) Configured() bool

Configured reports whether at least one trusted proxy network is set. When it is false ClientIP always returns the TCP peer address.

func (*TrustedProxies) TrustsPeer added in v0.15.0

func (t *TrustedProxies) TrustsPeer(r *http.Request) bool

TrustsPeer reports whether the request's immediate TCP peer is a configured trusted proxy, i.e. whether its X-Forwarded-* headers may be believed.

type UploadAuditPublisher added in v0.16.0

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

UploadAuditPublisher is a webhook.Publisher that forwards every event to the wrapped publisher and records each artifact upload as an artifact.uploaded audit event against its repository, naming the package and version and the authenticated caller. Every format handler announces a committed upload through the publisher, so this is the one place that sees them all; the generic request row of AuditMiddleware knows neither the repository nor the package, and also exists for uploads that failed.

func NewUploadAuditPublisher added in v0.16.0

func NewUploadAuditPublisher(next webhook.Publisher) *UploadAuditPublisher

NewUploadAuditPublisher wraps next (which may be nil).

func (*UploadAuditPublisher) Dispatch added in v0.16.0

func (u *UploadAuditPublisher) Dispatch(ctx context.Context, repoID, eventType string, payload map[string]any)

Dispatch implements webhook.Publisher.

Jump to

Keyboard shortcuts

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