auth

package
v0.3.0 Latest Latest
Warning

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

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

Documentation

Overview

Package auth provides JWT authentication and authorization for CodeAI.

Index

Constants

This section is empty.

Variables

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

func ContextWithUser(ctx context.Context, user *User) context.Context

ContextWithUser returns a new context with the user attached.

func ExtractToken

func ExtractToken(r *http.Request) string

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

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

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 JWKS

type JWKS struct {
	Keys []JWK `json:"keys"`
}

JWKS represents a JSON Web Key Set.

type JWKSCache

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

JWKSCache caches RSA public keys fetched from a JWKS endpoint.

func NewJWKSCache

func NewJWKSCache(url string, refreshTTL time.Duration) *JWKSCache

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

func (c *JWKSCache) GetKey(ctx context.Context, kid string) (*rsa.PublicKey, error)

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

func (c *JWKSCache) GetKeyByID(kid string) (*rsa.PublicKey, bool)

GetKeyByID retrieves a public key by its key ID without triggering a refresh.

func (*JWKSCache) KeyCount

func (c *JWKSCache) KeyCount() int

KeyCount returns the number of keys currently in the cache.

func (*JWKSCache) LastRefresh

func (c *JWKSCache) LastRefresh() time.Time

LastRefresh returns the time of the last successful refresh.

func (*JWKSCache) Refresh

func (c *JWKSCache) Refresh(ctx context.Context) error

Refresh fetches the JWKS from the configured URL and updates the cache.

func (*JWKSCache) SetLogger

func (c *JWKSCache) SetLogger(logger *slog.Logger)

SetLogger sets a custom logger for the cache.

func (*JWKSCache) StartRefreshLoop

func (c *JWKSCache) StartRefreshLoop(ctx context.Context)

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

func (m *Middleware) RequireAnyRole(roles ...string) func(http.Handler) http.Handler

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

func (m *Middleware) RequirePermission(permission string) func(http.Handler) http.Handler

RequirePermission returns middleware that checks for a specific permission. Must be used after Authenticate middleware.

func (*Middleware) RequireRole

func (m *Middleware) RequireRole(role string) func(http.Handler) http.Handler

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

func UserFromContext(ctx context.Context) *User

UserFromContext retrieves the authenticated user from the request context. Returns nil if no user is present.

func (*User) HasPermission

func (u *User) HasPermission(permission string) bool

HasPermission checks if the user has the specified permission.

func (*User) HasRole

func (u *User) HasRole(role string) bool

HasRole checks if the user has the specified role.

type Validator

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

Validator validates JWTs and extracts user information.

func NewValidator

func NewValidator(config Config) (*Validator, error)

NewValidator creates a new JWT validator with the given configuration.

func NewValidatorWithLogger

func NewValidatorWithLogger(config Config, logger *slog.Logger) (*Validator, error)

NewValidatorWithLogger creates a new JWT validator with a custom logger.

func (*Validator) SetJWKSCache

func (v *Validator) SetJWKSCache(cache *JWKSCache)

SetJWKSCache sets a custom JWKS cache (useful for testing).

func (*Validator) StartJWKSRefresh

func (v *Validator) StartJWKSRefresh(ctx context.Context)

StartJWKSRefresh starts a background goroutine that periodically refreshes the JWKS.

func (*Validator) ValidateToken

func (v *Validator) ValidateToken(ctx context.Context, tokenStr string) (*User, error)

ValidateToken validates a JWT string and returns the extracted user.

Jump to

Keyboard shortcuts

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