Migrate auth to AuthGuard, retiring local Postgres-backed accounts
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:
1 parent
a1c29728f0
commit
9a6ec940f7
48 files changed
+12401
-511
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user