auth

package
v1.0.39 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MinPasswordLength is the shortest accepted local password.
	MinPasswordLength = 12
	// MaxPasswordLength bounds the bcrypt input: bcrypt only considers the
	// first 72 bytes, so longer inputs must be rejected rather than silently
	// truncated.
	MaxPasswordLength = 72
)
View Source
const SessionCookie = "cp_session"

SessionCookie is the browser cookie that carries a session or API token for WebSocket upgrades and file downloads. Those clients cannot set an Authorization header. The token must not be placed in the URL (MINE-185).

View Source
const UserContextKey contextKey = "authenticated_user"

Variables

View Source
var (
	ErrInvalidCredentials   = errors.New("invalid credentials")
	ErrUserNotActive        = errors.New("user is not active")
	ErrInvalidToken         = errors.New("invalid token")
	ErrSessionExpired       = errors.New("session expired")
	ErrLocalAuthDisabled    = errors.New("local authentication is disabled")
	ErrRegistrationDisabled = errors.New("registration is disabled")
	ErrSessionTimeoutMin    = errors.New("session timeout must be at least 300 seconds (5 minutes)")
	ErrAPITokenExpired      = errors.New("api token has expired")
	ErrAPITokenNotFound     = errors.New("api token not found")
	ErrInvalidRecoveryKey   = errors.New("invalid recovery key")
	// ErrNoAuthProvider is returned when the configuration would leave the
	// panel with no authentication provider and no explicit opt-in to run
	// without authentication.
	ErrNoAuthProvider = errors.New("no authentication provider is enabled")
)
View Source
var ErrPasswordTooWeak = errors.New("password does not meet the minimum requirements")

ErrPasswordTooWeak is returned when a password does not satisfy the policy.

Functions

func GenerateRecoveryCodes added in v1.0.39

func GenerateRecoveryCodes(n int) ([]string, error)

GenerateRecoveryCodes returns n random recovery codes.

func GenerateTOTPSecret added in v1.0.39

func GenerateTOTPSecret() (string, error)

GenerateTOTPSecret returns a base32-encoded 20-byte secret suitable for TOTP.

func SessionTokenFromRequest added in v1.0.39

func SessionTokenFromRequest(r *http.Request) string

SessionTokenFromRequest returns the session or API token from the Authorization header, then from SessionCookie. A ?token= query value is ignored so it cannot land in access logs, Referer, or browser history.

func TOTPCode added in v1.0.39

func TOTPCode(secret string, t time.Time) (string, error)

TOTPCode returns the current 6-digit code for secret at t.

func ValidatePassword

func ValidatePassword(password string) error

ValidatePassword enforces the minimum policy for local accounts: at least MinPasswordLength characters, at most MaxPasswordLength bytes, at least two of four character classes, and not a well-known weak password.

func ValidateTOTP added in v1.0.39

func ValidateTOTP(secret, code string, t time.Time, window int) bool

ValidateTOTP reports whether code matches the secret within +/- window steps.

func VerifyCaptcha added in v1.0.39

func VerifyCaptcha(token, provider string) error

VerifyCaptcha validates a captcha token with the configured provider. Returns nil when verification succeeds or captcha is disabled.

func WithUser

func WithUser(ctx context.Context, user *AuthenticatedUser) context.Context

WithUser adds the authenticated user to context

Types

type AuthenticatedUser

type AuthenticatedUser struct {
	ID       string
	Username string
	Email    string
	Roles    []string
	Provider string // "local" or "oidc"
}

AuthenticatedUser represents a validated user in context

func GetUserFromContext

func GetUserFromContext(ctx context.Context) *AuthenticatedUser

GetUserFromContext retrieves the authenticated user from context

type LoginThrottle

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

LoginThrottle is a small in-memory limiter that slows online password guessing. Callers key it by client IP and by username; a key is blocked for a cooldown once it exceeds the failure threshold inside the window.

It is intentionally in-memory: the panel is a single process, and a restart clearing the counters is an acceptable trade-off against adding write load to the database on every failed login.

func NewLoginThrottle

func NewLoginThrottle() *LoginThrottle

NewLoginThrottle returns a throttle allowing 5 failures per 5 minutes before a 15 minute lockout.

func NewLoginThrottleWithLimits

func NewLoginThrottleWithLimits(max int, window, lockout time.Duration) *LoginThrottle

NewLoginThrottleWithLimits returns a throttle with custom thresholds. The username limiter uses a low ceiling (targeted guessing), while the client-IP limiter uses a higher one so a single attacker behind a shared NAT or reverse proxy cannot lock every user out.

func (*LoginThrottle) Allow

func (t *LoginThrottle) Allow(key string) (bool, time.Duration)

Allow reports whether an attempt for key may proceed and, if not, the time remaining in the lockout.

func (*LoginThrottle) Count

func (t *LoginThrottle) Count() int

Count returns the current number of tracked keys.

func (*LoginThrottle) Failure

func (t *LoginThrottle) Failure(key string) time.Duration

Failure records a failed attempt for key and returns the lockout duration if the key was just blocked.

func (*LoginThrottle) Prune

