security

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: AGPL-3.0 Imports: 6 Imported by: 0

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

Constants

This section is empty.

Variables

View Source
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

func AdminEndpoint(endpoint string, method ...string)

AdminEndpoint marks an endpoint as requiring admin privileges.

func AllowExpiredJwtEndpoint

func AllowExpiredJwtEndpoint(endpoint string, methos ...string)

AllowExpiredJwtEndpoint allows requests with expired JWT tokens. Use for token refresh endpoints where an expired token is expected.

func DenyVerifiedEndpoint

func DenyVerifiedEndpoint(endpoint string, methos ...string)

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

func GetClaims(ctx context.Context) (c *jwt.Claims, ok bool)

GetClaims retrieves the parsed JWT claims from the context. Returns nil and false if no claims are present (unauthenticated request).

func GetHost

func GetHost(ctx context.Context) (h string, ok bool)

GetHost retrieves the request host (domain without port).

func GetJwt

func GetJwt(ctx context.Context) (j string, ok bool)

GetJwt retrieves the raw JWT token string from the context.

func GetOrigIp

func GetOrigIp(ctx context.Context) (ip string, ok bool)

GetOrigIp retrieves the original client IP address (from X-Forwarded-For).

func GetRefreshToken

func GetRefreshToken(ctx context.Context) (r string, ok bool)

GetRefreshToken retrieves the refresh token from the context (from cookies).

func GetSecure

func GetSecure(ctx context.Context) (s bool, ok bool)

GetSecure returns whether the request was made over HTTPS.

func GetUserAgent

func GetUserAgent(ctx context.Context) (ua string, ok bool)

GetUserAgent retrieves the client's user agent string.

func PublicEndpoint

func PublicEndpoint(endpoint string, method ...string)

PublicEndpoint marks an endpoint as publicly accessible (no authentication required). Use for registration, health checks, and other public APIs.

func ServiceClientEndpoint

func ServiceClientEndpoint(endpoint string, scopes []string, method ...string)

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

func UnverifiedEndpoint(endpoint string, methos ...string)

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

type PublicKeysFn func() ([]string, error)

PublicKeysFn is a function that returns the public keys for JWT verification. Multiple keys support key rotation scenarios.

Jump to

Keyboard shortcuts

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