Migrate CollabTable's AuthGuard proxy onto shared/backend/auth
Lint / Lint (push) Successful in 38s
Tests / Go backend (push) Successful in 1m9s
Tests / Dashboard checks (push) Successful in 1m25s
Docker / Docker Build & Push (push) Successful in 4m32s

Replaces the ~1044-line bespoke session/login/TOTP/admin-user proxy
(backend/auth.go, built directly on authclient) with
sharedauth.NewWithStore, the same shared engine GameStream and
OmniLogger already migrated onto. A tiny collabTableAuthStore adapter
delegates the local one-time setup-claim flag to the existing
collabtable_setup_state table/queries; CollabTable never had a
"require login" toggle, so LoginRequired always reports true and
SetLoginRequired is a no-op.

The local authguard_totp_cache (GetCachedTOTPEnabled/
SetCachedTOTPEnabled) is retired: the shared engine reads TOTP status
live from AuthGuard's GET /api/me. Its table is left in place, same as
the already-dormant auth_users/auth_sessions tables.

URL paths and HTTP methods are unchanged; only response shapes
changed to the shared engine's standardized ones (nested `user: {...}`,
`data: {...}` for TOTP setup/enable/disable). Updated
frontend/src/lib/api.js to translate these back into the shapes the
rest of the frontend already expects, and AppShell.svelte's
saveProfile to always send the current username/email (UpdateMe
requires a non-empty email on every call).

Known behavior differences: POST /api/auth/setup now returns 201
instead of 200; PUT/PATCH /api/auth/users/{id} now returns the updated
user instead of {"ok":true}; POST /api/auth/credentials no longer
forces re-login after a successful change (no bulk session-invalidation
call exists in the shared engine, only single-session Logout).

The separate device/sync API bearer-token scheme (requireAPIToken,
handleTokenStatus/handleTokenRegenerate) is untouched other than
resolving the caller's identity via sharedauth.UserFromContext instead
of local session lookups.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Sonnet 5 committed 2026-09-13 21:11:53 +02:00
1 parent aae8d3807d
commit 6e13364ebd
7 files changed
+300 -1230

No files matched your search

+41 -170
View File
@@ -1,194 +1,65 @@
package main
import (
"errors"
"context"
"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)
}
// The bulk of what auth_test.go used to cover (username/email normalization,
// session-cookie parsing, AuthGuard-unreachable error surfacing, AuthGuard
// error forwarding) is now sharedauth's own responsibility and covered by
// that package's tests (shared/backend/auth). What's left to test here is
// CollabTable's own tiny addition: the collabTableAuthStore adapter wired
// into newAuthService (see auth.go).
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)
func TestCollabTableAuthStoreLoginRequiredAlwaysTrue(t *testing.T) {
store := collabTableAuthStore{}
required, err := store.LoginRequired(context.Background())
if err != nil {
t.Fatalf("currentUserID() error = %v, want nil in disabled mode", err)
t.Fatalf("LoginRequired() error = %v", 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)
if !required {
t.Fatal("LoginRequired() = false, want true: CollabTable always requires a session when AuthGuard is configured")
}
}
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)")
func TestCollabTableAuthStoreSetLoginRequiredIsNoOp(t *testing.T) {
store := collabTableAuthStore{}
if err := store.SetLoginRequired(context.Background(), false); err != nil {
t.Fatalf("SetLoginRequired() error = %v, want nil (CollabTable has no such toggle)", err)
}
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
// Confirm it really didn't change anything observable.
required, err := store.LoginRequired(context.Background())
if err != nil {
t.Fatalf("LoginRequired() error = %v", err)
}
if !required {
t.Fatal("SetLoginRequired(false) unexpectedly changed LoginRequired()'s answer")
}
}
// 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 TestNewAuthServiceBuildsAService(t *testing.T) {
// newAuthService must not panic given a nil *DB and no AuthGuard URL
// (auth-disabled mode) -- the store adapter's IsSetupClaimed/
// TryClaimSetup/UnclaimSetup only get called once a real request comes in
// and AuthGuard is enabled, so construction alone must be safe.
if service := newAuthService(nil, "", false); service == nil {
t.Fatal("newAuthService() returned nil")
}
}
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"})
func TestExtractBearerRequiresBearerPrefix(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/api/lists", nil)
req.Header.Set("Authorization", "Bearer sometoken")
if got := extractBearer(req); got != "sometoken" {
t.Fatalf("extractBearer() = %q, want %q", got, "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)
req = httptest.NewRequest(http.MethodGet, "/api/lists", nil)
req.Header.Set("Authorization", "sometoken")
if got := extractBearer(req); got != "" {
t.Fatalf("extractBearer() = %q, want empty for a header missing the Bearer prefix", got)
}
}