package main import ( "context" "crypto/rand" "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" ) // AuthGuard migration // ==================== // // 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. // // 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. // // 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. // // 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. 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. 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 } func newAuthService(authGuard *authclient.Client, db *DB, secureCookie bool) *AuthService { return &AuthService{db: db, authGuard: authGuard, secureCookie: secureCookie} } func normalizeUsername(value string) (string, error) { value = strings.TrimSpace(value) if value == "" || len([]rune(value)) > maxUsernameLength { return "", errUsernameRequired } return value, nil } func normalizeEmail(value string) (string, error) { value = strings.ToLower(strings.TrimSpace(value)) if value == "" || len([]rune(value)) > maxEmailLength || strings.Count(value, "@") != 1 { return "", errEmailRequired } parts := strings.SplitN(value, "@", 2) if parts[0] == "" || parts[1] == "" || !strings.Contains(parts[1], ".") { return "", errEmailRequired } return value, nil } func validatePassword(value string) error { if len([]rune(value)) < minPasswordLength { return errPasswordTooShort } return nil } func randomToken() (string, error) { buffer := make([]byte, 32) if _, err := rand.Read(buffer); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(buffer), nil } func hashToken(token string) string { sum := sha256.Sum256([]byte(token)) 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 { cookie, err := r.Cookie(authclient.DefaultCookieName) if err != nil || cookie.Value == "" { return "" } return cookie.Value } // 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) { http.SetCookie(w, &http.Cookie{ Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true, Secure: a.secureCookie, SameSite: http.SameSiteLaxMode, MaxAge: -1, }) http.SetCookie(w, &http.Cookie{ Name: legacySessionCookieName, Value: "", Path: "/", HttpOnly: true, Secure: a.secureCookie, SameSite: http.SameSiteLaxMode, MaxAge: -1, }) } // 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 // 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 } 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)) 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) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } 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()) return } token, err := randomToken() if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } if err := a.db.regenerateAPIToken(r.Context(), userID, 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) { var apiErr *authclient.APIError if errors.As(err, &apiErr) { writeJSONError(w, apiErr.StatusCode, apiErr.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) } }