middleware

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ContextKeyUser stores the authenticated user in request context
	ContextKeyUser contextKey = "user"

	// ContextKeyAuthType stores the authentication method used (session or api_token)
	ContextKeyAuthType contextKey = "auth_type"

	// ContextKeyTokenID stores the API token ID if token auth was used
	ContextKeyTokenID contextKey = "api_token_id"

	// ContextKeyTokenScopes stores the API token scopes if token auth was used
	ContextKeyTokenScopes contextKey = "api_token_scopes"

	// ContextKeyTokenExpiresAt stores the API token expiration time if token auth was used
	ContextKeyTokenExpiresAt contextKey = "api_token_expires_at"
)
View Source
const (
	AuthTypeSession  = "session"
	AuthTypeAPIToken = "api_token"
)

Authentication type constants

View Source
const (
	// TokenExpiringSoonThreshold is the duration before expiration to warn clients (7 days)
	TokenExpiringSoonThreshold = 7 * 24 * time.Hour

	// HeaderTokenExpiresAt is the header name for token expiration timestamp
	HeaderTokenExpiresAt = "X-Token-Expires-At"

	// HeaderTokenExpiresSoon is the header name indicating token expires soon
	HeaderTokenExpiresSoon = "X-Token-Expires-Soon"
)

Token expiration warning constants

Variables

This section is empty.

Functions

func APITokenAuditLog added in v1.5.0

func APITokenAuditLog(repos *repository.Repositories) func(http.Handler) http.Handler

APITokenAuditLog middleware logs API token usage after the request completes. It should be applied to routes that support API token authentication. This middleware captures the HTTP response status code and logs it along with the request details for audit purposes.

func APITokensEnabled added in v1.5.0

func APITokensEnabled(cfg *config.Config) func(http.Handler) http.Handler

APITokensEnabled creates a middleware that requires API tokens feature to be enabled.

func AdminAuth

func AdminAuth(repos *repository.Repositories) func(http.Handler) http.Handler

AdminAuth middleware checks for valid admin session

func BackupsEnabled added in v1.5.0

func BackupsEnabled(cfg *config.Config) func(http.Handler) http.Handler

BackupsEnabled creates a middleware that requires backups feature to be enabled.

func CSRFProtection

func CSRFProtection(repos *repository.Repositories) func(http.Handler) http.Handler

CSRFProtection middleware validates CSRF tokens for state-changing requests

func CreateLoginRateLimiter added in v1.5.0

func CreateLoginRateLimiter(repo repository.RateLimitRepository, useDBRateLimiting bool, limitType string, maxAttempts int, windowMinutes int, config ConfigProvider) func(http.Handler) http.Handler

CreateLoginRateLimiter returns the appropriate login rate limiter middleware. If repo is non-nil and useDBRateLimiting is true, uses database-backed rate limiting. Otherwise, falls back to in-memory rate limiting.

Parameters: - repo: RateLimitRepository for database-backed limiting (can be nil) - useDBRateLimiting: whether to use database-backed rate limiting - limitType: "admin_login" or "user_login" - maxAttempts: maximum login attempts allowed - windowMinutes: rate limit window duration - config: configuration provider for proxy settings

func DBRateLimitLoginMiddleware added in v1.5.0

func DBRateLimitLoginMiddleware(repo repository.RateLimitRepository, limitType string, maxAttempts int, windowMinutes int, config ConfigProvider) func(http.Handler) http.Handler

DBRateLimitLoginMiddleware creates a rate limit middleware for login endpoints using database storage. It tracks login attempts by IP address with configurable limits. SECURITY: Uses atomic increment-before-request to prevent TOCTOU race conditions. SECURITY: Fails closed for security-critical operations to prevent brute force during DB issues.

func DBRateLimitMiddleware added in v1.5.0

func DBRateLimitMiddleware(rl *DBRateLimiter) func(http.Handler) http.Handler

DBRateLimitMiddleware creates a middleware that enforces rate limits using database storage.

func FeatureFlagRequired added in v1.5.0

func FeatureFlagRequired(checker FeatureFlagChecker, featureName string) func(http.Handler) http.Handler

FeatureFlagRequired creates a middleware that requires a specific feature to be enabled. Usage:

FeatureFlagRequired(cfg.Features.IsWebhooksEnabled, "webhooks")(handler)

func GetAuthTypeFromContext

func GetAuthTypeFromContext(r *http.Request) string

GetAuthTypeFromContext retrieves the authentication type from request context Returns empty string if not set

func GetTokenExpiresAtFromContext added in v1.5.0

func GetTokenExpiresAtFromContext(r *http.Request) *time.Time

GetTokenExpiresAtFromContext retrieves the API token expiration time from request context Returns nil if not using token auth or token doesn't expire

func GetTokenIDFromContext added in v1.5.0

func GetTokenIDFromContext(r *http.Request) int64

GetTokenIDFromContext retrieves the API token ID from the request context. Returns 0 if no token ID is set (e.g., session auth or unauthenticated).

func GetTokenScopesFromContext

func GetTokenScopesFromContext(r *http.Request) string

GetTokenScopesFromContext retrieves the API token scopes from request context Returns empty string if not using token auth

func GetUserFromContext

func GetUserFromContext(r *http.Request) *models.User

GetUserFromContext retrieves the authenticated user from request context Returns nil if no user is authenticated

func IPBlockCheck

