Migrate auth to AuthGuard, retiring local Postgres-backed accounts
Lint / Lint (push) Failing after 32s
Tests / Go backend (push) Successful in 54s
Tests / Dashboard checks (push) Successful in 51s
Docker / Docker Build & Push (push) Successful in 5m14s

Same pattern as GameStream (commit 6a46007), adapted for CollabTable
being genuinely multi-user (not single-admin): admin user management
(list/create/update/delete, role reassignment, superadmin protection)
is fully proxied to AuthGuard, which already enforces the same rules
CollabTable checked locally. Cookie forwarding, no local session token,
AUTHGUARD_URL optional (unset = auth fully disabled), transport
failures always surface as errAuthGuardUnavailable rather than ever
letting a request through - proven with live tests against a closed
socket.

CollabTable's device-sync API token feature (separate from browser
sessions) is deliberately left local-only regardless of AUTHGUARD_URL,
keyed by a new currentUserID helper (AuthGuard's id when enabled, the
shared placeholder id 0 when disabled) - a real, functional token
either way, not faked data.

Real bug found and fixed: api_tokens.user_id had a hard FK into the
local auth_users table, which would reject new tokens once accounts
stop being written locally. Dropped the now-invalid FK.

Known, accepted gap (same as GameStream): self-service profile editing
for non-admin accounts is lost, since AuthGuard only exposes an admin
endpoint, no self-edit. TOTP QR issuer branding now comes from AuthGuard
rather than CollabTable.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-01 01:34:48 +02:00
1 parent a1c29728f0
commit 9a6ec940f7
48 files changed
+12401 -511

No files matched your search

