Documentation
¶
Overview ¶
Package auth provides JWT authentication and authorization for CodeAI.
Index ¶
- Variables
- func ContextWithUser(ctx context.Context, user *User) context.Context
- func ExtractToken(r *http.Request) string
- type AuthRequirement
- type Config
- type HTTPClient
- type JWK
- type JWKS
- type JWKSCache
- func (c *JWKSCache) GetKey(ctx context.Context, kid string) (*rsa.PublicKey, error)
- func (c *JWKSCache) GetKeyByID(kid string) (*rsa.PublicKey, bool)
- func (c *JWKSCache) KeyCount() int
- func (c *JWKSCache) LastRefresh() time.Time
- func (c *JWKSCache) Refresh(ctx context.Context) error
- func (c *JWKSCache) SetLogger(logger *slog.Logger)
- func (c *JWKSCache) StartRefreshLoop(ctx context.Context)
- type Middleware
- func (m *Middleware) Authenticate(requirement AuthRequirement) func(http.Handler) http.Handler
- func (m *Middleware) OptionalAuth() func(http.Handler) http.Handler
- func (m *Middleware) RequireAnyRole(roles ...string) func(http.Handler) http.Handler
- func (m *Middleware) RequireAuth() func(http.Handler) http.Handler
- func (m *Middleware) RequirePermission(permission string) func(http.Handler) http.Handler
- func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler
- type User
- type Validator
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidToken indicates the token is malformed or has an invalid signature. ErrInvalidToken = errors.New("invalid token") // ErrExpiredToken indicates the token has expired. ErrExpiredToken = errors.New("token has expired") // ErrInvalidIssuer indicates the token issuer doesn't match the expected value. ErrInvalidIssuer = errors.New("invalid token issuer") // ErrInvalidAudience indicates the token audience doesn't match the expected value. ErrInvalidAudience = errors.New("invalid token audience") // ErrMissingToken indicates no authentication token was provided. ErrMissingToken = errors.New("missing authentication token") // ErrKeyNotFound indicates the signing key was not found (for JWKS lookups). ErrKeyNotFound = errors.New("signing key not found") // ErrUnsupportedAlgorithm indicates the token uses an unsupported signing algorithm. ErrUnsupportedAlgorithm = errors.New("unsupported signing algorithm") // ErrNoSecretConfigured indicates HS256 was requested but no secret is configured. ErrNoSecretConfigured = errors.New("no secret configured for symmetric algorithm") // ErrNoPublicKeyConfigured indicates RS256 was requested but no public key is available. ErrNoPublicKeyConfigured = errors.New("no public key configured for asymmetric algorithm") // ErrJWKSFetchFailed indicates failure to fetch keys from the JWKS endpoint. ErrJWKSFetchFailed = errors.New("failed to fetch JWKS") // ErrJWKSDecodeFailed indicates failure to decode the JWKS response. ErrJWKSDecodeFailed = errors.New("failed to decode JWKS") )
Sentinel errors for JWT authentication.
Functions ¶
func ContextWithUser ¶
ContextWithUser returns a new context with the user attached.
func ExtractToken ¶
ExtractToken extracts the JWT from a request. It checks the Authorization header (Bearer token), query parameter, and cookie.
Types ¶
type AuthRequirement ¶
type AuthRequirement string
AuthRequirement specifies the authentication requirement for an endpoint.
const ( // AuthRequired requires a valid token; returns 401 if missing/invalid. AuthRequired AuthRequirement = "required" // AuthOptional accepts requests with or without a token; invalid tokens are ignored. AuthOptional AuthRequirement = "optional" // AuthPublic allows all requests without any token validation. AuthPublic AuthRequirement = "public" )
type Config ¶
type Config struct {
Issuer string // Expected issuer (iss claim)
Audience string // Expected audience (aud claim)
Secret string // Secret key for HS256/HS384/HS512
PublicKey string // PEM-encoded public key for RS256/RS384/RS512
JWKSURL string // URL to fetch JWKS from
RolesClaim string // Claim name containing roles (default: "roles")
PermsClaim string // Claim name containing permissions
}
Config holds JWT validation configuration.
type HTTPClient ¶
HTTPClient is an interface for HTTP operations (for testing).
type JWK ¶
type JWK struct {
Kid string `json:"kid"` // Key ID
Kty string `json:"kty"` // Key Type (RSA, EC, etc.)
Alg string `json:"alg"` // Algorithm
Use string `json:"use"` // Usage (sig, enc)
N string `json:"n"` // RSA modulus
E string `json:"e"` // RSA exponent
}
JWK represents a JSON Web Key.
type JWKSCache ¶
type JWKSCache struct {
// contains filtered or unexported fields
}
JWKSCache caches RSA public keys fetched from a JWKS endpoint.
func NewJWKSCache ¶
NewJWKSCache creates a new JWKS cache with the given URL and refresh interval.
func NewJWKSCacheWithClient ¶
func NewJWKSCacheWithClient(url string, refreshTTL time.Duration, client HTTPClient) *JWKSCache
NewJWKSCacheWithClient creates a new JWKS cache with a custom HTTP client.
func (*JWKSCache) GetKey ¶
GetKey retrieves a public key by its key ID. If the key is not in the cache, it attempts to refresh from the JWKS endpoint.
func (*JWKSCache) GetKeyByID ¶
GetKeyByID retrieves a public key by its key ID without triggering a refresh.
func (*JWKSCache) LastRefresh ¶
LastRefresh returns the time of the last successful refresh.
func (*JWKSCache) StartRefreshLoop ¶
StartRefreshLoop starts a background goroutine that periodically refreshes the cache. The loop runs until the context is canceled.
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware creates HTTP middleware that validates JWTs and attaches user info to the context.
func NewMiddleware ¶
func NewMiddleware(validator *Validator) *Middleware
NewMiddleware creates a new authentication middleware with the given validator.
func (*Middleware) Authenticate ¶
func (m *Middleware) Authenticate(requirement AuthRequirement) func(http.Handler) http.Handler
Authenticate returns middleware that enforces the specified authentication requirement.
func (*Middleware) OptionalAuth ¶
func (m *Middleware) OptionalAuth() func(http.Handler) http.Handler
OptionalAuth is a convenience method that creates middleware with optional authentication.
func (*Middleware) RequireAnyRole ¶
RequireAnyRole returns middleware that checks for any of the specified roles. Must be used after Authenticate middleware.
func (*Middleware) RequireAuth ¶
func (m *Middleware) RequireAuth() func(http.Handler) http.Handler
RequireAuth is a convenience method that creates middleware requiring authentication.
func (*Middleware) RequirePermission ¶
RequirePermission returns middleware that checks for a specific permission. Must be used after Authenticate middleware.
func (*Middleware) RequireRole ¶
RequireRole returns middleware that checks for a specific role. Must be used after Authenticate middleware.
type User ¶
type User struct {
ID string
Email string
Name string
Roles []string
Permissions []string
Claims map[string]any
Token string
ExpiresAt time.Time
}
User represents an authenticated user extracted from a JWT.
func UserFromContext ¶
UserFromContext retrieves the authenticated user from the request context. Returns nil if no user is present.
func (*User) HasPermission ¶
HasPermission checks if the user has the specified permission.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator validates JWTs and extracts user information.
func NewValidator ¶
NewValidator creates a new JWT validator with the given configuration.
func NewValidatorWithLogger ¶
NewValidatorWithLogger creates a new JWT validator with a custom logger.
func (*Validator) SetJWKSCache ¶
SetJWKSCache sets a custom JWKS cache (useful for testing).
func (*Validator) StartJWKSRefresh ¶
StartJWKSRefresh starts a background goroutine that periodically refreshes the JWKS.