auth

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: GPL-3.0 Imports: 17 Imported by: 0

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

View Source
const (
	RoleAdmin = "admin"
	RoleUser  = "user"
)

Roles.

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

View Source
const APIKeyPrefix = "pnl_"

APIKeyPrefix starts every personal API key, so keys are easy to spot (also for secret scanners).

View Source
const DefaultSessionTTL = 30 * 24 * time.Hour

DefaultSessionTTL is how long a session lasts without being used.

Variables

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

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

KnownScopes lists every scope, in display order.

Functions

func HashInviteToken

func HashInviteToken(token string) []byte

HashInviteToken hashes an invite token to look it up.

func NewInviteToken

func NewInviteToken() (token string, hash []byte)

NewInviteToken returns a fresh invite token and its stored hash.

func RoleScopes

func RoleScopes(role string) []string

RoleScopes are the scopes a role may hold. A session holds all of them; an API key holds the ones it was created with.

func WithPrincipal

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

WithPrincipal returns ctx carrying p.

Types

type Argon2Params

type Argon2Params struct {
	MemoryKiB   uint32
	Iterations  uint32
	Parallelism uint8
}

Argon2Params are argon2id cost parameters.

type ClientInfo

type ClientInfo struct {
	IP        string
	UserAgent string
}

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.

func (*Hasher) Hash

func (h *Hasher) Hash(ctx context.Context, password string) (string, error)

Hash returns a PHC-format argon2id hash of password.

func (*Hasher) Verify

func (h *Hasher) Verify(ctx context.Context, password, encoded string) (ok, rehash bool, err error)

Verify reports whether password matches encoded, and whether the hash should be replaced because its parameters are outdated.

func (*Hasher) VerifyDummy

func (h *Hasher) VerifyDummy(ctx context.Context, password string)

VerifyDummy spends the same time as a real check, for unknown users, so response times don't reveal which usernames exist.

type Method

type Method string

Method is how a caller authenticated.

const (
	MethodSession Method = "session"
	MethodAPIKey  Method = "api_key"
)

type NewSession

type NewSession struct {
	Session   db.Session
	Token     string
	CSRFToken string
}

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

func FromContext(ctx context.Context) *Principal

FromContext returns the caller, or nil for anonymous requests.

func (*Principal) CheckCSRF

func (p *Principal) CheckCSRF(token string) bool

CheckCSRF reports whether token is the session's CSRF token.

func (*Principal) HasScope

func (p *Principal) HasScope(scope string) bool

HasScope reports whether the caller holds scope.

func (*Principal) IsAdmin

func (p *Principal) IsAdmin() bool

IsAdmin reports whether the caller is an admin.

type RateLimitedError

type RateLimitedError struct{ RetryAfter time.Duration }

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

func NewService(st *store.Store, hasher *Hasher, log *slog.Logger) *Service

NewService returns the auth service.

func (*Service) AuthenticateAPIKey

func (s *Service) AuthenticateAPIKey(ctx context.Context, key string) (*Principal, error)

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

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

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

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

ChangePassword changes the caller's password after checking the current one, and ends their other sessions.

func (*Service) CleanExpired

func (s *Service) CleanExpired(ctx context.Context) (int64, error)

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

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

DeleteAPIKey revokes one of the user's keys.

func (*Service) DeleteSession

func (s *Service) DeleteSession(ctx context.Context, userID, id uuid.UUID) error

DeleteSession ends one of the user's sessions.

func (*Service) Hasher

func (s *Service) Hasher() *Hasher

Hasher returns the password hasher.

func (*Service) ListAPIKeys

func (s *Service) ListAPIKeys(ctx context.Context, userID uuid.UUID) ([]db.ApiKey, error)

ListAPIKeys lists a user's keys.

func (*Service) ListSessions

func (s *Service) ListSessions(ctx context.Context, userID uuid.UUID) ([]db.Session, error)

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) Logout

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

Logout ends a session.

func (*Service) SessionTTL

func (s *Service) SessionTTL() time.Duration

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.

Jump to

Keyboard shortcuts

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