auth

package
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2026 License: MIT Imports: 21 Imported by: 0

README

AegisGate Authentication Package

Enterprise-grade authentication system for AegisGate.

Features

  • OAuth 2.0 (Google, Microsoft, GitHub, Okta, Auth0)
  • SAML 2.0 support (Azure, Okta)
  • Local username/password authentication
  • Role-Based Access Control (RBAC)
  • Session management with secure cookies
  • Zero external dependencies

Files

  • auth.go - Core types and configuration
  • utils.go - Helper functions
  • session.go - Session management
  • local.go - Local authentication
  • oauth.go - OAuth 2.0 implementation
  • middleware.go - HTTP middleware
  • handlers.go - HTTP handlers
  • auth_test.go - Unit tests

Status

Build: SUCCESS Vet: PASSED Dependencies: Zero external (Go standard library only)

Documentation

Index

Constants

This section is empty.

Variables

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

RolePermissions maps roles to permissions.

Functions

func ConstantTimeCompare added in v1.0.10

func ConstantTimeCompare(a, b string) bool

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

func RequireRole(roles ...Role) func(http.Handler) http.Handler

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) IsExpired added in v1.0.10

func (k *APIKey) IsExpired() bool

IsExpired checks if the API key has expired

func (*APIKey) IsValid added in v1.0.10

func (k *APIKey) IsValid() bool

IsValid checks if the API key is valid for use

func (*APIKey) MarshalJSON added in v1.0.10

func (k *APIKey) MarshalJSON() ([]byte, error)

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

func (*Config) Validate

func (c *Config) Validate() error

Validate validates the 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

func GetClaimsFromContext added in v1.0.10

func GetClaimsFromContext(ctx context.Context) (*JWTClaims, bool)

GetClaimsFromContext retrieves the JWT claims from the request context

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 JWTHeader added in v1.0.10

type JWTHeader struct {
	Algorithm string `json:"alg"`
	Type      string `json:"typ"`
}

JWTHeader represents the JWT header

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

type LocalUserConfig struct {
	PasswordHash string
	Salt         string
	Role         Role
	Enabled      bool
}

LocalUserConfig holds local user credentials

type LocalUserInfo

type LocalUserInfo struct {
	Username string
	Role     Role
	Enabled  bool
}

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

func NewManager(config *Config) (*Manager, error)

NewManager creates a new authentication manager

func (*Manager) Close

func (m *Manager) Close()

Close shuts down the authentication manager

func (*Manager) CreateLocalUser

func (m *Manager) CreateLocalUser(username, password string, role Role) error

CreateLocalUser creates a new local user

func (*Manager) CreateSession

func (m *Manager) CreateSession(user *User, r *http.Request) (*Session, error)

CreateSession creates a new authenticated session

func (*Manager) GetActiveSessions

func (m *Manager) GetActiveSessions() []*Session

GetActiveSessions returns all active sessions

func (*Manager) GetConfig

func (m *Manager) GetConfig() *Config

GetConfig returns the authentication configuration

func (*Manager) GetSession

func (m *Manager) GetSession(sessionID string) (*Session, error)

GetSession retrieves a session by ID

func (*Manager) GetSessionFromContext

func (m *Manager) GetSessionFromContext(ctx context.Context) *Session

GetSessionFromContext retrieves session from request context

func (*Manager) GetSessionFromRequest

func (m *Manager) GetSessionFromRequest(r *http.Request) (*Session, error)

GetSessionFromRequest extracts session from HTTP request cookie

func (*Manager) GetUserFromContext

func (m *Manager) GetUserFromContext(ctx context.Context) *User

GetUserFromContext retrieves user from request context

func (*Manager) GetUserSessions

func (m *Manager) GetUserSessions(userID string) []*Session

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) Handler

func (m *Manager) Handler() http.Handler

Handler returns HTTP handlers for authentication

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

func (m *Manager) InvalidateSession(sessionID string) error

InvalidateSession marks a session as inactive

func (*Manager) InvalidateUserSessions

func (m *Manager) InvalidateUserSessions(userID string)

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) Logout

func (m *Manager) Logout(w http.ResponseWriter, r *http.Request) error

Logout handles user logout

func (*Manager) OptionalAuth

func (m *Manager) OptionalAuth(next http.Handler) http.Handler

OptionalAuth middleware adds user to context if authenticated, but doesn't require it

func (*Manager) RefreshSession

func (m *Manager) RefreshSession(sessionID string) error

RefreshSession extends session expiration

func (*Manager) RequireAdmin

func (m *Manager) RequireAdmin(next http.Handler) http.Handler

RequireAdmin middleware ensures user is an admin

func (*Manager) RequireAuth

func (m *Manager) RequireAuth(next http.Handler) http.Handler

RequireAuth middleware ensures user is authenticated

func (*Manager) RequirePermission

func (m *Manager) RequirePermission(permission Permission) func(http.Handler) http.Handler

RequirePermission middleware checks if user has specific permission

func (*Manager) RequireRole

func (m *Manager) RequireRole(role Role) func(http.Handler) http.Handler

RequireRole middleware checks if user has specific role

type OAuthEndpoints

type OAuthEndpoints struct {
	AuthURL     string
	TokenURL    string
	UserInfoURL string
	Scopes      []string
}

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 Role

type Role string

Role represents user authorization level

const (

	// RoleAdmin defines the administrator role level.
	RoleAdmin Role = "admin"
	// RoleOperator defines the operator role level.
	RoleOperator Role = "operator"
	RoleViewer   Role = "viewer"
	RoleService  Role = "service"
)

func (Role) AtLeast

func (r Role) AtLeast(required Role) bool

AtLeast returns true if this role has at least the required level

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

func (s *Session) IsExpired() bool

IsExpired checks if the session has expired. IsExpired checks if the session has expired.

func (*Session) IsValid

func (s *Session) IsValid() bool

IsValid checks if the session is valid and not expired. IsValid checks if the session is valid and not expired.

func (*Session) Refresh

func (s *Session) Refresh(duration time.Duration)

Refresh updates the session expiration time. Refresh updates the session expiration time.

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

func GetUserFromContext(ctx context.Context) (*User, bool)

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.

func (*User) IsAdmin

func (u *User) IsAdmin() bool

IsAdmin returns true if user has admin role. IsAdmin returns true if user has admin role.

Jump to

Keyboard shortcuts

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