sonda/internal/auth/service.go
tgiachi 3a739dc3ae feat: add sondad server with config, storage, auth and listening API
- feat(config): TOML config with env overrides, strict parsing and validation
- feat(storage): SQLite (modernc) and PostgreSQL (pgx) backends through bun,
  embedded per-driver SQL migrations with a transactional runner
- feat(schema): catalog tables (artists, albums, tracks, audio_files with
  per-root paths), users and listening events with idempotency keys
- feat(auth): Argon2id password hashing, HS256 JWT tokens, first-user-only
  registration and login
- feat(api): gin REST API under /api/v1 (health, register, login, listens)
  with a consistent error envelope, body limit and request logging
- feat(sondad): zap logger, graceful shutdown, composition root in main
- chore: example config, .gitignore for secrets, DB files, IDE and agent files
2026-11-11 12:06:15 +01:00

121 lines
3.6 KiB
Go

// Package auth implements local users, password hashing and JWT access tokens.
package auth
import (
"context"
"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")
)
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
)
// User is a local account. The password hash never leaves the store layer.
type User struct {
ID int64
Username string
CreatedAt time.Time
}
// UserStore is what the service needs from persistence.
type UserStore interface {
CountUsers(ctx context.Context) (int, error)
// CreateUser returns ErrUsernameTaken when the name exists (case-insensitive).
CreateUser(ctx context.Context, username, passwordHash string) (User, error)
// UserByUsername returns ErrUserNotFound when there is no such user.
UserByUsername(ctx context.Context, username string) (User, string, error)
}
// LoginResult is returned by a successful login.
type LoginResult struct {
Token string
ExpiresAt time.Time
User User
}
// Service registers users and logs them in.
type Service struct {
store UserStore
tokens *TokenIssuer
mu sync.Mutex // serialises Register so only one first user can win
dummyOnce sync.Once
dummyHash string
}
// NewService builds a Service.
func NewService(store UserStore, tokens *TokenIssuer) *Service {
return &Service{store: store, tokens: tokens}
}
// Register creates the first user. Once any user exists, registration is
// closed: there is no admin flow yet.
func (s *Service) Register(ctx context.Context, username, password string) (User, error) {
if !usernameRe.MatchString(username) {
return User{}, fmt.Errorf("%w: username must be 3-64 characters: letters, digits, '.', '_' or '-'", ErrInvalidInput)
}
if len(password) < minPasswordLen || len(password) > maxPasswordLen {
return User{}, fmt.Errorf("%w: password must be %d-%d bytes", ErrInvalidInput, minPasswordLen, maxPasswordLen)
}
s.mu.Lock()
defer s.mu.Unlock()
n, err := s.store.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.store.CreateUser(ctx, username, hash)
}
// Login checks the credentials and returns a signed token.
// Unknown user and wrong password are indistinguishable to the caller.
func (s *Service) Login(ctx context.Context, username, password string) (LoginResult, error) {
user, hash, err := s.store.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 LoginResult{}, ErrInvalidCredentials
}
if err != nil {
return LoginResult{}, fmt.Errorf("find user: %w", err)
}
if !VerifyPassword(hash, password) {
return LoginResult{}, ErrInvalidCredentials
}
token, exp, err := s.tokens.Issue(user)
if err != nil {
return LoginResult{}, err
}
return LoginResult{Token: token, ExpiresAt: exp, User: user}, nil
}
func (s *Service) fakeHash() string {
s.dummyOnce.Do(func() { s.dummyHash, _ = HashPassword("sonda-dummy-password") })
return s.dummyHash
}