Documentation
¶
Overview ¶
Package auth authenticates callers (browser sessions and personal API keys), hashes passwords, limits login attempts and decides which scopes a caller holds.
Index ¶
- Constants
- Variables
- func HashInviteToken(token string) []byte
- func NewInviteToken() (token string, hash []byte)
- func RoleScopes(role string) []string
- func WithPrincipal(ctx context.Context, p *Principal) context.Context
- type Argon2Params
- type ClientInfo
- type FailureLimiter
- type Hasher
- type Method
- type NewSession
- type Principal
- type RateLimitedError
- type Service
- func (s *Service) AuthenticateAPIKey(ctx context.Context, key string) (*Principal, error)
- func (s *Service) AuthenticateSession(ctx context.Context, token string) (*Principal, error)
- func (s *Service) ChangePassword(ctx context.Context, p *Principal, current, next string) error
- func (s *Service) CleanExpired(ctx context.Context) (int64, error)
- func (s *Service) CreateAPIKey(ctx context.Context, u db.User, name string, scopes []string, ...) (db.ApiKey, string, error)
- func (s *Service) DeleteAPIKey(ctx context.Context, userID, id uuid.UUID) error
- func (s *Service) DeleteSession(ctx context.Context, userID, id uuid.UUID) error
- func (s *Service) Hasher() *Hasher
- func (s *Service) ListAPIKeys(ctx context.Context, userID uuid.UUID) ([]db.ApiKey, error)
- func (s *Service) ListSessions(ctx context.Context, userID uuid.UUID) ([]db.Session, error)
- func (s *Service) Login(ctx context.Context, username, password string, ci ClientInfo) (db.User, NewSession, error)
- func (s *Service) Logout(ctx context.Context, p *Principal) error
- func (s *Service) SessionTTL() time.Duration
- func (s *Service) StartSession(ctx context.Context, q *db.Queries, u db.User, ci ClientInfo) (NewSession, error)
Constants ¶
const ( RoleAdmin = "admin" RoleUser = "user" )
Roles.
const ( // ScopeRead allows GET requests. ScopeRead = "read" // ScopeWrite allows requests that change something. ScopeWrite = "write" // ScopeAdmin allows admin endpoints (admins' keys only). ScopeAdmin = "admin" // ScopeMetricsRead allows scraping /metrics on the API port (admins' // keys only). ScopeMetricsRead = "metrics:read" )
API key scopes.
const APIKeyPrefix = "pnl_"
APIKeyPrefix starts every personal API key, so keys are easy to spot (also for secret scanners).
const DefaultSessionTTL = 30 * 24 * time.Hour
DefaultSessionTTL is how long a session lasts without being used.
Variables ¶
var ( ErrInvalidCredentials = errors.New("auth: invalid username or password") ErrDisabled = errors.New("auth: account disabled") ErrInvalidAPIKey = errors.New("auth: invalid or expired API key") ErrNotFound = errors.New("auth: not found") ErrScopeNotAllowed = errors.New("auth: scope not allowed for this account") ErrExpiryInPast = errors.New("auth: expiry is in the past") )
Errors callers map to responses.
var DefaultArgon2 = Argon2Params{MemoryKiB: 19 * 1024, Iterations: 2, Parallelism: 1}
DefaultArgon2 follows the common recommendation for argon2id (19 MiB, two passes), which keeps a login cheap enough for small home servers.
var KnownScopes = []string{ScopeRead, ScopeWrite, ScopeAdmin, ScopeMetricsRead}
KnownScopes lists every scope, in display order.
Functions ¶
func HashInviteToken ¶
HashInviteToken hashes an invite token to look it up.
func NewInviteToken ¶
NewInviteToken returns a fresh invite token and its stored hash.
func RoleScopes ¶
RoleScopes are the scopes a role may hold. A session holds all of them; an API key holds the ones it was created with.
Types ¶
type Argon2Params ¶
Argon2Params are argon2id cost parameters.
type ClientInfo ¶
ClientInfo describes where a request came from.
type FailureLimiter ¶
type FailureLimiter struct {
// contains filtered or unexported fields
}
FailureLimiter counts failures per key in a fixed window and blocks a key once it reaches the limit, until its window ends. It lives in memory: a restart forgets it, which is fine for slowing down password guessing.
func NewFailureLimiter ¶
func NewFailureLimiter(max int, window time.Duration) *FailureLimiter
NewFailureLimiter allows max failures per key per window.
func (*FailureLimiter) Blocked ¶
func (l *FailureLimiter) Blocked(key string) (bool, time.Duration)
Blocked reports whether key is blocked, and for how long.
func (*FailureLimiter) Fail ¶
func (l *FailureLimiter) Fail(key string)
Fail records a failure for key.
func (*FailureLimiter) Reset ¶
func (l *FailureLimiter) Reset(key string)
Reset forgets key's failures (after a successful login).
type Hasher ¶
type Hasher struct {
// contains filtered or unexported fields
}
Hasher hashes and verifies passwords with argon2id. It caps how many hashes run at once, so a burst of logins can't exhaust memory.
func NewHasher ¶
func NewHasher(p Argon2Params, concurrency int) *Hasher
NewHasher returns a hasher running at most concurrency hashes at a time.
type NewSession ¶
NewSession is a freshly created session with its secrets, which exist only here: the database keeps a hash of the token.
type Principal ¶
type Principal struct {
User db.User
Method Method
// SessionID and CSRFToken are set for sessions.
SessionID uuid.UUID
CSRFToken string
// APIKeyID is set for API keys.
APIKeyID uuid.UUID
// Scopes the caller holds.
Scopes []string
}
Principal is an authenticated caller.
func FromContext ¶
FromContext returns the caller, or nil for anonymous requests.
type RateLimitedError ¶
RateLimitedError says a login was refused because of too many failures.
func (*RateLimitedError) Error ¶
func (e *RateLimitedError) Error() string
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service signs users in and authenticates requests.
func NewService ¶
NewService returns the auth service.
func (*Service) AuthenticateAPIKey ¶
AuthenticateAPIKey resolves a personal API key. Unknown, expired and disabled users' keys are ErrInvalidAPIKey: a request that sends a key must not silently become anonymous.
func (*Service) AuthenticateSession ¶
AuthenticateSession resolves a session token. It returns nil without an error when the token is unknown or expired, or the user is disabled: the request is then anonymous. Sessions slide: using one extends it.
func (*Service) ChangePassword ¶
ChangePassword changes the caller's password after checking the current one, and ends their other sessions.
func (*Service) CleanExpired ¶
CleanExpired deletes expired sessions.
func (*Service) CreateAPIKey ¶
func (s *Service) CreateAPIKey(ctx context.Context, u db.User, name string, scopes []string, expiresAt *time.Time) (db.ApiKey, string, error)
CreateAPIKey creates a key for u. The key itself is returned only here.
func (*Service) DeleteAPIKey ¶
DeleteAPIKey revokes one of the user's keys.
func (*Service) DeleteSession ¶
DeleteSession ends one of the user's sessions.
func (*Service) ListAPIKeys ¶
ListAPIKeys lists a user's keys.
func (*Service) ListSessions ¶
ListSessions lists a user's live sessions.
func (*Service) Login ¶
func (s *Service) Login(ctx context.Context, username, password string, ci ClientInfo) (db.User, NewSession, error)
Login checks a username and password and starts a session.
func (*Service) SessionTTL ¶
SessionTTL is how long a session lasts without being used.
func (*Service) StartSession ¶
func (s *Service) StartSession(ctx context.Context, q *db.Queries, u db.User, ci ClientInfo) (NewSession, error)
StartSession creates a session for u with q (so it can join a transaction) and records the login.