auth

package
v0.0.0-...-92dd6e1 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: MIT Imports: 12 Imported by: 0

Documentation

Overview

Package auth provides authentication for Bifrost.

Package auth provides authentication for Bifrost.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidCredentials    = errors.New("invalid credentials")
	ErrUserNotFound          = errors.New("user not found")
	ErrUserDisabled          = errors.New("user disabled")
	ErrAuthRequired          = errors.New("authentication required")
	ErrAuthMethodUnsupported = errors.New("authentication method not supported")
	ErrConfigInvalid         = errors.New("invalid auth configuration")
	ErrConnectionFailed      = errors.New("authentication service connection failed")
	ErrTimeout               = errors.New("authentication timeout")
)

Common authentication errors.

Functions

func ExtractBasicAuth

func ExtractBasicAuth(r *http.Request) (username, password string, ok bool)

ExtractBasicAuth extracts Basic auth credentials from a request.

func ExtractBearerToken

func ExtractBearerToken(r *http.Request) (string, bool)

ExtractBearerToken extracts a Bearer token from the Authorization header.

func ExtractProxyAuth

func ExtractProxyAuth(r *http.Request) (username, password string, ok bool)

ExtractProxyAuth extracts Proxy-Authorization credentials from a request.

func ExtractProxyBearerToken

func ExtractProxyBearerToken(r *http.Request) (string, bool)

ExtractProxyBearerToken extracts a Bearer token from the Proxy-Authorization header.

func GetAllPlugins

func GetAllPlugins() map[string]Plugin

GetAllPlugins returns a map of all registered plugins.

func GetClientCert

func GetClientCert(ctx context.Context) *x509.Certificate

GetClientCert retrieves the client certificate from the context.

func HashPassword

func HashPassword(password string) (string, error)

HashPassword creates a bcrypt hash of a password. This is a convenience function for creating password hashes.

func IsAuthRequired

func IsAuthRequired(err error) bool

IsAuthRequired checks if an error indicates authentication is required.

func IsInvalidCredentials

func IsInvalidCredentials(err error) bool

IsInvalidCredentials checks if an error indicates invalid credentials.

func ListPlugins

func ListPlugins() []string

ListPlugins returns a sorted list of all registered plugin names.

func RegisterPlugin

func RegisterPlugin(name string, p Plugin)

RegisterPlugin registers a plugin with the given name. This is typically called from init() functions in plugin packages. If a plugin with the same name is already registered, it will be overwritten.

Types

type AuthError

type AuthError struct {
	Authenticator string
	Operation     string
	Err           error
}

AuthError wraps an authentication error with additional context.

func NewAuthError

func NewAuthError(authenticator, op string, err error) *AuthError

NewAuthError creates a new AuthError.

func (*AuthError) Error

func (e *AuthError) Error() string

func (*AuthError) Unwrap

func (e *AuthError) Unwrap() error

type Authenticator

type Authenticator interface {
	// Authenticate validates credentials and returns user info.
	Authenticate(ctx context.Context, username, password string) (*UserInfo, error)

	// Name returns the authenticator name.
	Name() string

	// Type returns the authenticator type.
	Type() string
}

Authenticator is the interface for authentication providers.

type BruteForceConfig

type BruteForceConfig struct {
	// MaxAttempts is the maximum failed attempts before lockout (default: 5)
	MaxAttempts int `yaml:"max_attempts"`
	// LockoutTime is the initial lockout duration (default: 1 minute)
	LockoutTime time.Duration `yaml:"lockout_time"`
	// MaxLockout is the maximum lockout duration for exponential backoff (default: 1 hour)
	MaxLockout time.Duration `yaml:"max_lockout"`
	// WindowSize is the time window for counting attempts (default: 15 minutes)
	WindowSize time.Duration `yaml:"window_size"`
}

BruteForceConfig configures brute force protection.

type BruteForceProtector

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

