package main import ( "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "net/http" "strings" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" ) // AuthGuard migration onto the shared auth engine // ===================================================== // // 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). // // 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}. // // 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. // // 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 // passed to sharedauth.NewWithStore only so Logout also clears a stale // copy left over in a browser from before the migration. legacySessionCookieName = "collabtable_session" ) // 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 (s collabTableAuthStore) LoginRequired(ctx context.Context) (bool, error) { return true, nil } 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 { return "", err } return base64.RawURLEncoding.EncodeToString(buffer), nil } func hashToken(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } // 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, matching the pre-migration behavior. func (s *Server) handleTokenStatus(w http.ResponseWriter, r *http.Request) { user := sharedauth.UserFromContext(r.Context()) if user == nil { writeJSONError(w, http.StatusUnauthorized, "Authentication required") return } hasToken, err := s.db.hasAPIToken(r.Context(), user.ID) if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } writeJSON(w, http.StatusOK, map[string]bool{"hasToken": hasToken}) } 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() if err != nil { writeJSONError(w, http.StatusInternalServerError, "Internal server error") return } 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}) }