func (t *LoginThrottle) Prune() int

Prune sweeps and removes all expired entries, returning the number of evicted keys.

func (*LoginThrottle) Reset

func (t *LoginThrottle) Reset(key string)

Reset clears the failure state for key after a successful login.

type Manager

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

func NewManager

func NewManager(store *db.Store, enforcer *rbac.Enforcer, cfg *config.AuthConfig) (*Manager, error)

func (*Manager) AnonymousUser

func (m *Manager) AnonymousUser() *AuthenticatedUser

func (*Manager) AuthenticateFromHeader

func (m *Manager) AuthenticateFromHeader(ctx context.Context, authHeader string) (*AuthenticatedUser, error)

AuthenticateFromHeader validates the bearer token from an Authorization header value. Handles session tokens, API tokens, no-auth bypass, and anonymous access.

func (*Manager) ChangePassword

func (m *Manager) ChangePassword(ctx context.Context, userID, oldPassword, newPassword string) error

func (*Manager) CreateLocalUser

func (m *Manager) CreateLocalUser(ctx context.Context, username, email, password string) (*db.User, error)

func (*Manager) GenerateAPIToken

func (m *Manager) GenerateAPIToken(ctx context.Context, userID, name string, expiresInDays *int32) (string, *db.APIToken, error)

Creates a new API token for a user. Plaintext is returned, SHA-256 hash is stored

func (*Manager) GenerateModuleToken

func (m *Manager) GenerateModuleToken(ctx context.Context, userID, moduleName, moduleID string) (string, *db.APIToken, error)

Creates API token for a module, tied to the creating user's identity

func (*Manager) GetConfig

func (m *Manager) GetConfig() *config.AuthConfig

func (*Manager) GetRecoveryKey

func (m *Manager) GetRecoveryKey() string

func (*Manager) InvalidateUserSessions

func (m *Manager) InvalidateUserSessions(ctx context.Context, userID, exceptToken string) error

InvalidateUserSessions deletes every stored session for userID except the one identified by exceptToken (pass "" to delete all). It is called after a password change so a stolen session cannot outlive the credential rotation.

func (*Manager) IsAnonymousAccessEnabled

func (m *Manager) IsAnonymousAccessEnabled() bool

func (*Manager) IsAnyAuthEnabled

func (m *Manager) IsAnyAuthEnabled() bool

func (*Manager) IsLocalAuthEnabled

func (m *Manager) IsLocalAuthEnabled() bool

func (*Manager) IsRegistrationAllowed

func (m *Manager) IsRegistrationAllowed() bool

func (*Manager) Login

func (m *Manager) Login(ctx context.Context, username, password string) (*db.User, []string, string, time.Time, error)

func (*Manager) Logout

func (m *Manager) Logout(ctx context.Context, token string) error

func (*Manager) NoAuthAllowed

func (m *Manager) NoAuthAllowed() bool

NoAuthAllowed reports whether the operator explicitly permitted the panel to run without any authentication provider.

func (*Manager) RecoveryKeyCreated

func (m *Manager) RecoveryKeyCreated() bool

RecoveryKeyCreated reports whether this process generated a new key. Later starts adopt the stored key and must not print it again.

func (*Manager) RotateRecoveryKey

func (m *Manager) RotateRecoveryKey(ctx context.Context) (string, error)

RotateRecoveryKey replaces the break-glass key. The previous key stops working.

func (*Manager) UpdateSettings

func (m *Manager) UpdateSettings(ctx context.Context, localEnabled, allowReg, anonAccess *bool, sessionTimeout *int32) error

UpdateSettings updates mutable auth settings. Only non-nil parameters are applied.

func (*Manager) UseRecoveryKey

func (m *Manager) UseRecoveryKey(ctx context.Context, key string) error

func (*Manager) ValidateAPIToken

func (m *Manager) ValidateAPIToken(ctx context.Context, rawToken string) (*AuthenticatedUser, error)

Validates a raw API token (dp_...) and returns the authenticated user.

func (*Manager) ValidateSession

func (m *Manager) ValidateSession(ctx context.Context, token string) (*AuthenticatedUser, error)

type OIDCHandler

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

func NewOIDCHandler

func NewOIDCHandler(manager *Manager, store *db.Store, cfg *config.OIDCConfig, log *logger.Logger) (*OIDCHandler, error)

func (*OIDCHandler) HandleCallback

func (h *OIDCHandler) HandleCallback(w http.ResponseWriter, r *http.Request)

func (*OIDCHandler) HandleLogin

func (h *OIDCHandler) HandleLogin(w http.ResponseWriter, r *http.Request)

func (*OIDCHandler) IsEnabled

func (h *OIDCHandler) IsEnabled() bool

type WebAuthnChallenge added in v1.0.39

type WebAuthnChallenge struct {
	Challenge string
	RPID      string
}

WebAuthnChallenge represents a registration/authentication challenge.

func BeginPasskeyRegistration added in v1.0.39

func BeginPasskeyRegistration(userID string) (WebAuthnChallenge, error)

BeginPasskeyRegistration creates a challenge for a new passkey (MINE-198).

Jump to

Keyboard shortcuts

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