BruteForceProtector protects against brute force authentication attacks. It tracks failed login attempts per IP address and username, implementing exponential backoff for repeated failures.

func NewBruteForceProtector

func NewBruteForceProtector(cfg BruteForceConfig) *BruteForceProtector

NewBruteForceProtector creates a new brute force protector.

func (*BruteForceProtector) Close

func (bf *BruteForceProtector) Close()

Close stops the cleanup goroutine.

func (*BruteForceProtector) GetLockoutRemaining

func (bf *BruteForceProtector) GetLockoutRemaining(key string) time.Duration

GetLockoutRemaining returns the remaining lockout time for a key. Returns 0 if not locked out.

func (*BruteForceProtector) IsAllowed

func (bf *BruteForceProtector) IsAllowed(key string) bool

IsAllowed checks if an authentication attempt is allowed for the given key. The key should be a combination of IP address and/or username. Returns true if allowed, false if blocked due to too many failed attempts.

func (*BruteForceProtector) RecordFailure

func (bf *BruteForceProtector) RecordFailure(key string)

RecordFailure records a failed authentication attempt.

func (*BruteForceProtector) RecordSuccess

func (bf *BruteForceProtector) RecordSuccess(key string)

RecordSuccess records a successful authentication, resetting the tracker.

func (*BruteForceProtector) Stats

Stats returns statistics about the brute force protector.

type BruteForceStats

type BruteForceStats struct {
	TrackedKeys     int           `json:"tracked_keys"`
	CurrentLockouts int           `json:"current_lockouts"`
	MaxAttempts     int           `json:"max_attempts"`
	LockoutTime     time.Duration `json:"lockout_time"`
	WindowSize      time.Duration `json:"window_size"`
}

BruteForceStats holds statistics about brute force protection.

type ChainAuthenticator

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

ChainAuthenticator tries multiple authenticators in priority order.

func NewChainAuthenticator

func NewChainAuthenticator() *ChainAuthenticator

NewChainAuthenticator creates a new chain authenticator.

func (*ChainAuthenticator) AddAuthenticator

func (c *ChainAuthenticator) AddAuthenticator(name string, priority int, auth Authenticator)

AddAuthenticator adds an authenticator to the chain.

func (*ChainAuthenticator) Authenticate

func (c *ChainAuthenticator) Authenticate(ctx context.Context, username, password string) (*UserInfo, error)

Authenticate tries each authenticator in priority order. Returns success on the first successful authentication. Returns ErrInvalidCredentials if all authenticators fail.

func (*ChainAuthenticator) Authenticators

func (c *ChainAuthenticator) Authenticators() []string

Authenticators returns the list of authenticator names in priority order.

func (*ChainAuthenticator) Count

func (c *ChainAuthenticator) Count() int

Count returns the number of authenticators in the chain.

func (*ChainAuthenticator) Name

func (c *ChainAuthenticator) Name() string

Name returns the chain authenticator name.

func (*ChainAuthenticator) Type

func (c *ChainAuthenticator) Type() string

Type returns the authenticator type.

type ContextKey

type ContextKey string

ContextKey is a type for context keys used by the auth package.

const (
	// UserInfoContextKey is the context key for user information.
	UserInfoContextKey ContextKey = "auth_user_info"
	// ClientCertContextKey is the context key for client certificate.
	ClientCertContextKey ContextKey = "auth_client_cert"
)

type Factory

type Factory struct{}

Factory creates authenticators from provider configurations.

func NewFactory

func NewFactory() *Factory

NewFactory creates a new authenticator factory.

func (*Factory) Create

func (f *Factory) Create(cfg ProviderConfig) (Authenticator, error)

Create creates a single authenticator from a provider configuration.

func (*Factory) CreateChain

func (f *Factory) CreateChain(providers []ProviderConfig) (Authenticator, error)

