auth

package
v0.2.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 32 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package auth implements local authentication (ADR-0005): argon2id passwords, server-side sessions stored in SQLite, CSRF protection, the first-run setup token and login rate limiting.

Index

Constants

View Source
const (
	MinPasswordLen = 12   // characters
	MaxPasswordLen = 1024 // bytes; bounds hashing cost
)

Password policy.

View Source
const (
	DefaultIdleTimeout     = 24 * time.Hour
	DefaultAbsoluteTimeout = 30 * 24 * time.Hour

	// RoleAdmin is the only role in MVP (ADR-0009).
	RoleAdmin = authz.RoleAdmin
)

Defaults (ADR-0005).

View Source
const APIKeyPrefix = "nerdui_"

APIKeyPrefix starts every key, so it is recognizable (secret scanners, logs).

View Source
const CSRFHeader = "X-CSRF-Token"

CSRFHeader carries the per-session CSRF token on unsafe requests.

View Source
const CodeMFASetupRequired = "mfa_setup_required"

CodeMFASetupRequired: the administrator requires two-factor authentication and the user has not set it up; only the session and two-factor endpoints are available.

View Source
const CookieName = "nerdui_session"

CookieName is the session cookie (ADR-0005).

Variables

View Source
var (
	ErrAPIKeyNotFound = errors.New("API key not found")
	ErrInvalidAPIKey  = errors.New("invalid API key settings")
	ErrTooManyAPIKeys = fmt.Errorf("%w: at most %d keys per user", ErrInvalidAPIKey, maxAPIKeysPerUser)
	ErrNotWithAPIKey  = errors.New("not allowed with an API key: sign in with a password")
)

Errors of API key management.

View Source
var (
	ErrMFAInvalidCode    = errors.New("invalid or already used code")
	ErrMFANotStarted     = errors.New("start two-factor setup first")
	ErrMFANotEnabled     = errors.New("two-factor authentication is not enabled")
	ErrMFAChallenge      = errors.New("the sign-in attempt expired; enter your password again")
	ErrMFASetupRequired  = errors.New("set up two-factor authentication first")
	ErrMFAAlreadyEnabled = errors.New("two-factor authentication is already enabled; disable it first")
)
View Source
var (
	ErrInvalidCredentials = errors.New("invalid username or password")
	ErrUnauthenticated    = errors.New("not authenticated")
	ErrSetupCompleted     = errors.New("setup has already been completed")
	ErrInvalidSetupToken  = errors.New("invalid setup token")
	ErrInvalidUsername    = errors.New("username must be 1-64 characters: letters, digits, '.', '_' or '-'")
	ErrUserNotFound       = errors.New("user not found")
	ErrUserDisabled       = errors.New("account is disabled")
)

Errors returned by the service.

View Source
var (
	ErrUsernameTaken  = errors.New("username is already taken")
	ErrOwnAccount     = errors.New("use your account settings to change your own account")
	ErrLastAdmin      = errors.New("at least one active administrator is required")
	ErrWrongPassword  = errors.New("current password is incorrect")
	ErrSamePassword   = errors.New("the new password must differ from the current one")
	ErrPasswordChange = errors.New("change your temporary password first")
)

