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
- Variables
- func CSRF(next http.Handler) http.Handler
- func HashPassword(password string, p Argon2Params) (string, error)
- func PasswordChanged(next http.Handler) http.Handler
- func ResetMFAOffline(ctx context.Context, st *store.Store, username string, now time.Time) error
- func ResetPassword(ctx context.Context, st *store.Store, username, password string, now time.Time) error
- func SameOrigin(r *http.Request) bool
- func SubjectFromRequest(r *http.Request) (authz.Subject, bool)
- func ValidatePassword(p string) error
- func VerifyPassword(password, encoded string, want Argon2Params) (ok, needsRehash bool, err error)
- func WithPrincipal(ctx context.Context, p Principal) context.Context
- type APIKey
- type Argon2Params
- type Auditor
- type Client
- type CreatedAPIKey
- type Issued
- type KeyOptions
- type KeyRef
- type Limiter
- type MFAChallengeError
- type MFAChallengeResponse
- type MFAEnrollment
- type MFAStatus
- type Options
- type Preferences
- type Principal
- type RateLimitedError
- type SecuritySettings
- type Service
- func (s *Service) Authenticate(ctx context.Context, token string) (Principal, error)
- func (s *Service) AuthenticateKey(ctx context.Context, token string) (Principal, error)
- func (s *Service) ChangePassword(ctx context.Context, p Principal, current, next string) error
- func (s *Service) CleanupLoop(ctx context.Context)
- func (s *Service) CreateAPIKey(ctx context.Context, userID int64, name string, o KeyOptions) (APIKey, string, error)
- func (s *Service) CreateUser(ctx context.Context, username, password string) (UserDetail, string, error)
- func (s *Service) DeleteAPIKey(ctx context.Context, userID, id int64) error
- func (s *Service) DeleteUser(ctx context.Context, actor, id int64) error
- func (s *Service) DisableMFA(ctx context.Context, userID int64, password string) error
- func (s *Service) EnableMFA(ctx context.Context, userID int64, code string) ([]string, error)
- func (s *Service) GetPreferences(ctx context.Context, userID int64) (Preferences, error)
- func (s *Service) GetUser(ctx context.Context, id int64) (UserDetail, error)
- func (s *Service) ListAPIKeys(ctx context.Context, userID int64) ([]APIKey, error)
- func (s *Service) ListUsers(ctx context.Context) ([]UserDetail, error)
- func (s *Service) Login(ctx context.Context, username, password string, c Client) (User, Issued, error)
- func (s *Service) LoginMFA(ctx context.Context, token, code string, c Client) (User, Issued, error)
- func (s *Service) Logout(ctx context.Context, p Principal) error
- func (s *Service) MFAEnrolled(next http.Handler) http.Handler
- func (s *Service) MFAStatusOf(ctx context.Context, userID int64) (MFAStatus, error)
- func (s *Service) NewBackupCodes(ctx context.Context, userID int64, password string) ([]string, error)
- func (s *Service) OptionalSession(next http.Handler) http.Handler
- func (s *Service) RequireMFA(ctx context.Context) bool
- func (s *Service) RequireSession(next http.Handler) http.Handler
- func (s *Service) ResetMFA(ctx context.Context, actorID, userID int64) error
- func (s *Service) Routes(r chi.Router, g *authz.Guard)
- func (s *Service) SecureCookie() bool
- func (s *Service) SetDisabled(ctx context.Context, actor, id int64, disabled bool) (UserDetail, error)
- func (s *Service) SetPreferences(ctx context.Context, userID int64, p Preferences) (Preferences, error)
- func (s *Service) SetRequireMFA(ctx context.Context, on bool) error
- func (s *Service) SetTemporaryPassword(ctx context.Context, actor, id int64, password string) (string, error)
- func (s *Service) Setup(ctx context.Context, token, username, password string, c Client) (User, Issued, error)
- func (s *Service) SetupRequired() bool
- func (s *Service) StartMFA(ctx context.Context, userID int64, password string) (MFAEnrollment, error)
- type SessionResponse
- type User
- type UserDetail
- type UserPasswordResponse
Constants ¶
const ( MinPasswordLen = 12 // characters MaxPasswordLen = 1024 // bytes; bounds hashing cost )
Password policy.
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).
const APIKeyPrefix = "nerdui_"
APIKeyPrefix starts every key, so it is recognizable (secret scanners, logs).
const CSRFHeader = "X-CSRF-Token"
CSRFHeader carries the per-session CSRF token on unsafe requests.
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.
const CookieName = "nerdui_session"
CookieName is the session cookie (ADR-0005).
Variables ¶
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.
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") )
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.
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).
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.
var ( // ErrInvalidPreferences is returned for values outside the allowed ones. ErrInvalidPreferences = errors.New("invalid preferences") )
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 ¶
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 ¶
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
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 ¶
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 ¶
SubjectFromRequest adapts the request's principal for the authorizer (authz.SubjectFunc).
func ValidatePassword ¶
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).
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
Auditor records authentication attempts; *audit.Recorder implements it.
type CreatedAPIKey ¶
CreatedAPIKey is the response to creating a key: the key itself is shown only here.
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 ¶
NewLimiter returns a limiter with the defaults: 5 failures per minute, blocks from 1 to 15 minutes.
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
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.
type RateLimitedError ¶
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 ¶
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 ¶
Authenticate resolves a session token (from the cookie) to a principal.
func (*Service) AuthenticateKey ¶
AuthenticateKey resolves an API key to its principal. Unknown, expired keys and keys of disabled users are ErrUnauthenticated.
func (*Service) ChangePassword ¶
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 ¶
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 ¶
DeleteAPIKey revokes a key of a user; requests with it are rejected at once.
func (*Service) DeleteUser ¶
DeleteUser removes another user and their sessions.
func (*Service) DisableMFA ¶ added in v0.2.0
DisableMFA turns two-factor authentication off after checking the password.
func (*Service) EnableMFA ¶ added in v0.2.0
EnableMFA confirms the pending secret with a code and returns new backup codes.
func (*Service) GetPreferences ¶
GetPreferences returns a user's preferences, or the defaults.
func (*Service) ListAPIKeys ¶
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
LoginMFA completes a login with the second factor and creates a session.
func (*Service) MFAEnrolled ¶ added in v0.2.0
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
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 ¶
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
RequireMFA reports whether every user must use two-factor authentication.
func (*Service) RequireSession ¶
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
ResetMFA turns off another user's two-factor authentication (administrators, e.g. a lost phone).
func (*Service) Routes ¶
Routes registers the authentication and user management endpoints under the API root.
func (*Service) SecureCookie ¶
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
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 ¶
SetupRequired reports whether the first admin still has to be created.
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.