CreateChain creates a chain authenticator from multiple provider configurations. Providers are sorted by priority (lowest first) and only enabled providers are included.

func (*Factory) ValidateProviders

func (f *Factory) ValidateProviders(providers []ProviderConfig) error

ValidateProviders validates a list of provider configurations without creating authenticators.

type HTTPCredentials

type HTTPCredentials struct {
	Username string
	Password string
	Token    string
}

HTTPCredentials extracts credentials from an HTTP request.

type Middleware

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

Middleware provides HTTP authentication middleware.

func NewMiddleware

func NewMiddleware(authenticator Authenticator, realm string) *Middleware

NewMiddleware creates a new auth middleware.

func (*Middleware) Authenticate

func (m *Middleware) Authenticate(ctx context.Context, username, password string) (*UserInfo, error)

Authenticate performs authentication and returns the user info.

func (*Middleware) AuthenticateForProxy

func (m *Middleware) AuthenticateForProxy(ctx context.Context, username, password string) (*UserInfo, error)

AuthenticateForProxy authenticates for proxy use (returns user or anonymous).

func (*Middleware) Handler

func (m *Middleware) Handler(next http.Handler) http.Handler

Handler wraps an HTTP handler with authentication.

func (*Middleware) MultiAuthHandler

func (m *Middleware) MultiAuthHandler(next http.Handler) http.Handler

MultiAuthHandler wraps an HTTP handler with multiple authentication methods. It supports: Basic auth, Bearer tokens, API keys, and client certificates.

func (*Middleware) MultiProxyAuthHandler

func (m *Middleware) MultiProxyAuthHandler(next http.Handler) http.Handler

MultiProxyAuthHandler wraps an HTTP handler with multiple proxy authentication methods.

func (*Middleware) ProxyHandler

func (m *Middleware) ProxyHandler(next http.Handler) http.Handler

ProxyHandler wraps an HTTP handler with proxy authentication.

func (*Middleware) SetAPIKeyAuth

func (m *Middleware) SetAPIKeyAuth(auth Authenticator, headerName string)

SetAPIKeyAuth sets an API key authenticator and header name.

type Mode

type Mode string

Mode represents an authentication mode.

const (
	// ModeNone disables authentication.
	ModeNone Mode = "none"
	// ModeNative uses native username/password authentication.
	ModeNative Mode = "native"
	// ModeSystem uses system authentication (PAM on Linux, etc.)
	ModeSystem Mode = "system"
	// ModeLDAP uses LDAP authentication.
	ModeLDAP Mode = "ldap"
	// ModeOAuth uses OAuth/OIDC authentication.
	ModeOAuth Mode = "oauth"
)

type Plugin

type Plugin interface {
	// Type returns the plugin type identifier (e.g., "native", "ldap", "oauth").
	Type() string

	// Description returns a human-readable description of the plugin.
	Description() string

	// Create creates an authenticator instance from the given configuration.
	// The config map contains plugin-specific configuration values.
	Create(config map[string]any) (Authenticator, error)

	// ValidateConfig validates the configuration without creating an authenticator.
	// Returns an error if the configuration is invalid.
	ValidateConfig(config map[string]any) error

	// DefaultConfig returns the default configuration for this plugin.
	DefaultConfig() map[string]any

	// ConfigSchema returns a JSON schema describing the configuration options.
	// This can be used for documentation and validation by UI tools.
	// Returns an empty string if no schema is available.
	ConfigSchema() string
}

Plugin is the interface for authentication plugins. Each plugin is responsible for creating and configuring its authenticator type.

func GetPlugin

func GetPlugin(name string) (Plugin, bool)

GetPlugin returns a plugin by name. Returns nil and false if the plugin is not found.

type PluginInfo

type PluginInfo struct {
	Name          string         `json:"name"`
	Type          string         `json:"type"`
	Description   string         `json:"description"`
	DefaultConfig map[string]any `json:"default_config,omitempty"`
	ConfigSchema  string         `json:"config_schema,omitempty"`
}