User management errors (#74, ADR-0016).

View Source
var DefaultArgon2 = Argon2Params{Memory: 19 * 1024, Time: 2, Threads: 1, SaltLen: 16, KeyLen: 32}

DefaultArgon2 follows the OWASP recommendation (19 MiB, 2 iterations, 1 thread), which is affordable on small ARM boards.

View Source
var (
	// ErrInvalidPreferences is returned for values outside the allowed ones.
	ErrInvalidPreferences = errors.New("invalid preferences")
)
View Source
var ErrWeakPassword = fmt.Errorf("password must be %d to %d characters long", MinPasswordLen, MaxPasswordLen)

ErrWeakPassword is returned for passwords that violate the policy.

Functions

func CSRF

func CSRF(next http.Handler) http.Handler

CSRF protects unsafe methods of authenticated routes: the X-CSRF-Token header must match the session's token, and a present Origin header must match the request host. Must run after RequireSession.

func HashPassword

func HashPassword(password string, p Argon2Params) (string, error)

HashPassword returns a PHC-formatted argon2id hash: $argon2id$v=19$m=19456,t=2,p=1$<salt>$<key>.

func PasswordChanged

func PasswordChanged(next http.Handler) http.Handler

PasswordChanged rejects requests of sessions that still have to replace a temporary password (#74) with 403 password_change_required. Must run after RequireSession; only the caller's own session endpoints (me, logout, password) are exempt.

func ResetMFAOffline added in v0.2.0

func ResetMFAOffline(ctx context.Context, st *store.Store, username string, now time.Time) error

ResetMFAOffline turns off a user's two-factor authentication and revokes their sessions. It is used by `nerdui admin reset-mfa` and works without a running server, e.g. when the only administrator lost both the phone and the backup codes.

func ResetPassword

func ResetPassword(ctx context.Context, st *store.Store, username, password string, now time.Time) error

ResetPassword sets a new password for username, enables the account and revokes all of its sessions. It is used by `nerdui admin reset-password` and works without a running server; the operator chose the password, so it does not have to be changed.

func SameOrigin

func SameOrigin(r *http.Request) bool

SameOrigin reports whether the request's Origin header (if present) matches its Host. Browsers always send Origin on cross-origin and unsafe requests.

func SubjectFromRequest

func SubjectFromRequest(r *http.Request) (authz.Subject, bool)

SubjectFromRequest adapts the request's principal for the authorizer (authz.SubjectFunc).

func ValidatePassword

func ValidatePassword(p string) error

ValidatePassword checks the password policy.

func VerifyPassword

func VerifyPassword(password, encoded string, want Argon2Params) (ok, needsRehash bool, err error)

VerifyPassword reports whether password matches the encoded hash, and whether the hash uses weaker parameters than want (so callers can transparently rehash).

func WithPrincipal

func WithPrincipal(ctx context.Context, p Principal) context.Context

WithPrincipal returns a context carrying p.

Types

type APIKey

type APIKey struct {
	ID       int64  `json:"id"`
	Name     string `json:"name"`
	Prefix   string `json:"prefix"`
	ReadOnly bool   `json:"readOnly"`
	// Permissions limits the key to these actions (#80); absent, the key may do everything
	// its user may.
	Permissions []string   `json:"permissions,omitempty"`
	CreatedAt   time.Time  `json:"createdAt"`
	ExpiresAt   *time.Time `json:"expiresAt,omitempty"`
	LastUsedAt  *time.Time `json:"lastUsedAt,omitempty"`
}

APIKey describes a key without its secret. Keep in sync with api/openapi.yaml.

type Argon2Params

type Argon2Params struct {
	Memory  uint32 // KiB
	Time    uint32
	Threads uint8
	SaltLen uint32
	KeyLen  uint32
}

Argon2Params are the argon2id cost parameters; they are stored in every hash so they can be raised later without breaking existing passwords.

type Auditor added in v0.2.0

type Auditor interface {
	Auth(r *http.Request, action, username string, ok bool, msg string)
}

Auditor records authentication attempts; *audit.Recorder implements it.

type Client

type Client struct {
	IP        string
	UserAgent string
}

Client describes where a request came from (stored with the session for auditing).

type CreatedAPIKey

type CreatedAPIKey struct {
	APIKey
	Key string `json:"key"`
}

CreatedAPIKey is the response to creating a key: the key itself is shown only here.

type Issued

type Issued struct {
	Token     string
	CSRFToken string
	ExpiresAt time.Time
}

Issued is a newly created session; Token goes into the cookie and is never stored.

type KeyOptions added in v0.2.0

type KeyOptions struct {
	ReadOnly  bool
	ExpiresAt *time.Time
	// Permissions limits the key to these actions; nil: no limit beyond the user's.
	Permissions []string
}

KeyOptions are the limits of a new API key.

type KeyRef

type KeyRef struct {
	ID       int64
	Name     string
	Prefix   string
	ReadOnly bool
	// Permissions is nil for a key without limits.
	Permissions []authz.Action
}

KeyRef identifies the API key a principal authenticated with.

type Limiter

type Limiter struct {
	MaxFailures int
	Window      time.Duration
	BaseBlock   time.Duration
	MaxBlock    time.Duration
	// contains filtered or unexported fields
}

Limiter throttles failed authentication attempts per key (client IP, username). After MaxFailures failures within Window the key is blocked; every further block doubles, from BaseBlock up to MaxBlock (ADR-0005).

func NewLimiter

func NewLimiter(now func() time.Time) *Limiter

NewLimiter returns a limiter with the defaults: 5 failures per minute, blocks from 1 to 15 minutes.

func (*Limiter) Allow

func (l *Limiter) Allow(key string) (retryAfter time.Duration, ok bool)

Allow reports whether an attempt for key may proceed; otherwise it returns how long to wait.

func (*Limiter) Fail

func (l *Limiter) Fail(key string)

Fail records a failed attempt.

func (*Limiter) Reset

func (l *Limiter) Reset(key string)

Reset forgets key, e.g. after a successful login.

type MFAChallengeError added in v0.2.0

type MFAChallengeError struct{ Token string }

MFAChallengeError is returned by Login when the password was right and a second factor is needed: the client sends Token with a code to LoginMFA.

func (*MFAChallengeError) Error added in v0.2.0

func (e *MFAChallengeError) Error() string

type MFAChallengeResponse added in v0.2.0

type MFAChallengeResponse struct {
	MFARequired bool   `json:"mfaRequired"`
	MFAToken    string `json:"mfaToken"`
}

MFAChallengeResponse is returned by login when a second factor is needed. Keep in sync with api/openapi.yaml.

type MFAEnrollment added in v0.2.0

type MFAEnrollment struct {
	Secret string `json:"secret"`
	URI    string `json:"uri"`
}

MFAEnrollment is a new secret to add to an authenticator app.

type MFAStatus added in v0.2.0

type MFAStatus struct {
	Enabled         bool `json:"enabled"`
	BackupCodesLeft int  `json:"backupCodesLeft"`
	// Required: the administrator requires it from every user.
	Required bool `json:"required"`
}

MFAStatus describes a user's two-factor authentication. Keep in sync with api/openapi.yaml.

type Options

type Options struct {
	// Audit, when set, records setups and logins, also failed ones (#79).
	Audit        Auditor
	SecureCookie bool
	// CookiePath limits the session cookie to nerdui's base path (#222); "" means "/".
	CookiePath      string
	IdleTimeout     time.Duration
	AbsoluteTimeout time.Duration
	Argon2          Argon2Params
	Now             func() time.Time
	Logger          *slog.Logger
}

Options configures the service.

type Preferences

type Preferences struct {
	// Theme is auto (the system's), light or dark.
	Theme string `json:"theme"`
	// DateFormat is relative ("5 min ago"), local (the browser's locale) or iso.
	DateFormat string `json:"dateFormat"`
	// RefreshSeconds polls lists in addition to live events; 0 turns it off.
	RefreshSeconds int `json:"refreshSeconds"`
	// HiddenColumns lists hidden columns per table.
	HiddenColumns map[string][]string `json:"hiddenColumns"`
}

Preferences are a user's interface settings (#90), kept on the server so they follow the user across browsers. Keep in sync with api/openapi.yaml.

func DefaultPreferences

func DefaultPreferences() Preferences

DefaultPreferences apply until a user saves their own.

func (*Preferences) Validate

func (p *Preferences) Validate() error

Validate checks every field against the allowed values.

type Principal

type Principal struct {
	User      User
	CSRFToken string
	ExpiresAt time.Time

	// APIKey is set when the request authenticated with an API key instead of a session.
	APIKey *KeyRef
	// contains filtered or unexported fields
}

Principal is the authenticated caller attached to a request context.

func PrincipalFrom

func PrincipalFrom(ctx context.Context) (Principal, bool)

PrincipalFrom returns the authenticated principal, if any.

type RateLimitedError

type RateLimitedError struct{ RetryAfter time.Duration }

RateLimitedError carries the time until the next attempt is allowed.

func (*RateLimitedError) Error

func (e *RateLimitedError) Error() string

type SecuritySettings added in v0.2.0

type SecuritySettings struct {
	RequireMFA bool `json:"requireMfa"`
}

SecuritySettings are the server-wide sign-in rules. Keep in sync with api/openapi.yaml.

type Service

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

Service is the authentication service.

func New

func New(ctx context.Context, st *store.Store, opts Options) (*Service, error)

New creates the service. When the database has no users, it generates a one-time setup token and logs it (ADR-0005): whoever creates the first admin must have access to the logs.

func (*Service) Authenticate

func (s *Service) Authenticate(ctx context.Context, token string) (Principal, error)

Authenticate resolves a session token (from the cookie) to a principal.

func (*Service) AuthenticateKey

func (s *Service) AuthenticateKey(ctx context.Context, token string) (Principal, error)

AuthenticateKey resolves an API key to its principal. Unknown, expired keys and keys of disabled users are ErrUnauthenticated.

func (*Service) ChangePassword

func (s *Service) ChangePassword(ctx context.Context, p Principal, current, next string) error

ChangePassword changes the caller's own password after verifying the current one. It clears the temporary-password flag and revokes the caller's other sessions.

func (*Service) CleanupLoop

func (s *Service) CleanupLoop(ctx context.Context)

CleanupLoop deletes expired sessions periodically until ctx is done.

func (*Service) CreateAPIKey

func (s *Service) CreateAPIKey(ctx context.Context, userID int64, name string, o KeyOptions) (APIKey, string, error)

CreateAPIKey creates a key for a user and returns it with its secret, which is not stored. The caller checks that the user has every permission of the key.

func (*Service) CreateUser

func (s *Service) CreateUser(ctx context.Context, username, password string) (UserDetail, string, error)

CreateUser adds an administrator with a temporary password that must be changed at the first sign-in. An empty password is generated and returned; a given one is returned empty.

func (*Service) DeleteAPIKey

func (s *Service) DeleteAPIKey(ctx context.Context, userID, id int64) error

DeleteAPIKey revokes a key of a user; requests with it are rejected at once.

func (*Service) DeleteUser

func (s *Service) DeleteUser(ctx context.Context, actor, id int64) error

DeleteUser removes another user and their sessions.

func (*Service) DisableMFA added in v0.2.0

func (s *Service) DisableMFA(ctx context.Context, userID int64, password string) error

DisableMFA turns two-factor authentication off after checking the password.

func (*Service) EnableMFA added in v0.2.0

func (s *Service) EnableMFA(ctx context.Context, userID int64, code string) ([]string, error)

EnableMFA confirms the pending secret with a code and returns new backup codes.

func (*Service) GetPreferences

func (s *Service) GetPreferences(ctx context.Context, userID int64) (Preferences, error)

GetPreferences returns a user's preferences, or the defaults.

func (*Service) GetUser

func (s *Service) GetUser(ctx context.Context, id int64) (UserDetail, error)

GetUser returns one user.

func (*Service) ListAPIKeys

func (s *Service) ListAPIKeys(ctx context.Context, userID int64) ([]APIKey, error)

ListAPIKeys returns a user's keys, newest first.

func (*Service) ListUsers

func (s *Service) ListUsers(ctx context.Context) ([]UserDetail, error)

ListUsers returns all users sorted by username.

func (*Service) Login

func (s *Service) Login(ctx context.Context, username, password string, c Client) (User, Issued, error)

Login verifies credentials and creates a session.

func (*Service) LoginMFA added in v0.2.0

func (s *Service) LoginMFA(ctx context.Context, token, code string, c Client) (User, Issued, error)

LoginMFA completes a login with the second factor and creates a session.

func (*Service) Logout

func (s *Service) Logout(ctx context.Context, p Principal) error

Logout revokes the principal's session.

func (*Service) MFAEnrolled added in v0.2.0

func (s *Service) MFAEnrolled(next http.Handler) http.Handler

MFAEnrolled blocks sessions without two-factor authentication while it is required. API keys are not affected: they are a separate credential.

func (*Service) MFAStatusOf added in v0.2.0

func (s *Service) MFAStatusOf(ctx context.Context, userID int64) (MFAStatus, error)

MFAStatusOf returns a user's status.

func (*Service) NewBackupCodes added in v0.2.0

func (s *Service) NewBackupCodes(ctx context.Context, userID int64, password string) ([]string, error)

NewBackupCodes replaces a user's backup codes after checking the password.

func (*Service) OptionalSession

func (s *Service) OptionalSession(next http.Handler) http.Handler

OptionalSession attaches the principal when a valid session cookie is present and otherwise passes the request through unchanged.

func (*Service) RequireMFA added in v0.2.0

func (s *Service) RequireMFA(ctx context.Context) bool

RequireMFA reports whether every user must use two-factor authentication.

func (*Service) RequireSession

func (s *Service) RequireSession(next http.Handler) http.Handler

RequireSession rejects requests without a valid session or API key with 401. An "Authorization: Bearer" header is an API key (#87); otherwise the session cookie is used.

func (*Service) ResetMFA added in v0.2.0

func (s *Service) ResetMFA(ctx context.Context, actorID, userID int64) error

ResetMFA turns off another user's two-factor authentication (administrators, e.g. a lost phone).

func (*Service) Routes

func (s *Service) Routes(r chi.Router, g *authz.Guard)

Routes registers the authentication and user management endpoints under the API root.

func (*Service) SecureCookie

func (s *Service) SecureCookie() bool

SecureCookie reports whether session cookies are marked Secure.

func (*Service) SetDisabled

func (s *Service) SetDisabled(ctx context.Context, actor, id int64, disabled bool) (UserDetail, error)

SetDisabled disables or enables another user. Disabling revokes the user's sessions.

func (*Service) SetPreferences

func (s *Service) SetPreferences(ctx context.Context, userID int64, p Preferences) (Preferences, error)

SetPreferences validates and saves a user's preferences.

func (*Service) SetRequireMFA added in v0.2.0

func (s *Service) SetRequireMFA(ctx context.Context, on bool) error

SetRequireMFA turns the requirement on or off.

func (*Service) SetTemporaryPassword

func (s *Service) SetTemporaryPassword(ctx context.Context, actor, id int64, password string) (string, error)

SetTemporaryPassword sets another user's password, revokes their sessions and requires a change at the next sign-in. An empty password is generated and returned.

func (*Service) Setup

func (s *Service) Setup(ctx context.Context, token, username, password string, c Client) (User, Issued, error)

Setup creates the first admin account and logs it in.

func (*Service) SetupRequired

func (s *Service) SetupRequired() bool

SetupRequired reports whether the first admin still has to be created.

func (*Service) StartMFA added in v0.2.0

func (s *Service) StartMFA(ctx context.Context, userID int64, password string) (MFAEnrollment, error)

StartMFA creates a pending secret after checking the password.

type SessionResponse

type SessionResponse struct {
	User      User      `json:"user"`
	CSRFToken string    `json:"csrfToken"`
	ExpiresAt time.Time `json:"expiresAt"`
	// MFASetupRequired: two-factor authentication is required and the user has none yet (#75).
	MFASetupRequired bool `json:"mfaSetupRequired"`
}

SessionResponse is returned by setup, login and me. Keep in sync with api/openapi.yaml.

type User

type User struct {
	ID       int64  `json:"id"`
	Username string `json:"username"`
	Role     string `json:"role"`
	// MustChangePassword is set after an administrator chose the password (#74): until the
	// user changes it, only their own session endpoints are available.
	MustChangePassword bool `json:"mustChangePassword"`
	// MFAEnabled: the user signs in with a second factor (#75).
	MFAEnabled bool `json:"mfaEnabled"`
}

User is the public view of a user.

type UserDetail

type UserDetail struct {
	User
	Disabled    bool       `json:"disabled"`
	CreatedAt   time.Time  `json:"createdAt"`
	LastLoginAt *time.Time `json:"lastLoginAt,omitempty"`
}

UserDetail is the administrator's view of a user.

type UserPasswordResponse

type UserPasswordResponse struct {
	User              *UserDetail `json:"user,omitempty"`
	GeneratedPassword string      `json:"generatedPassword,omitempty"`
}

UserPasswordResponse carries a generated temporary password; it is shown once.

Jump to

Keyboard shortcuts

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