Documentation
¶
Overview ¶
Package middleware provides HTTP middleware for authentication and authorization.
Package middleware provides HTTP middleware for SystemForge session management.
Index ¶
- Constants
- func APIKeyMiddleware(config APIKeyMiddlewareConfig) func(http.Handler) http.Handler
- func ChiAuth(jwtService *jwt.Service) func(http.Handler) http.Handler
- func ChiAuthOptional(jwtService *jwt.Service) func(http.Handler) http.Handler
- func ChiRequireAnyPermission(permissions ...string) func(http.Handler) http.Handler
- func ChiRequireAnyRole(roles ...string) func(http.Handler) http.Handler
- func ChiRequireOrganization() func(http.Handler) http.Handler
- func ChiRequirePermission(permission string) func(http.Handler) http.Handler
- func ChiRequirePlatformAdmin() func(http.Handler) http.Handler
- func ChiRequireRole(role string) func(http.Handler) http.Handler
- func ClaimsFromContext(ctx context.Context) *jwt.Claims
- func ContextWithClaims(ctx context.Context, claims *jwt.Claims) context.Context
- func GetAPIKey(ctx context.Context) *apikey.APIKey
- func HTTPAuth(jwtService *jwt.Service) func(http.Handler) http.Handler
- func HTTPAuthForAudience(jwtService *jwt.Service, audiences ...string) func(http.Handler) http.Handler
- func HTTPAuthOptional(jwtService *jwt.Service) func(http.Handler) http.Handler
- func HTTPAuthOptionalWithObservability(jwtService *jwt.Service, obs *observability.Observability) func(http.Handler) http.Handler
- func HTTPAuthWithObservability(jwtService *jwt.Service, obs *observability.Observability) func(http.Handler) http.Handler
- func HasAllPermissions(ctx context.Context, permissions ...string) bool
- func HasAnyPermission(ctx context.Context, permissions ...string) bool
- func HasAnyRole(ctx context.Context, roles ...string) bool
- func HasPermission(ctx context.Context, permission string) bool
- func HasRole(ctx context.Context, role string) bool
- func IsPlatformAdminFromContext(ctx context.Context) bool
- func OptionalAPIKey(service *apikey.Service) func(http.Handler) http.Handler
- func OrganizationIDFromContext(ctx context.Context) *uuid.UUID
- func PermissionsFromContext(ctx context.Context) []string
- func PrincipalIDFromContext(ctx context.Context) uuid.UUID
- func PrincipalTypeFromContext(ctx context.Context) string
- func RequireAPIKey(service *apikey.Service) func(http.Handler) http.Handler
- func RequireAPIKeyWithScopes(service *apikey.Service, scopes ...string) func(http.Handler) http.Handler
- func RequireAnyPermission(permissions ...string) func(http.Handler) http.Handler
- func RequireAnyRole(roles ...string) func(http.Handler) http.Handler
- func RequireAnyScope(scopes ...string) func(http.Handler) http.Handler
- func RequireOrganization() func(http.Handler) http.Handler
- func RequirePermission(permission string) func(http.Handler) http.Handler
- func RequirePlatformAdmin() func(http.Handler) http.Handler
- func RequireRole(role string) func(http.Handler) http.Handler
- func RequireScope(scope string) func(http.Handler) http.Handler
- func RoleFromContext(ctx context.Context) string
- func UserIDFromContext(ctx context.Context) uuid.UUID
- type APIKeyMiddlewareConfig
- type ErrorResponse
- type Principal
Constants ¶
const ( // ContextKeyAPIKey is the context key for the validated API key. ContextKeyAPIKey contextKey = "api_key" // ContextKeyPrincipal is the context key for the authenticated principal. ContextKeyPrincipal contextKey = "principal" )
Variables ¶
This section is empty.
Functions ¶
func APIKeyMiddleware ¶
func APIKeyMiddleware(config APIKeyMiddlewareConfig) func(http.Handler) http.Handler
APIKeyMiddleware creates middleware that validates API keys.
func ChiAuth ¶
ChiAuth returns a Chi-compatible middleware that validates JWT tokens. This is an alias for HTTPAuth since Chi uses the standard http.Handler interface.
Usage with Chi:
r := chi.NewRouter()
r.Use(middleware.ChiAuth(jwtService))
r.Get("/api/protected", protectedHandler)
func ChiAuthOptional ¶
ChiAuthOptional returns a Chi-compatible middleware that validates JWT tokens if present. This is an alias for HTTPAuthOptional since Chi uses the standard http.Handler interface.
Usage with Chi:
r := chi.NewRouter()
r.Use(middleware.ChiAuthOptional(jwtService))
r.Get("/api/public", publicHandler)
func ChiRequireAnyPermission ¶
ChiRequireAnyPermission returns a Chi-compatible middleware that requires any of the specified permissions.
func ChiRequireAnyRole ¶
ChiRequireAnyRole returns a Chi-compatible middleware that requires any of the specified roles.
func ChiRequireOrganization ¶
ChiRequireOrganization returns a Chi-compatible middleware that requires organization context.
func ChiRequirePermission ¶
ChiRequirePermission returns a Chi-compatible middleware that requires a specific permission.
func ChiRequirePlatformAdmin ¶
ChiRequirePlatformAdmin returns a Chi-compatible middleware that requires platform admin status.
func ChiRequireRole ¶
ChiRequireRole returns a Chi-compatible middleware that requires a specific role.
Usage with Chi:
r.Group(func(r chi.Router) {
r.Use(middleware.ChiAuth(jwtService))
r.Use(middleware.ChiRequireRole("admin"))
r.Get("/api/admin", adminHandler)
})
func ClaimsFromContext ¶
ClaimsFromContext extracts JWT claims from the context. Returns nil if no claims are present.
func ContextWithClaims ¶
ContextWithClaims returns a new context with the JWT claims attached.
func HTTPAuth ¶
HTTPAuth returns a standard http.Handler middleware that validates JWT tokens. It extracts the token from the Authorization header (Bearer scheme) and attaches the claims to the request context. Only access tokens addressed to the service's Config.Audience are accepted.
func HTTPAuthForAudience ¶ added in v0.14.0
func HTTPAuthForAudience(jwtService *jwt.Service, audiences ...string) func(http.Handler) http.Handler
HTTPAuthForAudience is HTTPAuth for routes that serve one kind of client: it admits only access tokens addressed to one of the audiences (for example jwt.AudienceBFF on browser routes), so a token minted for another audience, such as a narrowly scoped API token, cannot be used as a full session. HTTPAuth accepts any token addressed to this application, whatever kind of client it was minted for.
func HTTPAuthOptional ¶
HTTPAuthOptional returns middleware that validates JWT tokens if present, but allows requests without tokens to proceed.
func HTTPAuthOptionalWithObservability ¶
func HTTPAuthOptionalWithObservability(jwtService *jwt.Service, obs *observability.Observability) func(http.Handler) http.Handler
HTTPAuthOptionalWithObservability returns optional JWT validation middleware with observability. If obs is nil, metrics are not recorded.
func HTTPAuthWithObservability ¶
func HTTPAuthWithObservability(jwtService *jwt.Service, obs *observability.Observability) func(http.Handler) http.Handler
HTTPAuthWithObservability returns JWT validation middleware with observability. If obs is nil, metrics are not recorded.
func HasAllPermissions ¶
HasAllPermissions checks if the user has all of the specified permissions.
func HasAnyPermission ¶
HasAnyPermission checks if the user has any of the specified permissions.
func HasAnyRole ¶
HasAnyRole checks if the user has any of the specified roles.
func HasPermission ¶
HasPermission checks if the user has a specific permission.
func IsPlatformAdminFromContext ¶
IsPlatformAdminFromContext checks if the user is a platform admin. Returns false if no claims are present.
func OptionalAPIKey ¶
OptionalAPIKey creates middleware that validates API keys if present but doesn't require them.
func OrganizationIDFromContext ¶
OrganizationIDFromContext extracts the organization ID from the context. Returns nil if no organization context is present.
func PermissionsFromContext ¶
PermissionsFromContext extracts the user's permissions from the context. Returns nil if no permissions are present.
func PrincipalIDFromContext ¶
PrincipalIDFromContext extracts the principal ID from the context. Returns uuid.Nil if no claims or principal ID is present.
func PrincipalTypeFromContext ¶
PrincipalTypeFromContext extracts the principal type from the context. Returns empty string if no claims are present.
func RequireAPIKey ¶
RequireAPIKey creates middleware that requires a valid API key. This is a convenience function with default configuration.
func RequireAPIKeyWithScopes ¶
func RequireAPIKeyWithScopes(service *apikey.Service, scopes ...string) func(http.Handler) http.Handler
RequireAPIKeyWithScopes creates middleware that requires specific scopes.
func RequireAnyPermission ¶
RequireAnyPermission returns middleware that requires any of the specified permissions. Must be used after HTTPAuth middleware.
func RequireAnyRole ¶
RequireAnyRole returns middleware that requires the user to have any of the specified roles. Must be used after HTTPAuth middleware.
func RequireAnyScope ¶
RequireAnyScope creates middleware that checks for any of the given scopes.
func RequireOrganization ¶
RequireOrganization returns middleware that requires an organization context. Must be used after HTTPAuth middleware.
func RequirePermission ¶
RequirePermission returns middleware that requires a specific permission. Must be used after HTTPAuth middleware.
func RequirePlatformAdmin ¶
RequirePlatformAdmin returns middleware that requires platform admin status. Must be used after HTTPAuth middleware.
func RequireRole ¶
RequireRole returns middleware that requires the user to have a specific role. Must be used after HTTPAuth middleware.
func RequireScope ¶
RequireScope creates middleware that checks for a specific scope. This should be used after APIKeyMiddleware.
func RoleFromContext ¶
RoleFromContext extracts the user's role from the context. Returns empty string if no role is present.
Types ¶
type APIKeyMiddlewareConfig ¶
type APIKeyMiddlewareConfig struct {
// Service is the API key service.
Service *apikey.Service
// RequiredScopes are scopes that must be present (all required).
RequiredScopes []string
// AnyScopes requires at least one of these scopes.
AnyScopes []string
// HeaderName is the header containing the API key.
// Default: "Authorization" with "Bearer" scheme.
HeaderName string
// AllowQueryParam enables API key in query parameter.
// Default: false (more secure).
AllowQueryParam bool
// QueryParamName is the query parameter name.
// Default: "api_key".
QueryParamName string
// RecordUsage updates the last used timestamp on each request.
// Default: true.
RecordUsage bool
// OnError is called when authentication fails.
// If nil, returns 401 Unauthorized.
OnError func(w http.ResponseWriter, r *http.Request, err error)
// OnSuccess is called after successful authentication.
OnSuccess func(r *http.Request, key *apikey.APIKey)
// IPExtractor extracts the client IP from the request.
// If nil, uses r.RemoteAddr.
IPExtractor func(r *http.Request) string
// Observability is the observability provider for metrics.
// If nil, no metrics are recorded.
Observability *observability.Observability
}
APIKeyMiddlewareConfig contains configuration for the API key middleware.
func DefaultAPIKeyMiddlewareConfig ¶
func DefaultAPIKeyMiddlewareConfig() APIKeyMiddlewareConfig
DefaultAPIKeyMiddlewareConfig returns default configuration.
type ErrorResponse ¶
ErrorResponse represents an error response body.
type Principal ¶
type Principal struct {
// Type is "user" or "api_key".
Type string `json:"type"`
// ID is the principal's unique identifier.
ID uuid.UUID `json:"id"`
// UserID is the user's ID (same as ID for users, owner ID for API keys).
UserID uuid.UUID `json:"user_id"`
// OrganizationID is the organization context (optional).
OrganizationID *uuid.UUID `json:"organization_id,omitempty"`
// Scopes are the permissions granted to this principal.
Scopes []string `json:"scopes,omitempty"`
// Environment is "live" or "test" for API keys.
Environment string `json:"environment,omitempty"`
// Metadata contains additional principal data.
Metadata map[string]string `json:"metadata,omitempty"`
}
Principal represents an authenticated entity (user or API key).
func GetPrincipal ¶
GetPrincipal retrieves the authenticated principal from the request context.