Documentation
¶
Overview ¶
Package auth handles user authentication: password hashing, JWT issuance with revocable sessions, and password resets.
Index ¶
- Constants
- Variables
- func NormalizeScopes(scopes []string) ([]string, error)
- func SessionFingerprint(key []byte, passwordHash string) string
- type APIKeyService
- func (s *APIKeyService) Create(userID uint, workspaceID *uint, name string, allowedIPs, scopes []string, ...) (plaintext string, key *models.APIKey, err error)
- func (s *APIKeyService) CreateBilling(userID uint, name string, allowedIPs []string) (plaintext string, key *models.APIKey, err error)
- func (s *APIKeyService) CreateEphemeral(userID, workspaceID uint, appID *uint, name string, scopes []string, ...) (plaintext string, key *models.APIKey, err error)
- func (s *APIKeyService) Revoke(id uint) error
- func (s *APIKeyService) SetQuota(q *quota.Service)
- func (s *APIKeyService) SweepExpiredEphemeral(now time.Time) (int, error)
- func (s *APIKeyService) Verify(plaintext string) (*models.APIKey, error)
- type Service
- func (s *Service) Authenticate(identifier, password string) (*models.User, error)
- func (s *Service) BeginTwoFactorSetup(user *models.User) (secret, url string, err error)
- func (s *Service) ChangePassword(userID uint, currentPassword, newPassword string) error
- func (s *Service) CompletePasswordReset(ctx context.Context, token, newPassword string) (*models.User, error)
- func (s *Service) ConfirmEmailVerification(rawToken string) (*models.User, error)
- func (s *Service) ConfirmTwoFactor(user *models.User, code string) (recoveryCodes []string, err error)
- func (s *Service) CreateEmailVerification(user *models.User) (rawToken string, err error)
- func (s *Service) CreatePasswordReset(email string) (rawToken string, user *models.User, err error)
- func (s *Service) CreateResetSession(ctx context.Context, userID uint) (string, error)
- func (s *Service) DisableTwoFactor(user *models.User, code string) error
- func (s *Service) IssueToken(user *models.User) (token, jti string, err error)
- func (s *Service) RecoveryCodesRemaining(userID uint) int
- func (s *Service) RegenerateRecoveryCodes(user *models.User, code string) ([]string, error)
- func (s *Service) ResetPassword(rawToken, newPassword string) (uint, error)
- func (s *Service) Revoke(ctx context.Context, jti string)
- func (s *Service) SetEmailVerifications(r *repositories.EmailVerificationRepository)
- func (s *Service) SetTOTPIssuer(fn func() string)
- func (s *Service) VerifyLoginCode(user *models.User, code string) bool
- func (s *Service) VerifySecondFactor(user *models.User, code string) error
Constants ¶
const ClaimPasswordFingerprint = "pwf"
ClaimPasswordFingerprint is the session claim binding a token to the password it was issued under.
const EmailVerificationTTL = 48 * time.Hour
EmailVerificationTTL bounds a verification link. Longer than a password reset: the address may sit unread overnight, and the link grants nothing but proof the recipient can read their own mail.
const PasswordResetTTL = time.Hour
PasswordResetTTL is the lifetime of a password-reset token.
const TokenTTL = 24 * time.Hour
TokenTTL is the lifetime of an issued access token (and its session).
Variables ¶
var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrEmailTaken = errors.New("email already registered") ErrAccountDisabled = errors.New("account is disabled") ErrInvalidToken = errors.New("invalid or expired token") // ErrServiceAccountSession refuses a console session to a service account: it uses API keys only. ErrServiceAccountSession = errors.New("service accounts cannot sign in") ErrTwoFactorAlreadyEnabled = errors.New("two-factor authentication is already enabled") ErrTwoFactorNotEnabled = errors.New("two-factor authentication is not enabled") ErrTwoFactorNotInitiated = errors.New("two-factor setup has not been initiated") ErrInvalidTwoFactorCode = errors.New("invalid two-factor code") )
var ErrInvalidAPIKey = errors.New("invalid API key")
Functions ¶
func NormalizeScopes ¶
NormalizeScopes validates, deduplicates, and defaults a requested scope set. An empty set defaults to read-only; an unknown scope is an error.
func SessionFingerprint ¶ added in v1.10.12
SessionFingerprint keys the user's password hash with the JWT secret, so a session carries proof of the password it was issued under without carrying the hash. Any password change, however it is made, changes it and so ends every older session.
Types ¶
type APIKeyService ¶
type APIKeyService struct {
// contains filtered or unexported fields
}
func NewAPIKeyService ¶
func NewAPIKeyService(keys *repositories.APIKeyRepository) *APIKeyService
func (*APIKeyService) Create ¶
func (s *APIKeyService) Create(userID uint, workspaceID *uint, name string, allowedIPs, scopes []string, expiresAt *time.Time) (plaintext string, key *models.APIKey, err error)
Create generates a new API key, persists its hash, and returns the one-time plaintext token (shown to the user only once).
func (*APIKeyService) CreateBilling ¶ added in v1.10.21
func (s *APIKeyService) CreateBilling(userID uint, name string, allowedIPs []string) (plaintext string, key *models.APIKey, err error)
CreateBilling mints a billing key: scope billing only, account-wide, owned by the platform billing service user. It bypasses NormalizeScopes because users can never pick that scope.
func (*APIKeyService) CreateEphemeral ¶
func (s *APIKeyService) CreateEphemeral(userID, workspaceID uint, appID *uint, name string, scopes []string, expiresAt time.Time) (plaintext string, key *models.APIKey, err error)
CreateEphemeral mints a short-lived, machine-minted API key for a runner job: workspace-scoped, bound to one application, expiring at the job deadline, and marked Ephemeral so it is hidden from the UI and excluded from the MaxAPIKeys quota. No quota check — job credentials never count against a plan.
func (*APIKeyService) Revoke ¶
func (s *APIKeyService) Revoke(id uint) error
Revoke marks a key revoked (used to kill a run's ephemeral credentials the moment the run reaches a terminal state).
func (*APIKeyService) SetQuota ¶
func (s *APIKeyService) SetQuota(q *quota.Service)
SetQuota wires the plan/quota enforcer (nil-safe; nil skips checks).
func (*APIKeyService) SweepExpiredEphemeral ¶
func (s *APIKeyService) SweepExpiredEphemeral(now time.Time) (int, error)
SweepExpiredEphemeral deletes ephemeral job keys past their expiry — a belt-and-suspenders cleanup for keys orphaned by a runner that died without its run releasing them. Returns the number deleted.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
func NewService ¶
func NewService(users *repositories.UserRepository, resets *repositories.PasswordResetRepository, recovery *repositories.TwoFactorRecoveryRepository, store *session.Store, jwtSecret string) *Service
func (*Service) Authenticate ¶
Authenticate verifies credentials and returns the user. The identifier is either an email address or a username handle — an '@' selects the email lookup, otherwise the username — and a miss on the primary lookup falls back to the other, so an unusual-looking username still resolves.
func (*Service) BeginTwoFactorSetup ¶
BeginTwoFactorSetup generates a fresh TOTP secret for the user, stores it encrypted but not yet enabled, and returns the secret plus an otpauth:// URL the client renders as a QR code. Calling it again before confirming rotates the pending secret.
func (*Service) ChangePassword ¶
ChangePassword verifies an authenticated user's current password and sets a new one. Distinct from the token-based ResetPassword: this is the self-service path from the security page, gated by the current password rather than an emailed token.
func (*Service) CompletePasswordReset ¶ added in v1.1.0
func (s *Service) CompletePasswordReset(ctx context.Context, token, newPassword string) (*models.User, error)
CompletePasswordReset consumes a reset-session token, sets the user's new password, clears the must-change flag, and returns the user so the caller can issue a full session. Errors when the token is invalid, expired, or already used.
func (*Service) ConfirmEmailVerification ¶ added in v1.9.6
ConfirmEmailVerification consumes a token and marks the address verified. Returns the user so a caller can greet them by name.
func (*Service) ConfirmTwoFactor ¶
func (s *Service) ConfirmTwoFactor(user *models.User, code string) (recoveryCodes []string, err error)
ConfirmTwoFactor validates a code against the pending secret and, on success, activates two-factor authentication and issues a fresh set of single-use recovery codes (returned in plaintext, shown to the user once).
func (*Service) CreateEmailVerification ¶ added in v1.9.6
CreateEmailVerification issues a fresh verification link for a user, retiring any outstanding one so a re-send leaves exactly one live link.
func (*Service) CreatePasswordReset ¶
CreatePasswordReset issues a reset token for an email. It returns the raw token (to be emailed) and never reveals whether the email exists.
func (*Service) CreateResetSession ¶ added in v1.1.0
CreateResetSession issues a short-lived, single-use reset-session token in Redis for the forced-password-change flow: a user with an admin-set password gets this instead of a full session at login, and exchanges it for a real session once they set their own.
func (*Service) DisableTwoFactor ¶
DisableTwoFactor turns off two-factor authentication after verifying a code (a TOTP code or a recovery code), clearing the stored secret and any codes.
func (*Service) IssueToken ¶
IssueToken creates a signed JWT carrying a unique jti. Service accounts are refused here, the one place every console session is minted.
func (*Service) RecoveryCodesRemaining ¶
RecoveryCodesRemaining reports how many unused recovery codes the user has.
func (*Service) RegenerateRecoveryCodes ¶
RegenerateRecoveryCodes verifies a current TOTP code and replaces the user's recovery codes with a fresh set, returned in plaintext.
func (*Service) ResetPassword ¶
ResetPassword consumes a reset token, sets a new password and returns the user's id.
func (*Service) SetEmailVerifications ¶ added in v1.9.6
func (s *Service) SetEmailVerifications(r *repositories.EmailVerificationRepository)
SetEmailVerifications wires the verification token store (nil-safe).
func (*Service) SetTOTPIssuer ¶ added in v1.10.7
SetTOTPIssuer wires the name authenticator apps show for this instance. Unset shows "Miabi".
func (*Service) VerifyLoginCode ¶
VerifyLoginCode checks a second-factor input at login: it tries the TOTP code first, then falls back to consuming a one-time recovery code.