- fix(storage): lock the user row when rotating a refresh token or changing a password, so on PostgreSQL a token minted during a password change can no longer survive the revoke-everything that runs at the same time - fix(auth): a replay of a just-rotated refresh token (two tabs, a retrying client) now fails without revoking the winner's new token; only a replay after RefreshReuseGrace is treated as theft and revokes every session - fix(auth): changing or resetting a password and revoking the user's refresh tokens now happen in one transaction - docs(auth): note that the last-admin rule relies on a single instance - test: password change racing with a refresh (25 rounds, both databases), grace window, winner's token still valid after concurrent rotation
374 lines
12 KiB
Go
374 lines
12 KiB
Go
// Package auth implements local users, roles, password hashing, JWT access
|
|
// tokens and rotating refresh tokens.
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"regexp"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
// Errors returned by the service. Handlers map them to HTTP statuses.
|
|
var (
|
|
ErrInvalidInput = errors.New("invalid input")
|
|
ErrUsernameTaken = errors.New("username already taken")
|
|
ErrUserNotFound = errors.New("user not found")
|
|
ErrInvalidCredentials = errors.New("invalid username or password")
|
|
ErrRegistrationClosed = errors.New("registration is closed")
|
|
ErrInvalidRefreshToken = errors.New("invalid refresh token")
|
|
ErrLastAdmin = errors.New("cannot remove the last admin")
|
|
)
|
|
|
|
var usernameRe = regexp.MustCompile(`^[A-Za-z0-9._-]{3,64}$`)
|
|
|
|
const (
|
|
minPasswordLen = 8
|
|
maxPasswordLen = 256 // caps the work an attacker can force on the KDF
|
|
)
|
|
|
|
// RefreshReuseGrace is how long after a rotation the old refresh token is
|
|
// treated as a harmless race (two tabs, a client retrying) instead of theft.
|
|
// Inside the window the replay fails but the user's other sessions survive.
|
|
const RefreshReuseGrace = 10 * time.Second
|
|
|
|
// User is a local account. The password hash never leaves the store layer.
|
|
type User struct {
|
|
ID int64
|
|
Username string
|
|
IsAdmin bool
|
|
CreatedAt time.Time
|
|
}
|
|
|
|
// RefreshToken is the stored form of a refresh token: only a hash, never the token.
|
|
type RefreshToken struct {
|
|
UserID int64
|
|
TokenHash string
|
|
ExpiresAt time.Time
|
|
}
|
|
|
|
// UserStore is what the service needs to persist users.
|
|
type UserStore interface {
|
|
CountUsers(ctx context.Context) (int, error)
|
|
CountAdmins(ctx context.Context) (int, error)
|
|
// CreateUser returns ErrUsernameTaken when the name exists (case-insensitive).
|
|
CreateUser(ctx context.Context, username, passwordHash string, isAdmin bool) (User, error)
|
|
// UserByUsername and UserByID return the password hash too, and ErrUserNotFound.
|
|
UserByUsername(ctx context.Context, username string) (User, string, error)
|
|
UserByID(ctx context.Context, id int64) (User, string, error)
|
|
ListUsers(ctx context.Context) ([]User, error)
|
|
// The three below return ErrUserNotFound for an unknown id.
|
|
SetAdmin(ctx context.Context, id int64, isAdmin bool) error
|
|
DeleteUser(ctx context.Context, id int64) error
|
|
// SetPasswordHash replaces the hash and, in the same transaction, revokes
|
|
// every refresh token of the user: a password change signs them out
|
|
// everywhere, with no window where the password changed but sessions live.
|
|
SetPasswordHash(ctx context.Context, id int64, passwordHash string, now time.Time) error
|
|
}
|
|
|
|
// RefreshStore is what the service needs to persist refresh tokens.
|
|
type RefreshStore interface {
|
|
SaveRefreshToken(ctx context.Context, t RefreshToken) error
|
|
// RotateRefreshToken atomically revokes the active, unexpired token with
|
|
// hash oldHash and stores next for the same user, returning that user.
|
|
// An unknown or expired token gives ErrInvalidRefreshToken. A token that
|
|
// was already revoked is a reuse: unless it was revoked less than
|
|
// RefreshReuseGrace ago, every token of its user is revoked. Either way
|
|
// ErrInvalidRefreshToken is returned.
|
|
RotateRefreshToken(ctx context.Context, oldHash string, next RefreshToken, now time.Time) (userID int64, err error)
|
|
// RevokeRefreshToken is idempotent and ignores unknown tokens.
|
|
RevokeRefreshToken(ctx context.Context, hash string, now time.Time) error
|
|
}
|
|
|
|
// Session is what a client receives after logging in or refreshing.
|
|
type Session struct {
|
|
AccessToken string
|
|
AccessExpiresAt time.Time
|
|
RefreshToken string
|
|
RefreshExpiresAt time.Time
|
|
User User
|
|
}
|
|
|
|
// Service handles accounts and sessions.
|
|
type Service struct {
|
|
users UserStore
|
|
refresh RefreshStore
|
|
tokens *TokenIssuer
|
|
refreshTTL time.Duration
|
|
now func() time.Time
|
|
|
|
// mu serialises registration and admin changes inside this process, which
|
|
// is what keeps the last-admin rule. Sonda is a single-instance server: two
|
|
// instances on one PostgreSQL database could still demote the last two
|
|
// admins at the same time.
|
|
mu sync.Mutex
|
|
dummyOnce sync.Once
|
|
dummyHash string
|
|
}
|
|
|
|
// NewService builds a Service.
|
|
func NewService(users UserStore, refresh RefreshStore, tokens *TokenIssuer, refreshTTL time.Duration) *Service {
|
|
return &Service{users: users, refresh: refresh, tokens: tokens, refreshTTL: refreshTTL, now: time.Now}
|
|
}
|
|
|
|
// ---- validation ----
|
|
|
|
func validateUsername(username string) error {
|
|
if !usernameRe.MatchString(username) {
|
|
return fmt.Errorf("%w: username must be 3-64 characters: letters, digits, '.', '_' or '-'", ErrInvalidInput)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func validatePassword(password string) error {
|
|
if len(password) < minPasswordLen || len(password) > maxPasswordLen {
|
|
return fmt.Errorf("%w: password must be %d-%d bytes", ErrInvalidInput, minPasswordLen, maxPasswordLen)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ---- registration and login ----
|
|
|
|
// Register creates the first user, who becomes the admin. Once any user
|
|
// exists, registration is closed: admins create further accounts.
|
|
func (s *Service) Register(ctx context.Context, username, password string) (User, error) {
|
|
if err := validateUsername(username); err != nil {
|
|
return User{}, err
|
|
}
|
|
if err := validatePassword(password); err != nil {
|
|
return User{}, err
|
|
}
|
|
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
n, err := s.users.CountUsers(ctx)
|
|
if err != nil {
|
|
return User{}, fmt.Errorf("count users: %w", err)
|
|
}
|
|
if n > 0 {
|
|
return User{}, ErrRegistrationClosed
|
|
}
|
|
hash, err := HashPassword(password)
|
|
if err != nil {
|
|
return User{}, err
|
|
}
|
|
return s.users.CreateUser(ctx, username, hash, true)
|
|
}
|
|
|
|
// Login checks the credentials and opens a session.
|
|
// Unknown user and wrong password are indistinguishable to the caller.
|
|
func (s *Service) Login(ctx context.Context, username, password string) (Session, error) {
|
|
user, hash, err := s.users.UserByUsername(ctx, username)
|
|
if errors.Is(err, ErrUserNotFound) {
|
|
// Spend the same time as a real check to avoid revealing which names exist.
|
|
VerifyPassword(s.fakeHash(), password)
|
|
return Session{}, ErrInvalidCredentials
|
|
}
|
|
if err != nil {
|
|
return Session{}, fmt.Errorf("find user: %w", err)
|
|
}
|
|
if !VerifyPassword(hash, password) {
|
|
return Session{}, ErrInvalidCredentials
|
|
}
|
|
return s.openSession(ctx, user)
|
|
}
|
|
|
|
func (s *Service) fakeHash() string {
|
|
s.dummyOnce.Do(func() { s.dummyHash, _ = HashPassword("sonda-dummy-password") })
|
|
return s.dummyHash
|
|
}
|
|
|
|
func (s *Service) openSession(ctx context.Context, user User) (Session, error) {
|
|
raw, hash, err := newRefreshToken()
|
|
if err != nil {
|
|
return Session{}, err
|
|
}
|
|
exp := s.now().Add(s.refreshTTL)
|
|
if err := s.refresh.SaveRefreshToken(ctx, RefreshToken{UserID: user.ID, TokenHash: hash, ExpiresAt: exp}); err != nil {
|
|
return Session{}, fmt.Errorf("save refresh token: %w", err)
|
|
}
|
|
return s.sign(user, raw, exp)
|
|
}
|
|
|
|
func (s *Service) sign(user User, refreshRaw string, refreshExp time.Time) (Session, error) {
|
|
access, accessExp, err := s.tokens.Issue(user)
|
|
if err != nil {
|
|
return Session{}, err
|
|
}
|
|
return Session{
|
|
AccessToken: access, AccessExpiresAt: accessExp,
|
|
RefreshToken: refreshRaw, RefreshExpiresAt: refreshExp,
|
|
User: user,
|
|
}, nil
|
|
}
|
|
|
|
// ---- refresh and logout ----
|
|
|
|
// Refresh exchanges a refresh token for a new session. The old token stops
|
|
// working; presenting it again revokes every session of that user.
|
|
func (s *Service) Refresh(ctx context.Context, refreshToken string) (Session, error) {
|
|
if refreshToken == "" {
|
|
return Session{}, ErrInvalidRefreshToken
|
|
}
|
|
raw, hash, err := newRefreshToken()
|
|
if err != nil {
|
|
return Session{}, err
|
|
}
|
|
now := s.now()
|
|
exp := now.Add(s.refreshTTL)
|
|
|
|
userID, err := s.refresh.RotateRefreshToken(ctx, hashRefreshToken(refreshToken),
|
|
RefreshToken{TokenHash: hash, ExpiresAt: exp}, now)
|
|
if err != nil {
|
|
return Session{}, err
|
|
}
|
|
user, _, err := s.users.UserByID(ctx, userID)
|
|
if errors.Is(err, ErrUserNotFound) {
|
|
return Session{}, ErrInvalidRefreshToken
|
|
}
|
|
if err != nil {
|
|
return Session{}, fmt.Errorf("find user: %w", err)
|
|
}
|
|
return s.sign(user, raw, exp)
|
|
}
|
|
|
|
// Logout revokes one refresh token. It is idempotent and never reveals
|
|
// whether the token existed.
|
|
func (s *Service) Logout(ctx context.Context, refreshToken string) error {
|
|
if refreshToken == "" {
|
|
return nil
|
|
}
|
|
return s.refresh.RevokeRefreshToken(ctx, hashRefreshToken(refreshToken), s.now())
|
|
}
|
|
|
|
func newRefreshToken() (raw, hash string, err error) {
|
|
b := make([]byte, 32)
|
|
if _, err := rand.Read(b); err != nil {
|
|
return "", "", fmt.Errorf("generate refresh token: %w", err)
|
|
}
|
|
raw = base64.RawURLEncoding.EncodeToString(b)
|
|
return raw, hashRefreshToken(raw), nil
|
|
}
|
|
|
|
func hashRefreshToken(raw string) string {
|
|
sum := sha256.Sum256([]byte(raw))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
// ---- own account ----
|
|
|
|
// User returns the account with the given id.
|
|
func (s *Service) User(ctx context.Context, id int64) (User, error) {
|
|
u, _, err := s.users.UserByID(ctx, id)
|
|
return u, err
|
|
}
|
|
|
|
// ChangePassword sets a new password after checking the current one, and
|
|
// signs the user out everywhere.
|
|
func (s *Service) ChangePassword(ctx context.Context, userID int64, current, next string) error {
|
|
_, hash, err := s.users.UserByID(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !VerifyPassword(hash, current) {
|
|
return ErrInvalidCredentials
|
|
}
|
|
return s.setPassword(ctx, userID, next)
|
|
}
|
|
|
|
func (s *Service) setPassword(ctx context.Context, userID int64, password string) error {
|
|
if err := validatePassword(password); err != nil {
|
|
return err
|
|
}
|
|
hash, err := HashPassword(password)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return s.users.SetPasswordHash(ctx, userID, hash, s.now())
|
|
}
|
|
|
|
// ---- admin ----
|
|
|
|
// ListUsers returns every account.
|
|
func (s *Service) ListUsers(ctx context.Context) ([]User, error) {
|
|
return s.users.ListUsers(ctx)
|
|
}
|
|
|
|
// CreateUser creates an account. Callers must have checked that the actor is an admin.
|
|
func (s *Service) CreateUser(ctx context.Context, username, password string, isAdmin bool) (User, error) {
|
|
if err := validateUsername(username); err != nil {
|
|
return User{}, err
|
|
}
|
|
if err := validatePassword(password); err != nil {
|
|
return User{}, err
|
|
}
|
|
hash, err := HashPassword(password)
|
|
if err != nil {
|
|
return User{}, err
|
|
}
|
|
return s.users.CreateUser(ctx, username, hash, isAdmin)
|
|
}
|
|
|
|
// SetAdmin grants or removes the admin role. The last admin cannot be demoted.
|
|
func (s *Service) SetAdmin(ctx context.Context, id int64, isAdmin bool) (User, error) {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
user, _, err := s.users.UserByID(ctx, id)
|
|
if err != nil {
|
|
return User{}, err
|
|
}
|
|
if user.IsAdmin && !isAdmin {
|
|
if err := s.ensureAnotherAdmin(ctx); err != nil {
|
|
return User{}, err
|
|
}
|
|
}
|
|
if err := s.users.SetAdmin(ctx, id, isAdmin); err != nil {
|
|
return User{}, err
|
|
}
|
|
user.IsAdmin = isAdmin
|
|
return user, nil
|
|
}
|
|
|
|
// ResetPassword sets a new password without knowing the old one and signs the
|
|
// user out everywhere. Callers must have checked that the actor is an admin.
|
|
func (s *Service) ResetPassword(ctx context.Context, id int64, password string) error {
|
|
return s.setPassword(ctx, id, password)
|
|
}
|
|
|
|
// DeleteUser removes an account and its sessions. The last admin cannot be deleted.
|
|
func (s *Service) DeleteUser(ctx context.Context, id int64) error {
|
|
s.mu.Lock()
|
|
defer s.mu.Unlock()
|
|
|
|
user, _, err := s.users.UserByID(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if user.IsAdmin {
|
|
if err := s.ensureAnotherAdmin(ctx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return s.users.DeleteUser(ctx, id)
|
|
}
|
|
|
|
// ensureAnotherAdmin fails with ErrLastAdmin when only one admin exists.
|
|
// The caller must hold s.mu and have checked that the target is an admin.
|
|
func (s *Service) ensureAnotherAdmin(ctx context.Context) error {
|
|
n, err := s.users.CountAdmins(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("count admins: %w", err)
|
|
}
|
|
if n <= 1 {
|
|
return ErrLastAdmin
|
|
}
|
|
return nil
|
|
}
|