816 lines
29 KiB
Go
816 lines
29 KiB
Go
// Package auth contains the shared single-account/session persistence used by
|
|
// the self-hosted web services. HTTP handlers, cookies, authorization policy,
|
|
// and application-specific roles remain in each service.
|
|
package auth
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// User is the shared account record. PasswordHash should never be serialized
|
|
// into an API response.
|
|
type User struct {
|
|
ID int64
|
|
Username string
|
|
Email string
|
|
PasswordHash string
|
|
Role Role
|
|
CreatedAt time.Time
|
|
UpdatedAt time.Time
|
|
// LastLoginAt is nil until the account's first successful POST
|
|
// /api/login (registration alone does not set it - see UpdateLastLogin).
|
|
LastLoginAt *time.Time
|
|
}
|
|
|
|
// Store performs common auth persistence against a caller-owned pool.
|
|
type Store struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
// NewStore creates an auth store. The pool remains owned by the caller.
|
|
func NewStore(pool *pgxpool.Pool) *Store {
|
|
return &Store{pool: pool}
|
|
}
|
|
|
|
// SchemaOptions controls optional auth schema features.
|
|
type SchemaOptions struct {
|
|
// SingleUser adds a constraint that allows exactly one account. This is the
|
|
// default model for GameStream, SimpleCollection, and home-server tools.
|
|
SingleUser bool
|
|
// APITokens creates the optional per-user API token table.
|
|
APITokens bool
|
|
// ProjectScoping creates auth_known_projects/auth_user_projects, backing per-user
|
|
// project-access restriction (see Store.SetUserProjects/IsProjectAllowed). Only AuthGuard
|
|
// itself needs this - every other project only ever calls AuthGuard's own API, never these
|
|
// tables directly.
|
|
ProjectScoping bool
|
|
}
|
|
|
|
// DefaultSchemaOptions returns the single-account schema used by most small
|
|
// self-hosted services.
|
|
func DefaultSchemaOptions() SchemaOptions {
|
|
return SchemaOptions{SingleUser: true}
|
|
}
|
|
|
|
// EnsureSchema creates the shared auth tables and indexes idempotently.
|
|
func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions) error {
|
|
if pool == nil {
|
|
return errors.New("auth postgres pool is nil")
|
|
}
|
|
|
|
// Only a table that predates the role column needs its oldest account promoted, so the
|
|
// promotion below runs once, in the migration that adds the column.
|
|
var roleColumnMissing bool
|
|
if err := pool.QueryRow(ctx, `
|
|
SELECT NOT EXISTS (
|
|
SELECT 1 FROM information_schema.columns
|
|
WHERE table_schema = current_schema() AND table_name = 'auth_users' AND column_name = 'role'
|
|
)`).Scan(&roleColumnMissing); err != nil {
|
|
return fmt.Errorf("check auth schema: %w", err)
|
|
}
|
|
|
|
_, err := pool.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS auth_users (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
username TEXT NOT NULL UNIQUE,
|
|
email TEXT NOT NULL DEFAULT '',
|
|
password_hash TEXT NOT NULL,
|
|
role TEXT NOT NULL DEFAULT 'user',
|
|
totp_secret TEXT NOT NULL DEFAULT '',
|
|
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
|
last_used_step BIGINT NOT NULL DEFAULT -1,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
|
last_login_at TIMESTAMPTZ
|
|
);
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_secret TEXT NOT NULL DEFAULT '';
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_used_step BIGINT NOT NULL DEFAULT -1;
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
|
|
-- last_login_at is nullable (NULL means "never logged in" - registration
|
|
-- alone does not count, only a successful POST /api/login) and has no
|
|
-- DEFAULT, unlike every other column here.
|
|
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
|
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_email_idx
|
|
ON auth_users (lower(email)) WHERE email <> '';
|
|
|
|
CREATE TABLE IF NOT EXISTS auth_sessions (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
expires_at TIMESTAMPTZ NOT NULL,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_expiry_idx ON auth_sessions (expires_at);
|
|
CREATE INDEX IF NOT EXISTS auth_sessions_user_idx ON auth_sessions (user_id);
|
|
`)
|
|
if err != nil {
|
|
return fmt.Errorf("ensure auth schema: %w", err)
|
|
}
|
|
|
|
if err := ensureUsernameCaseIndex(ctx, pool); err != nil {
|
|
return err
|
|
}
|
|
|
|
if roleColumnMissing {
|
|
if _, err := pool.Exec(ctx, `
|
|
UPDATE auth_users SET role = 'superadmin'
|
|
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
|
|
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
|
|
`); err != nil {
|
|
return fmt.Errorf("promote oldest auth user: %w", err)
|
|
}
|
|
}
|
|
|
|
if options.SingleUser {
|
|
if _, err := pool.Exec(ctx, `
|
|
CREATE UNIQUE INDEX IF NOT EXISTS auth_users_singleton_idx ON auth_users ((true));
|
|
`); err != nil {
|
|
return fmt.Errorf("ensure single-user auth constraint: %w", err)
|
|
}
|
|
} else if _, err := pool.Exec(ctx, `DROP INDEX IF EXISTS auth_users_singleton_idx`); err != nil {
|
|
return fmt.Errorf("remove single-user auth constraint: %w", err)
|
|
}
|
|
|
|
if options.ProjectScoping {
|
|
if _, err := pool.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS auth_known_projects (
|
|
project TEXT PRIMARY KEY,
|
|
label TEXT NOT NULL DEFAULT '',
|
|
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE TABLE IF NOT EXISTS auth_user_projects (
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
project TEXT NOT NULL,
|
|
PRIMARY KEY (user_id, project)
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_user_projects_project_idx ON auth_user_projects (project);
|
|
`); err != nil {
|
|
return fmt.Errorf("ensure project-scoping schema: %w", err)
|
|
}
|
|
}
|
|
|
|
if options.APITokens {
|
|
if _, err := pool.Exec(ctx, `
|
|
CREATE TABLE IF NOT EXISTS auth_api_tokens (
|
|
id BIGSERIAL PRIMARY KEY,
|
|
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
|
|
token_hash TEXT NOT NULL UNIQUE,
|
|
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
|
);
|
|
CREATE INDEX IF NOT EXISTS auth_api_tokens_user_idx ON auth_api_tokens (user_id);
|
|
`); err != nil {
|
|
return fmt.Errorf("ensure auth API-token schema: %w", err)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ensureUsernameCaseIndex makes usernames unique ignoring case, so "Admin" and "admin" cannot both
|
|
// be registered. The index is created only while no such pair exists: a database that already
|
|
// holds one still starts, logs the clashing names, and gets the index on the first start after an
|
|
// operator has renamed or removed one of each pair.
|
|
func ensureUsernameCaseIndex(ctx context.Context, pool *pgxpool.Pool) error {
|
|
rows, err := pool.Query(ctx, `
|
|
SELECT min(username) FROM auth_users GROUP BY lower(username) HAVING count(*) > 1
|
|
ORDER BY 1 LIMIT 10
|
|
`)
|
|
if err != nil {
|
|
return fmt.Errorf("check duplicate usernames: %w", err)
|
|
}
|
|
var clashing []string
|
|
for rows.Next() {
|
|
var name string
|
|
if err := rows.Scan(&name); err != nil {
|
|
rows.Close()
|
|
return fmt.Errorf("check duplicate usernames: %w", err)
|
|
}
|
|
clashing = append(clashing, name)
|
|
}
|
|
rows.Close()
|
|
if err := rows.Err(); err != nil {
|
|
return fmt.Errorf("check duplicate usernames: %w", err)
|
|
}
|
|
if len(clashing) > 0 {
|
|
log.Printf("[auth] usernames that differ only by case exist (%q); the case-insensitive username index was not created. Rename or remove one account of each pair and restart.", clashing)
|
|
return nil
|
|
}
|
|
if _, err := pool.Exec(ctx, `CREATE UNIQUE INDEX IF NOT EXISTS auth_users_username_lower_idx ON auth_users (lower(username))`); err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
// An account was registered between the check and the index build; the next start retries.
|
|
log.Printf("[auth] the case-insensitive username index was not created because a clashing username was just added: %v", err)
|
|
return nil
|
|
}
|
|
return fmt.Errorf("ensure username index: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// TOTPState is the private provisioning state for one account. Secret must
|
|
// never be included in an API response.
|
|
type TOTPState struct {
|
|
Secret string
|
|
Enabled bool
|
|
LastUsedStep int64
|
|
}
|
|
|
|
// GetTOTPState reads the stored TOTP provisioning state for an account.
|
|
func (s *Store) GetTOTPState(ctx context.Context, userID int64) (TOTPState, error) {
|
|
if err := s.validate(); err != nil {
|
|
return TOTPState{}, err
|
|
}
|
|
var state TOTPState
|
|
err := s.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(last_used_step, -1) FROM auth_users WHERE id = $1`, userID).Scan(&state.Secret, &state.Enabled, &state.LastUsedStep)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return TOTPState{}, nil
|
|
}
|
|
if err != nil {
|
|
return TOTPState{}, fmt.Errorf("get TOTP state: %w", err)
|
|
}
|
|
return state, nil
|
|
}
|
|
|
|
// SetTOTPSecret stores a pending secret without enabling two-factor auth. It refuses while TOTP is
|
|
// already enabled, so a replaced secret cannot silently switch the second factor off.
|
|
func (s *Store) SetTOTPSecret(ctx context.Context, userID int64, secret string) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
tag, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $2 AND NOT totp_enabled`, secret, userID)
|
|
if err != nil {
|
|
return fmt.Errorf("set TOTP secret: %w", err)
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
state, err := s.GetTOTPState(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if state.Enabled {
|
|
return ErrTOTPAlreadyEnabled
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// EnableTOTP marks a previously provisioned secret as active and records the
|
|
// step used to confirm it, preventing that code from being reused at login.
|
|
func (s *Store) EnableTOTP(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
|
|
if err := s.validate(); err != nil {
|
|
return false, err
|
|
}
|
|
tag, err := s.pool.Exec(ctx, `
|
|
UPDATE auth_users
|
|
SET totp_enabled = true, last_used_step = $1, updated_at = now()
|
|
WHERE id = $2 AND totp_secret = $3 AND NOT totp_enabled AND last_used_step < $1
|
|
`, step, userID, secret)
|
|
if err != nil {
|
|
return false, fmt.Errorf("enable TOTP: %w", err)
|
|
}
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
// ConsumeTOTPStep advances an account's accepted TOTP step only once. The
|
|
// expected secret and enabled flag are part of the update so a concurrent
|
|
// disable or re-enrollment cannot consume a code against stale state.
|
|
func (s *Store) ConsumeTOTPStep(ctx context.Context, userID int64, secret string, step int64) (bool, error) {
|
|
if err := s.validate(); err != nil {
|
|
return false, err
|
|
}
|
|
tag, err := s.pool.Exec(ctx, `
|
|
UPDATE auth_users
|
|
SET last_used_step = $1, updated_at = now()
|
|
WHERE id = $2 AND totp_enabled AND totp_secret = $3 AND last_used_step < $1
|
|
`, step, userID, secret)
|
|
if err != nil {
|
|
return false, fmt.Errorf("consume TOTP step: %w", err)
|
|
}
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
// DisableTOTP clears both the active and pending TOTP secret.
|
|
func (s *Store) DisableTOTP(ctx context.Context, userID int64) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, last_used_step = -1, updated_at = now() WHERE id = $1`, userID)
|
|
if err != nil {
|
|
return fmt.Errorf("disable TOTP: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CountUsers returns the number of configured accounts.
|
|
func (s *Store) CountUsers(ctx context.Context) (int, error) {
|
|
if err := s.validate(); err != nil {
|
|
return 0, err
|
|
}
|
|
var count int
|
|
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
|
|
return 0, fmt.Errorf("count auth users: %w", err)
|
|
}
|
|
return count, nil
|
|
}
|
|
|
|
// CreateUser inserts an account and returns ErrUserExists for a uniqueness
|
|
// conflict, including the single-user constraint.
|
|
func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash string) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validateCredentials(username, passwordHash); err != nil {
|
|
return nil, err
|
|
}
|
|
var user User
|
|
err := s.pool.QueryRow(ctx, `
|
|
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
|
VALUES ($1, $2, $3,
|
|
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
|
|
now())
|
|
RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
|
`, username, email, passwordHash).Scan(
|
|
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
|
|
)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return nil, ErrUserExists
|
|
}
|
|
return nil, fmt.Errorf("create auth user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// FindByIdentifier looks up a user by exact username or case-insensitive email.
|
|
func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
// Usernames are tried before emails, so an identifier resolves to one account in a fixed order.
|
|
user, err := s.find(ctx, `
|
|
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
|
FROM auth_users
|
|
WHERE username = $1
|
|
`, identifier)
|
|
if err != nil || user != nil {
|
|
return user, err
|
|
}
|
|
return s.find(ctx, `
|
|
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
|
FROM auth_users
|
|
WHERE lower(email) = lower($1)
|
|
`, identifier)
|
|
}
|
|
|
|
// FindByID looks up a user by primary key.
|
|
func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.find(ctx, `
|
|
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
|
FROM auth_users WHERE id = $1
|
|
`, id)
|
|
}
|
|
|
|
// UpdateCredentials updates the normalized account fields and password hash.
|
|
func (s *Store) UpdateCredentials(ctx context.Context, id int64, username, email, passwordHash string) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if err := validateCredentials(username, passwordHash); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.pool.Exec(ctx, `
|
|
UPDATE auth_users
|
|
SET username = $1, email = $2, password_hash = $3, updated_at = now()
|
|
WHERE id = $4
|
|
`, username, email, passwordHash, id)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return ErrUserExists
|
|
}
|
|
return fmt.Errorf("update auth credentials: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpgradePasswordHash replaces an old verifier only if it is still current,
|
|
// so a concurrent password change cannot be overwritten by a login rehash.
|
|
func (s *Store) UpgradePasswordHash(ctx context.Context, id int64, oldHash, newHash string) (bool, error) {
|
|
if err := s.validate(); err != nil {
|
|
return false, err
|
|
}
|
|
tag, err := s.pool.Exec(ctx, `
|
|
UPDATE auth_users SET password_hash = $1, updated_at = now()
|
|
WHERE id = $2 AND password_hash = $3
|
|
`, newHash, id, oldHash)
|
|
if err != nil {
|
|
return false, fmt.Errorf("upgrade password hash: %w", err)
|
|
}
|
|
return tag.RowsAffected() == 1, nil
|
|
}
|
|
|
|
// ListUsers returns the non-secret account fields used by the shared user
|
|
// management screen.
|
|
func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT id, username, email, role, created_at, updated_at, last_login_at
|
|
FROM auth_users ORDER BY created_at, id
|
|
`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list auth users: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
users := make([]User, 0)
|
|
for rows.Next() {
|
|
var user User
|
|
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt); err != nil {
|
|
return nil, fmt.Errorf("scan auth user: %w", err)
|
|
}
|
|
users = append(users, user)
|
|
}
|
|
return users, rows.Err()
|
|
}
|
|
|
|
// CreateManagedUser creates a user with an explicit, already-authorized role.
|
|
func (s *Store) CreateManagedUser(ctx context.Context, username, email, passwordHash string, role Role) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := validateCredentials(username, passwordHash); err != nil {
|
|
return nil, err
|
|
}
|
|
role = NormalizeRole(string(role))
|
|
var user User
|
|
err := s.pool.QueryRow(ctx, `
|
|
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
|
|
VALUES ($1, $2, $3, $4, now())
|
|
RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
|
|
`, username, email, passwordHash, role).Scan(
|
|
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
|
|
)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return nil, ErrUserExists
|
|
}
|
|
return nil, fmt.Errorf("create managed auth user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|
|
|
|
// UpdateUser updates account fields and, when supplied, its role.
|
|
func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passwordHash string, role *Role) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if err := validateCredentials(username, passwordHash); err != nil {
|
|
return err
|
|
}
|
|
if role == nil {
|
|
return s.UpdateCredentials(ctx, id, username, email, passwordHash)
|
|
}
|
|
*role = NormalizeRole(string(*role))
|
|
_, err := s.pool.Exec(ctx, `
|
|
UPDATE auth_users
|
|
SET username = $1, email = $2, password_hash = $3, role = $4, updated_at = now()
|
|
WHERE id = $5
|
|
`, username, email, passwordHash, *role, id)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
|
return ErrUserExists
|
|
}
|
|
return fmt.Errorf("update managed auth user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UpdateLastLogin stamps last_login_at to now(). Callers should treat this as
|
|
// best-effort: an already-successful login (the session is live) shouldn't
|
|
// fail because this update didn't - see AuthGuard's handleLogin for the
|
|
// intended "log and continue" pattern.
|
|
func (s *Store) UpdateLastLogin(ctx context.Context, id int64) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `UPDATE auth_users SET last_login_at = now() WHERE id = $1`, id); err != nil {
|
|
return fmt.Errorf("update last login: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteUser removes one account. Callers enforce the superadmin/self policy.
|
|
func (s *Store) DeleteUser(ctx context.Context, id int64) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil {
|
|
return fmt.Errorf("delete auth user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// CreateSession stores a hash of a session token until expiresAt.
|
|
func (s *Store) CreateSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
_, err := s.pool.Exec(ctx, `
|
|
INSERT INTO auth_sessions (user_id, token_hash, expires_at)
|
|
VALUES ($1, $2, $3)
|
|
`, userID, tokenHash, expiresAt)
|
|
if err != nil {
|
|
return fmt.Errorf("create auth session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// FindSessionUser resolves an unexpired session to its user.
|
|
func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
return s.find(ctx, `
|
|
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at, u.last_login_at
|
|
FROM auth_sessions s
|
|
JOIN auth_users u ON u.id = s.user_id
|
|
WHERE s.token_hash = $1 AND s.expires_at > now()
|
|
`, tokenHash)
|
|
}
|
|
|
|
// DeleteSession removes one session, typically during logout.
|
|
func (s *Store) DeleteSession(ctx context.Context, tokenHash string) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash); err != nil {
|
|
return fmt.Errorf("delete auth session: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteSessionsForUser invalidates all sessions after credential changes.
|
|
func (s *Store) DeleteSessionsForUser(ctx context.Context, userID int64) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID); err != nil {
|
|
return fmt.Errorf("delete auth sessions for user: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteAllUsers removes every shared account. The auth schema's foreign keys
|
|
// cascade this to browser sessions and API tokens, allowing a fresh bootstrap.
|
|
func (s *Store) DeleteAllUsers(ctx context.Context) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil {
|
|
return fmt.Errorf("delete all auth users: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// DeleteExpiredSessions performs the periodic session cleanup shared by the
|
|
// services. A caller can run it from its own scheduler.
|
|
func (s *Store) DeleteExpiredSessions(ctx context.Context) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE expires_at < now()`); err != nil {
|
|
return fmt.Errorf("delete expired auth sessions: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// KnownProject is one project ProjectConfigurator has registered, pushed to AuthGuard so its
|
|
// admin UI can offer real, live project keys instead of free-form text - see SetKnownProjects.
|
|
type KnownProject struct {
|
|
Key string
|
|
Label string
|
|
}
|
|
|
|
// SetKnownProjects replaces the full set of known projects (pushed by ProjectConfigurator's
|
|
// PUT /api/projects/internal whenever its registered-project list changes). A project no longer
|
|
// registered is dropped, so the admin UI never offers a stale key; existing auth_user_projects
|
|
// rows for a removed project are left alone (harmless - IsProjectAllowed only ever compares
|
|
// against a user's own rows, never against auth_known_projects).
|
|
func (s *Store) SetKnownProjects(ctx context.Context, projects []KnownProject) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("set known projects: %w", err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
if _, err := tx.Exec(ctx, `DELETE FROM auth_known_projects`); err != nil {
|
|
return fmt.Errorf("set known projects: %w", err)
|
|
}
|
|
for _, project := range projects {
|
|
key := strings.ToLower(strings.TrimSpace(project.Key))
|
|
if key == "" {
|
|
continue
|
|
}
|
|
if _, err := tx.Exec(ctx, `
|
|
INSERT INTO auth_known_projects (project, label, updated_at) VALUES ($1, $2, now())
|
|
ON CONFLICT (project) DO UPDATE SET label = EXCLUDED.label, updated_at = now()
|
|
`, key, strings.TrimSpace(project.Label)); err != nil {
|
|
return fmt.Errorf("set known projects: %w", err)
|
|
}
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return fmt.Errorf("set known projects: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// KnownProjects returns every registered project, ordered by key.
|
|
func (s *Store) KnownProjects(ctx context.Context) ([]KnownProject, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := s.pool.Query(ctx, `SELECT project, label FROM auth_known_projects ORDER BY project`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list known projects: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
projects := make([]KnownProject, 0)
|
|
for rows.Next() {
|
|
var project KnownProject
|
|
if err := rows.Scan(&project.Key, &project.Label); err != nil {
|
|
return nil, fmt.Errorf("scan known project: %w", err)
|
|
}
|
|
projects = append(projects, project)
|
|
}
|
|
return projects, rows.Err()
|
|
}
|
|
|
|
// SetUserProjects replaces the full set of projects userID is restricted to. An empty projects
|
|
// list means unrestricted (see IsProjectAllowed) - the default for every account until an
|
|
// administrator explicitly scopes it, so this feature is opt-in and never breaks an existing
|
|
// deployment's accounts on upgrade.
|
|
func (s *Store) SetUserProjects(ctx context.Context, userID int64, projects []string) error {
|
|
if err := s.validate(); err != nil {
|
|
return err
|
|
}
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("set user projects: %w", err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
if _, err := tx.Exec(ctx, `DELETE FROM auth_user_projects WHERE user_id = $1`, userID); err != nil {
|
|
return fmt.Errorf("set user projects: %w", err)
|
|
}
|
|
seen := map[string]bool{}
|
|
for _, project := range projects {
|
|
key := strings.ToLower(strings.TrimSpace(project))
|
|
if key == "" || seen[key] {
|
|
continue
|
|
}
|
|
seen[key] = true
|
|
if _, err := tx.Exec(ctx, `INSERT INTO auth_user_projects (user_id, project) VALUES ($1, $2)`, userID, key); err != nil {
|
|
return fmt.Errorf("set user projects: %w", err)
|
|
}
|
|
}
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return fmt.Errorf("set user projects: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UserProjects returns the projects userID is restricted to, or an empty slice when unrestricted.
|
|
func (s *Store) UserProjects(ctx context.Context, userID int64) ([]string, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := s.pool.Query(ctx, `SELECT project FROM auth_user_projects WHERE user_id = $1 ORDER BY project`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list user projects: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
projects := make([]string, 0)
|
|
for rows.Next() {
|
|
var project string
|
|
if err := rows.Scan(&project); err != nil {
|
|
return nil, fmt.Errorf("scan user project: %w", err)
|
|
}
|
|
projects = append(projects, project)
|
|
}
|
|
return projects, rows.Err()
|
|
}
|
|
|
|
// UserProjectsByUser bulk-loads every user's project restrictions in one query, for the admin
|
|
// user list screen (avoids one query per row).
|
|
func (s *Store) UserProjectsByUser(ctx context.Context) (map[int64][]string, error) {
|
|
if err := s.validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
rows, err := s.pool.Query(ctx, `SELECT user_id, project FROM auth_user_projects ORDER BY user_id, project`)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list user projects: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
result := map[int64][]string{}
|
|
for rows.Next() {
|
|
var userID int64
|
|
var project string
|
|
if err := rows.Scan(&userID, &project); err != nil {
|
|
return nil, fmt.Errorf("scan user project: %w", err)
|
|
}
|
|
result[userID] = append(result[userID], project)
|
|
}
|
|
return result, rows.Err()
|
|
}
|
|
|
|
// IsProjectAllowed reports whether userID may authenticate against project: true when the
|
|
// account has no project restrictions at all (the default for every account), or when project is
|
|
// one of its assigned projects. An empty project (a caller that sent no project-key header - a
|
|
// service not yet migrated to identify itself, or a browser request straight to AuthGuard's own
|
|
// web UI, which is not itself a "project" another service authenticates against) is always
|
|
// allowed; restriction only ever applies once a caller actually identifies itself.
|
|
func (s *Store) IsProjectAllowed(ctx context.Context, userID int64, project string) (bool, error) {
|
|
project = strings.ToLower(strings.TrimSpace(project))
|
|
if project == "" {
|
|
return true, nil
|
|
}
|
|
if err := s.validate(); err != nil {
|
|
return false, err
|
|
}
|
|
var total int
|
|
if err := s.pool.QueryRow(ctx, `SELECT count(*) FROM auth_user_projects WHERE user_id = $1`, userID).Scan(&total); err != nil {
|
|
return false, fmt.Errorf("count user projects: %w", err)
|
|
}
|
|
if total == 0 {
|
|
return true, nil
|
|
}
|
|
var allowed bool
|
|
if err := s.pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM auth_user_projects WHERE user_id = $1 AND project = $2)`, userID, project).Scan(&allowed); err != nil {
|
|
return false, fmt.Errorf("check user project: %w", err)
|
|
}
|
|
return allowed, nil
|
|
}
|
|
|
|
var ErrUserExists = errors.New("auth user already exists")
|
|
|
|
// ErrTOTPAlreadyEnabled is returned by SetTOTPSecret while two-factor auth is on.
|
|
var ErrTOTPAlreadyEnabled = errors.New("auth: TOTP is already enabled; disable it before setting a new secret")
|
|
|
|
// ErrEmptyPasswordHash is returned when a credential write has no password hash.
|
|
var ErrEmptyPasswordHash = errors.New("auth: password hash is required")
|
|
|
|
// ErrInvalidUsername is returned for a username containing "@", which would be read as an email.
|
|
var ErrInvalidUsername = errors.New("auth: username cannot contain @")
|
|
|
|
// validateCredentials refuses a credential write that would leave an account without a password
|
|
// hash, or that stores a username which could be mistaken for another account's email.
|
|
func validateCredentials(username, passwordHash string) error {
|
|
if passwordHash == "" {
|
|
return ErrEmptyPasswordHash
|
|
}
|
|
if strings.Contains(username, "@") {
|
|
return ErrInvalidUsername
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) validate() error {
|
|
if s == nil || s.pool == nil {
|
|
return errors.New("auth store has no postgres pool")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
|
|
var user User
|
|
err := s.pool.QueryRow(ctx, query, arg).Scan(
|
|
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
|
|
)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("find auth user: %w", err)
|
|
}
|
|
return &user, nil
|
|
}
|