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

+42 -31
View File
@@ -1,31 +1,42 @@
#################################################################
# Server
#################################################################
PORT=3000
APP_VERSION=dev
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
COOKIE_SECURE=false
#################################################################
# PostgreSQL configuration
#################################################################
# Postgres connection string (bring your own - this app does not run Postgres for you).
# Example: postgres://user:password@localhost:5432/collabtable
DATABASE_URL=
#################################################################
# Startup resilience and sync tuning
#################################################################
# DB init retry interval in milliseconds (default: 5000)
DB_INIT_RETRY_INTERVAL_MS=5000
# Max DB init retry attempts. 0 means retry forever (default: 0)
DB_INIT_RETRY_MAX_ATTEMPTS=0
# Allow at most this much client clock skew into sync timestamps (default: 0)
# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops.
SYNC_MAX_FUTURE_SKEW_MS=0
# Notification retention period in milliseconds (default: 7 days)
NOTIF_RETENTION_MS=604800000
#################################################################
# Server
#################################################################
PORT=3000
APP_VERSION=dev
# Set to "true" once served over HTTPS - marks the admin session cookie Secure.
COOKIE_SECURE=false
#################################################################
# Authentication (AuthGuard)
#################################################################
# Base URL of the AuthGuard centralized identity service this app authenticates
# through instead of a local user table.
# AUTHGUARD_URL=https://auth.example.com
# Leaving AUTHGUARD_URL unset does NOT fall back to any local account store --
# it disables authentication entirely (no login screen, everything open).
# Only run without it for local development or a deployment you are certain
# does not need access control.
#################################################################
# PostgreSQL configuration
#################################################################
# Postgres connection string (bring your own - this app does not run Postgres for you).
# Example: postgres://user:password@localhost:5432/collabtable
DATABASE_URL=
#################################################################
# Startup resilience and sync tuning
#################################################################
# DB init retry interval in milliseconds (default: 5000)
DB_INIT_RETRY_INTERVAL_MS=5000
# Max DB init retry attempts. 0 means retry forever (default: 0)
DB_INIT_RETRY_MAX_ATTEMPTS=0
# Allow at most this much client clock skew into sync timestamps (default: 0)
# Keep this at 0 to prevent future-dated rows from being re-sent in hot loops.
SYNC_MAX_FUTURE_SKEW_MS=0
# Notification retention period in milliseconds (default: 7 days)
NOTIF_RETENTION_MS=604800000
+17 -5
View File
@@ -8,8 +8,10 @@ Svelte dashboard and the Android synchronization API from one container.
- REST API for lists, fields, items, and item values
- Transactional HTTP synchronization with soft-delete tombstones
- Notification polling for background refreshes
- Single-admin browser session with bcrypt-hashed credentials
- Long-lived bearer API token for Android and other sync clients
- Multi-user browser sessions (with per-account roles/admin user management) authenticated
through AuthGuard, a centralized identity service shared across projects (optional -- see
`AUTHGUARD_URL` below)
- Long-lived bearer API token for Android and other sync clients (independent of AuthGuard)
- Embedded SvelteKit dashboard
- Idempotent PostgreSQL schema initialization
@@ -21,11 +23,12 @@ docker build -f docker/Dockerfile -t collabtable-server .
docker run -d --name collabtable-server --restart unless-stopped \
-p 3000:3000 \
-e DATABASE_URL=postgres://user:password@host:5432/collabtable \
-e AUTHGUARD_URL=https://auth.example.com \
-e COOKIE_SECURE=false \
collabtable-server
```
Open `http://localhost:3000` to create the administrator account. Generate an API token from
Open `http://localhost:3000` to create the first account. Generate an API token from
the dashboard's Settings menu and enter it in the Android app.
## Local development
@@ -73,8 +76,13 @@ notification events.
- `GET /api/auth/token/status`
- `POST /api/auth/token/regenerate`
Browser authentication uses the `collabtable_session` HTTP-only cookie. There is one admin
account per database. API tokens are hashed at rest and shown only when generated.
Browser authentication proxies to AuthGuard (`AUTHGUARD_URL`), which sets and reads its own
`auth_session` HTTP-only cookie; CollabTable itself mints no session token. Any number of
accounts can exist, with `user`/`admin`/`superadmin` roles managed via `/api/auth/users`.
`AUTHGUARD_URL` is optional: leaving it unset disables authentication entirely (no login
screen, nothing gated) rather than falling back to any local account store -- only use that for
local development or a deployment you are certain does not need access control. API tokens are
unrelated to AuthGuard (see below), hashed at rest, and shown only when generated.
### Data
@@ -104,6 +112,10 @@ account per database. API tokens are hashed at rest and shown only when generate
- `APP_VERSION` — optional version displayed in the dashboard, default `dev`
- `COOKIE_SECURE` — set to `true` when served over HTTPS
- `DATABASE_URL` — PostgreSQL connection string, required
- `AUTHGUARD_URL` — base URL of the AuthGuard identity service CollabTable authenticates
against, default unset (auth disabled). Leaving it unset does not fall back to any local
account store -- it disables authentication entirely, treating every request as
authenticated with nothing gated.
- `DB_INIT_RETRY_INTERVAL_MS` — startup retry delay, default `5000`
- `DB_INIT_RETRY_MAX_ATTEMPTS` — maximum startup attempts, `0` retries forever
- `SYNC_MAX_FUTURE_SKEW_MS` — allowed client timestamp skew, default `0`
+685 -270
View File
File diff suppressed because it is too large. Load diff
+194
View File
@@ -0,0 +1,194 @@
package main
import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// unreachableAuthGuardClient returns an authclient.Client pointed at a real
// address that is guaranteed to refuse the connection: an httptest.Server
// that has already been closed. This exercises a genuine transport-level
// failure (connection refused), the same failure mode as "AUTHGUARD_URL is
// configured but AuthGuard is down/unreachable", rather than simulating it by
// hand.
func unreachableAuthGuardClient(t *testing.T) *authclient.Client {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := srv.URL
srv.Close()
return authclient.New(url)
}
func TestAuthNormalization(t *testing.T) {
username, err := normalizeUsername(" admin ")
if err != nil || username != "admin" {
t.Fatalf("normalizeUsername() = %q, %v", username, err)
}
email, err := normalizeEmail(" Admin@Example.COM ")
if err != nil || email != "admin@example.com" {
t.Fatalf("normalizeEmail() = %q, %v", email, err)
}
if err := validatePassword("short"); err == nil {
t.Fatal("validatePassword() accepted a short password")
}
}
func TestSessionTokenReadsAuthGuardCookie(t *testing.T) {
a := &AuthService{}
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
if got := a.sessionToken(req); got != "sometoken" {
t.Fatalf("sessionToken() = %q, want %q", got, "sometoken")
}
}
func TestSessionTokenIgnoresLegacyCookieName(t *testing.T) {
// The pre-migration collabtable_session cookie is no longer read as a
// session credential; only AuthGuard's own auth_session cookie is.
a := &AuthService{}
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
req.AddCookie(&http.Cookie{Name: legacySessionCookieName, Value: "stale-value"})
if got := a.sessionToken(req); got != "" {
t.Fatalf("sessionToken() = %q, want empty for a legacy-only cookie", got)
}
}
func TestWriteAuthGuardErrorForwardsAPIError(t *testing.T) {
rec := httptest.NewRecorder()
writeAuthGuardError(rec, &authclient.APIError{StatusCode: http.StatusConflict, Message: "username or email is already in use"}, "fallback")
if rec.Code != http.StatusConflict {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusConflict)
}
if body := rec.Body.String(); body == "" {
t.Fatal("response body was empty")
}
}
func TestWriteAuthGuardErrorFallsBackForTransportFailures(t *testing.T) {
rec := httptest.NewRecorder()
writeAuthGuardError(rec, errors.New("dial tcp: connection refused"), "unable to reach AuthGuard")
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusInternalServerError)
}
}
func TestCurrentUserIDUsesPlaceholderWhenAuthDisabled(t *testing.T) {
a := &AuthService{}
req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil)
id, ok, err := a.currentUserID(req)
if err != nil {
t.Fatalf("currentUserID() error = %v, want nil in disabled mode", err)
}
if !ok {
t.Fatal("currentUserID() ok = false, want true in disabled mode (every request shares the placeholder identity)")
}
if id != localProfile.ID {
t.Fatalf("currentUserID() id = %d, want %d (localProfile.ID)", id, localProfile.ID)
}
}
func TestRequireSessionLetsRequestThroughWhenAuthDisabled(t *testing.T) {
a := &AuthService{}
nextCalled := false
handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
nextCalled = true
}))
req := httptest.NewRequest(http.MethodGet, "/api/tech-stack", nil)
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if !nextCalled {
t.Fatal("requireSession did not let the request through despite auth being disabled (AUTHGUARD_URL unset)")
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
}
// The following tests cover the specific failure mode of AUTHGUARD_URL being
// configured but AuthGuard being unreachable (connection refused). This must
// never be silently treated as "no session" (which would either let an
// unauthenticated request through, for requireSession, or show a bare "please
// log in" screen with no indication anything is wrong, for handleStatus) --
// it must surface as a distinct, visible error. See currentUser/
// currentProfile's doc comments and errAuthGuardUnavailable.
func TestCurrentUserSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
user, err := a.currentUser(req)
if err == nil {
t.Fatal("currentUser() returned no error for an unreachable AuthGuard; want a transport error")
}
if errors.Is(err, authclient.ErrInvalidSession) {
t.Fatal("currentUser() classified a transport failure as ErrInvalidSession -- this would make requireSession treat 'AuthGuard is down' as 'not logged in' instead of a 500")
}
if user != nil {
t.Fatalf("currentUser() returned a user (%+v) despite AuthGuard being unreachable", user)
}
}
func TestCurrentProfileSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
req := httptest.NewRequest(http.MethodGet, "/api/auth/status", nil)
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
profile, token, err := a.currentProfile(req)
if err == nil {
t.Fatal("currentProfile() returned no error for an unreachable AuthGuard; want a transport error")
}
if profile != nil {
t.Fatalf("currentProfile() returned a profile (%+v) despite AuthGuard being unreachable", profile)
}
if token != "" {
t.Fatalf("currentProfile() returned a token (%q) alongside an error", token)
}
}
func TestCurrentUserIDSurfacesErrorWhenAuthGuardUnreachable(t *testing.T) {
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
req := httptest.NewRequest(http.MethodGet, "/api/auth/token/status", nil)
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
if _, ok, err := a.currentUserID(req); err == nil || ok {
t.Fatalf("currentUserID() = (ok=%v, err=%v), want ok=false and a non-nil transport error", ok, err)
}
}
func TestRequireSessionReturns500RatherThanLettingRequestThroughWhenAuthGuardUnreachable(t *testing.T) {
a := &AuthService{authGuard: unreachableAuthGuardClient(t)}
nextCalled := false
handler := a.requireSession(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
nextCalled = true
}))
req := httptest.NewRequest(http.MethodGet, "/api/status", nil)
req.AddCookie(&http.Cookie{Name: authclient.DefaultCookieName, Value: "sometoken"})
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if nextCalled {
t.Fatal("requireSession let the request through to the wrapped handler despite AuthGuard being unreachable")
}
if rec.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want %d (must not be 401 'please log in' or 200)", rec.Code, http.StatusInternalServerError)
}
if body := rec.Body.String(); !strings.Contains(strings.ToLower(body), "authentication service") {
t.Fatalf("response body = %q, want a message identifying the authentication service as the problem", body)
}
}
+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
}
+32 -17
View File
@@ -15,6 +15,8 @@ import (
"time"
_ "github.com/joho/godotenv/autoload"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
)
// The SvelteKit build is copied here by the Docker builder before go build.
@@ -50,7 +52,20 @@ func main() {
go database.pruneExpiredSessions(ctx)
go database.cleanupNotifications(ctx)
auth := newAuthService(database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
// AuthGuard is optional (see auth.go's top-of-file "Auth-disabled mode"
// section): a nil client means every request is treated as already
// authenticated, with nothing gated -- an explicit choice for local
// development or a standalone deployment, not a degraded fallback.
authGuardURL := strings.TrimSpace(os.Getenv("AUTHGUARD_URL"))
var authGuard *authclient.Client
if authGuardURL != "" {
authGuard = authclient.New(authGuardURL)
fmt.Printf("auth: AuthGuard at %s\n", authGuardURL)
} else {
fmt.Println("auth: DISABLED (AUTHGUARD_URL not set) -- every request is treated as authenticated")
}
auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true"))
server := &Server{db: database, auth: auth, startTime: time.Now()}
webRoot, err := fs.Sub(webFS, "web")
@@ -121,19 +136,19 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
mux.HandleFunc("POST /api/auth/reset/confirm", s.auth.handleResetConfirm)
mux.HandleFunc("POST /api/auth/setup", s.auth.handleSetup)
mux.HandleFunc("POST /api/auth/login", s.auth.handleLogin)
mux.Handle("POST /api/auth/logout", s.auth.requireSession(s.auth.handleLogout))
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(s.auth.handleUpdateCredentials))
mux.Handle("GET /api/auth/users", s.auth.requireSession(s.auth.handleUsers))
mux.Handle("POST /api/auth/users", s.auth.requireSession(s.auth.handleUsers))
mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(s.auth.handleUser))
mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(s.auth.handleTOTPStatus))
mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(s.auth.handleTOTPSetup))
mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(s.auth.handleTOTPEnable))
mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(s.auth.handleTOTPDisable))
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(s.auth.handleTokenStatus))
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(s.auth.handleTokenRegenerate))
mux.Handle("POST /api/auth/logout", s.auth.requireSession(http.HandlerFunc(s.auth.handleLogout)))
mux.Handle("POST /api/auth/credentials", s.auth.requireSession(http.HandlerFunc(s.auth.handleUpdateCredentials)))
mux.Handle("GET /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
mux.Handle("POST /api/auth/users", s.auth.requireSession(http.HandlerFunc(s.auth.handleUsers)))
mux.Handle("PUT /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
mux.Handle("PATCH /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
mux.Handle("DELETE /api/auth/users/{id}", s.auth.requireSession(http.HandlerFunc(s.auth.handleUser)))
mux.Handle("GET /api/auth/totp/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPStatus)))
mux.Handle("POST /api/auth/totp/setup", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPSetup)))
mux.Handle("POST /api/auth/totp/enable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPEnable)))
mux.Handle("POST /api/auth/totp/disable", s.auth.requireSession(http.HandlerFunc(s.auth.handleTOTPDisable)))
mux.Handle("GET /api/auth/token/status", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenStatus)))
mux.Handle("POST /api/auth/token/regenerate", s.auth.requireSession(http.HandlerFunc(s.auth.handleTokenRegenerate)))
// Sync/collaboration API routes use a long-lived bearer token shared by the
// user's devices. This is deliberately separate from browser sessions.
@@ -163,8 +178,8 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) {
// The dashboard is a public SPA shell, but its data and tech-stack endpoints
// are protected by the browser session.
mux.Handle("GET /api/tech-stack", s.auth.requireSession(s.handleTechStack))
mux.Handle("GET /web/data", s.auth.requireSession(s.handleWebData))
mux.Handle("GET /api/tech-stack", s.auth.requireSession(http.HandlerFunc(s.handleTechStack)))
mux.Handle("GET /web/data", s.auth.requireSession(http.HandlerFunc(s.handleWebData)))
mux.Handle("/", spaFileServer(webRoot))
}
@@ -274,7 +289,7 @@ type stackEntry struct {
Value string `json:"value"`
}
func (s *Server) handleTechStack(w http.ResponseWriter, _ *http.Request, _ *AuthUser) {
func (s *Server) handleTechStack(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, techStackResponse{
AppVersion: envOrDefault("APP_VERSION", "dev"),
Stack: []stackEntry{
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"time"
)
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request, _ *AuthUser) {
func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
lists, err := s.db.queryLists(r.Context(), false, nil)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")