+110 -186
View File
@@ -9,7 +9,6 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth"
sharedpostgres "repos.gfranz.ch/Gabriel20xx/shared/backend/postgres"
)
@@ -100,6 +99,15 @@ func (d *DB) initSchema(ctx context.Context) error {
ALTER TABLE fields ADD COLUMN IF NOT EXISTS alignment TEXT NOT NULL DEFAULT 'start';
-- auth_users/auth_sessions are RETIRED as of the AuthGuard migration:
-- account and session state now lives in AuthGuard's own database,
-- reached over HTTP via authclient (see auth.go). These two tables and
-- their schema are deliberately left in place rather than dropped --
-- dropping tables/data is a separate, more destructive decision outside
-- the scope of that migration -- but no Go code reads or writes them for
-- authentication purposes anymore. pruneExpiredSessions keeps running
-- only as harmless best-effort cleanup of whatever rows a pre-migration
-- deployment already had.
CREATE TABLE IF NOT EXISTS auth_users (
id BIGSERIAL PRIMARY KEY,
username TEXT NOT NULL UNIQUE,
@@ -131,13 +139,53 @@ func (d *DB) initSchema(ctx context.Context) error {
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);
-- collabtable_setup_state tracks only whether THIS CollabTable instance
-- has completed its one-time "create the first account" setup flow
-- against AuthGuard (see handleSetup in auth.go). It intentionally holds
-- no credentials or account identity of its own -- AuthGuard is the sole
-- source of truth for accounts -- just the boolean that used to be
-- derived from "COUNT(*) FROM auth_users" before the migration.
CREATE TABLE IF NOT EXISTS collabtable_setup_state (
id SMALLINT PRIMARY KEY DEFAULT 1,
claimed BOOLEAN NOT NULL DEFAULT FALSE,
claimed_at TIMESTAMPTZ,
CHECK (id = 1)
);
-- authguard_totp_cache is a best-effort, locally-cached mirror of "does
-- this AuthGuard account have TOTP enabled", keyed by AuthGuard's own
-- numeric user id. AuthGuard's HTTP API (deliberately not modified by
-- this migration) has no endpoint to query current TOTP status, only to
-- enable/verify/disable it, so CollabTable keeps this cache updated
-- itself at every point it can observe the true state (successful TOTP
-- verify/disable calls, and a successful login attempted without a TOTP
-- token, which AuthGuard would have rejected had TOTP been enabled). See
-- handleTOTPStatus's doc comment in auth.go for the full reasoning and
-- its known staleness caveat.
CREATE TABLE IF NOT EXISTS authguard_totp_cache (
authguard_user_id BIGINT PRIMARY KEY,
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
-- api_tokens backs the long-lived per-account bearer token CollabTable's
-- own devices use for the sync API (requireAPIToken in auth.go) -- a
-- concern entirely separate from browser-session auth, so it is NOT
-- proxied to AuthGuard. Its user_id used to be a foreign key into this
-- database's own auth_users; now that account identity lives in
-- AuthGuard (or, when AUTHGUARD_URL is unset, every caller shares the
-- fixed placeholder id 0 -- see localProfile/currentUserID in auth.go),
-- user_id is just an opaque identity id with no matching row in the
-- (now dormant) local auth_users table, so the FK constraint a
-- pre-migration deployment already has is dropped below.
CREATE TABLE IF NOT EXISTS api_tokens (
id BIGSERIAL PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES auth_users(id) ON DELETE CASCADE,
user_id BIGINT NOT NULL,
token_hash TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS api_tokens_user_idx ON api_tokens(user_id);
ALTER TABLE api_tokens DROP CONSTRAINT IF EXISTS api_tokens_user_id_fkey;
`)
if err != nil {
return fmt.Errorf("initialize schema: %w", err)
@@ -181,210 +229,86 @@ func (d *DB) cleanupNotifications(ctx context.Context) {
}
}
type AuthUser struct {
ID int64
Username string
Email string
PasswordHash string
TOTPSecret string
TOTPEnabled bool
Role string
}
// --- AuthGuard migration: local-only auxiliary state ------------------------
//
// Everything below is new state introduced by the AuthGuard migration. None
// of it is account/credential data -- that all lives in AuthGuard now -- it
// is bookkeeping CollabTable keeps about itself. See auth.go for how each is
// used.
var ErrSingletonUserExists = errors.New("a user already exists")
func (d *DB) countUsers(ctx context.Context) (int, error) {
var count int
if err := d.pool.QueryRow(ctx, `SELECT count(*) FROM auth_users`).Scan(&count); err != nil {
return 0, fmt.Errorf("count users: %w", err)
}
return count, nil
}
func (d *DB) deleteAllUsers(ctx context.Context) error {
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_users`); err != nil {
return fmt.Errorf("delete all users: %w", err)
}
return nil
}
func (d *DB) createUser(ctx context.Context, username, email, passwordHash string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, 'superadmin', now())
RETURNING id, username, email, role
`, username, email, passwordHash).Scan(&user.ID, &user.Username, &user.Email, &user.Role)
if err != nil {
if sharedpostgres.IsUniqueViolation(err) {
return nil, ErrSingletonUserExists
}
return nil, fmt.Errorf("create user: %w", err)
}
user.PasswordHash = passwordHash
return &user, nil
}
func (d *DB) getUserByIdentifier(ctx context.Context, identifier string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
SELECT id, username, email, password_hash, COALESCE(totp_secret, ''), COALESCE(totp_enabled, false), COALESCE(role, 'user')
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
`, identifier).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role)
// IsSetupClaimed reports whether this CollabTable instance has already
// completed its one-time setup flow (see TryClaimSetup).
func (d *DB) IsSetupClaimed(ctx context.Context) (bool, error) {
var claimed bool
err := d.pool.QueryRow(ctx, `SELECT claimed FROM collabtable_setup_state WHERE id = 1`).Scan(&claimed)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
return false, nil
}
if err != nil {
return nil, fmt.Errorf("get user: %w", err)
return false, fmt.Errorf("check setup claim: %w", err)
}
return &user, nil
return claimed, nil
}
func (d *DB) getSessionUser(ctx context.Context, tokenHash string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
SELECT u.id, u.username, u.email, u.password_hash, COALESCE(u.totp_secret, ''), COALESCE(u.totp_enabled, false), COALESCE(u.role, 'user')
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).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("get session user: %w", err)
}
return &user, nil
}
func (d *DB) createSession(ctx context.Context, userID int64, tokenHash string, expiresAt time.Time) error {
_, err := d.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 session: %w", err)
}
return nil
}
func (d *DB) deleteSession(ctx context.Context, tokenHash string) error {
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE token_hash = $1`, tokenHash)
if err != nil {
return fmt.Errorf("delete session: %w", err)
}
return nil
}
func (d *DB) updateUserCredentials(ctx context.Context, userID int64, username, email, passwordHash string) error {
_, err := d.pool.Exec(ctx, `
UPDATE auth_users
SET username = $1, email = $2, password_hash = $3, updated_at = now()
WHERE id = $4
`, username, email, passwordHash, userID)
if err != nil {
return fmt.Errorf("update user credentials: %w", err)
}
return nil
}
func (d *DB) listUsers(ctx context.Context) ([]AuthUser, error) {
rows, err := d.pool.Query(ctx, `
SELECT id, username, email, COALESCE(role, 'user'), COALESCE(totp_enabled, false)
FROM auth_users ORDER BY created_at, id
// TryClaimSetup atomically flips the local "setup completed" flag from
// unclaimed to claimed and reports whether this call was the one that did so.
// A caller that wins the claim but then fails to actually create the
// AuthGuard account (e.g. a validation error, or AuthGuard being unreachable)
// must call UnclaimSetup to reopen the slot for a later retry.
func (d *DB) TryClaimSetup(ctx context.Context) (bool, error) {
tag, err := d.pool.Exec(ctx, `
INSERT INTO collabtable_setup_state (id, claimed, claimed_at) VALUES (1, TRUE, now())
ON CONFLICT (id) DO UPDATE SET claimed = TRUE, claimed_at = now()
WHERE collabtable_setup_state.claimed = FALSE
`)
if err != nil {
return nil, fmt.Errorf("list users: %w", err)
return false, fmt.Errorf("claim setup: %w", err)
}
defer rows.Close()
users := make([]AuthUser, 0)
for rows.Next() {
var user AuthUser
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.TOTPEnabled); err != nil {
return nil, fmt.Errorf("scan user: %w", err)
}
users = append(users, user)
}
return users, rows.Err()
return tag.RowsAffected() > 0, nil
}
func (d *DB) getUserByID(ctx context.Context, id int64) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
SELECT id, username, email, password_hash, COALESCE(totp_secret, ''),
COALESCE(totp_enabled, false), COALESCE(role, 'user')
FROM auth_users WHERE id = $1
`, id).Scan(&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.TOTPSecret, &user.TOTPEnabled, &user.Role)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("get user by id: %w", err)
}
return &user, nil
}
func (d *DB) createManagedUser(ctx context.Context, username, email, passwordHash, role string) (*AuthUser, error) {
var user AuthUser
err := d.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, role
`, username, email, passwordHash, sharedauth.NormalizeRole(role)).Scan(&user.ID, &user.Username, &user.Email, &user.Role)
if err != nil {
if sharedpostgres.IsUniqueViolation(err) {
return nil, ErrSingletonUserExists
}
return nil, fmt.Errorf("create managed user: %w", err)
}
return &user, nil
}
func (d *DB) updateManagedUser(ctx context.Context, id int64, username, email, passwordHash, role string) error {
_, err := d.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, sharedauth.NormalizeRole(role), id)
if err != nil {
return fmt.Errorf("update managed user: %w", err)
// UnclaimSetup reopens the setup flow after a claimed-but-failed setup
// attempt (see TryClaimSetup).
func (d *DB) UnclaimSetup(ctx context.Context) error {
if _, err := d.pool.Exec(ctx, `UPDATE collabtable_setup_state SET claimed = FALSE, claimed_at = NULL WHERE id = 1`); err != nil {
return fmt.Errorf("unclaim setup: %w", err)
}
return nil
}
func (d *DB) deleteUser(ctx context.Context, id int64) error {
if _, err := d.pool.Exec(ctx, `DELETE FROM auth_users WHERE id = $1`, id); err != nil {
return fmt.Errorf("delete user: %w", err)
}
return nil
// ClearSetupClaim resets the local "setup completed" flag so the setup screen
// reappears. Used by the local break-glass password-reset flow (see
// handleResetConfirm in auth.go) -- it deliberately does not touch the
// underlying AuthGuard account at all.
func (d *DB) ClearSetupClaim(ctx context.Context) error {
return d.UnclaimSetup(ctx)
}
func (d *DB) getTOTPState(ctx context.Context, userID int64) (string, bool, error) {
var secret string
// GetCachedTOTPEnabled returns the best-effort locally-cached TOTP-enabled
// state for an AuthGuard account, or false if this instance has never
// observed that account's TOTP state. See handleTOTPStatus's doc comment in
// auth.go.
func (d *DB) GetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64) (bool, error) {
var enabled bool
err := d.pool.QueryRow(ctx, `SELECT COALESCE(totp_secret, ''), COALESCE(totp_enabled, false) FROM auth_users WHERE id = $1`, userID).Scan(&secret, &enabled)
return secret, enabled, err
}
func (d *DB) setTOTPSecret(ctx context.Context, userID int64, secret string) error {
_, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = $1, totp_enabled = false, updated_at = now() WHERE id = $2`, secret, userID)
return err
}
func (d *DB) enableTOTP(ctx context.Context, userID int64) error {
_, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_enabled = true, updated_at = now() WHERE id = $1 AND totp_secret <> ''`, userID)
return err
}
func (d *DB) disableTOTP(ctx context.Context, userID int64) error {
_, err := d.pool.Exec(ctx, `UPDATE auth_users SET totp_secret = '', totp_enabled = false, updated_at = now() WHERE id = $1`, userID)
return err
}
func (d *DB) deleteSessionsForUser(ctx context.Context, userID int64) error {
_, err := d.pool.Exec(ctx, `DELETE FROM auth_sessions WHERE user_id = $1`, userID)
err := d.pool.QueryRow(ctx, `SELECT totp_enabled FROM authguard_totp_cache WHERE authguard_user_id = $1`, authGuardUserID).Scan(&enabled)
if errors.Is(err, pgx.ErrNoRows) {
return false, nil
}
if err != nil {
return fmt.Errorf("delete sessions for user: %w", err)
return false, fmt.Errorf("get cached totp state: %w", err)
}
return enabled, nil
}
// SetCachedTOTPEnabled upserts the best-effort locally-cached TOTP-enabled
// state for an AuthGuard account.
func (d *DB) SetCachedTOTPEnabled(ctx context.Context, authGuardUserID int64, enabled bool) error {
_, err := d.pool.Exec(ctx, `
INSERT INTO authguard_totp_cache (authguard_user_id, totp_enabled, updated_at) VALUES ($1, $2, now())
ON CONFLICT (authguard_user_id) DO UPDATE SET totp_enabled = $2, updated_at = now()
`, authGuardUserID, enabled)
if err != nil {
return fmt.Errorf("set cached totp state: %w", err)
}
return nil
}