auth

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jul 28, 2025 License: AGPL-3.0 Imports: 12 Imported by: 0

Documentation

Overview

internal/auth/handlers.go

internal/auth/memory_store.go

internal/auth/middleware.go

internal/auth/oauth.go

internal/auth/resource_metadata.go

internal/auth/token_store.go

Index

Constants

View Source
const (
	ClientContextKey   contextKey = "oauth_client"
	TokenContextKey    contextKey = "oauth_token"
	UserContextKey     contextKey = "oauth_user"
	ScopeContextKey    contextKey = "oauth_scope"
	AuthTypeContextKey contextKey = "auth_type"
)
View Source
const (
	// Random string generation lengths
	AuthCodeLength          = 32
	AccessTokenLength       = 64
	RefreshTokenLength      = 64
	ClientIDLength          = 40
	ClientSecretLength      = 8
	StateLength             = 32
	NonceLength             = 32
	PKCECodeVerifierLength  = 64
	PKCECodeChallengeLength = 128

	// Auth timing constants
	AuthCodeLifetimeMinutes = 10
	DefaultCleanupInterval  = 5 // minutes

	// String split parameter
	AuthHeaderSplitParts = 2
)

Variables

This section is empty.

Functions

func GetAuthTypeFromContext

func GetAuthTypeFromContext(ctx context.Context) (string, bool)

GetAuthTypeFromContext extracts authentication type from request context

func GetScopeFromContext

func GetScopeFromContext(ctx context.Context) (string, bool)

GetScopeFromContext extracts scope from request context

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (string, bool)

GetUserFromContext extracts user ID from request context

func IsAPIKeyAuth

func IsAPIKeyAuth(ctx context.Context) bool

IsAPIKeyAuth checks if request was authenticated with API key

func IsOAuthAuth

func IsOAuthAuth(ctx context.Context) bool

IsOAuthAuth checks if request was authenticated with OAuth

Types

type APIKeyMiddleware

type APIKeyMiddleware struct {
	APIKey string
	Next   http.Handler
}

APIKeyMiddleware is middleware that checks for a valid API key

func NewAPIKeyMiddleware

func NewAPIKeyMiddleware(apiKey string, next http.Handler) *APIKeyMiddleware

NewAPIKeyMiddleware creates a new APIKeyMiddleware

func (*APIKeyMiddleware) ServeHTTP

