Documentation
¶
Overview ¶
Package security provides authentication context utilities and endpoint authorization profiles for SwayRider services.
Context Values ¶
After authentication middleware runs, various values are stored in the request context and can be retrieved using the Get* functions:
claims, ok := security.GetClaims(ctx) // JWT claims token, ok := security.GetJwt(ctx) // Raw JWT string ip, ok := security.GetOrigIp(ctx) // Client IP address host, ok := security.GetHost(ctx) // Request host
Endpoint Profiles ¶
Endpoint profiles define authorization requirements for API endpoints:
// Allow public access (no authentication required)
security.PublicEndpoint("/api/health")
// Require admin privileges
security.AdminEndpoint("/api/admin/users")
// Allow service-to-service calls with specific scopes
security.ServiceClientEndpoint("/api/internal/mail", []string{"mail:send"})
Index ¶
- Variables
- func AdminEndpoint(endpoint string, method ...string)
- func AllowExpiredJwtEndpoint(endpoint string, methos ...string)
- func DenyVerifiedEndpoint(endpoint string, methos ...string)
- func EndpointProfiles() map[string]EndpointProfile
- func GetClaims(ctx context.Context) (c *jwt.Claims, ok bool)
- func GetHost(ctx context.Context) (h string, ok bool)
- func GetJwt(ctx context.Context) (j string, ok bool)
- func GetOrigIp(ctx context.Context) (ip string, ok bool)
- func GetRefreshToken(ctx context.Context) (r string, ok bool)
- func GetSecure(ctx context.Context) (s bool, ok bool)
- func GetUserAgent(ctx context.Context) (ua string, ok bool)
- func PublicEndpoint(endpoint string, method ...string)
- func ServiceClientEndpoint(endpoint string, scopes []string, method ...string)
- func SetEndpointProfile(endpoint string, profile EndpointProfile, method ...string)
- func UnverifiedEndpoint(endpoint string, methos ...string)
- type ContextKey
- type EndpointProfile
- type PublicKeysFn
Constants ¶
This section is empty.
Variables ¶
var ( ErrMetaDataNotFound = errors.New("metadata not found") ErrNoAuthToken = errors.New("no authorization token") ErrInvalidAuthHeader = errors.New("invalid authorization header") ErrInvalidJwt = errors.New("invalid jwt") ErrUserNotAdmin = errors.New("user is not admin") ErrUserMissingRequiredAccount = errors.New("user is missing required account") ErrUserNotVerified = errors.New("user is not verified") ErrUserAlreadyVerified = errors.New("user is already verified") ErrNoKeys = errors.New("no public keys") ErrServiceClientNotAllowed = errors.New("service client not allowed") )
Authentication and authorization errors returned by endpoint profile evaluation.
Functions ¶
func AdminEndpoint ¶
AdminEndpoint marks an endpoint as requiring admin privileges.
func AllowExpiredJwtEndpoint ¶
AllowExpiredJwtEndpoint allows requests with expired JWT tokens. Use for token refresh endpoints where an expired token is expected.
func DenyVerifiedEndpoint ¶
DenyVerifiedEndpoint denies access to users who have already verified their email. Use for verification endpoints that should only be accessible to unverified users.
func EndpointProfiles ¶
func EndpointProfiles() map[string]EndpointProfile
EndpointProfiles returns all registered endpoint profiles.
func GetClaims ¶
GetClaims retrieves the parsed JWT claims from the context. Returns nil and false if no claims are present (unauthenticated request).
func GetRefreshToken ¶
GetRefreshToken retrieves the refresh token from the context (from cookies).
func GetUserAgent ¶
GetUserAgent retrieves the client's user agent string.
func PublicEndpoint ¶
PublicEndpoint marks an endpoint as publicly accessible (no authentication required). Use for registration, health checks, and other public APIs.
func ServiceClientEndpoint ¶
ServiceClientEndpoint allows service clients to call the endpoint
If no scopes are provided: "*" is added, allowing unscoped access
func SetEndpointProfile ¶
func SetEndpointProfile(endpoint string, profile EndpointProfile, method ...string)
SetEndpointProfile registers a complete endpoint profile. The method parameter allows setting profiles for specific HTTP methods.
func UnverifiedEndpoint ¶
UnverifiedEndpoint allows unverified users (email not verified) to access the endpoint. Use for endpoints that unverified users need, like profile management.
Types ¶
type ContextKey ¶
type ContextKey string
ContextKey is a string type used for context value keys to avoid collisions.
const ( ClaimsKey ContextKey = "claims" // JWT claims (*jwt.Claims) JwtKey ContextKey = "jwt" // Raw JWT token string RefreshKey ContextKey = "refresh" // Refresh token string OrigIpKey ContextKey = "originalIp" // Original client IP address UserAgentKey ContextKey = "userAgent" // Client user agent string HostKey ContextKey = "host" // Request host (domain) SecureKey ContextKey = "secure" // Whether request was over HTTPS )
Context keys for storing authentication and request metadata.
type EndpointProfile ¶
type EndpointProfile struct {
// Incase of a pure HTTP Endpoint, you can use this to put specific restrictions
// on the http method
// Leave empty to put the restriction on all variants
// You can register an empty one and then override a specific method as well
HttpMethod string
// AllowPublic allows unauthenticated users
// use to allow registration and some public available functionalities
AllowPublic bool
// AllowUnverified allows unverified users (email not yet verified)
// use to deny the actual functionality besides login and account management
AllowUnverified bool
// DenyVerified denies verified users (email already verified)
// use for only allowing verification of unverified users
DenyVerified bool
// Allow expired jwt's
// use this for example for refresh tokens, we require a jwt to be present,
// but we allow it to be expired as we are using the refresh token to Generate
// a new jwt
AllowExpiredJwt bool
// Requires the caller to be an admin user
RequiresAdmin bool
// List of account types that are allowed, if empty all are allowed
AllowedAccountTypes []string
// AllowService allows service claims to call the endpoint
AllowService bool
// AllowedScopes whitelists certain scopes to call the endpoint
// If no scopes are provided, no service clients are allowed
// If "*" is provided, all service clients are allowed
AllowedScopes []string
}
EndpointProfile definition
Default constructed object results in a restrcition set that requires a valid jwt token with standard authenticaiton behaviour. Any exceptions to the rule, e.g. unrestricted access, unverified access, etc needs tp be set via a custom restriction object on the endpont.
func GetEndpointProfile ¶
func GetEndpointProfile(endpoint string) EndpointProfile
GetEndpointProfile returns the profile for the given endpoint path. Returns a zero-value EndpointProfile if not found (requires auth by default).
func GetEndpointProfileForMethod ¶
func GetEndpointProfileForMethod(endpoint string, method string) EndpointProfile
GetEndpointProfileForMethod returns the profile for an endpoint with HTTP method specificity. It first checks for "METHOD /path" key, then falls back to "/path" key.
func (EndpointProfile) Evaluate ¶
func (p EndpointProfile) Evaluate( token *string, publicKeysFn PublicKeysFn, l *log.Logger, ) (claims *jwt.Claims, err error)
Evaluate validates a request against this endpoint's security profile. It verifies the JWT token and checks all authorization requirements.
Returns the parsed claims on success, or an error if authorization fails. For public endpoints with no token, returns (nil, nil).
type PublicKeysFn ¶
PublicKeysFn is a function that returns the public keys for JWT verification. Multiple keys support key rotation scenarios.