middlewares

package
v0.0.0-...-8241180 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func HTTPSRedirectMiddleware

func HTTPSRedirectMiddleware(httpsPort uint16, canonicalHosts []string) func(http.Handler) http.Handler

HTTPSRedirectMiddleware sends plain HTTP traffic to HTTPS. canonicalHosts are the names the certificate covers: when the list holds at least one non-wildcard name, a request carrying any other Host is redirected to the first such name instead of to the name the client asked for. Wildcard entries (*.example.com) cannot form a valid Location target, so a list of only wildcards behaves like an empty one: the client's Host is kept.

Types

type AuthMiddleware

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

func NewAuthMiddleware

func NewAuthMiddleware(
	authService authService,
	userRepo repositories.UserRepository,
	tokenRepo repositories.PersonalAccessTokenRepository,
	revocation auth.TokenRevocation,
	tokenCache cache.Cache,
	responder base.Responder,
	auditLogger audit.Logger,
) *AuthMiddleware

func (*AuthMiddleware) Middleware

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

func (*AuthMiddleware) OptionalMiddleware

func (m *AuthMiddleware) OptionalMiddleware(next http.Handler) http.Handler

OptionalMiddleware allows requests to pass through even without authentication but still validates and adds user to context if token is present.

type CORSMiddleware

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

func NewCORSMiddleware

func NewCORSMiddleware(cfg *config.Config) *CORSMiddleware

func (*CORSMiddleware) Middleware

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

type IsAdminMiddleware

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

func NewIsAdminMiddleware

func NewIsAdminMiddleware(
	rbac base.RBAC,
	responder base.Responder,
	auditLogger audit.Logger,
) *IsAdminMiddleware

func (*IsAdminMiddleware) Middleware

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

type LoginRateLimitMiddleware

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

LoginRateLimitMiddleware throttles repeated failed authentication attempts against /api/auth/login, mitigating OWASP API2:2023 / API4:2023 and CWE-307.

The limiter increments two counters in the cache after every failed login: one keyed by client IP, one keyed by submitted login/email. Either counter crossing its limit causes future attempts to be rejected with 429 until the window elapses. Successful logins reset only the username counter; the IP counter continues to count attempts so a compromised IP can still be slowed.

func NewLoginRateLimitMiddleware

func NewLoginRateLimitMiddleware(
	c cache.Cache,
	responder base.Responder,
	opts ...LoginRateLimitOption,
) *LoginRateLimitMiddleware

func (*LoginRateLimitMiddleware) Middleware

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

type LoginRateLimitOption

type LoginRateLimitOption func(*LoginRateLimitMiddleware)

LoginRateLimitOption configures the middleware at construction time.

func WithLoginRateLimitAuditLogger

func WithLoginRateLimitAuditLogger(l audit.Logger) LoginRateLimitOption

WithLoginRateLimitAuditLogger wires the security audit logger so failed and rate-limit-blocked login attempts are recorded.

func WithLoginRateLimitClientIPHeader

func WithLoginRateLimitClientIPHeader(h string) LoginRateLimitOption

WithLoginRateLimitClientIPHeader picks an HTTP header to use as the trusted client IP (when running behind a reverse proxy that sets X-Real-IP or similar).

func WithLoginRateLimitKeyPrefix

func WithLoginRateLimitKeyPrefix(prefix string) LoginRateLimitOption

WithLoginRateLimitKeyPrefix overrides the cache key namespace. A route that reuses this limiter (the SSO ticket exchange) must pass its own prefix so its failures do not share counters with /api/auth/login — otherwise a customer retrying a stale magic link would lock themselves out of password login.

func WithLoginRateLimitPerIP

func WithLoginRateLimitPerIP(n int) LoginRateLimitOption

WithLoginRateLimitPerIP overrides the per-IP failure limit.

func WithLoginRateLimitPerUsername

func WithLoginRateLimitPerUsername(n int) LoginRateLimitOption

WithLoginRateLimitPerUsername overrides the per-username failure limit.

func WithLoginRateLimitWindow

func WithLoginRateLimitWindow(d time.Duration) LoginRateLimitOption

WithLoginRateLimitWindow overrides the sliding window duration.

type MFAEnrollmentScopeMiddleware

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

MFAEnrollmentScopeMiddleware enforces that a session established from an MFA-enrollment token — issued at login to an admin who crossed the MFA hard-fail threshold (see services/mfanudge) — is only honoured on endpoints that explicitly opted in: the 2FA setup/confirm/recovery routes, the profile read, logout and the public config. On any other endpoint such a session is rejected with 403, so a forced-enrollment user cannot reach the rest of the API until 2FA is enrolled.

It must run after the auth middleware (the session is read from context) and before the handler. A request without an enrollment-scoped session passes through untouched, so it is safe to wrap every route with it.