func IPBlockCheck(repos *repository.Repositories, cfg ProxyConfigProvider) func(http.Handler) http.Handler

IPBlockCheck middleware checks if the client IP is blocked

func LoggingMiddleware

func LoggingMiddleware(next http.Handler) http.Handler

LoggingMiddleware logs HTTP requests with method, path, status, duration, and IP

func MFAEnabled added in v1.5.0

func MFAEnabled(cfg *config.Config) func(http.Handler) http.Handler

MFAEnabled creates a middleware that requires MFA feature to be enabled.

func MalwareScanEnabled added in v1.5.0

func MalwareScanEnabled(cfg *config.Config) func(http.Handler) http.Handler

MalwareScanEnabled creates a middleware that requires malware scan feature to be enabled.

func OptionalUserAuth

func OptionalUserAuth(repos *repository.Repositories) func(http.Handler) http.Handler

OptionalUserAuth middleware checks for a user session or API token but doesn't require it If valid auth exists, it adds the user to the context If no auth or invalid auth, it continues without error

func RateLimitAdminLogin

func RateLimitAdminLogin() func(http.Handler) http.Handler

RateLimitAdminLogin rate limits admin login attempts

func RateLimitMiddleware

func RateLimitMiddleware(rl *RateLimiter) func(http.Handler) http.Handler

RateLimitMiddleware creates a middleware that enforces rate limits

func RateLimitTOTPVerify added in v1.5.0

func RateLimitTOTPVerify() func(http.Handler) http.Handler

RateLimitTOTPVerify rate limits TOTP verification attempts per user/IP Prevents brute-force attacks on 6-digit TOTP codes

func RateLimitUserLogin

func RateLimitUserLogin() func(http.Handler) http.Handler

RateLimitUserLogin rate limits user login attempts

func RecoveryMiddleware

func RecoveryMiddleware(next http.Handler) http.Handler

RecoveryMiddleware recovers from panics and returns a 500 error

func RequireScope

func RequireScope(requiredScope string) func(http.Handler) http.Handler

RequireScope middleware ensures the API token has the required scope Must be used AFTER UserAuth middleware Session auth bypasses scope checks (has full access)

func SSOEnabled added in v1.5.0

func SSOEnabled(cfg *config.Config) func(http.Handler) http.Handler

SSOEnabled creates a middleware that requires SSO feature to be enabled.

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware(next http.Handler) http.Handler

SecurityHeadersMiddleware adds security-related HTTP headers to all responses These headers protect against: - Clickjacking (X-Frame-Options) - MIME sniffing attacks (X-Content-Type-Options) - Cross-site scripting (Content-Security-Policy, X-XSS-Protection) - Information leakage (X-Content-Type-Options)

func SetCSRFCookie

func SetCSRFCookie(w http.ResponseWriter, cfg *config.Config) (string, error)

SetCSRFCookie sets a CSRF token cookie for admin pages

func SetUserCSRFCookie added in v1.5.0

func SetUserCSRFCookie(w http.ResponseWriter, cfg *config.Config) (string, error)

SetUserCSRFCookie sets a CSRF token cookie for user pages (site-wide scope)

func UserAuth

func UserAuth(repos *repository.Repositories) func(http.Handler) http.Handler

UserAuth middleware checks for valid user session OR API token It tries Bearer token first, then falls back to session cookie

func UserCSRFProtection added in v1.5.0

func UserCSRFProtection(repos *repository.Repositories) func(http.Handler) http.Handler

UserCSRFProtection middleware validates CSRF tokens for user routes (non-admin) This accepts any valid user session, not just admin sessions

func WebhooksEnabled added in v1.5.0

func WebhooksEnabled(cfg *config.Config) func(http.Handler) http.Handler

WebhooksEnabled creates a middleware that requires webhooks feature to be enabled.

Types

type ConfigProvider

type ConfigProvider interface {
	GetRateLimitUpload() int
	GetRateLimitDownload() int
	GetTrustProxyHeaders() string
	GetTrustedProxyIPs() string
}

ConfigProvider interface allows RateLimiter to read current rate limit values

type DBRateLimiter added in v1.5.0

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

DBRateLimiter manages rate limiting using database-backed storage. This enables rate limiting to work across multiple application instances.

func NewDBRateLimiter added in v1.5.0

func NewDBRateLimiter(config ConfigProvider, repo repository.RateLimitRepository) *DBRateLimiter

NewDBRateLimiter creates a new database-backed rate limiter.

func (*DBRateLimiter) Stop added in v1.5.0

func (rl *DBRateLimiter) Stop()

Stop stops the cleanup goroutine.

type FeatureFlagChecker added in v1.5.0

type FeatureFlagChecker func() bool

FeatureFlagCheck is a middleware factory that checks if a feature is enabled. If the feature is disabled, it returns a 403 Forbidden response. This allows enterprise features to be disabled at runtime.

type ProxyConfigProvider

type ProxyConfigProvider interface {
	GetTrustProxyHeaders() string
	GetTrustedProxyIPs() string
}

ProxyConfigProvider interface for getting proxy trust settings

type RateLimiter

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

RateLimiter manages rate limiting per IP address

func NewRateLimiter

func NewRateLimiter(config ConfigProvider) *RateLimiter

NewRateLimiter creates a new rate limiter with the given configuration provider

func (*RateLimiter) Stop

func (rl *RateLimiter) Stop()

Stop stops the cleanup goroutine

Jump to

Keyboard shortcuts

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