func (m *APIKeyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface

type AccessToken

type AccessToken struct {
	Token     string                 `json:"access_token"`
	Type      string                 `json:"token_type"`
	ClientID  string                 `json:"client_id"`
	UserID    string                 `json:"user_id"`
	Scope     string                 `json:"scope"`
	ExpiresAt time.Time              `json:"expires_at"`
	CreatedAt time.Time              `json:"created_at"`
	Claims    map[string]interface{} `json:"claims,omitempty"`
	Revoked   bool                   `json:"revoked"`
}

AccessToken represents an access token

func GetTokenFromContext

func GetTokenFromContext(ctx context.Context) (*AccessToken, bool)

GetTokenFromContext extracts access token from request context

func (*AccessToken) IsExpired

func (t *AccessToken) IsExpired() bool

IsExpired checks if the access token is expired

type AuthenticationMiddleware

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

AuthenticationMiddleware validates OAuth tokens and API keys

func NewAuthenticationMiddleware

func NewAuthenticationMiddleware(server *AuthorizationServer) *AuthenticationMiddleware

NewAuthenticationMiddleware creates a new authentication middleware

func (*AuthenticationMiddleware) FlexibleAuthentication

func (m *AuthenticationMiddleware) FlexibleAuthentication(preferOAuth bool) func(http.Handler) http.Handler

FlexibleAuthentication middleware that accepts either OAuth or API key with preference

func (*AuthenticationMiddleware) OptionalAuthentication

func (m *AuthenticationMiddleware) OptionalAuthentication(next http.Handler) http.Handler

OptionalAuthentication middleware that optionally validates OAuth token or API key

func (*AuthenticationMiddleware) RequireAPIKey

func (m *AuthenticationMiddleware) RequireAPIKey(next http.Handler) http.Handler

RequireAPIKey middleware that only accepts API key authentication (legacy)

func (*AuthenticationMiddleware) RequireAuthentication

func (m *AuthenticationMiddleware) RequireAuthentication(next http.Handler) http.Handler

RequireAuthentication middleware that requires valid OAuth token or API key

func (*AuthenticationMiddleware) RequireScope

func (m *AuthenticationMiddleware) RequireScope(requiredScope string) func(http.Handler) http.Handler

RequireScope middleware that requires specific OAuth scope

func (*AuthenticationMiddleware) SetAPIKey

func (m *AuthenticationMiddleware) SetAPIKey(apiKey string)

SetAPIKey sets the API key for fallback authentication

type AuthorizationCode

type AuthorizationCode struct {
	Code            string                 `json:"code"`
	ClientID        string                 `json:"client_id"`
	UserID          string                 `json:"user_id"`
	RedirectURI     string                 `json:"redirect_uri"`
	Scope           string                 `json:"scope"`
	ExpiresAt       time.Time              `json:"expires_at"`
	CreatedAt       time.Time              `json:"created_at"`
	Challenge       string                 `json:"code_challenge,omitempty"`
	ChallengeMethod string                 `json:"code_challenge_method,omitempty"`
	State           string                 `json:"state,omitempty"`
	Nonce           string                 `json:"nonce,omitempty"`
	Claims          map[string]interface{} `json:"claims,omitempty"`
	Used            bool                   `json:"used"`
}

AuthorizationCode represents an authorization code

func (*AuthorizationCode) IsExpired

func (c *AuthorizationCode) IsExpired() bool

IsExpired checks if the authorization code is expired

type AuthorizationRequest

type AuthorizationRequest struct {
	ResponseType        string
	ClientID            string
	RedirectURI         string
	Scope               string
	State               string
	CodeChallenge       string
	CodeChallengeMethod string
	Nonce               string
}

AuthorizationRequest represents an authorization request

type AuthorizationServer

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

AuthorizationServer implements OAuth 2.1 authorization server

func NewAuthorizationServer

func NewAuthorizationServer(config *AuthorizationServerConfig, logger *logging.Logger) *AuthorizationServer

NewAuthorizationServer creates a new OAuth 2.1 authorization server

func (*AuthorizationServer) CleanupExpiredTokens

func (s *AuthorizationServer) CleanupExpiredTokens()

CleanupExpiredTokens removes expired tokens (can be called periodically)

func (*AuthorizationServer) GetAllAccessTokens

func (s *AuthorizationServer) GetAllAccessTokens() []TokenInfo

func (*AuthorizationServer) GetAllClients

func (s *AuthorizationServer) GetAllClients() []*OAuthClient

GetAllClients returns all registered clients

func (*AuthorizationServer) GetClient

func (s *AuthorizationServer) GetClient(clientID string) (*OAuthClient, bool)

GetClient retrieves a client by ID

func (*AuthorizationServer) GetMetadata

GetMetadata returns OAuth 2.0 Authorization Server Metadata

func (*AuthorizationServer) GetTokenCount

func (s *AuthorizationServer) GetTokenCount() (int, int, int)

GetTokenCount returns the number of active tokens (for monitoring)

func (*AuthorizationServer) HandleAuthorize

func (s *AuthorizationServer) HandleAuthorize(w http.ResponseWriter, r *http.Request)

func (*AuthorizationServer) HandleDiscovery

func (s *AuthorizationServer) HandleDiscovery(w http.ResponseWriter, r *http.Request)

HandleDiscovery handles requests to /.well-known/oauth-authorization-server

func (*AuthorizationServer) HandleRegister

func (s *AuthorizationServer) HandleRegister(w http.ResponseWriter, r *http.Request)

HandleRegister handles dynamic client registration

func (*AuthorizationServer) HandleRevoke

func (s *AuthorizationServer) HandleRevoke(w http.ResponseWriter, r *http.Request)

HandleRevoke handles token revocation requests

func (*AuthorizationServer) HandleToken

func (s *AuthorizationServer) HandleToken(w http.ResponseWriter, r *http.Request)

HandleToken handles token requests

func (*AuthorizationServer) HandleUserInfo

func (s *AuthorizationServer) HandleUserInfo(w http.ResponseWriter, r *http.Request)

HandleUserInfo handles userinfo requests

func (*AuthorizationServer) HasScope

func (s *AuthorizationServer) HasScope(tokenScope, requiredScope string) bool

HasScope checks if a token scope includes the required scope

func (*AuthorizationServer) RegisterClient

func (s *AuthorizationServer) RegisterClient(config *OAuthConfig) (*OAuthClient, error)

RegisterClient registers a new OAuth client

func (*AuthorizationServer) ValidateAccessToken

func (s *AuthorizationServer) ValidateAccessToken(token string) (*AccessToken, error)

ValidateAccessToken validates an access token and returns it if valid

func (*AuthorizationServer) ValidateClient

func (s *AuthorizationServer) ValidateClient(clientID, clientSecret string) (*OAuthClient, error)

ValidateClient validates client credentials

type AuthorizationServerConfig

type AuthorizationServerConfig struct {
	Issuer                                 string   `json:"issuer" yaml:"issuer"`
	AuthorizationEndpoint                  string   `json:"authorization_endpoint" yaml:"authorization_endpoint"`
	TokenEndpoint                          string   `json:"token_endpoint" yaml:"token_endpoint"`
	UserinfoEndpoint                       string   `json:"userinfo_endpoint" yaml:"userinfo_endpoint"`     // Add this
	RevocationEndpoint                     string   `json:"revocation_endpoint" yaml:"revocation_endpoint"` // Add this
	JWKSUri                                string   `json:"jwks_uri,omitempty" yaml:"jwks_uri,omitempty"`
	RegistrationEndpoint                   string   `json:"registration_endpoint,omitempty" yaml:"registration_endpoint,omitempty"`
	ScopesSupported                        []string `json:"scopes_supported,omitempty" yaml:"scopes_supported,omitempty"`
	ResponseTypesSupported                 []string `json:"response_types_supported" yaml:"response_types_supported"`
	ResponseModesSupported                 []string `json:"response_modes_supported,omitempty" yaml:"response_modes_supported,omitempty"`
	GrantTypesSupported                    []string `json:"grant_types_supported" yaml:"grant_types_supported"`
	TokenEndpointAuthMethodsSupported      []string `json:"token_endpoint_auth_methods_supported" yaml:"token_endpoint_auth_methods_supported"`
	RevocationEndpointAuthMethodsSupported []string `json:"revocation_endpoint_auth_methods_supported,omitempty" yaml:"revocation_endpoint_auth_methods_supported,omitempty"` // Add this
	CodeChallengeMethodsSupported          []string `json:"code_challenge_methods_supported" yaml:"code_challenge_methods_supported"`
	ServiceDocumentation                   string   `json:"service_documentation,omitempty" yaml:"service_documentation,omitempty"`
	UILocalesSupported                     []string `json:"ui_locales_supported,omitempty" yaml:"ui_locales_supported,omitempty"`
	OpPolicyURI                            string   `json:"op_policy_uri,omitempty" yaml:"op_policy_uri,omitempty"`
	OpTosURI                               string   `json:"op_tos_uri,omitempty" yaml:"op_tos_uri,omitempty"`
	DeviceAuthorizationEndpoint            string   `json:"device_authorization_endpoint,omitempty" yaml:"device_authorization_endpoint,omitempty"`
}

AuthorizationServerConfig contains server configuration

type CodeVerifier

type CodeVerifier interface {
	VerifyCodeChallenge(verifier, challenge, method string) bool
	GenerateCodeVerifier() (string, error)
	GenerateCodeChallenge(verifier, method string) (string, error)
}

CodeVerifier interface for PKCE

type DefaultCodeVerifier

type DefaultCodeVerifier struct{}

DefaultCodeVerifier implements CodeVerifier

func (*DefaultCodeVerifier) GenerateCodeChallenge

func (v *DefaultCodeVerifier) GenerateCodeChallenge(verifier, method string) (string, error)

GenerateCodeChallenge generates a PKCE code challenge

func (*DefaultCodeVerifier) GenerateCodeVerifier

func (v *DefaultCodeVerifier) GenerateCodeVerifier() (string, error)

GenerateCodeVerifier generates a PKCE code verifier

func (*DefaultCodeVerifier) VerifyCodeChallenge

func (v *DefaultCodeVerifier) VerifyCodeChallenge(verifier, challenge, method string) bool

VerifyCodeChallenge verifies a PKCE code challenge

type DefaultTokenGenerator

type DefaultTokenGenerator struct{}

DefaultTokenGenerator implements TokenGenerator

func (*DefaultTokenGenerator) GenerateAccessToken

func (g *DefaultTokenGenerator) GenerateAccessToken() (string, error)

GenerateAccessToken generates an access token

func (*DefaultTokenGenerator) GenerateAuthorizationCode

func (g *DefaultTokenGenerator) GenerateAuthorizationCode() (string, error)

GenerateAuthorizationCode generates an authorization code

func (*DefaultTokenGenerator) GenerateClientID

func (g *DefaultTokenGenerator) GenerateClientID() (string, error)

GenerateClientID generates a client ID

func (*DefaultTokenGenerator) GenerateClientSecret

func (g *DefaultTokenGenerator) GenerateClientSecret() (string, error)

GenerateClientSecret generates a client secret

func (*DefaultTokenGenerator) GenerateDeviceCode

func (g *DefaultTokenGenerator) GenerateDeviceCode() (string, error)

GenerateDeviceCode generates a device code

func (*DefaultTokenGenerator) GenerateRefreshToken

func (g *DefaultTokenGenerator) GenerateRefreshToken() (string, error)

GenerateRefreshToken generates a refresh token

func (*DefaultTokenGenerator) GenerateState

func (g *DefaultTokenGenerator) GenerateState() (string, error)

GenerateState generates a state parameter

func (*DefaultTokenGenerator) GenerateUserCode

func (g *DefaultTokenGenerator) GenerateUserCode() (string, error)

GenerateUserCode generates a user code

type DeviceCode

type DeviceCode struct {
	DeviceCode      string    `json:"device_code"`
	UserCode        string    `json:"user_code"`
	VerificationURI string    `json:"verification_uri"`
	ExpiresAt       time.Time `json:"expires_at"`
	Interval        int       `json:"interval"`
	ClientID        string    `json:"client_id"`
	Scope           string    `json:"scope"`
	UserID          string    `json:"user_id,omitempty"`
	Authorized      bool      `json:"authorized"`
}

DeviceCode represents a device authorization code

type MemoryTokenStore

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

func NewMemoryTokenStore

func NewMemoryTokenStore() *MemoryTokenStore

func (*MemoryTokenStore) CleanupExpiredTokens

func (ts *MemoryTokenStore) CleanupExpiredTokens()

func (*MemoryTokenStore) Close

func (ts *MemoryTokenStore) Close()

func (*MemoryTokenStore) GetAccessToken

func (ts *MemoryTokenStore) GetAccessToken(token string) (*AccessToken, error)

func (*MemoryTokenStore) GetStats

func (ts *MemoryTokenStore) GetStats() (int, int, int)

func (*MemoryTokenStore) RevokeAccessToken

func (ts *MemoryTokenStore) RevokeAccessToken(token string) error

func (*MemoryTokenStore) StoreAccessToken

func (ts *MemoryTokenStore) StoreAccessToken(token *AccessToken) error

type OAuthClient

type OAuthClient struct {
	ID                      string    `json:"client_id"`
	Secret                  string    `json:"client_secret,omitempty"`
	RedirectURIs            []string  `json:"redirect_uris"`
	GrantTypes              []string  `json:"grant_types"`
	ResponseTypes           []string  `json:"response_types"`
	Scope                   string    `json:"scope,omitempty"`
	ClientName              string    `json:"client_name,omitempty"`
	ClientURI               string    `json:"client_uri,omitempty"`
	LogoURI                 string    `json:"logo_uri,omitempty"`
	TosURI                  string    `json:"tos_uri,omitempty"`
	PolicyURI               string    `json:"policy_uri,omitempty"`
	TokenEndpointAuthMethod string    `json:"token_endpoint_auth_method"`
	CreatedAt               time.Time `json:"client_id_issued_at"`
	ExpiresAt               time.Time `json:"client_secret_expires_at,omitempty"`
	SoftwareID              string    `json:"software_id,omitempty"`
	SoftwareVersion         string    `json:"software_version,omitempty"`
	CodeChallengeMethod     string    `json:"code_challenge_method,omitempty"`
	Public                  bool      `json:"public"`
}

OAuthClient represents a registered OAuth client

func GetClientFromContext

func GetClientFromContext(ctx context.Context) (*OAuthClient, bool)

GetClientFromContext extracts OAuth client from request context

type OAuthConfig

type OAuthConfig struct {
	ClientID            string   `json:"client_id" yaml:"client_id"`
	ClientSecret        string   `json:"client_secret,omitempty" yaml:"client_secret,omitempty"`
	RedirectURIs        []string `json:"redirect_uris" yaml:"redirect_uris"`
	GrantTypes          []string `json:"grant_types" yaml:"grant_types"`
	ResponseTypes       []string `json:"response_types" yaml:"response_types"`
	Scope               string   `json:"scope,omitempty" yaml:"scope,omitempty"`
	TokenEndpointAuth   string   `json:"token_endpoint_auth_method" yaml:"token_endpoint_auth_method"`
	ClientName          string   `json:"client_name,omitempty" yaml:"client_name,omitempty"`
	ClientURI           string   `json:"client_uri,omitempty" yaml:"client_uri,omitempty"`
	LogoURI             string   `json:"logo_uri,omitempty" yaml:"logo_uri,omitempty"`
	TosURI              string   `json:"tos_uri,omitempty" yaml:"tos_uri,omitempty"`
	PolicyURI           string   `json:"policy_uri,omitempty" yaml:"policy_uri,omitempty"`
	SoftwareID          string   `json:"software_id,omitempty" yaml:"software_id,omitempty"`
	SoftwareVersion     string   `json:"software_version,omitempty" yaml:"software_version,omitempty"`
	CodeChallengeMethod string   `json:"code_challenge_method,omitempty" yaml:"code_challenge_method,omitempty"`
}

OAuthConfig represents OAuth 2.1 configuration

type ProtectedResourceMetadata

type ProtectedResourceMetadata struct {
	Resource               string   `json:"resource,omitempty"`
	AuthorizationServers   []string `json:"authorization_servers"`
	JWKSUri                string   `json:"jwks_uri,omitempty"`
	BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
	ResourceDocumentation  string   `json:"resource_documentation,omitempty"`
	ResourcePolicyURI      string   `json:"resource_policy_uri,omitempty"`
	ResourceTosURI         string   `json:"resource_tos_uri,omitempty"`
	ScopesSupported        []string `json:"scopes_supported,omitempty"`
}

ProtectedResourceMetadata represents OAuth 2.0 Protected Resource Metadata (RFC 9728)

type RefreshToken

type RefreshToken struct {
	Token     string    `json:"refresh_token"`
	ClientID  string    `json:"client_id"`
	UserID    string    `json:"user_id"`
	Scope     string    `json:"scope"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
	Revoked   bool      `json:"revoked"`
}

RefreshToken represents a refresh token

func (*RefreshToken) IsExpired

func (t *RefreshToken) IsExpired() bool

IsExpired checks if the refresh token is expired

type ResourceMetadataHandler

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

ResourceMetadataHandler handles protected resource metadata requests

func NewResourceMetadataHandler

func NewResourceMetadataHandler(authServers []string, scopes []string) *ResourceMetadataHandler

NewResourceMetadataHandler creates a new resource metadata handler

func (*ResourceMetadataHandler) AddAuthorizationServer

func (h *ResourceMetadataHandler) AddAuthorizationServer(server string)

AddAuthorizationServer adds an authorization server

func (*ResourceMetadataHandler) GetMetadata

GetMetadata returns the current metadata

func (*ResourceMetadataHandler) HandleProtectedResourceMetadata

func (h *ResourceMetadataHandler) HandleProtectedResourceMetadata(w http.ResponseWriter, r *http.Request)

HandleProtectedResourceMetadata handles requests to /.well-known/oauth-protected-resource

func (*ResourceMetadataHandler) RemoveAuthorizationServer

func (h *ResourceMetadataHandler) RemoveAuthorizationServer(server string)

RemoveAuthorizationServer removes an authorization server

func (*ResourceMetadataHandler) SetDocumentation

func (h *ResourceMetadataHandler) SetDocumentation(uri string)

SetDocumentation sets the resource documentation URI

func (*ResourceMetadataHandler) SetJWKSUri

func (h *ResourceMetadataHandler) SetJWKSUri(uri string)

SetJWKSUri sets the JWKS URI

func (*ResourceMetadataHandler) SetPolicyURI

func (h *ResourceMetadataHandler) SetPolicyURI(uri string)

SetPolicyURI sets the resource policy URI

func (*ResourceMetadataHandler) SetResource

func (h *ResourceMetadataHandler) SetResource(resource string)

SetResource sets the resource identifier

func (*ResourceMetadataHandler) SetTosURI

func (h *ResourceMetadataHandler) SetTosURI(uri string)

SetTosURI sets the resource terms of service URI

type TokenGenerator

type TokenGenerator interface {
	GenerateAuthorizationCode() (string, error)
	GenerateAccessToken() (string, error)
	GenerateRefreshToken() (string, error)
	GenerateDeviceCode() (string, error)
	GenerateUserCode() (string, error)
	GenerateState() (string, error)
	GenerateClientID() (string, error)
	GenerateClientSecret() (string, error)
}

TokenGenerator interface for generating tokens

type TokenInfo

type TokenInfo struct {
	ClientID  string    `json:"client_id"`
	UserID    string    `json:"user_id"`
	Scope     string    `json:"scope"`
	ExpiresAt time.Time `json:"expires_at"`
	CreatedAt time.Time `json:"created_at"`
	Revoked   bool      `json:"revoked"`
}

type TokenStore

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

TokenStore manages the lifecycle of OAuth tokens and codes in memory.

func NewTokenStore

func NewTokenStore() *TokenStore

NewTokenStore creates and starts a new in-memory token store.

func (*TokenStore) Close

func (ts *TokenStore) Close()

Close stops the cleanup routine.

func (*TokenStore) GetAccessToken

func (ts *TokenStore) GetAccessToken(tokenStr string) (*AccessToken, error)

GetAccessToken retrieves a valid access token.

func (*TokenStore) GetAndUseAuthorizationCode

func (ts *TokenStore) GetAndUseAuthorizationCode(codeStr string) (*AuthorizationCode, error)

GetAndUseAuthorizationCode retrieves a valid auth code and marks it as used.

func (*TokenStore) GetRefreshToken

func (ts *TokenStore) GetRefreshToken(tokenStr string) (*RefreshToken, error)

GetRefreshToken retrieves a valid refresh token.

func (*TokenStore) RevokeAccessToken

func (ts *TokenStore) RevokeAccessToken(tokenStr string)

RevokeAccessToken marks an access token as revoked.

func (*TokenStore) RevokeRefreshToken

func (ts *TokenStore) RevokeRefreshToken(tokenStr string)

RevokeRefreshToken marks a refresh token as revoked.

func (*TokenStore) StoreAccessToken

func (ts *TokenStore) StoreAccessToken(token *AccessToken)

StoreAccessToken adds an access token to the store.

func (*TokenStore) StoreAuthorizationCode

func (ts *TokenStore) StoreAuthorizationCode(code *AuthorizationCode)

StoreAuthorizationCode adds an authorization code to the store.

func (*TokenStore) StoreRefreshToken

func (ts *TokenStore) StoreRefreshToken(token *RefreshToken)

StoreRefreshToken adds a refresh token to the store.

Jump to

Keyboard shortcuts

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