enforce mirrors AUTH_REQUIRE_MFA_FOR_ADMINS: with the feature disabled an enrollment-scoped token that is still in circulation (minted before the operator turned the flag off) is honoured as a full session — otherwise its bearer would stay locked out of the API with no enrollment modal to escape through.

func NewMFAEnrollmentScopeMiddleware

func NewMFAEnrollmentScopeMiddleware(
	responder base.Responder,
	auditLogger audit.Logger,
	enforce bool,
) *MFAEnrollmentScopeMiddleware

func (*MFAEnrollmentScopeMiddleware) Middleware

func (m *MFAEnrollmentScopeMiddleware) Middleware(next http.Handler, allowMFAEnrollment bool) http.Handler

type MetricsTokenMiddleware

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

MetricsTokenMiddleware guards the Prometheus scrape endpoint with a static bearer token (OWASP API2:2023 Broken Authentication: the endpoint is outside the session-based API, so it gets its own credential). A wrong or missing token answers 401 with no detail and is recorded in the audit log; the comparison is constant-time.

func NewMetricsTokenMiddleware

func NewMetricsTokenMiddleware(token string, auditLogger audit.Logger) *MetricsTokenMiddleware

func (*MetricsTokenMiddleware) Middleware

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

type PersonalAccessMiddleware

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

func NewPersonalAccessMiddleware

func NewPersonalAccessMiddleware(
	personalAccessTokenRepo repositories.PersonalAccessTokenRepository,
	responder base.Responder,
) *PersonalAccessMiddleware

func (*PersonalAccessMiddleware) Middleware

func (m *PersonalAccessMiddleware) Middleware(
	next http.Handler,
	abilities []domain.PATAbility,
) http.Handler

type RecoveryMiddleware

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

func NewRecoveryMiddleware

func NewRecoveryMiddleware(responder base.Responder) *RecoveryMiddleware

func (*RecoveryMiddleware) Middleware

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

type SecurityHeadersMiddleware

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

SecurityHeadersMiddleware emits the global HTTP response security headers (HSTS, X-Content-Type-Options, X-Frame-Options, Referrer-Policy and Content-Security-Policy). All header values are precomputed at construction so the per-request hot path is a fixed sequence of Header().Set() calls.

Headers are set before delegating to the next handler so that downstream handlers that explicitly set their own header (e.g. the file-manager stream path that emits "Content-Security-Policy: sandbox" for user file content) override the global value for their response.

func NewSecurityHeadersMiddleware

func NewSecurityHeadersMiddleware(cfg *config.Config, staticFS fs.FS) (*SecurityHeadersMiddleware, error)

NewSecurityHeadersMiddleware precomputes every header value. It returns an error (and never partially-builds the middleware) when CSP is enabled with a generated policy but the embedded static FS is missing one of the HTML files whose inline-script hash the policy depends on — a corrupt build should fail at startup, not at the first request that triggers a violation.

func (*SecurityHeadersMiddleware) Middleware

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

Middleware returns a handler that stamps the precomputed security headers on every response. When the master switch is off it returns next unchanged so disabled deployments pay zero per-request cost.

type ShortLivedScopeMiddleware

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

ShortLivedScopeMiddleware enforces that single-use short-lived tokens are only honoured on endpoints that explicitly opted in — the WebSocket upgrades and file downloads, the only places a token must travel in the URL. On any other endpoint a short-lived session is rejected with 403, shrinking the blast radius if such a token leaks via logs/history/proxies.

It must run after the auth middleware (the session is read from context) and before the handler. A request without a short-lived session passes through untouched, so it is safe to wrap every route with it.

func NewShortLivedScopeMiddleware

func NewShortLivedScopeMiddleware(
	responder base.Responder,
	auditLogger audit.Logger,
) *ShortLivedScopeMiddleware

func (*ShortLivedScopeMiddleware) Middleware

func (m *ShortLivedScopeMiddleware) Middleware(next http.Handler, allowShortLived bool) http.Handler

type TokenAdminGuardMiddleware

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

TokenAdminGuardMiddleware rejects personal-access-token (PAT) sessions on administrative routes that do not declare explicit PAT abilities.

Such routes never pass through PersonalAccessMiddleware, so without this guard a PAT would be gated only by the user's RBAC admin role (IsAdminMiddleware) — the token's declared ability scope is ignored entirely, letting a narrowly scoped PAT perform any admin action the owning user may. This guard fails closed: an admin action via PAT is only reachable on routes that explicitly check the token's abilities. Non-token (session) callers pass through untouched to the normal admin check.

func NewTokenAdminGuardMiddleware

func NewTokenAdminGuardMiddleware(responder base.Responder, auditLogger audit.Logger) *TokenAdminGuardMiddleware

func (*TokenAdminGuardMiddleware) Middleware

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

Jump to

Keyboard shortcuts

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