Documentation
¶
Overview ¶
Package auth provides common password validation and security utilities for authentication.
Package auth provides universal authentication context and utilities for consolidating authentication patterns across the Lesser application.
Package auth provides centralized authentication extraction functions This consolidates the auth extraction patterns found across 80+ handler files
Index ¶
- Constants
- Variables
- func AdminAuth(config MiddlewareConfig) apptheory.Middleware
- func AgentAccessTokenTTL(cfg *config.Config) time.Duration
- func AgentRuntimeClientIDs() []string
- func AgentRuntimeRefreshExpiries(now time.Time, idleTTL, absoluteTTL time.Duration) (time.Time, time.Time)
- func CSRFMiddleware(manager *CSRFManager) func(http.HandlerFunc) http.HandlerFunc
- func CanonicalOAuthScopes() []string
- func CoalesceAgentRuntimeLabel(primary, fallback string) string
- func ConstantTimeCompare(a, b string) bool
- func ConstantTimeComparePadded(a, b string) bool
- func ConstantTimeDelay()
- func CreateAPIAuthMiddleware(oauthService common.OAuthServiceInterface, logger *zap.Logger) apptheory.Middleware
- func CreateAPIAuthMiddlewareFromAuthAndOAuthServices(authService *AuthService, oauthService *OAuthService, logger *zap.Logger) apptheory.Middleware
- func CreateAPIAuthMiddlewareFromAuthService(authService *AuthService, logger *zap.Logger) apptheory.Middleware
- func CreateFederationAuthMiddleware(oauthService common.OAuthServiceInterface, logger *zap.Logger) apptheory.Middleware
- func CreateFederationAuthMiddlewareFromAuthService(authService *AuthService, logger *zap.Logger) apptheory.Middleware
- func CreateGraphQLAuthMiddleware(oauthService common.OAuthServiceInterface, logger *zap.Logger) apptheory.Middleware
- func CreateGraphQLAuthMiddlewareFromAuthService(authService *AuthService, logger *zap.Logger) apptheory.Middleware
- func CreatePrincipalContextBridgeFromAuthAndOAuthServices(authService *AuthService, oauthService *OAuthService, logger *zap.Logger, ...) apptheory.Middleware
- func CreatePrincipalContextBridgeFromAuthService(authService *AuthService, logger *zap.Logger, serviceName string) apptheory.Middleware
- func CreatePrincipalContextBridgeFromOAuthService(oauthService *OAuthService, logger *zap.Logger, serviceName string) apptheory.Middleware
- func DefaultScopes() []string
- func ExtractBearerToken(authHeader string) (string, error)
- func FollowAuth(config MiddlewareConfig) apptheory.Middleware
- func GenerateCSRFTokenHandler(manager *CSRFManager) http.HandlerFunc
- func GeneratePasswordHint(password string) []string
- func GetAuthenticatedUsername(ctx *apptheory.Context) string
- func GetJWTClaims(ctx *apptheory.Context) common.Claims
- func GetLegacyAuthContext(ctx *apptheory.Context) *common.AuthContext
- func GetUsernameFromContext(ctx *apptheory.Context, oauthService OAuthServiceInterface) (string, error)
- func GetUsernameFromStandardContext(ctx context.Context) (string, error)
- func HashOAuthClientSecret(secret string) (string, error)
- func HashPassword(password string) (string, error)
- func IsAgentRuntimeClientID(clientID string) bool
- func IsAgentRuntimeRefreshToken(token *storage.RefreshToken) bool
- func IsAppTheoryContextAuthenticated(ctx *apptheory.Context) bool
- func IsAuthenticated(ctx *apptheory.Context) bool
- func IsCommonPassword(password string) bool
- func IsTestMode(_ *apptheory.Context) bool
- func LegacyAuthContextFromAppTheoryContext(ctx *apptheory.Context) *common.AuthContext
- func ListAgentRuntimeSessions(ctx context.Context, repos StorageProvider, username string) ([]storage.RefreshToken, error)
- func NewAppTheoryPrincipalHookFromAuthAndOAuthServices(authService *AuthService, oauthService *OAuthService, logger *zap.Logger, ...) apptheory.PrincipalAuthHook
- func NewAppTheoryPrincipalHookFromAuthService(authService *AuthService, logger *zap.Logger, serviceName string) apptheory.PrincipalAuthHook
- func NewAppTheoryPrincipalHookFromOAuthService(oauthService *OAuthService, logger *zap.Logger, serviceName string) apptheory.PrincipalAuthHook
- func OptionalAuth(config MiddlewareConfig) apptheory.Middleware
- func ParseAgentPublicKey(keyType string, publicKey string) (crypto.PublicKey, error)
- func PasswordStrength(password string) int
- func PasswordStrengthLabel(strength int) string
- func PasswordStrengthWithConfig(password string, cfg PasswordStrengthConfig) int
- func PrincipalFromClaims(claims *Claims) *apptheory.AuthPrincipal
- func ReadAuth(config MiddlewareConfig) apptheory.Middleware
- func RecordAgentRuntimeAuthFailure(ctx context.Context, repos StorageProvider, token *storage.RefreshToken, ...) error
- func RecordAgentRuntimeAuthSuccess(ctx context.Context, repos StorageProvider, token *storage.RefreshToken, ...) error
- func RequireAuth(ctx *apptheory.Context, oauthService OAuthServiceInterface) error
- func RequireAuthFromStandardContext(ctx context.Context) error
- func RequireReadAccess(ctx *apptheory.Context) error
- func RequireWriteAccess(ctx *apptheory.Context) error
- func RequiredAuth(config MiddlewareConfig) apptheory.Middleware
- func RequiredAuthWithMultipleScopes(config MiddlewareConfig) apptheory.Middleware
- func RevokeAgentRuntimeFamily(ctx context.Context, repos StorageProvider, token *storage.RefreshToken, ...) error
- func RevokeAgentRuntimeSession(ctx context.Context, repos StorageProvider, ...) error
- func RevokeAllAgentRuntimeSessions(ctx context.Context, repos StorageProvider, ...) error
- func ScopeGrantAllows(granted, requested string) bool
- func ScopeSetAllows(grantedScopes, requestedScopes []string) bool
- func SetAccountInStandardContext(ctx context.Context, account *AuthenticatedAccount) context.Context
- func SetAuthContext(ctx *apptheory.Context, authCtx *Context)
- func TimingSafeStringSliceContains(slice []string, target string) bool
- func TimingSafeTokenValidation(providedToken, storedToken string) bool
- func ToWebAuthnCredential(c *storage.WebAuthnCredential) *webauthn.Credential
- func UsernameFromAppTheoryContext(ctx *apptheory.Context) string
- func ValidateAPIKey(provided string, getStoredKey func() (string, error)) error
- func ValidateAccountOwnership(account *AuthenticatedAccount, targetUsername string) error
- func ValidateAccountOwnershipOrAdmin(account *AuthenticatedAccount, targetUsername string) error
- func ValidatePassword(password string, username string) error
- func ValidatePublicOAuthScopes(scopes []string) error
- func ValidateScopes(scopes []string) error
- func ValidateSessionToken(token string, validateFunc func(string) (bool, error)) error
- func VerifyAgentChallengeSignature(keyType string, publicKey string, message string, signatureBase64 string) error
- func VerifyOAuthClientSecret(providedSecret, storedValue string) (bool, bool, error)
- func VerifyPassword(password, hash string) error
- func WithClaims(ctx context.Context, claims *Claims) context.Context
- func WriteAuth(config MiddlewareConfig) apptheory.Middleware
- type AWSSecretsManager
- func (sm *AWSSecretsManager) CleanupCache()
- func (sm *AWSSecretsManager) DeletePrivateKey(ctx context.Context, keyID string) error
- func (sm *AWSSecretsManager) GenerateAndStoreKeyPair(ctx context.Context, keyID string) (publicKeyPEM, privateKeyPEM string, err error)
- func (sm *AWSSecretsManager) GetCacheStats() map[string]interface{}
- func (sm *AWSSecretsManager) RetrievePrivateKey(ctx context.Context, keyID string) (string, error)
- func (sm *AWSSecretsManager) RotateKey(ctx context.Context, keyID string) (publicKeyPEM, privateKeyPEM string, err error)
- func (sm *AWSSecretsManager) StorePrivateKey(ctx context.Context, keyID, privateKeyPEM string) error
- type AdvancedSessionSecurityConfig
- type AgentRuntimeAuthDiagnostic
- type AgentRuntimeAuthStatus
- type AgentRuntimeTokenBundle
- type AgentRuntimeTokenIssueParams
- type AuditConfig
- type AuditEvent
- type AuditEventType
- type AuditLogger
- func (al *AuditLogger) GetIPAuditLogs(ctx context.Context, ipAddress string, limit int) ([]*AuditEvent, error)
- func (al *AuditLogger) GetSecurityEvents(ctx context.Context, startTime, endTime time.Time, ...) ([]*AuditEvent, error)
- func (al *AuditLogger) GetSessionAuditLogs(ctx context.Context, sessionID string) ([]*AuditEvent, error)
- func (al *AuditLogger) GetUserAuditLogs(ctx context.Context, username string, limit int) ([]*AuditEvent, error)
- func (al *AuditLogger) LogEvent(ctx context.Context, event *AuditEvent) error
- func (al *AuditLogger) LogLogin(ctx context.Context, username, ipAddress, userAgent, deviceName string, ...)
- func (al *AuditLogger) LogOAuthClientSecretRotation(ctx context.Context, username, ipAddress, userAgent, requestID string, ...)
- func (al *AuditLogger) LogOAuthToken(ctx context.Context, clientID, username, ipAddress string, ...)
- func (al *AuditLogger) LogSecurityEvent(ctx context.Context, eventType AuditEventType, username, ipAddress string, ...)
- func (al *AuditLogger) LogSession(ctx context.Context, username, sessionID, ipAddress string, ...)
- func (al *AuditLogger) LogWebAuthn(ctx context.Context, username, ipAddress, userAgent string, ...)
- type AuditSeverity
- type AuthResponse
- type AuthService
- func (as *AuthService) AuthenticateWithPassword(_ context.Context, _, _, _, _, _ string) (*AuthResponse, error)
- func (as *AuthService) BeginWebAuthnLogin(ctx context.Context, username string) (any, string, error)
- func (as *AuthService) BeginWebAuthnRegistration(ctx context.Context, username string) (any, string, error)
- func (as *AuthService) ChangePassword(_ context.Context, _, _, _ string) error
- func (as *AuthService) ClearAccountLockout(ctx context.Context, username string) error
- func (as *AuthService) CreateWalletChallenge(ctx context.Context, address string, chainID int, username string) (*storage.WalletChallenge, error)
- func (as *AuthService) DeleteWebAuthnCredential(ctx context.Context, username string, credentialID string) error
- func (as *AuthService) FinishWebAuthnLogin(ctx context.Context, username string, challenge string, response []byte, ...) (*AuthResponse, error)
- func (as *AuthService) FinishWebAuthnRegistration(ctx context.Context, username string, challenge string, response []byte, ...) error
- func (as *AuthService) GenerateAuthorizationCode() (string, error)
- func (as *AuthService) GenerateRecoveryToken(ctx context.Context, username string, recoveryMethod string) (string, error)
- func (as *AuthService) GetAccountStatus(ctx context.Context, username string) (*RateLimitStatus, error)
- func (as *AuthService) GetConfig() *ServiceConfig
- func (as *AuthService) GetStore() StorageProvider
- func (as *AuthService) GetUserDevices(ctx context.Context, username string) ([]*Device, error)
- func (as *AuthService) GetUserWallets(ctx context.Context, username string) ([]*storage.WalletCredential, error)
- func (as *AuthService) GetWalletByAddress(ctx context.Context, address string) (*storage.WalletCredential, error)
- func (as *AuthService) GetWalletChallenge(ctx context.Context, challengeID string) (*storage.WalletChallenge, error)
- func (as *AuthService) GetWebAuthnCredentials(ctx context.Context, username string) ([]*storage.WebAuthnCredential, error)
- func (as *AuthService) LinkWallet(ctx context.Context, username, address string, chainID int, walletType string) (bool, error)
- func (as *AuthService) LoginWithWallet(ctx context.Context, req *WalletVerifyRequest, ...) (*AuthResponse, error)
- func (as *AuthService) LoginWithWalletAfterLinking(ctx context.Context, username, deviceName, userAgent, ipAddress string) (*AuthResponse, error)
- func (as *AuthService) Logout(ctx context.Context, sessionID string) error
- func (as *AuthService) LogoutAllDevices(ctx context.Context, username string) error
- func (as *AuthService) MarkWalletChallengeSpent(ctx context.Context, challengeID string) error
- func (as *AuthService) RefreshAccessToken(ctx context.Context, refreshToken, ipAddress string) (*AuthResponse, error)
- func (as *AuthService) ResetWalletChallengeSpent(ctx context.Context, challengeID string) error
- func (as *AuthService) TrustDevice(ctx context.Context, username, deviceID string) error
- func (as *AuthService) UnlinkWallet(ctx context.Context, username, address string) error
- func (as *AuthService) UpdateWebAuthnCredentialName(ctx context.Context, username string, credentialID string, newName string) error
- func (as *AuthService) ValidateAccessToken(tokenString string) (*EnhancedClaims, error)
- func (as *AuthService) ValidateClient(ctx context.Context, clientID, clientSecret string) error
- func (as *AuthService) ValidateRedirectURI(ctx context.Context, clientID, redirectURI string) error
- func (as *AuthService) VerifySignatureOnly(ctx context.Context, challenge *storage.WalletChallenge, signature string) error
- func (as *AuthService) VerifyWalletSignature(ctx context.Context, req *WalletVerifyRequest) error
- type AuthenticatedAccount
- func ExtractOptionalAuth(ctx *apptheory.Context, oauthService OAuthServiceInterface) (*AuthenticatedAccount, error)
- func GetAccountFromContext(ctx *apptheory.Context, oauthService OAuthServiceInterface) (*AuthenticatedAccount, error)
- func GetAccountFromStandardContext(ctx context.Context) (*AuthenticatedAccount, error)
- func GetAuthenticatedAccountFromContext(ctx *apptheory.Context) (*AuthenticatedAccount, bool)
- func RequireAdminScope(ctx *apptheory.Context, oauthService OAuthServiceInterface) (*AuthenticatedAccount, error)
- func RequireAuthWithMultipleScopes(ctx *apptheory.Context, oauthService OAuthServiceInterface, scopes []string) (*AuthenticatedAccount, error)
- func RequireAuthWithScope(ctx *apptheory.Context, oauthService OAuthServiceInterface, scope string) (*AuthenticatedAccount, error)
- func RequireReadOrWriteScope(ctx *apptheory.Context, oauthService OAuthServiceInterface) (*AuthenticatedAccount, error)
- func RequireReadScope(ctx *apptheory.Context, oauthService OAuthServiceInterface) (*AuthenticatedAccount, error)
- func RequireWriteScope(ctx *apptheory.Context, oauthService OAuthServiceInterface) (*AuthenticatedAccount, error)
- type AuthenticationMiddleware
- type CSRFManager
- type CSRFStore
- type CSRFToken
- type Claims
- type Context
- func (ac *Context) HasScope(scope string) bool
- func (ac *Context) IsAdmin() bool
- func (ac *Context) IsExpired() bool
- func (ac *Context) RequireAuth() error
- func (ac *Context) RequireAuthWithResponse(ctx *apptheory.Context) (*apptheory.Response, error)
- func (ac *Context) RequireScope(scope string) error
- func (ac *Context) RequireScopeWithResponse(ctx *apptheory.Context, scope string) (*apptheory.Response, error)
- func (ac *Context) TimeUntilExpiry() time.Duration
- func (ac *Context) ToMap() map[string]interface{}
- type Device
- type DeviceFingerprint
- type DeviceFingerprintConfig
- type DeviceFingerprintManager
- func (dfm *DeviceFingerprintManager) GenerateEnhancedFingerprint(userAgent, ipAddress, acceptLang, acceptEncoding string, ...) *EnhancedDeviceFingerprint
- func (dfm *DeviceFingerprintManager) RegisterNewDevice(ctx context.Context, username string, fingerprint *EnhancedDeviceFingerprint, ...) (*DeviceInfo, error)
- func (dfm *DeviceFingerprintManager) UpdateDeviceFingerprint(ctx context.Context, deviceID string, fingerprint *EnhancedDeviceFingerprint) error
- func (dfm *DeviceFingerprintManager) ValidateDevice(ctx context.Context, username string, fingerprint *EnhancedDeviceFingerprint) (*DeviceValidationResult, error)
- type DeviceInfo
- type DeviceValidationResult
- type DynamORMCSRFStore
- func (s *DynamORMCSRFStore) CleanExpired() error
- func (s *DynamORMCSRFStore) CleanupUserTokens(userID string) error
- func (s *DynamORMCSRFStore) Delete(token string) error
- func (s *DynamORMCSRFStore) Get(token string) (*CSRFToken, error)
- func (s *DynamORMCSRFStore) GetUserActiveTokenCount(userID string) (int, error)
- func (s *DynamORMCSRFStore) Store(token string, csrf CSRFToken) error
- func (s *DynamORMCSRFStore) ValidateAndConsume(token string, userID string) error
- type EnhancedClaims
- type EnhancedDeviceFingerprint
- type FederationDeliveryService
- type MemoryCSRFStore
- type Middleware
- func (m *Middleware) RequireAuth(_ context.Context, request events.APIGatewayV2HTTPRequest) (*Claims, error)
- func (m *Middleware) RequireScope(claims *Claims, scope string) error
- func (m *Middleware) RequireUser(claims *Claims, username string) error
- func (m *Middleware) ValidateToken(authHeader string) (*Claims, error)
- type MiddlewareConfig
- type OAuthService
- func (s *OAuthService) GenerateAuthorizationCode() (string, error)
- func (s *OAuthService) GenerateTokens(ctx context.Context, username, clientID, ipAddress string, scopes []string) (accessToken, refreshToken string, err error)
- func (s *OAuthService) GenerateTokensWithAccessTokenTTL(ctx context.Context, username, clientID, ipAddress string, scopes []string, ...) (accessToken, refreshToken string, err error)
- func (s *OAuthService) GenerateTokensWithAccessTokenTTLAndClientContext(ctx context.Context, username, clientID, ipAddress string, scopes []string, ...) (accessToken, refreshToken string, err error)
- func (s *OAuthService) GenerateTokensWithAccessTokenTTLAndClientContextAndAudience(ctx context.Context, username, clientID, ipAddress string, scopes []string, ...) (accessToken, refreshToken string, err error)
- func (s *OAuthService) GenerateTokensWithContext(username, clientID, sessionID, deviceID, ipAddress, userAgent string, ...) (accessToken, refreshToken string, err error)
- func (s *OAuthService) ValidateAccessToken(tokenString string) (*Claims, error)
- func (s *OAuthService) ValidateAccessTokenWithContext(tokenString, expectedSessionID, expectedIP string, expectedTokenVersion int) (*Claims, error)
- func (s *OAuthService) ValidateClient(ctx context.Context, clientID, clientSecret string) error
- func (s *OAuthService) ValidateRedirectURI(ctx context.Context, clientID, redirectURI string) error
- func (s *OAuthService) ValidateScopes(ctx context.Context, clientID string, requestedScopes []string) error
- func (s *OAuthService) VerifyCodeChallenge(codeChallenge, codeVerifier, challengeMethod string) error
- type OAuthServiceAdapter
- type OAuthServiceInterface
- type PasswordPolicy
- type PasswordStrengthConfig
- type PublicMCPAccessBundle
- type RateLimitStatus
- type RateLimiter
- func (rl *RateLimiter) CheckRateLimit(ctx context.Context, username, ipAddress string) error
- func (rl *RateLimiter) ClearAccountLockout(ctx context.Context, username string) error
- func (rl *RateLimiter) GetAccountStatus(ctx context.Context, username string) (*RateLimitStatus, error)
- func (rl *RateLimiter) GetFailedAttempts(ctx context.Context, username string) (int, error)
- func (rl *RateLimiter) RecordAttempt(ctx context.Context, username, ipAddress string, success bool) error
- type RecoveryActivity
- type RecoveryCodeService
- func (s *RecoveryCodeService) ClearRecoveryCodes(ctx context.Context, username string) error
- func (s *RecoveryCodeService) GenerateRecoveryCodes(ctx context.Context, username string, count int) ([]string, error)
- func (s *RecoveryCodeService) GetRecoveryCodeCount(ctx context.Context, username string) (int, error)
- func (s *RecoveryCodeService) ValidateRecoveryCode(ctx context.Context, username, code string) (bool, error)
- type RecoveryFederationService
- func (s *RecoveryFederationService) GetSystemActorPrivateKey(ctx context.Context) (string, error)
- func (s *RecoveryFederationService) HandleTrusteeConfirmation(ctx context.Context, activity *activitypub.Activity) error
- func (s *RecoveryFederationService) RotateSystemActorKey(ctx context.Context) error
- func (s *RecoveryFederationService) SendRecoveryApprovalNotification(ctx context.Context, username string, recoveryToken string) error
- func (s *RecoveryFederationService) SendRecoveryRequest(ctx context.Context, request *storage.SocialRecoveryRequest, ...) error
- func (s *RecoveryFederationService) SendTrusteeInvitation(ctx context.Context, fromUser string, trusteeActorID string) error
- type RefreshToken
- type RefreshTokenStore
- func (s *RefreshTokenStore) CreateRefreshToken(ctx context.Context, userID string, deviceName string, ipAddress string) (*RefreshToken, error)
- func (s *RefreshTokenStore) GetRefreshToken(ctx context.Context, token string) (*RefreshToken, error)
- func (s *RefreshTokenStore) GetTokensByFamily(ctx context.Context, family string) ([]RefreshToken, error)
- func (s *RefreshTokenStore) GetTokensByUser(ctx context.Context, userID string) ([]RefreshToken, error)
- func (s *RefreshTokenStore) RevokeTokenFamily(ctx context.Context, family string, reason string) error
- func (s *RefreshTokenStore) RevokeUserTokens(ctx context.Context, userID string, reason string) error
- func (s *RefreshTokenStore) RotateRefreshToken(ctx context.Context, oldToken string, ipAddress string) (*RefreshToken, error)
- type SecretValue
- type SecretsManager
- type SecretsManagerConfig
- type SecurityValidationResult
- type ServiceConfig
- type Session
- type SessionAnomalyFlags
- type SessionExtension
- type SessionHealth
- type SessionLifecycleConfig
- type SessionLifecycleManager
- func (slm *SessionLifecycleManager) CleanupExpiredSessions(_ context.Context) error
- func (slm *SessionLifecycleManager) CreateSessionWithLifecycle(ctx context.Context, ...) (*Session, error)
- func (slm *SessionLifecycleManager) GetSessionHealth(ctx context.Context, sessionID string) (*SessionHealth, error)
- func (slm *SessionLifecycleManager) RefreshSessionWithRotation(ctx context.Context, refreshToken string, ipAddress, userAgent string) (*Session, string, error)
- func (slm *SessionLifecycleManager) RevokeAllUserSessionsWithReason(ctx context.Context, username, reason string) error
- func (slm *SessionLifecycleManager) ScheduleCleanup(ctx context.Context)
- type SessionManager
- func (sm *SessionManager) CleanupInactiveSessions(_ context.Context) error
- func (sm *SessionManager) CreateSession(ctx context.Context, ...) (*Session, error)
- func (sm *SessionManager) DetectAnomalousSession(_ context.Context, session *Session, currentIP string) (bool, string)
- func (sm *SessionManager) GetTokenVersion(username string) int
- func (sm *SessionManager) GetUserDevices(ctx context.Context, username string) ([]*Device, error)
- func (sm *SessionManager) InvalidateAllUserTokens(username string)
- func (sm *SessionManager) RevokeAllUserSessions(ctx context.Context, username string) error
- func (sm *SessionManager) RevokeSession(ctx context.Context, sessionID string) error
- func (sm *SessionManager) RotateRefreshToken(ctx context.Context, session *Session) (string, error)
- func (sm *SessionManager) TrustDevice(ctx context.Context, deviceID string) error
- func (sm *SessionManager) UpdateSessionActivity(ctx context.Context, sessionID, ipAddress string) error
- func (sm *SessionManager) ValidateRefreshToken(ctx context.Context, refreshToken string) (*Session, error)
- type SessionSecurityConfig
- type SessionSecurityManager
- func (ssm *SessionSecurityManager) CalculateSessionRisk(_ *Session, anomalies *SessionAnomalyFlags, ...) float64
- func (ssm *SessionSecurityManager) DetectSessionAnomalies(session *Session, currentFingerprint *DeviceFingerprint) *SessionAnomalyFlags
- func (ssm *SessionSecurityManager) GenerateCSRFToken() (string, error)
- func (ssm *SessionSecurityManager) GenerateDeviceFingerprint(userAgent, ipAddress, acceptLang string) *DeviceFingerprint
- func (ssm *SessionSecurityManager) GenerateSecureSessionCookie(sessionID, username string) (string, error)
- func (ssm *SessionSecurityManager) IsHighRiskUserAgent(userAgent string) bool
- func (ssm *SessionSecurityManager) LogSecurityEvent(eventType, sessionID, username, description string, ...)
- func (ssm *SessionSecurityManager) PreventSessionFixation(oldSessionID string) (string, error)
- func (ssm *SessionSecurityManager) RotateSessionSecrets(session *Session) error
- func (ssm *SessionSecurityManager) ShouldRequire2FA(riskScore float64, session *Session) bool
- func (ssm *SessionSecurityManager) ValidateCSRFToken(provided, expected string) bool
- func (ssm *SessionSecurityManager) ValidateSecurityHeaders(headers map[string]string) []string
- func (ssm *SessionSecurityManager) ValidateSessionSecurity(_ context.Context, session *Session, currentFingerprint *DeviceFingerprint) (*SecurityValidationResult, error)
- type SessionValidationConfig
- type SessionValidationRequest
- type SessionValidationResponse
- type SessionValidator
- func (sv *SessionValidator) QuickValidateSession(ctx context.Context, sessionID, ipAddress, userAgent string) (bool, error)
- func (sv *SessionValidator) ValidateRefreshTokenRequest(ctx context.Context, refreshToken, ipAddress, userAgent string) (*SessionValidationResponse, error)
- func (sv *SessionValidator) ValidateSession(ctx context.Context, request *SessionValidationRequest) (*SessionValidationResponse, error)
- type SocialRecoveryService
- func (s *SocialRecoveryService) AddTrustee(ctx context.Context, username, trusteeActorID string) error
- func (s *SocialRecoveryService) ConfirmRecovery(ctx context.Context, requestID, trusteeActorID string) error
- func (s *SocialRecoveryService) GetTrustees(ctx context.Context, username string) ([]*storage.TrusteeConfig, error)
- func (s *SocialRecoveryService) InitiateRecovery(ctx context.Context, username string) (*storage.SocialRecoveryRequest, error)
- func (s *SocialRecoveryService) RemoveTrustee(ctx context.Context, username, trusteeActorID string) error
- func (s *SocialRecoveryService) SetFederationService(fedService socialRecoveryFederationService)
- type StorageProvider
- type TokenBlacklist
- type UnifiedAuthMiddleware
- type WalletChallenge
- type WalletCredential
- type WalletService
- func (s *WalletService) CreateChallenge(ctx context.Context, address string, chainID int, username string) (*storage.WalletChallenge, error)
- func (s *WalletService) GetUserWallets(ctx context.Context, username string) ([]*storage.WalletCredential, error)
- func (s *WalletService) LinkWallet(ctx context.Context, username, address string, chainID int, walletType string) (bool, error)
- func (s *WalletService) UnlinkWallet(ctx context.Context, username, address string) error
- func (s *WalletService) VerifySignature(ctx context.Context, req *WalletVerifyRequest) (string, error)
- type WalletVerifyRequest
- type WebAuthnService
- func (s *WebAuthnService) BeginLogin(ctx context.Context, username string) (any, string, error)
- func (s *WebAuthnService) BeginRegistration(ctx context.Context, username string) (any, string, error)
- func (s *WebAuthnService) DeleteCredential(ctx context.Context, username string, credentialID string) error
- func (s *WebAuthnService) FinishLogin(ctx context.Context, username string, challenge string, response []byte) (*storage.WebAuthnCredential, error)
- func (s *WebAuthnService) FinishRegistration(ctx context.Context, username string, challenge string, response []byte, ...) error
- func (s *WebAuthnService) GetUserCredentials(ctx context.Context, username string) ([]*storage.WebAuthnCredential, error)
- func (s *WebAuthnService) UpdateCredentialName(ctx context.Context, username string, credentialID string, newName string) error
Constants ¶
const ( DelegatedAgentRuntimeClientID = "lesser-agent-delegation" SelfSovereignAgentRuntimeClientID = "lesser-agent-self-sovereign" )
Dedicated internal runtime client IDs. These are not part of the canonical public MCP client contract.
const ( ScopeRead = "read" ScopeWrite = "write" ScopeAdmin = "admin" )
Scopes define the permissions that can be granted
const ( GrantTypeAuthorizationCode = "authorization_code" GrantTypeRefreshToken = "refresh_token" GrantTypeClientCredentials = "client_credentials" )
Grant types
const ( // Access token duration: 1 hour is reasonable for external client applications // Balances security with usability - clients should use refresh tokens for longer sessions AccessTokenDuration = 1 * time.Hour // Refresh tokens should be rotated regularly RefreshTokenDuration = 7 * 24 * time.Hour // 7 days // Authorization codes must be very short-lived AuthCodeDuration = 5 * time.Minute // Token family tracking for refresh token rotation RefreshTokenFamilyExpiry = 30 * 24 * time.Hour // 30 days for family tracking )
Token expiration times
const ( ClientClassWeb = "web" ClientClassCLI = "cli" ClientClassAgent = "agent" )
Client classes identify the client category that minted an access token. These are used for server-side policy decisions (e.g., automation safety rails) without relying on spoofable headers.
const ( // Login attempts before lockout MaxLoginAttempts = 5 MaxIPAttempts = 20 // Lockout durations AccountLockoutDuration = 30 * time.Minute IPLockoutDuration = 1 * time.Hour // Time windows for counting attempts AttemptWindow = 15 * time.Minute // Rate limit keys RateLimitTypeAccount = "account" RateLimitTypeIP = "ip" )
Rate limiting constants
const ( // Read scopes ReadNotifications = "read:notifications" ReadFollows = "read:follows" ReadBlocks = "read:blocks" ReadFilters = "read:filters" // Write scopes WriteNotifications = "write:notifications" WriteFollows = "write:follows" WriteBlocks = "write:blocks" WriteFilters = "write:filters" )
OAuth 2.0 Scopes
const ( // ScopeFollow grants relationship-management capability on public OAuth surfaces. ScopeFollow = "follow" // ScopePush grants push-subscription capability on public OAuth surfaces. ScopePush = "push" )
const ( SessionDuration = 7 * 24 * time.Hour // 7 days (reduced from 30) ShortAccessTokenDuration = 1 * time.Hour // Align with client app expectations RefreshTokenRotationWindow = 1 * time.Hour // Reduced grace period (from 24h) MaxSessionsPerUser = 10 // Limit concurrent sessions SessionInactivityTimeout = 24 * time.Hour // Auto-logout after inactivity DeviceTrustPromotionThreshold = 7 * 24 * time.Hour // Days until device can be trusted // Device trust levels TrustLevelTrusted = "trusted" TrustLevelUntrusted = "untrusted" )
Session constants - enhanced security
const ( ChallengeDuration = 5 * time.Minute // WebAuthn challenges expire after 5 minutes MaxCredentialsPerUser = 10 // Maximum passkeys per user )
WebAuthn constants
const AgentRuntimeRefreshAbsoluteTTL = RefreshTokenFamilyExpiry
AgentRuntimeRefreshAbsoluteTTL caps the total lifetime of an agent runtime refresh session.
const AgentRuntimeRefreshIdleTTL = RefreshTokenDuration
AgentRuntimeRefreshIdleTTL is the sliding inactivity window for agent runtime refresh sessions.
const AuthContextKey = "auth_context"
AuthContextKey is the key used to store AuthContext in request context.
const (
// ContextKeyAuthenticatedAccount is the key for storing authenticated account in context
ContextKeyAuthenticatedAccount contextKey = "authenticated_account"
)
const DefaultAgentRuntimeDeviceLabel = "local-agent"
DefaultAgentRuntimeDeviceLabel is used when a runtime does not provide its own label.
const DefaultBcryptCost = 12
DefaultBcryptCost is the default cost factor for bcrypt hashing
const OAuthClientSecretHashPrefix = common.OAuthClientSecretHashPrefix
OAuthClientSecretHashPrefix marks hashed secrets stored for OAuth clients.
const (
SecurityActionDeny = "deny"
)
Security action constants
Variables ¶
var ( // ErrUnsupportedAgentKeyType is returned when the requested key type is not supported. ErrUnsupportedAgentKeyType = errors.New("unsupported agent key type") // ErrInvalidAgentPublicKey is returned when a provided agent public key cannot be parsed. ErrInvalidAgentPublicKey = errors.New("invalid agent public key") // ErrInvalidAgentSignature is returned when a provided signature cannot be verified. ErrInvalidAgentSignature = errors.New("invalid agent signature") )
var ( ErrInvalidCSRF = errors.New("invalid CSRF token") ErrExpiredCSRF = errors.New("expired CSRF token") ErrMissingCSRF = errors.New("missing CSRF token") )
CSRF-related errors
var ( // Basic password length errors ErrPasswordTooShort = apperrors.PasswordTooShort(8) ErrPasswordTooLong = apperrors.PasswordTooLong(72) // Length requirement error for policy validation ErrPasswordInsufficientLength = apperrors.PasswordInsufficientLength() // Passwordless enforcement ErrPasswordAuthDisabled = errors.New("password authentication is disabled") // Password processing errors ErrPasswordHashFailed = apperrors.PasswordHashingFailed(errors.New("password hashing failed")) // Character requirement errors ErrPasswordMissingUppercase = apperrors.PasswordMissingRequirement("uppercase letter") ErrPasswordMissingLowercase = apperrors.PasswordMissingRequirement("lowercase letter") ErrPasswordMissingNumber = apperrors.PasswordMissingRequirement("number") ErrPasswordMissingSpecialChar = apperrors.PasswordMissingRequirement("special character") // Content validation errors ErrPasswordContainsUsername = apperrors.PasswordContainsUsername() ErrPasswordTooCommon = apperrors.PasswordTooCommon() ErrPasswordSequentialPattern = apperrors.PasswordSequentialPattern() ErrPasswordRepeatedPattern = apperrors.PasswordRepeatedPattern() // Session security errors ErrCSRFTokenGeneration = apperrors.CSRFTokenGenerationFailed(errors.New("CSRF token generation failed")) ErrSessionIDGeneration = apperrors.SessionIDGenerationFailed(errors.New("session ID generation failed")) ErrCookieEntropyGeneration = apperrors.CookieEntropyGenerationFailed(errors.New("cookie entropy generation failed")) ErrCSRFTokenRotation = apperrors.CSRFTokenRotationFailed(errors.New("CSRF token rotation failed")) ErrCSRFValidationFailed = apperrors.CSRFValidationFailed() // OAuth token validation errors ErrUnexpectedSigningMethod = apperrors.UnexpectedSigningMethod() ErrSessionIDMismatch = apperrors.SessionIDMismatch() ErrIPAddressMismatch = apperrors.IPAddressMismatch() ErrTokenVersionMismatch = apperrors.TokenVersionMismatch() ErrTokenTooOld = apperrors.TokenTooOld() // Wallet authentication errors ErrNonceGeneration = apperrors.NonceGenerationFailed(errors.New("nonce generation failed")) ErrChallengeStorage = apperrors.ChallengeStorageFailed(errors.New("challenge storage failed")) ErrChallengeRetrieval = apperrors.ChallengeRetrievalFailed(errors.New("challenge retrieval failed")) ErrChallengeExpired = apperrors.WalletChallengeExpired() ErrMessageMismatch = apperrors.MessageMismatch() ErrAddressMismatch = apperrors.WalletAddressMismatch() ErrSignatureVerification = apperrors.SignatureVerificationFailed() ErrWalletCheck = apperrors.WalletCheckFailed(errors.New("wallet check failed")) ErrWalletStorage = apperrors.WalletStorageFailed(errors.New("wallet storage failed")) ErrWalletRetrieval = apperrors.WalletRetrievalFailed(errors.New("wallet retrieval failed")) ErrWalletDeletion = apperrors.WalletDeletionFailed(errors.New("wallet deletion failed")) ErrWalletAlreadyLinked = apperrors.WalletAlreadyLinked() ErrInvalidSignatureFormat = apperrors.InvalidSignatureFormat() ErrInvalidSignatureLength = apperrors.InvalidSignatureLength() ErrPublicKeyRecovery = apperrors.PublicKeyRecoveryFailed(errors.New("public key recovery failed")) ErrSignatureAddressMismatch = apperrors.SignatureAddressMismatch() // Social recovery errors ErrTrusteeActorIDRequired = apperrors.TrusteeActorIDRequired() ErrInsufficientTrustees = apperrors.InsufficientTrustees() ErrRecoveryTokenGeneration = apperrors.RecoveryTokenGenerationFailed(errors.New("recovery token generation failed")) ErrRecoveryRequestNotFound = apperrors.RecoveryRequestNotFound() ErrRecoveryRequestNotPending = apperrors.RecoveryRequestNotPending() ErrRecoveryRequestExpired = apperrors.RecoveryRequestExpired() ErrTrusteeAlreadyVoted = apperrors.TrusteeAlreadyVoted() // Social recovery repository operation errors ErrTrusteeStorage = apperrors.TrusteeStorageFailed(errors.New("trustee storage failed")) ErrTrusteeDeletion = apperrors.TrusteeDeletionFailed(errors.New("trustee deletion failed")) ErrTrusteeRetrieval = apperrors.TrusteeRetrievalFailed(errors.New("trustee retrieval failed")) ErrRecoveryRequestStorage = apperrors.RecoveryRequestStorageFailed(errors.New("recovery request storage failed")) ErrRecoveryRequestRetrieval = apperrors.RecoveryRequestRetrievalFailed(errors.New("recovery request retrieval failed")) ErrRecoveryRequestUpdate = apperrors.RecoveryRequestUpdateFailed(errors.New("recovery request update failed")) ErrRecoveryTokenStorage = apperrors.RecoveryTokenStorageFailed(errors.New("recovery token storage failed")) // WebAuthn service errors ErrWebAuthnServiceInit = apperrors.WebAuthnServiceInitFailed(errors.New("WebAuthn service init failed")) ErrUserRetrieval = apperrors.UserRetrievalFailed(errors.New("user retrieval failed")) ErrCredentialRetrieval = apperrors.CredentialRetrievalFailed(errors.New("credential retrieval failed")) ErrRegistrationBegin = apperrors.RegistrationBeginFailed(errors.New("registration begin failed")) ErrLoginBegin = apperrors.LoginBeginFailed(errors.New("login begin failed")) ErrSessionDataSerialization = apperrors.SessionDataSerializationFailed(errors.New("session data serialization failed")) ErrSessionDataDeserialization = apperrors.SessionDataDeserializationFailed(errors.New("session data deserialization failed")) ErrWebAuthnChallengeStorage = apperrors.WebAuthnChallengeStorageFailed(errors.New("WebAuthn challenge storage failed")) ErrCredentialResponse = apperrors.CredentialResponseParseFailed(errors.New("credential response parse failed")) ErrCredentialCreation = apperrors.CredentialCreationFailed(errors.New("credential creation failed")) ErrCredentialValidation = apperrors.CredentialValidationFailed(errors.New("credential validation failed")) ErrCredentialStorage = apperrors.CredentialStorageFailed(errors.New("credential storage failed")) ErrMaxCredentialsReached = apperrors.MaxCredentialsReached() ErrInvalidSessionDataType = apperrors.InvalidSessionDataType() ErrLastAuthMethodDelete = apperrors.LastAuthMethodDelete() // Recovery code errors ErrRecoveryCodeGeneration = apperrors.RecoveryCodeGenerationFailed(errors.New("recovery code generation failed")) ErrRecoveryCodeHashing = apperrors.RecoveryCodeHashingFailed(errors.New("recovery code hashing failed")) ErrRecoveryCodeStorage = apperrors.RecoveryCodeStorageFailed(errors.New("recovery code storage failed")) ErrRecoveryCodeRetrieval = apperrors.RecoveryCodeRetrievalFailed(errors.New("recovery code retrieval failed")) ErrRecoveryCodeMarkUsed = apperrors.RecoveryCodeMarkUsedFailed(errors.New("recovery code mark used failed")) ErrRecoveryCodeClear = apperrors.RecoveryCodeClearFailed(errors.New("recovery code clear failed")) // Secrets Manager errors ErrAWSConfigLoad = apperrors.AWSConfigLoadFailed(errors.New("AWS config load failed")) ErrSecretsManagerConnection = apperrors.SecretsManagerConnectionFailed(errors.New("secrets manager connection failed")) ErrInvalidPrivateKeyFormat = apperrors.InvalidPrivateKeyFormat() ErrSecretValueMarshal = apperrors.SecretValueMarshalFailed(errors.New("secret value marshal failed")) ErrSecretCreation = apperrors.SecretCreationFailed(errors.New("secret creation failed")) ErrPrivateKeyRetrieval = apperrors.PrivateKeyRetrievalFailed(errors.New("private key retrieval failed")) ErrSecretValueUnmarshal = apperrors.SecretValueUnmarshalFailed(errors.New("secret value unmarshal failed")) ErrRetrievedPrivateKeyInvalid = apperrors.RetrievedPrivateKeyInvalid() ErrSecretDeletion = apperrors.SecretDeletionFailed(errors.New("secret deletion failed")) ErrRSAKeyPairGeneration = apperrors.RSAKeyPairGenerationFailed(errors.New("RSA key pair generation failed")) ErrPrivateKeyMarshal = apperrors.PrivateKeyMarshalFailed(errors.New("private key marshal failed")) ErrPublicKeyMarshal = apperrors.PublicKeyMarshalFailed(errors.New("public key marshal failed")) ErrGeneratedPrivateKeyStorage = apperrors.GeneratedPrivateKeyStorageFailed(errors.New("generated private key storage failed")) ErrKeyPairGenerationRotation = apperrors.KeyPairGenerationRotationFailed(errors.New("key pair generation rotation failed")) ErrPEMBlockDecode = apperrors.PEMBlockDecodeFailed() ErrPrivateKeyParse = apperrors.PrivateKeyParseFailed(errors.New("private key parse failed")) ErrSecretValueNil = apperrors.SecretValueNil() ErrSecretRetrievalRetries = apperrors.SecretRetrievalRetriesFailed(errors.New("secret retrieval retries failed")) // Audit logging errors ErrAuditEventMarshal = apperrors.AuditEventMarshalFailed(errors.New("audit event marshal failed")) ErrSIEMRequestCreation = apperrors.SIEMRequestCreationFailed(errors.New("SIEM request creation failed")) ErrSIEMTransmission = apperrors.SIEMTransmissionFailed(errors.New("SIEM transmission failed")) ErrSIEMResponseError = apperrors.SIEMResponseError() // Rate limiting operation errors ErrIPRateLimitCheck = apperrors.IPRateLimitCheckFailed(errors.New("IP rate limit check failed")) ErrAccountRateLimitCheck = apperrors.AccountRateLimitCheckFailed(errors.New("account rate limit check failed")) ErrRecordIPAttempt = apperrors.RecordIPAttemptFailed(errors.New("record IP attempt failed")) ErrRecordAccountAttempt = apperrors.RecordAccountAttemptFailed(errors.New("record account attempt failed")) ErrGetIPAttemptCount = apperrors.GetIPAttemptCountFailed(errors.New("get IP attempt count failed")) ErrGetAccountAttemptCount = apperrors.GetAccountAttemptCountFailed(errors.New("get account attempt count failed")) ErrImposeIPLockout = apperrors.ImposeIPLockoutFailed(errors.New("impose IP lockout failed")) ErrImposeAccountLockout = apperrors.ImposeAccountLockoutFailed(errors.New("impose account lockout failed")) // Session management errors ErrRefreshTokenGeneration = apperrors.RefreshTokenGenerationFailed(errors.New("refresh token generation failed")) ErrDeviceIDRetrieval = apperrors.DeviceIDRetrievalFailed(errors.New("device ID retrieval failed")) ErrSessionStorage = apperrors.SessionStorageFailed(errors.New("session storage failed")) ErrNewRefreshTokenGeneration = apperrors.NewRefreshTokenGenerationFailed(errors.New("new refresh token generation failed")) ErrSessionUpdate = apperrors.SessionUpdateFailed(errors.New("session update failed")) ErrUserSessionsRetrieval = apperrors.UserSessionsRetrievalFailed(errors.New("user sessions retrieval failed")) ErrOldestSessionRemoval = apperrors.OldestSessionRemovalFailed(errors.New("oldest session removal failed")) ErrInvalidRefreshToken = apperrors.RefreshTokenInvalid() ErrSessionNotFound = apperrors.SessionNotFound("") ErrSessionExpired = apperrors.SessionExpired() ErrDeviceNotFound = apperrors.DeviceNotFound("") // Device fingerprinting errors ErrUserDevicesRetrieval = apperrors.UserDevicesRetrievalFailed(errors.New("user devices retrieval failed")) ErrDeviceCreation = apperrors.DeviceCreationFailed(errors.New("device creation failed")) ErrMaxDevicesExceeded = apperrors.MaxDevicesExceeded() // Device ownership errors ErrDeviceOwnershipMismatch = apperrors.DeviceOwnershipMismatch() // JWT validation errors ErrJWTUnexpectedSigningMethod = apperrors.JWTUnexpectedSigningMethod() // Recovery federation errors ErrInvalidActivityObject = apperrors.InvalidActivityObject() ErrNotRecoveryConfirmationActivity = apperrors.NotRecoveryConfirmationActivity() ErrMissingRequestID = apperrors.MissingRequestID() ErrFailedToDecodePEM = apperrors.FailedToDecodePEM() ErrUnsupportedPrivateKeyType = apperrors.UnsupportedPrivateKeyType() ErrSecretsManagerNotAvailable = apperrors.SecretsManagerNotAvailable() ErrSigningActorRetrievalFailed = apperrors.SigningActorRetrievalFailed(errors.New("signing actor retrieval failed")) ErrRecoveryConfirmationFailed = apperrors.RecoveryConfirmationFailed(errors.New("recovery confirmation failed")) ErrActorRetrievalFailed = apperrors.ActorRetrievalFailed(errors.New("actor retrieval failed")) ErrPrivateKeyParseFailed = apperrors.PrivateKeyParseFailed(errors.New("private key parse failed")) ErrPublicKeyMarshalFailed = apperrors.PublicKeyMarshalFailed(errors.New("public key marshal failed")) ErrSystemActorKeyRetrievalFailed = apperrors.SystemActorKeyRetrievalFailed(errors.New("system actor key retrieval failed")) ErrSystemActorKeyRotationFailed = apperrors.SystemActorKeyRotationFailed(errors.New("system actor key rotation failed")) // Session lifecycle errors ErrSessionSecurityValidationFailed = apperrors.SessionSecurityValidationFailed("") ErrSessionCannotBeExtended = apperrors.SessionCannotBeExtended("") ErrSessionMaxLifetimeReached = apperrors.SessionMaxLifetimeReached() ErrSessionExtensionDisabled = apperrors.SessionExtensionDisabled() ErrConcurrentSessionLimitExceeded = apperrors.ConcurrentSessionLimitExceeded() ErrRefreshTokenRotationFailed = apperrors.RefreshTokenRotationFailed(errors.New("refresh token rotation failed")) ErrInvalidRefreshTokenProvided = apperrors.InvalidRefreshTokenProvided() ErrSessionSecurityCheckFailed = apperrors.SessionSecurityCheckFailed(errors.New("session security check failed")) // Auth service operation errors ErrSessionCreationFailed = apperrors.SessionCreationFailed(errors.New("session creation failed")) ErrAccessTokenGenerationFailed = apperrors.AccessTokenGenerationFailed(errors.New("access token generation failed")) ErrPasswordHashingFailed = apperrors.PasswordHashingFailed(errors.New("password hashing failed")) ErrPasswordUpdateFailed = apperrors.PasswordUpdateFailed(errors.New("password update failed")) ErrSignatureVerificationFailed = apperrors.SignatureVerificationFailed() ErrUserRetrievalFailed = apperrors.UserRetrievalFailed(errors.New("user retrieval failed")) ErrRecoveryTokenGenerationFailed = apperrors.RecoveryTokenGenerationFailed(errors.New("recovery token generation failed")) ErrRecoveryTokenStorageFailed = apperrors.RecoveryTokenStorageFailed(errors.New("recovery token storage failed")) // Common authentication errors (moved from service.go) ErrInvalidCredentials = apperrors.InvalidCredentials() ErrUserNotFound = apperrors.UserNotFound("") ErrUserSuspended = apperrors.UserSuspended("") ErrUserNotApproved = apperrors.UserNotApproved("") ErrInvalidToken = apperrors.TokenInvalid("") ErrWebAuthnNotConfigured = apperrors.WebAuthnNotConfigured() )
Legacy error variables for backwards compatibility These are now wrappers around the centralized error system
var ( // ErrMissingAuthHeader is returned when Authorization header is missing ErrMissingAuthHeader = errors.New("missing authorization header") // ErrInvalidAuthHeader is returned when Authorization header is malformed ErrInvalidAuthHeader = errors.New("invalid authorization header") )
var ( // ErrInvalidGrant is returned when the authorization code is invalid or expired ErrInvalidGrant = errors.New("invalid_grant") // ErrInvalidClient is returned when the client is not authorized ErrInvalidClient = errors.New("invalid_client") // ErrInvalidRequest is returned when the request is malformed ErrInvalidRequest = errors.New("invalid_request") ErrUnauthorizedClient = errors.New("unauthorized_client") // ErrUnsupportedGrantType is returned when the grant type is not supported ErrUnsupportedGrantType = errors.New("unsupported_grant_type") // ErrInvalidCodeChallenge is returned when the code challenge doesn't match ErrInvalidCodeChallenge = errors.New("invalid_code_challenge") // ErrInvalidScope is returned when requested scopes are invalid ErrInvalidScope = errors.New("invalid_scope") // ErrInvalidAPIKey is returned when the API key is invalid ErrInvalidAPIKey = errors.New("invalid_api_key") )
var ( ErrTooManyAttempts = errors.New("too many login attempts") ErrAccountLocked = errors.New("account temporarily locked") ErrIPRateLimited = errors.New("IP address rate limited") )
Rate limiting errors
var ( // ErrTokenReuse indicates a refresh token was reused (security breach) ErrTokenReuse = errors.New("refresh token reuse detected") // ErrExpiredRefreshToken indicates the refresh token has expired ErrExpiredRefreshToken = errors.New("refresh token expired") )
var ( ErrChallengeNotFound = errors.New("challenge not found or expired") ErrCredentialNotFound = errors.New("credential not found") ErrInvalidCredential = errors.New("invalid credential") ErrUserHasNoCredentials = errors.New("user has no credentials") )
WebAuthn errors
var DefaultPasswordStrengthConfig = PasswordStrengthConfig{ MinLength: 8, LongLength: 16, LongBonus: 1, RequireAllCharacterTypesForLongBonus: true, SequentialPenalty: 2, SequentialPatternMinRun: 4, RepeatedPenalty: 1, }
DefaultPasswordStrengthConfig matches the built-in strength scoring used by PasswordStrength.
var DefaultPolicy = PasswordPolicy{ MinLength: 12, RequireUppercase: true, RequireLowercase: true, RequireNumbers: true, RequireSpecialChars: true, PreventCommonPasswords: true, }
DefaultPolicy defines the default password requirements
Functions ¶
func AdminAuth ¶
func AdminAuth(config MiddlewareConfig) apptheory.Middleware
AdminAuth creates middleware specifically for admin operations
func AgentAccessTokenTTL ¶ added in v1.1.46
AgentAccessTokenTTL returns the configured default lifetime for agent access tokens. When no agent-specific override is configured, Lesser falls back to the shared OAuth default.
func AgentRuntimeClientIDs ¶ added in v1.2.0
func AgentRuntimeClientIDs() []string
AgentRuntimeClientIDs returns the dedicated internal runtime client IDs that participate in runtime-session diagnostics and family rotation.
func AgentRuntimeRefreshExpiries ¶ added in v1.2.53
func AgentRuntimeRefreshExpiries(now time.Time, idleTTL, absoluteTTL time.Duration) (time.Time, time.Time)
AgentRuntimeRefreshExpiries returns the idle and absolute refresh-session expiries for an agent runtime token. Zero durations preserve Lesser's default runtime session bounds; positive durations allow delegation flows to cap refresh sessions to the requested TTL.
func CSRFMiddleware ¶
func CSRFMiddleware(manager *CSRFManager) func(http.HandlerFunc) http.HandlerFunc
CSRFMiddleware creates middleware for CSRF protection
func CanonicalOAuthScopes ¶ added in v1.1.53
func CanonicalOAuthScopes() []string
CanonicalOAuthScopes returns the externally-advertised Lesser OAuth scope catalog.
func CoalesceAgentRuntimeLabel ¶ added in v1.1.50
CoalesceAgentRuntimeLabel returns a stable label for operator-visible runtime sessions.
func ConstantTimeCompare ¶
ConstantTimeCompare performs a constant-time comparison of two strings
func ConstantTimeComparePadded ¶
ConstantTimeComparePadded performs a constant-time comparison without early exit on length mismatch. Length still influences runtime due to required padding work; for secrets of fixed length this is acceptable.
func ConstantTimeDelay ¶
func ConstantTimeDelay()
ConstantTimeDelay adds a small random delay to prevent timing analysis
func CreateAPIAuthMiddleware ¶
func CreateAPIAuthMiddleware(oauthService common.OAuthServiceInterface, logger *zap.Logger) apptheory.Middleware
CreateAPIAuthMiddleware creates standard API authentication middleware
func CreateAPIAuthMiddlewareFromAuthAndOAuthServices ¶ added in v1.2.37
func CreateAPIAuthMiddlewareFromAuthAndOAuthServices(authService *AuthService, oauthService *OAuthService, logger *zap.Logger) apptheory.Middleware
CreateAPIAuthMiddlewareFromAuthAndOAuthServices creates API auth middleware that preserves native session validation while also accepting OAuth-issued tokens.
func CreateAPIAuthMiddlewareFromAuthService ¶
func CreateAPIAuthMiddlewareFromAuthService(authService *AuthService, logger *zap.Logger) apptheory.Middleware
CreateAPIAuthMiddlewareFromAuthService creates API auth middleware from AuthService.
func CreateFederationAuthMiddleware ¶
func CreateFederationAuthMiddleware(oauthService common.OAuthServiceInterface, logger *zap.Logger) apptheory.Middleware
CreateFederationAuthMiddleware creates federation-specific authentication middleware
func CreateFederationAuthMiddlewareFromAuthService ¶
func CreateFederationAuthMiddlewareFromAuthService(authService *AuthService, logger *zap.Logger) apptheory.Middleware
CreateFederationAuthMiddlewareFromAuthService creates federation auth middleware from AuthService.
func CreateGraphQLAuthMiddleware ¶
func CreateGraphQLAuthMiddleware(oauthService common.OAuthServiceInterface, logger *zap.Logger) apptheory.Middleware
CreateGraphQLAuthMiddleware creates standard GraphQL authentication middleware
func CreateGraphQLAuthMiddlewareFromAuthService ¶
func CreateGraphQLAuthMiddlewareFromAuthService(authService *AuthService, logger *zap.Logger) apptheory.Middleware
CreateGraphQLAuthMiddlewareFromAuthService creates GraphQL auth middleware from AuthService.
func CreatePrincipalContextBridgeFromAuthAndOAuthServices ¶ added in v1.2.37
func CreatePrincipalContextBridgeFromAuthAndOAuthServices(authService *AuthService, oauthService *OAuthService, logger *zap.Logger, serviceName string) apptheory.Middleware
CreatePrincipalContextBridgeFromAuthAndOAuthServices mirrors principal data for both native session-backed tokens and OAuth-issued tokens into the legacy request context.
func CreatePrincipalContextBridgeFromAuthService ¶ added in v1.2.35
func CreatePrincipalContextBridgeFromAuthService(authService *AuthService, logger *zap.Logger, serviceName string) apptheory.Middleware
CreatePrincipalContextBridgeFromAuthService mirrors AuthService-backed principal data into the legacy request context.
func CreatePrincipalContextBridgeFromOAuthService ¶ added in v1.2.35
func CreatePrincipalContextBridgeFromOAuthService(oauthService *OAuthService, logger *zap.Logger, serviceName string) apptheory.Middleware
CreatePrincipalContextBridgeFromOAuthService mirrors OAuthService-backed principal data into the legacy request context.
func DefaultScopes ¶
func DefaultScopes() []string
DefaultScopes returns the default scopes for a user
func ExtractBearerToken ¶
ExtractBearerToken extracts the token from the Authorization header
func FollowAuth ¶
func FollowAuth(config MiddlewareConfig) apptheory.Middleware
FollowAuth creates middleware specifically for follow operations
func GenerateCSRFTokenHandler ¶
func GenerateCSRFTokenHandler(manager *CSRFManager) http.HandlerFunc
GenerateCSRFTokenHandler creates an endpoint to get CSRF tokens
func GeneratePasswordHint ¶
GeneratePasswordHint provides helpful hints for password improvement
func GetAuthenticatedUsername ¶
GetAuthenticatedUsername retrieves the authenticated username or empty string
func GetJWTClaims ¶
GetJWTClaims retrieves the JWT claims from context
func GetLegacyAuthContext ¶
func GetLegacyAuthContext(ctx *apptheory.Context) *common.AuthContext
GetLegacyAuthContext retrieves the authentication context from the request context.
func GetUsernameFromContext ¶
func GetUsernameFromContext(ctx *apptheory.Context, oauthService OAuthServiceInterface) (string, error)
GetUsernameFromContext extracts just the username from the context This consolidates the pattern: username, err := h.authenticateRequestWithScope(ctx, "read")
func GetUsernameFromStandardContext ¶
GetUsernameFromStandardContext extracts username from standard context
func HashOAuthClientSecret ¶
HashOAuthClientSecret hashes an OAuth client secret for storage.
func HashPassword ¶
HashPassword hashes a password using bcrypt
func IsAgentRuntimeClientID ¶ added in v1.1.50
IsAgentRuntimeClientID reports whether a client ID belongs to Lesser's long-lived agent runtime flows.
func IsAgentRuntimeRefreshToken ¶ added in v1.2.0
func IsAgentRuntimeRefreshToken(token *storage.RefreshToken) bool
IsAgentRuntimeRefreshToken reports whether a stored refresh token belongs to the dedicated internal runtime session model rather than ordinary public or compatibility OAuth rotation.
func IsAppTheoryContextAuthenticated ¶ added in v1.2.35
IsAppTheoryContextAuthenticated reports whether the request has authenticated AppTheory principal state.
func IsAuthenticated ¶
IsAuthenticated returns true if the request is authenticated
func IsCommonPassword ¶
IsCommonPassword checks if a password is in the common passwords list
func IsTestMode ¶
IsTestMode determines if the current request is in test mode
func LegacyAuthContextFromAppTheoryContext ¶ added in v1.2.35
func LegacyAuthContextFromAppTheoryContext(ctx *apptheory.Context) *common.AuthContext
LegacyAuthContextFromAppTheoryContext synthesizes the legacy common.AuthContext from AppTheory principal state.
func ListAgentRuntimeSessions ¶ added in v1.1.50
func ListAgentRuntimeSessions(ctx context.Context, repos StorageProvider, username string) ([]storage.RefreshToken, error)
ListAgentRuntimeSessions returns the current runtime refresh session records for an agent.
func NewAppTheoryPrincipalHookFromAuthAndOAuthServices ¶ added in v1.2.37
func NewAppTheoryPrincipalHookFromAuthAndOAuthServices(authService *AuthService, oauthService *OAuthService, logger *zap.Logger, serviceName string) apptheory.PrincipalAuthHook
NewAppTheoryPrincipalHookFromAuthAndOAuthServices builds an AppTheory principal hook that preserves native session validation while also accepting OAuth-issued access tokens on the same API surface.
func NewAppTheoryPrincipalHookFromAuthService ¶ added in v1.2.35
func NewAppTheoryPrincipalHookFromAuthService(authService *AuthService, logger *zap.Logger, serviceName string)