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 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 Client
- type CreatedAPIKey
- type Issued
- type KeyRef
- type Limiter
- type Options
- type Preferences
- type Principal
- type RateLimitedError
- 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, readOnly bool, ...) (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) 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) Logout(ctx context.Context, p Principal) error
- func (s *Service) OptionalSession(next http.Handler) http.Handler
- func (s *Service) RequireSession(next http.Handler) http.Handler
- 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) 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
- 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 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 ( 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 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"`
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 CreatedAPIKey ¶
CreatedAPIKey is the response to creating a key: the key itself is shown only here.
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 Options ¶
type Options struct {
SecureCookie bool
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 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, readOnly bool, expiresAt *time.Time) (APIKey, string, error)
CreateAPIKey creates a key for a user and returns it with its secret, which is not stored.
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) 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) OptionalSession ¶
OptionalSession attaches the principal when a valid session cookie is present and otherwise passes the request through unchanged.
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) 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) 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"`
}
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"`
}
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.