Documentation
¶
Index ¶
- Variables
- func ConstantTimeCompare(a, b string) bool
- func HasScope(scopes []APIKeyScope, target APIKeyScope) bool
- func JWTMiddleware(jwtService *JWTService, next http.Handler) http.Handler
- func RequireRole(roles ...Role) func(http.Handler) http.Handler
- func RequireScope(jwtService *JWTService, scopes ...APIKeyScope) func(http.Handler) http.Handler
- type APIKey
- type APIKeyOption
- type APIKeyRequest
- type APIKeyResponse
- type APIKeyScope
- type APIKeyService
- func (s *APIKeyService) GenerateKey(req *APIKeyRequest) (*APIKeyResponse, error)
- func (s *APIKeyService) Get(id string) (*APIKey, error)
- func (s *APIKeyService) HasScope(key *APIKey, scope APIKeyScope) bool
- func (s *APIKeyService) List(userID string) ([]*APIKey, error)
- func (s *APIKeyService) Revoke(id, userID string) error
- func (s *APIKeyService) ValidateKey(fullKey string) (*APIKey, error)
- type Config
- type JWTAlgorithm
- type JWTClaims
- type JWTConfig
- type JWTHeader
- type JWTService
- func (s *JWTService) GenerateAPIToken(apiKey *APIKey) (string, error)
- func (s *JWTService) GenerateTokenPair(user *User, customClaims map[string]interface{}) (*TokenPair, error)
- func (s *JWTService) GetActiveTokenInfo(userID string) (*TokenPair, bool)
- func (s *JWTService) RefreshTokenPair(refreshTokenString string) (*TokenPair, error)
- func (s *JWTService) RevokeAllUserTokens(userID, reason string) error
- func (s *JWTService) RevokeToken(tokenString, reason string) error
- func (s *JWTService) ValidateToken(tokenString string) (*JWTToken, error)
- type JWTToken
- type LocalUserConfig
- type LocalUserInfo
- type LoginResult
- type Manager
- func (m *Manager) Close()
- func (m *Manager) CreateLocalUser(username, password string, role Role) error
- func (m *Manager) CreateSession(user *User, r *http.Request) (*Session, error)
- func (m *Manager) GetActiveSessions() []*Session
- func (m *Manager) GetConfig() *Config
- func (m *Manager) GetSession(sessionID string) (*Session, error)
- func (m *Manager) GetSessionFromContext(ctx context.Context) *Session
- func (m *Manager) GetSessionFromRequest(r *http.Request) (*Session, error)
- func (m *Manager) GetUserFromContext(ctx context.Context) *User
- func (m *Manager) GetUserSessions(userID string) []*Session
- func (m *Manager) HandleOAuthCallback(w http.ResponseWriter, r *http.Request)
- func (m *Manager) Handler() http.Handler
- func (m *Manager) InitOAuthFlow(w http.ResponseWriter, r *http.Request)
- func (m *Manager) InvalidateSession(sessionID string) error
- func (m *Manager) InvalidateUserSessions(userID string)
- func (m *Manager) ListLocalUsers() []LocalUserInfo
- func (m *Manager) LocalLogin(w http.ResponseWriter, r *http.Request)
- func (m *Manager) Logout(w http.ResponseWriter, r *http.Request) error
- func (m *Manager) OptionalAuth(next http.Handler) http.Handler
- func (m *Manager) RefreshSession(sessionID string) error
- func (m *Manager) RequireAdmin(next http.Handler) http.Handler
- func (m *Manager) RequireAuth(next http.Handler) http.Handler
- func (m *Manager) RequirePermission(permission Permission) func(http.Handler) http.Handler
- func (m *Manager) RequireRole(role Role) func(http.Handler) http.Handler
- type OAuthEndpoints
- type OAuthTokenResponse
- type OAuthUserInfo
- type Permission
- type Provider
- type Role
- type Session
- type TokenPair
- type User
Constants ¶
This section is empty.
Variables ¶
var OAuthProviderEndpoints = map[Provider]OAuthEndpoints{ ProviderGoogle: { AuthURL: "https://accounts.google.com/o/oauth2/v2/auth", TokenURL: "https://oauth2.googleapis.com/token", UserInfoURL: "https://openidconnect.googleapis.com/v1/userinfo", Scopes: []string{"openid", "profile", "email"}, }, ProviderMicrosoft: { AuthURL: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize", TokenURL: "https://login.microsoftonline.com/common/oauth2/v2.0/token", UserInfoURL: "https://graph.microsoft.com/v1.0/me", Scopes: []string{"openid", "profile", "email", "User.Read"}, }, ProviderGitHub: { AuthURL: "https://github.com/login/oauth/authorize", TokenURL: "https://github.com/login/oauth/access_token", UserInfoURL: "https://api.github.com/user", Scopes: []string{"read:user", "user:email"}, }, ProviderOkta: { Scopes: []string{"openid", "profile", "email"}, }, ProviderAuth0: { Scopes: []string{"openid", "profile", "email"}, }, }
OAuthProviderEndpoints maps provider names to their OAuth endpoints.
var RolePermissions = map[Role][]Permission{ RoleAdmin: { PermViewDashboard, PermManagePolicies, PermManageCerts, PermViewLogs, PermManageUsers, PermViewReports, PermSystemConfig, PermViewAlerts, }, RoleOperator: { PermViewDashboard, PermManagePolicies, PermViewLogs, PermViewReports, PermViewAlerts, }, RoleViewer: { PermViewDashboard, PermViewReports, PermViewAlerts, }, RoleService: { PermViewDashboard, PermViewReports, }, }
RolePermissions maps roles to permissions.
Functions ¶
func ConstantTimeCompare ¶ added in v1.0.10
ConstantTimeCompare performs constant-time comparison to prevent timing attacks
func HasScope ¶ added in v1.0.10
func HasScope(scopes []APIKeyScope, target APIKeyScope) bool
HasScope checks if the scope list contains a specific scope
func JWTMiddleware ¶ added in v1.0.10
func JWTMiddleware(jwtService *JWTService, next http.Handler) http.Handler
JWTMiddleware creates middleware for JWT authentication
func RequireRole ¶ added in v1.0.10
RequireRole creates middleware that requires specific roles
func RequireScope ¶ added in v1.0.10
func RequireScope(jwtService *JWTService, scopes ...APIKeyScope) func(http.Handler) http.Handler
RequireScope creates middleware that requires specific scopes
Types ¶
type APIKey ¶ added in v1.0.10
type APIKey struct {
ID string `json:"id"`
Name string `json:"name"`
KeyPrefix string `json:"key_prefix"` // First 8 chars for identification
KeyHash string `json:"-"` // Never exposed
UserID string `json:"user_id"`
Scopes []APIKeyScope `json:"scopes"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
LastUsedAt *time.Time `json:"last_used_at,omitempty"`
RateLimit int `json:"rate_limit"` // Requests per minute
RateLimitCurr int `json:"-"`
RateLimitReset time.Time `json:"-"`
Active bool `json:"active"`
Revoked bool `json:"revoked"`
RevokedAt *time.Time `json:"revoked_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
APIKey represents an API key for programmatic access
func (*APIKey) CanAccess ¶ added in v1.0.10
func (k *APIKey) CanAccess(scope APIKeyScope) bool
CanAccess checks if the key has the required scope
func (*APIKey) MarshalJSON ¶ added in v1.0.10
MarshalJSON implements custom JSON marshaling to hide sensitive data
type APIKeyOption ¶ added in v1.0.10
type APIKeyOption func(*APIKeyService)
APIKeyOption configures the API key service
func WithDefaultRateLimit ¶ added in v1.0.10
func WithDefaultRateLimit(limit int) APIKeyOption
WithDefaultRateLimit sets the default rate limit
func WithKeyPrefix ¶ added in v1.0.10
func WithKeyPrefix(prefix string) APIKeyOption
WithKeyPrefix sets the key prefix
func WithMaxKeysPerUser ¶ added in v1.0.10
func WithMaxKeysPerUser(max int) APIKeyOption
WithMaxKeysPerUser sets the maximum keys per user
type APIKeyRequest ¶ added in v1.0.10
type APIKeyRequest struct {
Name string `json:"name"`
Scopes []APIKeyScope `json:"scopes"`
ExpiresIn time.Duration `json:"expires_in,omitempty"` // 0 = no expiration
RateLimit int `json:"rate_limit,omitempty"` // 0 = use default
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
APIKeyRequest represents a request to create an API key
type APIKeyResponse ¶ added in v1.0.10
type APIKeyResponse struct {
ID string `json:"id"`
Name string `json:"name"`
Key string `json:"key,omitempty"` // Only present on creation
KeyPrefix string `json:"key_prefix"`
Scopes []APIKeyScope `json:"scopes"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
RateLimit int `json:"rate_limit"`
CreatedAt time.Time `json:"created_at"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
APIKeyResponse represents the response when creating an API key The actual key is only shown once at creation time
type APIKeyScope ¶ added in v1.0.10
type APIKeyScope string
APIKeyScope defines the scope of access for an API key
const ( ScopeRead APIKeyScope = "read" ScopeWrite APIKeyScope = "write" ScopeAdmin APIKeyScope = "admin" ScopeMetrics APIKeyScope = "metrics:read" ScopeProxy APIKeyScope = "proxy:manage" ScopeReports APIKeyScope = "reports:read" ScopePolicies APIKeyScope = "policies:manage" ScopeUsers APIKeyScope = "users:manage" ScopeCerts APIKeyScope = "certificates:manage" ScopeWebhooks APIKeyScope = "webhooks:manage" )
func ValidScopes ¶ added in v1.0.10
func ValidScopes() []APIKeyScope
ValidScopes returns all valid API key scopes
type APIKeyService ¶ added in v1.0.10
type APIKeyService struct {
// contains filtered or unexported fields
}
APIKeyService handles API key management
func NewAPIKeyService ¶ added in v1.0.10
func NewAPIKeyService(db *sql.DB, auditLogger *opsec.SecureAuditLog, opts ...APIKeyOption) (*APIKeyService, error)
NewAPIKeyService creates a new API key service
func (*APIKeyService) GenerateKey ¶ added in v1.0.10
func (s *APIKeyService) GenerateKey(req *APIKeyRequest) (*APIKeyResponse, error)
GenerateKey generates a new API key
func (*APIKeyService) Get ¶ added in v1.0.10
func (s *APIKeyService) Get(id string) (*APIKey, error)
Get gets an API key by ID (without the actual key)
func (*APIKeyService) HasScope ¶ added in v1.0.10
func (s *APIKeyService) HasScope(key *APIKey, scope APIKeyScope) bool
HasScope checks if a key has a specific scope
func (*APIKeyService) List ¶ added in v1.0.10
func (s *APIKeyService) List(userID string) ([]*APIKey, error)
List lists all API keys for a user
func (*APIKeyService) Revoke ¶ added in v1.0.10
func (s *APIKeyService) Revoke(id, userID string) error
Revoke revokes an API key
func (*APIKeyService) ValidateKey ¶ added in v1.0.10
func (s *APIKeyService) ValidateKey(fullKey string) (*APIKey, error)
ValidateKey validates an API key and returns the associated key object
type Config ¶
type Config struct {
Provider Provider
ClientID string
ClientSecret string
RedirectURL string
AuthURL string
TokenURL string
UserInfoURL string
Scopes []string
SAMLMetadataURL string
SAMLIssuer string
SAMLCertPath string
SessionDuration time.Duration
CookieName string
CookieSecure bool
CookieHTTPOnly bool
CookieSameSite http.SameSite
RequireHTTPS bool
MaxSessions int
EnableMFA bool
AllowedDomains []string
BlockedDomains []string
LocalUsers map[string]LocalUserConfig
}
Config holds authentication configuration
func DefaultConfig ¶
func DefaultConfig() *Config
DefaultConfig returns default authentication configuration
type JWTAlgorithm ¶ added in v1.0.10
type JWTAlgorithm string
JWTAlgorithm represents the JWT signing algorithm
const ( AlgorithmHS256 JWTAlgorithm = "HS256" AlgorithmHS384 JWTAlgorithm = "HS384" AlgorithmHS512 JWTAlgorithm = "HS512" AlgorithmRS256 JWTAlgorithm = "RS256" AlgorithmRS384 JWTAlgorithm = "RS384" AlgorithmRS512 JWTAlgorithm = "RS512" AlgorithmNone JWTAlgorithm = "none" )
type JWTClaims ¶ added in v1.0.10
type JWTClaims struct {
Issuer string `json:"iss,omitempty"`
Subject string `json:"sub,omitempty"`
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
JWTID string `json:"jti,omitempty"`
Name string `json:"name,omitempty"`
Email string `json:"email,omitempty"`
Role Role `json:"role,omitempty"`
Permissions []Permission `json:"permissions,omitempty"`
Scopes []APIKeyScope `json:"scopes,omitempty"`
TenantID string `json:"tenant_id,omitempty"`
SessionID string `json:"session_id,omitempty"`
DeviceID string `json:"device_id,omitempty"`
MFAVerified bool `json:"mfa_verified,omitempty"`
RefreshTokenHash string `json:"-"`
Custom map[string]interface{} `json:"custom,omitempty"`
}
JWTClaims represents the standard JWT claims
type JWTConfig ¶ added in v1.0.10
type JWTConfig struct {
Algorithm JWTAlgorithm
Secret []byte
PrivateKey *rsa.PrivateKey
PublicKey *rsa.PublicKey
AccessTokenExpiry time.Duration
RefreshTokenExpiry time.Duration
Issuer string
Audience string
ValidateIssuer bool
ValidateAudience bool
RequireMFA bool
MaxTokensPerUser int
}
JWTConfig holds JWT configuration
func DefaultJWTConfig ¶ added in v1.0.10
func DefaultJWTConfig() *JWTConfig
DefaultJWTConfig returns default JWT configuration
type JWTService ¶ added in v1.0.10
type JWTService struct {
// contains filtered or unexported fields
}
JWTService handles JWT token operations
func NewJWTService ¶ added in v1.0.10
func NewJWTService(config *JWTConfig, auditLogger *opsec.SecureAuditLog) (*JWTService, error)
NewJWTService creates a new JWT service
func (*JWTService) GenerateAPIToken ¶ added in v1.0.10
func (s *JWTService) GenerateAPIToken(apiKey *APIKey) (string, error)
GenerateAPIToken generates a token for API key authentication
func (*JWTService) GenerateTokenPair ¶ added in v1.0.10
func (s *JWTService) GenerateTokenPair(user *User, customClaims map[string]interface{}) (*TokenPair, error)
GenerateTokenPair generates access and refresh tokens for a user
func (*JWTService) GetActiveTokenInfo ¶ added in v1.0.10
func (s *JWTService) GetActiveTokenInfo(userID string) (*TokenPair, bool)
GetActiveTokenInfo returns information about an active token
func (*JWTService) RefreshTokenPair ¶ added in v1.0.10
func (s *JWTService) RefreshTokenPair(refreshTokenString string) (*TokenPair, error)
RefreshTokenPair refreshes an access token using a refresh token
func (*JWTService) RevokeAllUserTokens ¶ added in v1.0.10
func (s *JWTService) RevokeAllUserTokens(userID, reason string) error
RevokeAllUserTokens revokes all tokens for a user
func (*JWTService) RevokeToken ¶ added in v1.0.10
func (s *JWTService) RevokeToken(tokenString, reason string) error
RevokeToken revokes a token
func (*JWTService) ValidateToken ¶ added in v1.0.10
func (s *JWTService) ValidateToken(tokenString string) (*JWTToken, error)
ValidateToken validates a JWT token and returns the claims
type JWTToken ¶ added in v1.0.10
type JWTToken struct {
Claims *JWTClaims
RawHeader string
RawPayload string
RawSignature string
Signature []byte
Valid bool
Errors []error
}
JWTToken represents a parsed JWT token
type LocalUserConfig ¶
LocalUserConfig holds local user credentials
type LocalUserInfo ¶
LocalUserInfo holds public user information
type LoginResult ¶
type LoginResult struct {
Success bool `json:"success"`
Token string `json:"token"`
Error string `json:"error"`
ExpiresAt time.Time `json:"expires_at"`
}
LoginResult represents the result of a login attempt
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager handles authentication and session management
func NewManager ¶
NewManager creates a new authentication manager
func (*Manager) CreateLocalUser ¶
CreateLocalUser creates a new local user
func (*Manager) CreateSession ¶
CreateSession creates a new authenticated session
func (*Manager) GetActiveSessions ¶
GetActiveSessions returns all active sessions
func (*Manager) GetSession ¶
GetSession retrieves a session by ID
func (*Manager) GetSessionFromContext ¶
GetSessionFromContext retrieves session from request context
func (*Manager) GetSessionFromRequest ¶
GetSessionFromRequest extracts session from HTTP request cookie
func (*Manager) GetUserFromContext ¶
GetUserFromContext retrieves user from request context
func (*Manager) GetUserSessions ¶
GetUserSessions returns all sessions for a user
func (*Manager) HandleOAuthCallback ¶
func (m *Manager) HandleOAuthCallback(w http.ResponseWriter, r *http.Request)
HandleOAuthCallback processes the OAuth callback response.
func (*Manager) InitOAuthFlow ¶
func (m *Manager) InitOAuthFlow(w http.ResponseWriter, r *http.Request)
InitOAuthFlow initiates the OAuth authentication flow. InitOAuthFlow initiates OAuth authentication flow for the given provider.
func (*Manager) InvalidateSession ¶
InvalidateSession marks a session as inactive
func (*Manager) InvalidateUserSessions ¶
InvalidateUserSessions invalidates all sessions for a user
func (*Manager) ListLocalUsers ¶
func (m *Manager) ListLocalUsers() []LocalUserInfo
ListLocalUsers returns all local users
func (*Manager) LocalLogin ¶
func (m *Manager) LocalLogin(w http.ResponseWriter, r *http.Request)
LocalLogin handles local username/password authentication
func (*Manager) OptionalAuth ¶
OptionalAuth middleware adds user to context if authenticated, but doesn't require it
func (*Manager) RefreshSession ¶
RefreshSession extends session expiration
func (*Manager) RequireAdmin ¶
RequireAdmin middleware ensures user is an admin
func (*Manager) RequireAuth ¶
RequireAuth middleware ensures user is authenticated
func (*Manager) RequirePermission ¶
RequirePermission middleware checks if user has specific permission
type OAuthEndpoints ¶
OAuthEndpoints holds OAuth provider endpoint URLs. OAuthEndpoints defines OAuth provider endpoint URLs.
type OAuthTokenResponse ¶
type OAuthTokenResponse struct {
AccessToken string
TokenType string
ExpiresIn int
RefreshToken string
IDToken string
Scope string
}
OAuthTokenResponse contains OAuth token response data. OAuthTokenResponse contains the OAuth token response from the provider.
type OAuthUserInfo ¶
type OAuthUserInfo struct {
ID string
Email string
Name string
GivenName string
FamilyName string
Picture string
VerifiedEmail bool
Provider string
}
OAuthUserInfo contains user information from OAuth provider. OAuthUserInfo represents user information returned by OAuth provider.
type Permission ¶
type Permission string
Permission represents a specific authorization permission
const ( // PermViewDashboard is the permission to view the dashboard. PermViewDashboard Permission = "view:dashboard" PermManagePolicies Permission = "manage:policies" PermManageCerts Permission = "manage:certificates" PermViewLogs Permission = "view:logs" PermManageUsers Permission = "manage:users" PermViewReports Permission = "view:reports" PermSystemConfig Permission = "system:config" PermViewAlerts Permission = "view:alerts" )
type Provider ¶
type Provider string
Provider represents an authentication provider type
const ( // ProviderGoogle identifies the Google OAuth provider. ProviderGoogle Provider = "google" // ProviderMicrosoft identifies the Microsoft OAuth provider. ProviderMicrosoft Provider = "microsoft" ProviderGitHub Provider = "github" ProviderOkta Provider = "okta" ProviderAuth0 Provider = "auth0" ProviderGeneric Provider = "generic_oauth" ProviderSAMLGeneric Provider = "saml" ProviderSAMLAzure Provider = "saml_azure" ProviderSALMOkta Provider = "saml_okta" ProviderLocal Provider = "local" )
type Session ¶
type Session struct {
ID string
UserID string
User *User
CreatedAt time.Time
ExpiresAt time.Time
LastActivity time.Time
IPAddress string
UserAgent string
Active bool
}
Session represents an authenticated session
func (*Session) IsExpired ¶
IsExpired checks if the session has expired. IsExpired checks if the session has expired.
type TokenPair ¶ added in v1.0.10
type TokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
ExpiresAt time.Time `json:"expires_at"`
}
TokenPair represents an access token and refresh token pair
type User ¶
type User struct {
ID string
Email string
Name string
Provider Provider
ProviderID string
Role Role
Permissions []Permission
Attributes map[string]interface{}
SessionID string
Authenticated bool
LastLogin time.Time
CreatedAt time.Time
}
User represents an authenticated user
func GetUserFromContext ¶ added in v1.0.10
GetUserFromContext retrieves the user from the request context
func (*User) HasPermission ¶
func (u *User) HasPermission(perm Permission) bool
HasPermission checks if the user has a specific permission. HasPermission checks if the user has a specific permission.