Files
CollabTable/backend/auth.go
T
Gabriel20xx 97c237be80
Lint / Lint (push) Successful in 1m8s
Tests / Go backend (push) Failing after 1m23s
Tests / Dashboard checks (push) Failing after 38s
Docker / Docker Build & Push (push) Failing after 6m29s
feat(sync): paginate Android sync with change tokens
2026-10-20 15:27:53 +00:00

227 lines
9.4 KiB
Go

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. The login
// requirement is runtime-controlled by ProjectConfigurator through
// sharedauth.Service's internal endpoint; this store supplies the conservative
// required-by-default fallback. 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, an optional bootstrap/override value: empty now means
// "pending" (see the package doc comment above and sharedauth's own
// "Auth-disabled mode" section) rather than disabled. authDisabled is
// AUTH_DISABLED, the explicit opt-out for local development or a standalone
// deployment that wants no AuthGuard integration at all -- it passes
// sharedauth.Disabled(), matching CollabTable's old unset-AUTHGUARD_URL
// behavior. "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, authDisabled bool) *sharedauth.Service {
var opts []sharedauth.ServiceOption
if authDisabled {
opts = append(opts, sharedauth.Disabled())
}
opts = append(opts, sharedauth.RequireSecret())
return sharedauth.NewWithStore(collabTableAuthStore{db: database}, legacySessionCookieName, secureCookies, authGuardURL, "collabtable", opts...)
}
// --- 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
}
// getAPITokenUserID answers 0 for an unknown token. 0 is also the
// placeholder identity used when login is off, so tokens minted without
// a session are refused here as well (see handleTokenRegenerate).
if userID == 0 {
writeJSONError(w, http.StatusUnauthorized, "Invalid API token")
return
}
ctx := context.WithValue(r.Context(), apiUserIDContextKey{}, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
type apiUserIDContextKey struct{}
func requestUserID(r *http.Request) int64 {
if userID, ok := r.Context().Value(apiUserIDContextKey{}).(int64); ok {
return userID
}
if user := sharedauth.UserFromContext(r.Context()); user != nil {
return user.ID
}
return 0
}
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, or while login is switched off, that middleware always
// resolves to sharedauth's fixed placeholder identity (ID 0). A token minted
// for it is stored, but requireAPIToken never accepts identity 0, so a caller
// without a session cannot turn it into access to the sync API.
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})
}