diff --git a/backend/auth.go b/backend/auth.go index a947e0c..820c00e 100644 --- a/backend/auth.go +++ b/backend/auth.go @@ -6,244 +6,148 @@ import ( "crypto/sha256" "encoding/base64" "encoding/hex" - "errors" "net/http" - "strconv" "strings" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" - authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" - "repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy" ) -// AuthGuard migration -// ==================== +// AuthGuard migration onto the shared auth engine +// ===================================================== // -// CollabTable used to be a fully self-contained, multi-user auth -// implementation: account and session state lived in this service's own -// PostgreSQL `auth_users`/`auth_sessions` tables (see db.go's schema, which -// is kept but no longer used for this -- see initSchema's doc comment). -// Unlike GameStream (a single-admin tool this migration was first proven -// against), CollabTable is a real multi-user collaboration app: it already -// had full admin user management (list/create/edit/delete other accounts, -// assign roles) before this migration, not just a single local admin -// account. That feature maps directly onto AuthGuard's own -// /api/admin/users endpoints (see AuthGuard/README.md), which enforce the -// exact same rules CollabTable's local implementation did (protected -// superadmin, no self-delete, role-reassignment restricted to superadmin -// actors) -- so handleUsers/handleUser below simply proxy and trust -// AuthGuard's authorization instead of re-checking those rules locally. +// CollabTable used to carry its own ~1044-line reimplementation of this file +// (account/session proxying to AuthGuard, TOTP proxying, admin user +// management, the local one-time setup-claim flag), built directly on the +// lower-level shared/backend/authclient package -- similar to what GameStream +// and OmniLogger used to have before they were migrated onto the shared +// engine (see Original/GameStream/backend/cmd/gamestreamd/auth.go). That +// reimplementation is gone: this file now only builds a sharedauth.Service +// (see shared/backend/auth/proxy.go for the full design doc, including its +// own "Setup flow" and "Auth-disabled mode" sections, both of which apply +// here unchanged) via a tiny Store adapter over *DB, and server.go wires +// *sharedauth.Service's methods directly onto CollabTable's existing +// /api/auth/... routes. The URL paths, HTTP methods, and this cookie name are +// unchanged; only the JSON response shapes changed to sharedauth's own +// (nested `user: {...}`, different field names) -- see the frontend changes +// alongside this migration (frontend/src/lib/api.js). // -// It now proxies every browser-session auth operation to AuthGuard -// (Web/Central/AuthGuard), a centralized identity service other projects -// share, via the `authclient` package (Web/Central/shared/backend/ -// authclient, vendored here at shared/backend/authclient). CollabTable's own -// /api/auth/... URL paths and JSON response shapes are UNCHANGED -- the -// frontend was not touched -- only what backs them changed. +// Known, deliberate behavior differences from the pre-migration code: +// - The local authguard_totp_cache table/GetCachedTOTPEnabled/ +// SetCachedTOTPEnabled this file used to maintain are gone (see db.go): +// sharedauth reads TOTP-enabled status live from AuthGuard's GET /api/me +// on every request instead of a local best-effort cache. +// - POST /api/auth/credentials (UpdateMe) no longer forces re-login: the +// pre-migration handleUpdateCredentials called AuthGuard's Logout after a +// successful update to force re-authentication. sharedauth.Service's +// UpdateMe has no equivalent step, so a credentials change now simply +// returns the updated account and leaves the current session valid. +// - POST /api/auth/setup now responds 201 Created (sharedauth.Signup) +// instead of the pre-migration 200 OK. +// - PUT/PATCH /api/auth/users/{id} now responds with the updated managed +// user (sharedauth.ManagedUpdateUser) instead of the pre-migration +// {"ok": true}. // -// One CollabTable feature this migration deliberately leaves alone: the -// long-lived per-account API bearer token used by a user's own devices to -// call the sync API (requireAPIToken below, and handleTokenStatus/ -// handleTokenRegenerate). That token is a device-pairing credential, not a -// browser session, and AuthGuard has no equivalent concept -- it stays -// entirely local, keyed by whatever numeric id currentUserID resolves to -// (an AuthGuard account id, or the fixed placeholder id when auth is -// disabled; see "Auth-disabled mode" below). Its api_tokens table no longer -// foreign-keys into auth_users; see db.go's comment on that table. +// The long-lived per-account API bearer token CollabTable's own devices use +// for the sync API (requireAPIToken, and handleTokenStatus/ +// handleTokenRegenerate below) is untouched by this migration -- it has +// nothing to do with AuthGuard accounts even when AuthGuard IS configured; +// see db.go's comment on api_tokens. handleTokenStatus/handleTokenRegenerate +// still resolve the caller's identity via the browser session (now through +// sharedauth.UserFromContext, populated by wrapping their routes in +// s.auth.Require -- see server.go) purely to scope which device token is +// being read/regenerated. // -// Session cookie / token model -// ----------------------------- -// AuthGuard sets its own `auth_session` cookie (authclient.DefaultCookieName) -// on register/login, whose scope (host-only, or a shared parent domain for -// real cross-project SSO) is entirely controlled by AuthGuard's own -// AUTH_COOKIE_DOMAIN setting -- CollabTable has no opinion on it. Rather -// than inventing a second cookie and a mapping between "CollabTable's -// session token" and "AuthGuard's session token", CollabTable forwards -// AuthGuard's Set-Cookie header straight through to the browser on -// register/login/logout (authclient.ForwardCookies), and reads that same -// `auth_session` cookie back off every incoming request to use as the -// bearer token on its server-to-server calls to AuthGuard (sessionToken/ -// currentUser below). CollabTable mints no session token of its own at all, -// which is both less code and automatically correct under whatever -// cookie-domain SSO topology AuthGuard is configured with. The frontend -// requires no changes for this -- it never reads the cookie's name or value -// itself, only relies on the browser sending it back. -// -// The pre-migration `collabtable_session` cookie name is retained only as -// something logout additionally clears, so a browser that still holds one -// from before this migration doesn't keep sending a now-meaningless cookie -// forever. -// -// Setup flow -// ---------- -// CollabTable's "first launch: create the first (superadmin) account" flow -// doesn't map onto AuthGuard, which is not scoped to a single project and -// has no concept of "this is CollabTable's initial account". CollabTable -// keeps a tiny local flag of its own -- collabtable_setup_state.claimed -// (db.go) -- that means only "has this CollabTable instance completed its -// setup screen once", with no credentials of any kind in it. handleSetup -// atomically claims that flag, registers the account against AuthGuard's -// POST /api/register, and unclaims it again if registration fails (so a bad -// attempt doesn't permanently lock out setup). -// -// The local claim alone would still show this "create account" form to a -// second, third, ... CollabTable instance's own first launch even though -// AuthGuard already has an account from the first one (or from AuthGuard's -// own web UI), since accounts are centralized -- there is no per-instance -// "initial account" once AuthGuard is shared. handleStatus and handleSetup -// both additionally call AuthGuard's GET /api/setup-status -// (authclient.Client.SetupStatus) and treat "AuthGuard already has an -// account" the same as "CollabTable's own setup is already claimed": show -// the login screen, refuse another registration through this flow. -// -// Known gaps versus the pre-migration behavior (AuthGuard was deliberately -// not modified for this migration, so these can only be closed by adding to -// AuthGuard itself later): -// - Self-service profile editing (POST /api/auth/credentials) needs -// AuthGuard's admin/users endpoint, which requires CanManageUsers. A -// plain "user"-role account (not admin/superadmin) has no self-service -// way to change its own username/email/password via AuthGuard today; see -// handleUpdateCredentials. This is a real regression for CollabTable -// specifically (a genuinely multi-user app): a plain collaborator who -// could previously edit their own profile now cannot, until AuthGuard -// grows a true self-service endpoint. -// - AuthGuard has no "is TOTP enabled" read endpoint, only -// enable/verify/disable, so handleTOTPStatus answers from a local -// best-effort cache instead of AuthGuard directly; see its doc comment. -// - The admin user list (GET /api/auth/users) similarly can't ask AuthGuard -// for other accounts' TOTP status, so TotpEnabled on entries other than -// the cache's own observations defaults to false. -// - The TOTP setup QR code's issuer name now comes from AuthGuard's own -// otpauth:// URI rather than being branded "CollabTable" locally, since -// AuthGuard (not CollabTable) generates the secret/URI now. -// - Changing a user's own credentials used to invalidate every session for -// that account (deleteSessionsForUser). AuthGuard has no bulk -// "invalidate every session for this account" call, only single-session -// Logout, so only the session used for the credentials request itself is -// guaranteed revoked; see handleUpdateCredentials. -// -// Auth-disabled mode (AUTHGUARD_URL unset) -// ----------------------------------------- -// AUTHGUARD_URL is optional. When it is unset, AuthService.authGuard is nil -// (AuthService.enabled() reports false) and CollabTable runs with -// authentication turned off entirely: every request is treated as already -// authenticated, with no login screen and nothing gated -- this is an -// explicit mode for local development or a standalone deployment that -// doesn't want centralized identity, not an error condition (unlike the -// pre-migration local-Postgres-auth design this replaced, there is no -// degraded/partial fallback state; it is either "AuthGuard" or "no auth" and -// never silently "local auth"). -// -// requireSession (gating logout/credentials/users/totp/token/tech-stack/web -// data) simply calls through to next without resolving a session at all in -// this mode. handleStatus/handleSetup/handleLogin each special-case this and -// return a fixed placeholder "authenticated" identity (localProfile) without -// ever touching AuthGuard or the local setup-claim flag, so the frontend -// never shows a login or setup screen. handleLogout is a no-op success. -// -// Features that need a *real* backing identity rather than just an access -// gate -- TOTP (setup/enable/disable; handleTOTPStatus alone still answers -// {enabled: false}), self-service profile editing, and admin user -// management's mutating calls -- have nothing meaningful to do without -// AuthGuard (there is no account to attach a TOTP secret to, no profile to -// edit, no user store to create/update/delete against) and return a clear -// errFeatureRequiresAuthGuard error instead of silently no-opping or faking -// data. GET /api/auth/users is the one exception: consistent with "nothing -// gated", it returns an empty list rather than an error, since listing -// (unlike mutating) has an honest, unsurprising answer when there is no user -// store: there are no managed users to show. -// -// The device-sync API token (handleTokenStatus/handleTokenRegenerate) is -// different from the features above: it has nothing to do with AuthGuard -// accounts even when AuthGuard IS configured (see the top of this comment), -// so it keeps working in disabled mode too, scoped to the fixed placeholder -// identity every request shares -- a real, functional token, not faked data; -// see currentUserID. - +// server.go's ProjectConfigurator-pushed AuthGuard URL retargeting +// (coreConfig.OnUpdate) still applies here: it now calls +// auth.SetAuthGuardBaseURL, which sharedauth.Service exposes precisely to +// retarget the AuthGuard client it builds internally. const ( // legacySessionCookieName is the cookie CollabTable itself used to mint // and read before the AuthGuard migration. Nothing sets it anymore; it is - // only referenced so logout can clear a stale copy left over in a browser - // from before the migration. + // passed to sharedauth.NewWithStore only so Logout also clears a stale + // copy left over in a browser from before the migration. legacySessionCookieName = "collabtable_session" - - minPasswordLength = 8 - maxUsernameLength = 64 - maxEmailLength = 254 ) -var ( - errAuthRequired = errors.New("Authentication required") - errSetupComplete = errors.New("Setup has already been completed.") - errInvalidCredentials = errors.New("Invalid username or password.") - errUsernameRequired = errors.New("Username is required.") - errEmailRequired = errors.New("Email is required and must be valid.") - errPasswordTooShort = errors.New("Password must be at least 8 characters.") - errInvalidAuthInput = errors.New("invalid authentication input") - errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.") - // errFeatureRequiresAuthGuard is returned by the handlers that need a real - // backing identity (not just an access gate) when AUTHGUARD_URL is unset; - // see the top-of-file doc comment's "Auth-disabled mode" section. - errFeatureRequiresAuthGuard = errors.New("This feature requires AUTHGUARD_URL to be configured.") - // errAuthGuardUnavailable is returned whenever currentUser/currentProfile - // propagate a non-nil error: by construction (see their doc comments) - // that only happens when AuthGuard could not be reached or gave an - // unusable response -- a real "invalid or expired session" is always - // resolved to (nil, nil) instead, never an error -- so every caller of - // these two can safely report this same, specific message rather than a - // generic "internal error" that would be indistinguishable from any - // other server bug. This matters most for handleStatus/requireSession: - // AUTHGUARD_URL being configured but unreachable must surface as a - // visible, distinct error in the UI rather than ever being confused with - // "please log in" or silently letting the request through unauthenticated. - errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.") -) - -// localProfile is the fixed placeholder identity handleStatus/handleSetup/ -// handleLogin report when auth is disabled (AUTHGUARD_URL unset). Role is -// superadmin so CanManageUsers reports true, consistent with "nothing -// gated": the frontend's own admin-only UI sections become visible too, even -// though the underlying admin endpoints have nothing to manage (see -// handleUsers/handleUser). Its ID (0) also doubles as the shared identity -// every request's device-sync API token is scoped to in this mode; see -// currentUserID. -var localProfile = authclient.PublicUser{ID: 0, Username: "local", Email: "", Role: string(sharedauth.RoleSuperAdmin)} - -// AuthService proxies CollabTable's existing /api/auth/... handlers to -// AuthGuard. See this file's top-of-file doc comment for the overall design. -type AuthService struct { - db *DB - authGuard *authclient.Client - secureCookie bool +// collabTableAuthStore adapts *DB to sharedauth.ProxyStore. CollabTable never +// had an independent "require login" toggle (a session was always required +// whenever AUTHGUARD_URL was configured at all) so LoginRequired always +// reports true and SetLoginRequired is a no-op -- server.go correspondingly +// wires sharedauth.Service.Require rather than the *IfLoginRequired +// middleware family. IsSetupClaimed/TryClaimSetup/UnclaimSetup delegate +// straight through to *DB's existing methods of the same name/signature (see +// db.go), reusing the collabtable_setup_state table/queries verbatim. +type collabTableAuthStore struct { + db *DB } -func newAuthService(authGuard *authclient.Client, db *DB, secureCookie bool) *AuthService { - return &AuthService{db: db, authGuard: authGuard, secureCookie: secureCookie} +func (s collabTableAuthStore) LoginRequired(ctx context.Context) (bool, error) { + return true, nil } -func normalizeUsername(value string) (string, error) { - normalized, ok := authproxy.NormalizeUsername(value, maxUsernameLength) - if !ok { - return "", errUsernameRequired - } - return normalized, nil -} - -func normalizeEmail(value string) (string, error) { - normalized, ok := authproxy.NormalizeEmail(value, maxEmailLength) - if !ok { - return "", errEmailRequired - } - return normalized, nil -} - -func validatePassword(value string) error { - if !authproxy.ValidPassword(value, minPasswordLength) { - return errPasswordTooShort - } +func (s collabTableAuthStore) SetLoginRequired(ctx context.Context, required bool) error { return nil } +func (s collabTableAuthStore) IsSetupClaimed(ctx context.Context) (bool, error) { + return s.db.IsSetupClaimed(ctx) +} + +func (s collabTableAuthStore) TryClaimSetup(ctx context.Context) (bool, error) { + return s.db.TryClaimSetup(ctx) +} + +func (s collabTableAuthStore) UnclaimSetup(ctx context.Context) error { + return s.db.UnclaimSetup(ctx) +} + +// newAuthService builds CollabTable's sharedauth.Service. authGuardURL is +// AUTHGUARD_URL; empty means auth-disabled mode (see the package doc comment +// above and sharedauth's own "Auth-disabled mode" section). "collabtable" is +// CollabTable's projectKey, letting an AuthGuard administrator restrict which +// accounts may log into CollabTable specifically -- handled entirely +// server-side by AuthGuard once passed here. +func newAuthService(database *DB, authGuardURL string, secureCookies bool) *sharedauth.Service { + return sharedauth.NewWithStore(collabTableAuthStore{db: database}, legacySessionCookieName, secureCookies, authGuardURL, "collabtable") +} + +// --- Device-sync API bearer token (unrelated to AuthGuard) ------------------ +// +// Everything below is CollabTable's separate, long-lived per-account API +// bearer-token scheme its own devices use to call the sync API. It has +// nothing to do with AuthGuard session/login and is deliberately NOT proxied +// there; see db.go's comment on the api_tokens table. + +func requireAPIToken(db *DB) func(http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := extractBearer(r) + if token == "" { + writeJSONError(w, http.StatusUnauthorized, "No bearer token provided") + return + } + userID, err := db.getAPITokenUserID(r.Context(), hashToken(token)) + if err != nil { + writeJSONError(w, http.StatusInternalServerError, "Internal server error") + return + } + if userID == 0 { + writeJSONError(w, http.StatusUnauthorized, "Invalid API token") + return + } + next.ServeHTTP(w, r) + }) + } +} + +func extractBearer(r *http.Request) string { + header := r.Header.Get("Authorization") + if !strings.HasPrefix(header, "Bearer ") { + return "" + } + return strings.TrimSpace(strings.TrimPrefix(header, "Bearer ")) +} + func randomToken() (string, error) { buffer := make([]byte, 32) if _, err := rand.Read(buffer); err != nil { @@ -257,620 +161,21 @@ func hashToken(token string) string { return hex.EncodeToString(sum[:]) } -// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file -// doc comment's "Auth-disabled mode" section. -func (a *AuthService) enabled() bool { - return a.authGuard != nil -} - -// sessionToken reads the AuthGuard session cookie off the incoming request. -// See the top-of-file doc comment's "Session cookie / token model" section. -func (a *AuthService) sessionToken(r *http.Request) string { - return authproxy.SessionToken(r) -} - -// clearSessionCookies clears both the AuthGuard cookie (as a fallback -- -// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies, -// already does this) and the pre-migration CollabTable cookie name. -func (a *AuthService) clearSessionCookies(w http.ResponseWriter) { - authproxy.ClearSessionCookies(w, legacySessionCookieName, a.secureCookie) -} - -// currentUser resolves the request's AuthGuard session cookie via the -// lightweight GET /api/session/validate call, or nil if the request is -// unauthenticated or the session is invalid/expired. This is intentionally -// the cheap check (no email, no role-derived fields) -- it's what gates -// every request through requireSession. -func (a *AuthService) currentUser(r *http.Request) (*authclient.User, error) { - token := a.sessionToken(r) - if token == "" { - return nil, nil - } - user, err := a.authGuard.Validate(r.Context(), token) - if err != nil { - if errors.Is(err, authclient.ErrInvalidSession) { - return nil, nil - } - return nil, err - } - return user, nil -} - -// currentProfile resolves the full account profile (email included) via -// AuthGuard's GET /api/me, for handlers that need more than currentUser's -// slim shape, alongside the session token itself (so the caller can make a -// further authenticated call to AuthGuard without re-reading the cookie). -func (a *AuthService) currentProfile(r *http.Request) (*authclient.PublicUser, string, error) { - token := a.sessionToken(r) - if token == "" { - return nil, "", nil - } - user, err := a.authGuard.Me(r.Context(), token) - if err != nil { - var apiErr *authclient.APIError - if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized { - return nil, "", nil - } - return nil, "", err - } - return user, token, nil -} - -// currentUserID resolves the caller's identity to a stable numeric id for -// purely-local, identity-keyed state that has nothing to do with AuthGuard's -// own account data -- currently just the device-sync API token (see -// handleTokenStatus/handleTokenRegenerate). When auth is disabled this is -// the fixed localProfile.ID (0): every request shares the same "local" -// identity, so a device-sync token minted in this mode is real and +// handleTokenStatus/handleTokenRegenerate let a signed-in browser session +// view/regenerate the bearer token its own devices use against the sync API. +// The caller's identity is resolved via sharedauth.UserFromContext, populated +// by the s.auth.Require wrapper server.go mounts these routes behind -- in +// auth-disabled mode that middleware always resolves to sharedauth's fixed +// placeholder identity (ID 0), so a token minted in that mode is real and // functional, just scoped to that one shared identity rather than a -// per-account AuthGuard identity. ok is false when auth is enabled but the -// caller has no valid session. -func (a *AuthService) currentUserID(r *http.Request) (id int64, ok bool, err error) { - if !a.enabled() { - return localProfile.ID, true, nil - } - user, err := a.currentUser(r) - if err != nil { - return 0, false, err - } +// per-account AuthGuard identity, matching the pre-migration behavior. +func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) { + user := sharedauth.UserFromContext(r.Context()) if user == nil { - return 0, false, nil - } - return user.ID, true, nil -} - -func (a *AuthService) requireSession(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - next.ServeHTTP(w, r) - return - } - user, err := a.currentUser(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if user == nil { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - next.ServeHTTP(w, r) - }) -} - -func (a *AuthService) requireAPIToken(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - token := extractBearer(r) - if token == "" { - writeJSONError(w, http.StatusUnauthorized, "No bearer token provided") - return - } - userID, err := a.db.getAPITokenUserID(r.Context(), hashToken(token)) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - if userID == 0 { - writeJSONError(w, http.StatusUnauthorized, "Invalid API token") - return - } - next.ServeHTTP(w, r) - }) -} - -func extractBearer(r *http.Request) string { - header := r.Header.Get("Authorization") - if !strings.HasPrefix(header, "Bearer ") { - return "" - } - return strings.TrimSpace(strings.TrimPrefix(header, "Bearer ")) -} - -type authStatusResponse struct { - SetupRequired bool `json:"setupRequired"` - Authenticated bool `json:"authenticated"` - ID int64 `json:"id,omitempty"` - Username string `json:"username,omitempty"` - Email string `json:"email,omitempty"` - Role string `json:"role,omitempty"` - CanManageUsers bool `json:"canManageUsers,omitempty"` - TotpEnabled bool `json:"totpEnabled,omitempty"` -} - -type credentialsRequest struct { - Identifier string `json:"identifier"` - Username string `json:"username"` - Email string `json:"email"` - Password string `json:"password"` - TotpToken string `json:"totpToken"` -} - -func (a *AuthService) statusResponse(ctx context.Context, user authclient.PublicUser) authStatusResponse { - totpEnabled, err := a.db.GetCachedTOTPEnabled(ctx, user.ID) - if err != nil { - // Best-effort cache; a read failure just means "assume disabled" rather - // than failing the whole status/login/setup response. - totpEnabled = false - } - return authStatusResponse{ - Authenticated: true, - ID: user.ID, - Username: user.Username, - Email: user.Email, - Role: user.Role, - CanManageUsers: sharedauth.CanManageUsers(user.Role), - TotpEnabled: totpEnabled, - } -} - -func (a *AuthService) handleStatus(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), localProfile)) + writeJSONError(w, http.StatusUnauthorized, "Authentication required") return } - - claimed, err := a.db.IsSetupClaimed(r.Context()) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - if !claimed { - // The local claim alone isn't enough to decide this: accounts are - // centralized in AuthGuard now, so another CollabTable instance (or - // AuthGuard's own web UI) may have already created one even though - // this instance's own setup was never claimed. Showing the "create - // your account" form in that case would let someone spin up a - // redundant plain user instead of just logging into the account that - // already exists -- see setupRequired below. - setupRequired, err := a.authGuard.SetupStatus(r.Context()) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if setupRequired { - writeJSON(w, http.StatusOK, authStatusResponse{SetupRequired: true}) - return - } - // AuthGuard already has an account; fall through to the ordinary - // "not authenticated" response so the frontend shows the login form - // instead of setup. - } - - profile, _, err := a.currentProfile(r) - if err != nil { - // Reachable-but-invalid-session already resolved to (nil, "", nil) - // inside currentProfile; getting here means AuthGuard itself could not - // be reached or gave an unusable response. This must never be - // conflated with "not authenticated" (which would incorrectly show the - // frontend's login screen with no indication anything is wrong) or - // silently proceed as authenticated -- see errAuthGuardUnavailable. - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if profile == nil { - writeJSON(w, http.StatusOK, authStatusResponse{}) - return - } - writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), *profile)) -} - -// handleSetup registers CollabTable's first account against AuthGuard's -// POST /api/register. See the top-of-file doc comment's "Setup flow" section -// for why this needs a small local claim flag instead of a count-based -// check. -func (a *AuthService) handleSetup(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), localProfile)) - return - } - - var request credentialsRequest - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") - return - } - username, err := normalizeUsername(request.Username) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - email, err := normalizeEmail(request.Email) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - if err := validatePassword(request.Password); err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - - claimed, err := a.db.TryClaimSetup(r.Context()) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - if !claimed { - writeJSONError(w, http.StatusConflict, errSetupComplete.Error()) - return - } - - // Belt-and-braces: handleStatus already keeps the frontend from ever - // showing this form once AuthGuard has any account (see its own - // SetupStatus check), but a stale page or a direct API call could still - // reach this handler. Reject it the same way as the local claim conflict - // above rather than creating a redundant plain user account. - if setupRequired, err := a.authGuard.SetupStatus(r.Context()); err != nil || !setupRequired { - if unclaimErr := a.db.UnclaimSetup(r.Context()); unclaimErr != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - writeJSONError(w, http.StatusConflict, errSetupComplete.Error()) - return - } - - result, err := a.authGuard.Register(r.Context(), username, email, request.Password) - if err != nil { - // The claim slot is only valid once actually backed by a real - // AuthGuard account; reopen it so a corrected retry can proceed. - if unclaimErr := a.db.UnclaimSetup(r.Context()); unclaimErr != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - writeAuthGuardError(w, err, "Unable to create account") - return - } - - if err := a.db.SetCachedTOTPEnabled(r.Context(), result.User.ID, false); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - authclient.ForwardCookies(w, result.Cookies) - writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), result.User)) -} - -func (a *AuthService) handleLogin(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), localProfile)) - return - } - - var request credentialsRequest - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") - return - } - identifier := strings.TrimSpace(request.Identifier) - if identifier == "" { - identifier = strings.TrimSpace(request.Username) - } - if identifier == "" || len([]rune(identifier)) > maxEmailLength { - writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error()) - return - } - - result, err := a.authGuard.Login(r.Context(), identifier, request.Password, request.TotpToken) - if err != nil { - var apiErr *authclient.APIError - if errors.As(err, &apiErr) { - if apiErr.TOTPRequired { - writeJSONError(w, http.StatusUnauthorized, "Two-factor authentication code required.") - return - } - if apiErr.StatusCode == http.StatusUnauthorized { - writeJSONError(w, http.StatusUnauthorized, errInvalidCredentials.Error()) - return - } - writeAuthGuardError(w, err, "Unable to sign in") - return - } - // A non-APIError here means the call to AuthGuard itself failed - // (transport/connectivity), as opposed to AuthGuard giving a real - // answer we didn't like above; see errAuthGuardUnavailable. - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - - // See this file's top-of-file doc comment: a successful login attempted - // WITHOUT a TOTP token is only possible when the account does not have - // TOTP enabled (AuthGuard would otherwise have rejected it), so this is an - // authoritative point to refresh the local cache. A successful login WITH - // a token is not equally conclusive (AuthGuard ignores an unnecessary - // token for an account that doesn't have TOTP enabled), so the cache is - // left as whatever handleTOTPEnable/Disable last set it to rather than - // guessed at here. - if strings.TrimSpace(request.TotpToken) == "" { - if err := a.db.SetCachedTOTPEnabled(r.Context(), result.User.ID, false); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - } - - authclient.ForwardCookies(w, result.Cookies) - writeJSON(w, http.StatusOK, a.statusResponse(r.Context(), result.User)) -} - -func (a *AuthService) handleTOTPStatus(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSON(w, http.StatusOK, map[string]bool{"enabled": false}) - return - } - user, err := a.currentUser(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if user == nil { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - enabled, err := a.db.GetCachedTOTPEnabled(r.Context(), user.ID) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"enabled": enabled}) -} - -// handleTOTPSetup provisions a pending TOTP secret via AuthGuard's POST -// /api/totp/enable (AuthGuard's "enable" is CollabTable's "setup" step -- -// naming differs, the two-step provision-then-confirm flow is identical). -// -// AuthGuard always (re-)provisions regardless of current state; the -// "already enabled" guard CollabTable had locally is reproduced here from -// the local cache to keep the same user-facing contract (the frontend only -// ever shows this action when it believes TOTP is currently off). -func (a *AuthService) handleTOTPSetup(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) - return - } - user, err := a.currentUser(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if user == nil { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - if enabled, err := a.db.GetCachedTOTPEnabled(r.Context(), user.ID); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } else if enabled { - writeJSONError(w, http.StatusConflict, "disable two-factor authentication before setting up a new secret") - return - } - - result, err := a.authGuard.TOTPEnable(r.Context(), a.sessionToken(r)) - if err != nil { - writeAuthGuardError(w, err, "unable to create two-factor setup") - return - } - writeJSON(w, http.StatusOK, map[string]any{ - "secret": result.Secret, - "otpauthUrl": result.OTPAuthURL, - "enabled": result.Enabled, - }) -} - -// handleTOTPEnable confirms a generated code via AuthGuard's POST -// /api/totp/verify, activating two-factor authentication (AuthGuard's -// "verify" is CollabTable's "enable" step; see handleTOTPSetup). -func (a *AuthService) handleTOTPEnable(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) - return - } - user, err := a.currentUser(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if user == nil { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - var request struct { - Token string `json:"token"` - } - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if err := a.authGuard.TOTPVerify(r.Context(), a.sessionToken(r), request.Token); err != nil { - writeJSONError(w, http.StatusUnauthorized, "Invalid authenticator code.") - return - } - if err := a.db.SetCachedTOTPEnabled(r.Context(), user.ID, true); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"enabled": true}) -} - -func (a *AuthService) handleTOTPDisable(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) - return - } - user, err := a.currentUser(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if user == nil { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - var request struct { - Token string `json:"token"` - } - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if err := a.authGuard.TOTPDisable(r.Context(), a.sessionToken(r), request.Token); err != nil { - writeJSONError(w, http.StatusUnauthorized, "Invalid authenticator code.") - return - } - if err := a.db.SetCachedTOTPEnabled(r.Context(), user.ID, false); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"enabled": false}) -} - -func (a *AuthService) handleLogout(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) - return - } - if token := a.sessionToken(r); token != "" { - cookies, err := a.authGuard.Logout(r.Context(), token) - if err != nil { - var apiErr *authclient.APIError - if !errors.As(err, &apiErr) { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - // An already-invalid/expired session is fine to treat as "already - // logged out" rather than an error. - } else { - authclient.ForwardCookies(w, cookies) - } - } - a.clearSessionCookies(w) - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -type updateCredentialsRequest struct { - CurrentPassword *string `json:"currentPassword"` - NewUsername *string `json:"newUsername"` - NewEmail *string `json:"newEmail"` - NewPassword *string `json:"newPassword"` -} - -// handleUpdateCredentials lets the caller edit their own username/email/ -// password. See the top-of-file doc comment's "Known gaps" section: -// AuthGuard only exposes account editing through its admin/users endpoint, -// which requires CanManageUsers, so a plain "user"-role account has no -// AuthGuard-backed way to self-edit today. CollabTable's existing frontend -// never sends CurrentPassword (see lib/api.js's updateCredentials), and -// AuthGuard's admin update endpoint has no notion of it either (an -// authorized caller is trusted without re-proving the current password), so -// that field is accepted for backward compatibility but not acted on. -func (a *AuthService) handleUpdateCredentials(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) - return - } - current, token, err := a.currentProfile(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if current == nil { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - - var request updateCredentialsRequest - if err := decodeJSON(r, &request); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") - return - } - - input := authclient.ManagedUserInput{} - if request.NewUsername != nil { - username, err := normalizeUsername(*request.NewUsername) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - input.Username = username - } - if request.NewEmail != nil { - email, err := normalizeEmail(*request.NewEmail) - if err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - input.Email = email - } - if request.NewPassword != nil && *request.NewPassword != "" { - if err := validatePassword(*request.NewPassword); err != nil { - writeJSONError(w, http.StatusBadRequest, err.Error()) - return - } - input.Password = *request.NewPassword - } - if request.NewUsername == nil && request.NewEmail == nil && input.Password == "" { - writeJSONError(w, http.StatusBadRequest, errInvalidAuthInput.Error()) - return - } - - if !sharedauth.CanManageUsers(current.Role) { - writeJSONError(w, http.StatusForbidden, errSelfServiceProfile.Error()) - return - } - - if err := a.authGuard.UpdateManagedUser(r.Context(), token, current.ID, input); err != nil { - writeAuthGuardError(w, err, "Unable to update account") - return - } - - // Match the pre-migration behavior of forcing re-authentication after a - // credential change. AuthGuard's admin-update endpoint does not itself - // invalidate sessions, and there is no self-service "invalidate all my - // other sessions" call, so only the session used for this request is - // guaranteed to be revoked; see the top-of-file doc comment's "Known - // gaps" section. - if _, err := a.authGuard.Logout(r.Context(), token); err != nil { - var apiErr *authclient.APIError - if !errors.As(err, &apiErr) { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - } - a.clearSessionCookies(w) - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request) { - userID, ok, err := a.currentUserID(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if !ok { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - hasToken, err := a.db.hasAPIToken(r.Context(), userID) + hasToken, err := s.db.hasAPIToken(r.Context(), user.ID) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return @@ -878,14 +183,10 @@ func (a *AuthService) handleTokenStatus(w http.ResponseWriter, r *http.Request) writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken}) } -func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Request) { - userID, ok, err := a.currentUserID(r) - if err != nil { - writeJSONError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) - return - } - if !ok { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) +func (s *Server) handleTokenRegenerate(w http.ResponseWriter, r *http.Request) { + user := sharedauth.UserFromContext(r.Context()) + if user == nil { + writeJSONError(w, http.StatusUnauthorized, "Authentication required") return } token, err := randomToken() @@ -893,152 +194,9 @@ func (a *AuthService) handleTokenRegenerate(w http.ResponseWriter, r *http.Reque writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } - if err := a.db.regenerateAPIToken(r.Context(), userID, hashToken(token)); err != nil { + if err := s.db.regenerateAPIToken(r.Context(), user.ID, hashToken(token)); err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } writeJSON(w, http.StatusOK, map[string]string{"token": token}) } - -type managedUserResponse struct { - ID int64 `json:"id"` - Username string `json:"username"` - Email string `json:"email"` - Role string `json:"role"` - TotpEnabled bool `json:"totpEnabled"` -} - -// managedUserView translates an AuthGuard ManagedUser into CollabTable's -// existing response shape. TotpEnabled reflects only what this CollabTable -// instance's local best-effort cache has observed for that account (see the -// top-of-file doc comment's "Known gaps" section) -- AuthGuard's admin/users -// endpoints do not report TOTP status at all, so an account this instance -// has never toggled 2FA for is reported as false regardless of its real -// state. -func (a *AuthService) managedUserView(ctx context.Context, user authclient.ManagedUser) managedUserResponse { - enabled, _ := a.db.GetCachedTOTPEnabled(ctx, user.ID) - return managedUserResponse{ID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, TotpEnabled: enabled} -} - -// writeAuthGuardError translates an authclient error into CollabTable's -// {"error": "...", "message": "..."} response shape. AuthGuard's own -// httpapi handlers were built directly from CollabTable's (and the other -// projects') original local implementations, so their status codes and -// messages already match -- AuthGuard's *APIError is forwarded close to -// verbatim rather than re-mapped by hand. A non-APIError (a transport -// failure actually reaching AuthGuard) falls back to a generic 500 with -// fallbackMessage. -func writeAuthGuardError(w http.ResponseWriter, err error, fallbackMessage string) { - if statusCode, message, ok := authproxy.APIErrorResponse(err); ok { - writeJSONError(w, statusCode, message) - return - } - writeJSONError(w, http.StatusInternalServerError, fallbackMessage) -} - -// handleUsers proxies admin user listing/creation to AuthGuard's -// GET/POST /api/admin/users. Authorization (CanManageUsers) is enforced by -// AuthGuard itself from the forwarded session token; CollabTable does not -// re-implement that check locally, so its 401/403 responses come straight -// from AuthGuard via writeAuthGuardError. See the top-of-file doc comment: -// AuthGuard's admin endpoints enforce the exact same rules CollabTable's -// local implementation did. -func (a *AuthService) handleUsers(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - switch r.Method { - case http.MethodGet: - // Nothing is gated in auth-disabled mode, and an empty list is an - // honest answer: there is no user store to list from. See the - // top-of-file doc comment's "Auth-disabled mode" section. - writeJSON(w, http.StatusOK, []managedUserResponse{}) - case http.MethodPost: - writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) - default: - w.WriteHeader(http.StatusMethodNotAllowed) - } - return - } - token := a.sessionToken(r) - if token == "" { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - switch r.Method { - case http.MethodGet: - users, err := a.authGuard.ListManagedUsers(r.Context(), token) - if err != nil { - writeAuthGuardError(w, err, "Unable to list users") - return - } - result := make([]managedUserResponse, 0, len(users)) - for _, user := range users { - result = append(result, a.managedUserView(r.Context(), user)) - } - writeJSON(w, http.StatusOK, result) - case http.MethodPost: - var input authclient.ManagedUserInput - if err := decodeJSON(r, &input); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") - return - } - created, err := a.authGuard.CreateManagedUser(r.Context(), token, input) - if err != nil { - writeAuthGuardError(w, err, "Unable to create user") - return - } - if err := a.db.SetCachedTOTPEnabled(r.Context(), created.ID, false); err != nil { - writeJSONError(w, http.StatusInternalServerError, "Internal server error") - return - } - writeJSON(w, http.StatusCreated, a.managedUserView(r.Context(), *created)) - default: - w.WriteHeader(http.StatusMethodNotAllowed) - } -} - -// handleUser proxies admin user update/delete to AuthGuard's -// PUT/DELETE /api/admin/users/{id}. See handleUsers's doc comment: AuthGuard -// enforces authorization (including the "the superadmin account is -// protected" and "this user cannot be deleted" rules) itself. -func (a *AuthService) handleUser(w http.ResponseWriter, r *http.Request) { - if !a.enabled() { - switch r.Method { - case http.MethodPut, http.MethodPatch, http.MethodDelete: - writeJSONError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) - default: - w.WriteHeader(http.StatusMethodNotAllowed) - } - return - } - token := a.sessionToken(r) - if token == "" { - writeJSONError(w, http.StatusUnauthorized, errAuthRequired.Error()) - return - } - id, err := strconv.ParseInt(r.PathValue("id"), 10, 64) - if err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid user id") - return - } - switch r.Method { - case http.MethodPut, http.MethodPatch: - var input authclient.ManagedUserInput - if err := decodeJSON(r, &input); err != nil { - writeJSONError(w, http.StatusBadRequest, "Invalid JSON body") - return - } - if err := a.authGuard.UpdateManagedUser(r.Context(), token, id, input); err != nil { - writeAuthGuardError(w, err, "Unable to update user") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) - case http.MethodDelete: - if err := a.authGuard.DeleteManagedUser(r.Context(), token, id); err != nil { - writeAuthGuardError(w, err, "Unable to delete user") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) - default: - w.WriteHeader(http.StatusMethodNotAllowed) - } -} diff --git a/backend/auth_test.go b/backend/auth_test.go index 38b038d..c1d24ae 100644 --- a/backend/auth_test.go +++ b/backend/auth_test.go @@ -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) } } diff --git a/backend/db.go b/backend/db.go index 313f86c..4deb3b3 100644 --- a/backend/db.go +++ b/backend/db.go @@ -152,16 +152,16 @@ func (d *DB) initSchema(ctx context.Context) error { 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. + -- authguard_totp_cache is RETIRED as of the migration onto + -- shared/backend/auth (sharedauth.Service): it used to be a + -- best-effort, locally-cached mirror of "does this AuthGuard account + -- have TOTP enabled", keyed by AuthGuard's own numeric user id, needed + -- because AuthGuard's HTTP API had no endpoint to query current TOTP + -- status, only to enable/verify/disable it. sharedauth.Service's + -- Me/Status/TOTPStatus now read TOTP-enabled status live from + -- AuthGuard's GET /api/me on every request instead, so no Go code + -- reads or writes this table anymore. Left in place rather than + -- dropped, same as auth_users/auth_sessions above. CREATE TABLE IF NOT EXISTS authguard_totp_cache ( authguard_user_id BIGINT PRIMARY KEY, totp_enabled BOOLEAN NOT NULL DEFAULT FALSE, @@ -276,34 +276,16 @@ func (d *DB) UnclaimSetup(ctx context.Context) error { return nil } -// 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 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 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 -} +// Note: this instance used to also keep a local best-effort cache of each +// AuthGuard account's TOTP-enabled state (GetCachedTOTPEnabled/ +// SetCachedTOTPEnabled, backed by the authguard_totp_cache table above) -- +// that existed only because the pre-migration code believed AuthGuard could +// not report TOTP status live. It can (GET /api/me), so sharedauth.Service's +// Me/Status/TOTPStatus now read it live from AuthGuard directly and this +// cache's Go code was deleted along with the migration onto that shared +// package. The authguard_totp_cache table itself (and any rows already in +// it) is left in place rather than dropped, same as auth_users/auth_sessions +// above. func (d *DB) hasAPIToken(ctx context.Context, userID int64) (bool, error) { var exists bool diff --git a/backend/routes_test.go b/backend/routes_test.go index 4ceed6b..8613439 100644 --- a/backend/routes_test.go +++ b/backend/routes_test.go @@ -6,6 +6,6 @@ import ( ) func TestRegisterRoutes(t *testing.T) { - server := &Server{auth: &AuthService{}} + server := &Server{auth: newAuthService(nil, "", false)} server.registerRoutes(http.NewServeMux(), webFS) } diff --git a/backend/server.go b/backend/server.go index bff792a..9ec0556 100644 --- a/backend/server.go +++ b/backend/server.go @@ -16,7 +16,7 @@ import ( _ "github.com/joho/godotenv/autoload" - authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" + sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" "repos.gfranz.ch/Gabriel20xx/shared/backend/carriernodeclient" "repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig" ) @@ -30,7 +30,7 @@ var webFS embed.FS type Server struct { db *DB - auth *AuthService + auth *sharedauth.Service startTime time.Time internalServiceSecret string coreConfig *coreconfig.Store @@ -57,38 +57,38 @@ func main() { go database.pruneExpiredSessions(ctx) go database.cleanupNotifications(ctx) - // 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. + // AuthGuard is optional (see auth.go's top-of-file doc comment and + // sharedauth's own "Auth-disabled mode" section): an unset AUTHGUARD_URL + // 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(database, authGuardURL, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true")) // coreConfig holds the AuthGuard/CarrierNode URLs ProjectConfigurator pushes once this project // is registered there (PUT /api/core-services/internal, see registerRoutes) -- AUTHGUARD_URL and // CARRIERNODE_URL above/below are only the bootstrap fallback used until the first push arrives. // See Core/ProjectConfigurator/README.md's "Pushing core service info to other projects". + // auth.SetAuthGuardBaseURL retargets the live AuthGuard client sharedauth.Service holds + // internally on every push, so AuthGuard moving to a new URL takes effect without a restart -- it + // is a no-op when this service was constructed in auth-disabled mode (AUTHGUARD_URL unset above). internalServiceSecret := strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")) carrierNodeURL := strings.TrimSpace(os.Getenv("CARRIERNODE_URL")) coreConfig := coreconfig.NewStore(coreconfig.Info{AuthGuardURL: authGuardURL, CarrierNodeURL: carrierNodeURL}) - if authGuard != nil { - coreConfig.OnUpdate(func(info coreconfig.Info) { - if info.AuthGuardURL != "" { - authGuard.SetBaseURL(info.AuthGuardURL) - } - }) - } + coreConfig.OnUpdate(func(info coreconfig.Info) { + if info.AuthGuardURL != "" { + auth.SetAuthGuardBaseURL(info.AuthGuardURL) + } + }) carrierNode := carriernodeclient.New(internalServiceSecret, func(context.Context) string { return coreConfig.CarrierNodeURL() }) - auth := newAuthService(authGuard, database, strings.EqualFold(os.Getenv("COOKIE_SECURE"), "true")) server := &Server{ db: database, auth: auth, @@ -165,27 +165,27 @@ func (s *Server) registerRoutes(mux *http.ServeMux, webRoot fs.FS) { // X-Internal-Auth-gated, not browser-session-gated -- ProjectConfigurator calls this directly // to push a fresh AuthGuard/CarrierNode URL (see coreConfig's construction in main above). mux.Handle("PUT /api/core-services/internal", coreconfig.Handler(s.internalServiceSecret, s.coreConfig)) - mux.HandleFunc("GET /api/auth/status", s.auth.handleStatus) - 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(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))) + mux.HandleFunc("GET /api/auth/status", s.auth.Status) + mux.HandleFunc("POST /api/auth/setup", s.auth.Signup) + mux.HandleFunc("POST /api/auth/login", s.auth.Login) + mux.Handle("POST /api/auth/logout", s.auth.Require(http.HandlerFunc(s.auth.Logout))) + mux.Handle("POST /api/auth/credentials", s.auth.Require(http.HandlerFunc(s.auth.UpdateMe))) + mux.Handle("GET /api/auth/users", s.auth.Require(http.HandlerFunc(s.auth.ManagedUsers))) + mux.Handle("POST /api/auth/users", s.auth.Require(http.HandlerFunc(s.auth.ManagedCreateUser))) + mux.Handle("PUT /api/auth/users/{id}", s.auth.Require(http.HandlerFunc(s.auth.ManagedUpdateUser))) + mux.Handle("PATCH /api/auth/users/{id}", s.auth.Require(http.HandlerFunc(s.auth.ManagedUpdateUser))) + mux.Handle("DELETE /api/auth/users/{id}", s.auth.Require(http.HandlerFunc(s.auth.ManagedDeleteUser))) + mux.Handle("GET /api/auth/totp/status", s.auth.Require(http.HandlerFunc(s.auth.TOTPStatus))) + mux.Handle("POST /api/auth/totp/setup", s.auth.Require(http.HandlerFunc(s.auth.TOTPInitiate))) + mux.Handle("POST /api/auth/totp/enable", s.auth.Require(http.HandlerFunc(s.auth.TOTPVerify))) + mux.Handle("POST /api/auth/totp/disable", s.auth.Require(http.HandlerFunc(s.auth.TOTPDisable))) + mux.Handle("GET /api/auth/token/status", s.auth.Require(http.HandlerFunc(s.handleTokenStatus))) + mux.Handle("POST /api/auth/token/regenerate", s.auth.Require(http.HandlerFunc(s.handleTokenRegenerate))) // Sync/collaboration API routes use a long-lived bearer token shared by the // user's devices. This is deliberately separate from browser sessions. api := func(handler http.Handler) http.Handler { - return s.auth.requireAPIToken(handler) + return requireAPIToken(s.db)(handler) } mux.Handle("GET /api/lists", api(http.HandlerFunc(s.handleListCollection))) mux.Handle("POST /api/lists", api(http.HandlerFunc(s.handleListCollection))) @@ -210,8 +210,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(http.HandlerFunc(s.handleTechStack))) - mux.Handle("GET /web/data", s.auth.requireSession(http.HandlerFunc(s.handleWebData))) + mux.Handle("GET /api/tech-stack", s.auth.Require(http.HandlerFunc(s.handleTechStack))) + mux.Handle("GET /web/data", s.auth.Require(http.HandlerFunc(s.handleWebData))) mux.Handle("/", spaFileServer(webRoot)) } diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js index 9bb3abe..9c199a1 100644 --- a/frontend/src/lib/api.js +++ b/frontend/src/lib/api.js @@ -37,42 +37,95 @@ export async function fetchHealth() { return { up: res.ok }; } +// flattenAuthStatus adapts sharedauth.Service's Status/Signup/Login response +// shape (a nested `user: {id, email, username, role, canManageUsers, +// mfaEnabled}`, since CollabTable's AuthGuard migration onto +// shared/backend/auth) back into the flat shape this frontend already +// expects (AppShell.svelte reads status.username/.email/.setupRequired/ +// .authenticated directly) - keeping the rest of the frontend from needing to +// change shape, the same translation GameStream/OmniLogger's frontends made +// for the same migration. +function flattenAuthStatus(payload) { + return { + setupRequired: payload?.setupRequired ?? false, + authenticated: payload?.authenticated ?? false, + authRequired: payload?.authRequired ?? true, + id: payload?.user?.id, + username: payload?.user?.username, + email: payload?.user?.email, + role: payload?.user?.role, + canManageUsers: payload?.user?.canManageUsers, + totpEnabled: payload?.user?.mfaEnabled, + }; +} + export async function fetchAuthStatus() { - return getJson('/api/auth/status'); + return flattenAuthStatus(await getJson('/api/auth/status')); } export async function setupAccount(username, email, password) { - return request('/api/auth/setup', { method: 'POST', body: JSON.stringify({ username, email, password }) }); + const { user } = await request('/api/auth/setup', { + method: 'POST', + body: JSON.stringify({ username, email, password }), + }); + return user; } export async function login(identifier, password, totpToken = '') { - return request('/api/auth/login', { method: 'POST', body: JSON.stringify({ identifier, password, totpToken }) }); + const { user } = await request('/api/auth/login', { + method: 'POST', + body: JSON.stringify({ identifier, password, totpToken }), + }); + return user; } export async function fetchTotpStatus() { return request('/api/auth/totp/status'); } +// setupTotp/enableTotp/disableTotp proxy to sharedauth.Service's +// TOTPInitiate/TOTPVerify/TOTPDisable, whose response bodies nest their +// payload under a `data` key (`{"data": {...}}`) instead of the pre-migration +// flat shape - unwrapped here so TotpSettings.svelte (@gabriel20xx/web-ui), +// which reads setup.secret/setup.otpauthUrl directly, needs no changes. export async function setupTotp() { - return request('/api/auth/totp/setup', { method: 'POST' }); + const { data } = await request('/api/auth/totp/setup', { method: 'POST' }); + return { secret: data.secret, otpauthUrl: data.otpauthUrl, enabled: data.enabled }; } export async function enableTotp(token) { - return request('/api/auth/totp/enable', { method: 'POST', body: JSON.stringify({ token }) }); + const { data } = await request('/api/auth/totp/enable', { + method: 'POST', + body: JSON.stringify({ token }), + }); + return { enabled: data.enabled }; } export async function disableTotp(token) { - return request('/api/auth/totp/disable', { method: 'POST', body: JSON.stringify({ token }) }); + const { data } = await request('/api/auth/totp/disable', { + method: 'POST', + body: JSON.stringify({ token }), + }); + return { enabled: data.enabled }; } export async function logout() { return request('/api/auth/logout', { method: 'POST' }); } +// updateCredentials proxies to sharedauth.Service's UpdateMe +// (POST /api/auth/credentials), which requires a valid, non-empty email on +// every call (it has no concept of "leave this field unchanged" for email the +// way CollabTable's pre-migration handler did) - newUsername/newEmail must +// always be the account's current values when the caller isn't actually +// changing them. ProfileDialog's form (@gabriel20xx/web-ui) always pre-fills +// and requires both fields, so AppShell.svelte's saveProfile always has them +// on hand. newPassword remains genuinely optional (omitted/blank leaves the +// password unchanged). export async function updateCredentials({ newUsername, newEmail, newPassword }) { return request('/api/auth/credentials', { method: 'POST', - body: JSON.stringify({ newUsername, newEmail, newPassword }), + body: JSON.stringify({ username: newUsername, email: newEmail, password: newPassword }), }); } diff --git a/frontend/src/lib/features/layout/AppShell.svelte b/frontend/src/lib/features/layout/AppShell.svelte index 4f41dec..ec0a6f4 100644 --- a/frontend/src/lib/features/layout/AppShell.svelte +++ b/frontend/src/lib/features/layout/AppShell.svelte @@ -20,9 +20,15 @@ let credentialsOpen = $state(false); async function saveProfile(input) { + // The backend's UpdateMe (POST /api/auth/credentials) requires a valid, + // non-empty email on every call - it has no concept of "leave this field + // unchanged" for email - so both username and email are always sent + // as-is; ProfileDialog's form always pre-fills and requires both fields, + // so they're never empty here. Only password is genuinely optional + // (blank means unchanged). await auth.updateCredentials({ - newUsername: input.username.trim() || undefined, - newEmail: input.email.trim() || undefined, + newUsername: input.username.trim(), + newEmail: input.email.trim(), newPassword: input.password || undefined, }); }