auth

package
v1.10.21 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0

Documentation

Overview

Package auth handles user authentication: password hashing, JWT issuance with revocable sessions, and password resets.

Index

Constants

View Source
const ClaimPasswordFingerprint = "pwf"

ClaimPasswordFingerprint is the session claim binding a token to the password it was issued under.

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

View Source
const PasswordResetTTL = time.Hour

PasswordResetTTL is the lifetime of a password-reset token.

View Source
const TokenTTL = 24 * time.Hour

TokenTTL is the lifetime of an issued access token (and its session).

Variables

View Source
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")
)
View Source
var ErrInvalidAPIKey = errors.New("invalid API key")

Functions

func NormalizeScopes

func NormalizeScopes(scopes []string) ([]string, error)

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

func SessionFingerprint(key []byte, passwordHash string) string

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.

func (*APIKeyService) Verify

func (s *APIKeyService) Verify(plaintext string) (*models.APIKey, error)

Verify validates a presented token and returns the matching key. The lookup is indexed on the prefix; the secret is compared in constant time, and the key must be neither revoked nor expired.

type Service

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

func (*Service) Authenticate

func (s *Service) Authenticate(identifier, password string) (*models.User, error)

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

func (s *Service) BeginTwoFactorSetup(user *models.User) (secret, url string, err error)

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

func (s *Service) ChangePassword(userID uint, currentPassword, newPassword string) error

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

func (s *Service) ConfirmEmailVerification(rawToken string) (*models.User, error)

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

func (s *Service) CreateEmailVerification(user *models.User) (rawToken string, err error)

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

func (s *Service) CreatePasswordReset(email string) (rawToken string, user *models.User, err error)

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

func (s *Service) CreateResetSession(ctx context.Context, userID uint) (string, error)

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

func (s *Service) DisableTwoFactor(user *models.User, code string) error

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

func (s *Service) IssueToken(user *models.User) (token, jti string, err error)

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

func (s *Service) RecoveryCodesRemaining(userID uint) int

RecoveryCodesRemaining reports how many unused recovery codes the user has.

func (*Service) RegenerateRecoveryCodes

func (s *Service) RegenerateRecoveryCodes(user *models.User, code string) ([]string, error)

RegenerateRecoveryCodes verifies a current TOTP code and replaces the user's recovery codes with a fresh set, returned in plaintext.

func (*Service) ResetPassword

func (s *Service) ResetPassword(rawToken, newPassword string) (uint, error)

ResetPassword consumes a reset token, sets a new password and returns the user's id.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, jti string)

Revoke blacklists a session by its jti until its natural expiry.

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

func (s *Service) SetTOTPIssuer(fn func() string)

SetTOTPIssuer wires the name authenticator apps show for this instance. Unset shows "Miabi".

func (*Service) VerifyLoginCode

func (s *Service) VerifyLoginCode(user *models.User, code string) bool

VerifyLoginCode checks a second-factor input at login: it tries the TOTP code first, then falls back to consuming a one-time recovery code.

func (*Service) VerifySecondFactor added in v1.10.7

func (s *Service) VerifySecondFactor(user *models.User, code string) error

VerifySecondFactor checks a TOTP code, or consumes a recovery code, for a user with two-factor enabled. Used by step-up checks such as the admin console unlock.

Jump to

Keyboard shortcuts

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