PluginInfo contains information about a registered plugin.

func GetPluginInfo

func GetPluginInfo(name string) (*PluginInfo, bool)

GetPluginInfo returns information about a specific plugin.

func ListPluginInfo

func ListPluginInfo() []PluginInfo

ListPluginInfo returns information about all registered plugins.

type ProviderConfig

type ProviderConfig struct {
	// Name is a unique identifier for this provider instance.
	Name string `yaml:"name" json:"name"`

	// Type is the plugin type (e.g., "native", "ldap", "oauth").
	Type string `yaml:"type" json:"type"`

	// Enabled indicates whether this provider is active.
	Enabled bool `yaml:"enabled" json:"enabled"`

	// Priority determines the order in which providers are tried (lower = first).
	Priority int `yaml:"priority" json:"priority"`

	// Config contains plugin-specific configuration.
	Config map[string]any `yaml:"config,omitempty" json:"config,omitempty"`
}

ProviderConfig represents a single authentication provider configuration.

type Result

type Result struct {
	Authenticated bool
	User          *UserInfo
	Error         error
}

Result represents an authentication result.

type UserInfo

type UserInfo struct {
	Username string            `json:"username"`
	Groups   []string          `json:"groups,omitempty"`
	Email    string            `json:"email,omitempty"`
	FullName string            `json:"full_name,omitempty"`
	Metadata map[string]string `json:"metadata,omitempty"`
}

UserInfo contains information about an authenticated user.

func GetUserInfo

func GetUserInfo(ctx context.Context) *UserInfo

GetUserInfo retrieves user information from the context.

Directories

Path Synopsis
Package mfa provides multi-factor authentication wrapper for Bifrost.
Package mfa provides multi-factor authentication wrapper for Bifrost.
Package negotiate provides HTTP Negotiate (SPNEGO/Kerberos/NTLM) authentication handling.
Package negotiate provides HTTP Negotiate (SPNEGO/Kerberos/NTLM) authentication handling.
plugin
apikey
Package apikey provides API key authentication for Bifrost.
Package apikey provides API key authentication for Bifrost.
hotp
Package hotp provides HMAC-based One-Time Password (HOTP) authentication for Bifrost.
Package hotp provides HMAC-based One-Time Password (HOTP) authentication for Bifrost.
jwt
Package jwt provides JWT token authentication for Bifrost.
Package jwt provides JWT token authentication for Bifrost.
kerberos
Package kerberos provides Kerberos/SPNEGO authentication for Bifrost.
Package kerberos provides Kerberos/SPNEGO authentication for Bifrost.
ldap
Package ldap provides LDAP/Active Directory authentication.
Package ldap provides LDAP/Active Directory authentication.
mtls
Package mtls provides mutual TLS (client certificate) authentication for Bifrost.
Package mtls provides mutual TLS (client certificate) authentication for Bifrost.
native
Package native provides username/password authentication with bcrypt hashes.
Package native provides username/password authentication with bcrypt hashes.
none
Package none provides the "none" authentication plugin which allows all requests.
Package none provides the "none" authentication plugin which allows all requests.
ntlm
Package ntlm provides NTLM/Negotiate authentication for Bifrost.
Package ntlm provides NTLM/Negotiate authentication for Bifrost.
oauth
Package oauth provides OAuth/OIDC authentication for Bifrost.
Package oauth provides OAuth/OIDC authentication for Bifrost.
system
Package system provides system (PAM) authentication for Bifrost.
Package system provides system (PAM) authentication for Bifrost.
totp
Package totp provides Time-based One-Time Password (TOTP) authentication for Bifrost.
Package totp provides Time-based One-Time Password (TOTP) authentication for Bifrost.
Package session provides session token storage and management for Bifrost.
Package session provides session token storage and management for Bifrost.

Jump to

Keyboard shortcuts

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