diff --git a/media-backend/.env.example b/media-backend/.env.example index d5489c1..ddcfe89 100644 --- a/media-backend/.env.example +++ b/media-backend/.env.example @@ -18,5 +18,6 @@ ANALYZER_MODELS_URL=http://127.0.0.1:8801 CORS_ORIGIN=http://localhost:5173 SESSION_COOKIE=mediacollection_session COOKIE_SECURE=false +AUTHGUARD_URL= INTERNAL_SERVICE_SECRET= MAX_UPLOAD_BYTES=50gb diff --git a/media-backend/internal/auth/auth.go b/media-backend/internal/auth/auth.go index 262a017..ffca852 100644 --- a/media-backend/internal/auth/auth.go +++ b/media-backend/internal/auth/auth.go @@ -1,14 +1,124 @@ +// Package auth is the media-collection family's /auth/... and /api/auth/... +// handlers, proxied to AuthGuard. +// +// AuthGuard migration +// ==================== +// This service used to be a fully self-contained auth implementation: +// account and session state lived in this service's own PostgreSQL +// `users`/`go_sessions` tables (see the database migration, whose +// CREATE TABLE statements are kept but no longer used for identity - see +// below). +// +// It now proxies every auth operation to AuthGuard (Web/Central/AuthGuard), +// a centralized identity service other projects in this workspace share, +// via the `authclient` package (Web/Central/shared/backend/authclient, +// resolved through this module's own `repos.gfranz.ch/Gabriel20xx/shared/backend` +// dependency - same module that already provided `sharedauth`). This +// service's own /auth/... and /api/auth/... URL paths and JSON response +// shapes are UNCHANGED - the frontend (media-webui) was not touched - only +// what backs them changed. This mirrors the migration +// Original/GameStream/backend/cmd/gamestreamd/auth.go and +// Forks/Bitmagnet/backend/internal/auth/service.go already did; read either +// file's top-of-file doc comment for the fuller rationale behind each +// design choice below. +// +// Unlike those two, this service still has a genuinely independent +// "loginRequired" concept (RequireIfLoginRequired/RequireAdminIfLoginRequired, +// backed by the `settings` table's `auth_required` key, toggled via +// GET/PUT /api/auth/access) predating this migration - a deployment can run +// with login turned OFF entirely so every action is available to anonymous +// visitors, independent of whether AuthGuard has any accounts at all. That +// toggle is NOT touched by this migration (it stays exactly as it was); only +// what CurrentUser resolves a session against changed. See "Auth-disabled +// mode" below for how the two interact. +// +// Session cookie / token model +// ----------------------------- +// AuthGuard sets its own `auth_session` cookie (authclient.DefaultCookieName) +// on register/login, whose scope is entirely controlled by AuthGuard's own +// deployment config. Rather than inventing a second cookie and a mapping +// between "this service's session token" and "AuthGuard's session token", +// this service forwards AuthGuard's Set-Cookie header straight through to +// the browser on signup/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). This service mints no session token of +// its own any more. The pre-migration SESSION_COOKIE name (configurable, +// default "mediacollection_session") 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 +// ---------- +// This service's "first launch: create the admin account" flow doesn't map +// onto AuthGuard, which is not single-admin-scoped and has no concept of +// "this is service X's initial account". A tiny local flag of its own - +// the `settings` table's `setup_claimed` key (isSetupClaimed/tryClaimSetup/ +// unclaimSetup below, reusing the same table/mechanism as `auth_required` +// rather than a new one) - means only "has this deployment completed its +// setup screen once", with no credentials of any kind in it. Signup +// atomically claims that flag, registers the account against AuthGuard's +// POST /api/register, and unclaims it again if registration fails. +// +// The local claim alone would still show the "create account" form to a +// second `-service` deployment's own first launch (or a second +// AuthGuard-connected project entirely) even though AuthGuard already has an +// account from the first one, since accounts are centralized. AdminNeeded +// and Signup both additionally call AuthGuard's GET /api/setup-status +// (authclient.Client.SetupStatus) and treat "AuthGuard already has an +// account" the same as "already claimed locally": report no setup needed, +// 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 (PUT /auth/me) needs AuthGuard's +// admin/users endpoint, which requires CanManageUsers. A plain +// "user"-role account has no self-service way to change its own +// username/email/password via AuthGuard today; see UpdateMe. +// - The `bio`/`avatarUrl` fields the pre-migration User type carried are +// dropped entirely: AuthGuard has no such concept, and grepping the +// frontend (media-webui) confirms neither field was ever actually read +// or set by any UI - they were dead weight even before this migration. +// +// Auth-disabled mode (AUTHGUARD_URL unset) +// ----------------------------------------- +// AUTHGUARD_URL is optional. When it is unset, Service.authGuard is nil +// (Service.enabled() reports false) and this service runs with +// authentication turned off entirely: CurrentUser always resolves to +// localProfile (a fixed placeholder superadmin identity), so every request +// is treated as already authenticated regardless of the `auth_required` +// setting - there is no login screen and nothing gated. This is an explicit +// mode for local development or a standalone deployment that doesn't want +// centralized identity, matching every other AuthGuard-migrated project's +// exact convention; it is not an error condition, and there is no +// degraded/partial "local auth" fallback state. +// +// Features that need a *real* backing identity rather than just an access +// gate - TOTP (initiate/verify/disable), 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. +// +// No local admin-reset flow +// -------------------------- +// This service used to expose POST /auth/reset/request + /auth/reset/confirm, +// an out-of-band console-code flow that wiped every local account. That has +// no meaning once there is no local account to wipe - accounts are +// centralized in AuthGuard now, and only AuthGuard's own web UI exposes an +// admin-reset affordance. Those two routes are removed entirely, not +// adapted (see server.go). package auth import ( "context" - "crypto/rand" - "crypto/sha256" - "encoding/base64" - "encoding/hex" "encoding/json" "errors" - "fmt" "io" "net/http" "strconv" @@ -20,26 +130,22 @@ import ( "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" sharedauth "repos.gfranz.ch/Gabriel20xx/shared/backend/auth" + authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient" ) +// User is this service's own /auth/... response shape - UNCHANGED from +// before this migration except Bio/Avatar (see the package doc comment's +// "Known gaps" section), sourced from AuthGuard's authclient.PublicUser via +// toUser rather than a local table. type User struct { ID int64 `json:"id"` Email string `json:"email"` Username string `json:"username,omitempty"` Role string `json:"role,omitempty"` CanManageUsers bool `json:"canManageUsers"` - Bio string `json:"bio,omitempty"` - Avatar string `json:"avatarUrl,omitempty"` MFAEnabled bool `json:"mfaEnabled"` } -type storedUser struct { - User - PasswordHash string - Disabled bool - TOTPSecret string -} - type contextKey struct{} var userContextKey contextKey @@ -48,26 +154,64 @@ var ( ErrUnauthorized = errors.New("authentication required") ErrForbidden = errors.New("administrator access required") ErrInvalidLogin = errors.New("Invalid username or password.") + // 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 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 can safely report this same, specific + // message rather than a generic "internal error" that would be + // indistinguishable from any other server bug. + errAuthGuardUnavailable = errors.New("Unable to reach the authentication service. Please try again shortly.") + errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.") ) -const loginRequiredSettingKey = "auth_required" +const ( + loginRequiredSettingKey = "auth_required" + setupClaimedSettingKey = "setup_claimed" + + minPasswordLength = 8 + maxUsernameLength = 64 + maxEmailLength = 254 +) + +// localProfile is the fixed placeholder identity CurrentUser/Signup/Login +// 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. +var localProfile = User{ID: 0, Username: "local", Email: "", Role: string(sharedauth.RoleSuperAdmin), CanManageUsers: true} type Service struct { db *pgxpool.Pool cookieName string secureCookies bool - sessionTTL time.Duration - resetManager *sharedauth.ResetManager + // authGuard is nil when AUTHGUARD_URL is unset; see the top-of-file doc + // comment's "Auth-disabled mode" section. + authGuard *authclient.Client } -func New(db *pgxpool.Pool, cookieName string, secureCookies bool) *Service { - return &Service{ - db: db, - cookieName: cookieName, - secureCookies: secureCookies, - sessionTTL: 7 * 24 * time.Hour, - resetManager: sharedauth.NewResetManager(), +// New constructs a Service. cookieName/secureCookies are retained only for +// clearing the pre-migration session cookie on logout (see the package doc +// comment's "Session cookie / token model" section) - the live session +// cookie this service actually reads/sets is always AuthGuard's own +// authclient.DefaultCookieName. authGuardURL is AUTHGUARD_URL; empty means +// auth-disabled mode. +func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL string) *Service { + var client *authclient.Client + if strings.TrimSpace(authGuardURL) != "" { + client = authclient.New(authGuardURL) } + return &Service{db: db, cookieName: cookieName, secureCookies: secureCookies, authGuard: client} +} + +// enabled reports whether AUTHGUARD_URL was configured. See the top-of-file +// doc comment's "Auth-disabled mode" section. +func (s *Service) enabled() bool { + return s.authGuard != nil } func UserFromContext(ctx context.Context) *User { @@ -75,40 +219,84 @@ func UserFromContext(ctx context.Context) *User { return value } +// sessionToken reads the AuthGuard session cookie off the incoming request. +// See the top-of-file doc comment's "Session cookie / token model" section. +func (s *Service) 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 cookie name. +func (s *Service) clearSessionCookies(w http.ResponseWriter) { + http.SetCookie(w, &http.Cookie{ + Name: authclient.DefaultCookieName, Value: "", Path: "/", HttpOnly: true, + Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1, + }) + http.SetCookie(w, &http.Cookie{ + Name: s.cookieName, Value: "", Path: "/", HttpOnly: true, + Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1, + }) +} + +// toUser translates AuthGuard's PublicUser into this service's own User +// response shape. +func toUser(profile authclient.PublicUser) *User { + return &User{ + ID: profile.ID, Email: profile.Email, Username: profile.Username, + Role: profile.Role, CanManageUsers: sharedauth.CanManageUsers(profile.Role), + MFAEnabled: profile.TOTPEnabled, + } +} + +// currentProfile resolves the request's AuthGuard session cookie via +// GET /api/me (which - unlike the cheaper GET /api/session/validate - +// carries TOTPEnabled directly, so this service needs no local TOTP-enabled +// cache the way GameStream's migration did), or nil if the request has no +// session cookie or AuthGuard reports it as invalid/expired. +func (s *Service) currentProfile(ctx context.Context, token string) (*authclient.PublicUser, error) { + if token == "" { + return nil, nil + } + profile, err := s.authGuard.Me(ctx, token) + if err != nil { + var apiErr *authclient.APIError + if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusUnauthorized { + return nil, nil + } + return nil, err + } + return profile, nil +} + +// CurrentUser is the single choke point every gating middleware below +// (Optional/Require/RequireAdmin/RequireUserManager/RequireIfLoginRequired/ +// RequireAdminIfLoginRequired) resolves a session through - none of them +// needed to change for this migration, only what CurrentUser itself does. func (s *Service) CurrentUser(r *http.Request) (*User, error) { - cookie, err := r.Cookie(s.cookieName) - if errors.Is(err, http.ErrNoCookie) || cookie.Value == "" { - return nil, nil + if !s.enabled() { + user := localProfile + return &user, nil } + profile, err := s.currentProfile(r.Context(), s.sessionToken(r)) if err != nil { return nil, err } - ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) - defer cancel() - var user User - var disabled bool - err = s.db.QueryRow(ctx, ` - SELECT u.id, u.email, COALESCE(u.username, ''), COALESCE(u.role, 'user'), - COALESCE(u.bio, ''), COALESCE(u.avatar_url, ''), u.disabled, COALESCE(u.mfa_enabled, false) - FROM go_sessions session - JOIN users u ON u.id = session.user_id - WHERE session.token_hash = $1 AND session.expires_at > NOW() - `, tokenHash(cookie.Value)).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &disabled, &user.MFAEnabled) - if errors.Is(err, pgx.ErrNoRows) || disabled { + if profile == nil { return nil, nil } - if err != nil { - return nil, err - } - user.CanManageUsers = sharedauth.CanManageUsers(user.Role) - return &user, nil + return toUser(*profile), nil } func (s *Service) Optional(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { user, err := s.CurrentUser(r) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication lookup failed") + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } if user != nil { @@ -130,7 +318,8 @@ func (s *Service) Require(next http.Handler) http.Handler { // RequireIfLoginRequired protects actions when the application has login // enabled, while allowing explicitly public installations to use actions that -// do not need a user identity. +// do not need a user identity. This toggle is independent of AuthGuard - see +// the package doc comment's second paragraph. func (s *Service) RequireIfLoginRequired(next http.Handler) http.Handler { return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if UserFromContext(r.Context()) != nil { @@ -189,6 +378,17 @@ func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler { })) } +func (s *Service) RequireUserManager(next http.Handler) http.Handler { + return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user := UserFromContext(r.Context()) + if !sharedauth.CanManageUsers(user.Role) { + writeError(w, http.StatusForbidden, ErrForbidden.Error()) + return + } + next.ServeHTTP(w, r) + })) +} + func IsAdmin(user *User) bool { if user == nil { return false @@ -204,12 +404,7 @@ func IsAdmin(user *User) bool { func (s *Service) Me(w http.ResponseWriter, r *http.Request) { user, err := s.CurrentUser(r) if err != nil { - writeError(w, http.StatusInternalServerError, "authentication lookup failed") - return - } - count, err := s.CountUsers(r.Context()) - if err != nil { - writeError(w, http.StatusInternalServerError, "authentication status unavailable") + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) return } loginRequired, err := s.LoginRequired(r.Context()) @@ -217,19 +412,28 @@ func (s *Service) Me(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, "authentication status unavailable") return } - writeJSON(w, http.StatusOK, map[string]any{ - "user": user, - "authRequired": loginRequired, - "setupRequired": count == 0, - }) + writeJSON(w, http.StatusOK, map[string]any{"user": user, "authRequired": loginRequired}) } +// UpdateMe lets the caller edit their own username/email/password. See the +// package 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. func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if user == nil { + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + current := UserFromContext(r.Context()) + if current == nil { writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) return } + if !sharedauth.CanManageUsers(current.Role) { + writeError(w, http.StatusForbidden, errSelfServiceProfile.Error()) + return + } var input struct { Email string `json:"email"` @@ -240,38 +444,29 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusBadRequest, "invalid JSON body") return } - - email := strings.ToLower(strings.TrimSpace(input.Email)) - username := strings.TrimSpace(input.Username) - if !strings.Contains(email, "@") || len(email) > 254 { - writeError(w, http.StatusBadRequest, "a valid email is required") + email, err := normalizeEmail(input.Email) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) return } - if username == "" || len([]rune(username)) > 64 { - writeError(w, http.StatusBadRequest, "a username is required") + username, err := normalizeUsername(input.Username) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) return } - passwordHash := "" + managedInput := authclient.ManagedUserInput{Username: username, Email: email} if input.Password != "" { if err := validatePassword(input.Password); err != nil { writeError(w, http.StatusBadRequest, err.Error()) return } - hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) - if err != nil { - writeError(w, http.StatusInternalServerError, "password could not be updated") - return - } - passwordHash = string(hash) + managedInput.Password = input.Password } - if _, err := s.db.Exec(r.Context(), ` - UPDATE users - SET email = $1, username = $2, password_hash = COALESCE(NULLIF($3, ''), password_hash) - WHERE id = $4 - `, email, username, passwordHash, user.ID); err != nil { - writeError(w, http.StatusBadRequest, "profile could not be updated") + token := s.sessionToken(r) + if err := s.authGuard.UpdateManagedUser(r.Context(), token, current.ID, managedInput); err != nil { + writeAuthGuardError(w, err, "profile could not be updated") return } @@ -283,24 +478,28 @@ func (s *Service) UpdateMe(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"user": updated}) } -func (s *Service) RequireUserManager(next http.Handler) http.Handler { - return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if !sharedauth.CanManageUsers(user.Role) { - writeError(w, http.StatusForbidden, ErrForbidden.Error()) - return - } - next.ServeHTTP(w, r) - })) -} - +// AdminNeeded answers GET /auth/bootstrap/admin-needed. See the package doc +// comment's "Setup flow" section. func (s *Service) AdminNeeded(w http.ResponseWriter, r *http.Request) { - count, err := s.CountUsers(r.Context()) + if !s.enabled() { + writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) + return + } + claimed, err := s.isSetupClaimed(r.Context()) if err != nil { writeError(w, http.StatusInternalServerError, "authentication status unavailable") return } - writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": count == 0}) + if claimed { + writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false}) + return + } + setupRequired, err := s.authGuard.SetupStatus(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired}) } func (s *Service) LoginRequired(ctx context.Context) (bool, error) { @@ -350,25 +549,472 @@ func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) { } func (s *Service) Status(w http.ResponseWriter, r *http.Request) { - count, err := s.CountUsers(r.Context()) + if !s.enabled() { + user := localProfile + writeJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": true, "user": &user}) + return + } + claimed, err := s.isSetupClaimed(r.Context()) if err != nil { writeError(w, http.StatusInternalServerError, "authentication status unavailable") return } - user, _ := s.CurrentUser(r) + setupRequired := false + if !claimed { + setupRequired, err = s.authGuard.SetupStatus(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + } + user, err := s.CurrentUser(r) + if err != nil { + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } loginRequired, err := s.LoginRequired(r.Context()) if err != nil { writeError(w, http.StatusInternalServerError, "authentication status unavailable") return } writeJSON(w, http.StatusOK, map[string]any{ - "setupRequired": count == 0, - "authenticated": user != nil, - "authRequired": loginRequired, - "user": user, + "setupRequired": setupRequired, "authenticated": user != nil, "authRequired": loginRequired, "user": user, }) } +// managedUserPayload translates an AuthGuard ManagedUser into this service's +// existing response shape. +func managedUserPayload(user authclient.ManagedUser) map[string]any { + return map[string]any{ + "id": user.ID, "username": user.Username, "email": user.Email, + "role": string(sharedauth.NormalizeRole(user.Role)), "createdAt": user.CreatedAt, + } +} + +// ManagedUsers proxies admin user listing to AuthGuard's GET /api/admin/users. +// Authorization (CanManageUsers) is enforced by AuthGuard itself from the +// forwarded session token; this service does not re-implement that check +// locally, so its 401/403 responses come straight from AuthGuard via +// writeAuthGuardError. +func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + // 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, []map[string]any{}) + return + } + users, err := s.authGuard.ListManagedUsers(r.Context(), s.sessionToken(r)) + if err != nil { + writeAuthGuardError(w, err, "users unavailable") + return + } + result := make([]map[string]any, 0, len(users)) + for _, user := range users { + result = append(result, managedUserPayload(user)) + } + writeJSON(w, http.StatusOK, result) +} + +// ManagedCreateUser proxies admin user creation to AuthGuard's +// POST /api/admin/users. See ManagedUsers's doc comment: AuthGuard enforces +// authorization (including which roles the caller may assign) itself. +func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + var input struct { + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + Role string `json:"role"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + managedInput := authclient.ManagedUserInput{Username: input.Username, Email: input.Email, Password: input.Password} + if role := strings.TrimSpace(input.Role); role != "" { + managedInput.Role = &role + } + created, err := s.authGuard.CreateManagedUser(r.Context(), s.sessionToken(r), managedInput) + if err != nil { + writeAuthGuardError(w, err, "user could not be created") + return + } + writeJSON(w, http.StatusCreated, managedUserPayload(*created)) +} + +// ManagedUpdateUser proxies admin user update to AuthGuard's +// PUT /api/admin/users/{id}. See ManagedUsers's doc comment: AuthGuard +// enforces authorization (including the "the superadmin account is +// protected" rule) itself. +func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid user id") + return + } + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + var input struct { + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + Role *string `json:"role"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + managedInput := authclient.ManagedUserInput{Username: input.Username, Email: input.Email, Password: input.Password, Role: input.Role} + if err := s.authGuard.UpdateManagedUser(r.Context(), s.sessionToken(r), id, managedInput); err != nil { + writeAuthGuardError(w, err, "user could not be updated") + return + } + users, err := s.authGuard.ListManagedUsers(r.Context(), s.sessionToken(r)) + if err != nil { + writeAuthGuardError(w, err, "user could not be loaded") + return + } + for _, user := range users { + if user.ID == id { + writeJSON(w, http.StatusOK, managedUserPayload(user)) + return + } + } + writeError(w, http.StatusNotFound, "user not found") +} + +// ManagedDeleteUser proxies admin user deletion to AuthGuard's +// DELETE /api/admin/users/{id}. See ManagedUsers's doc comment: AuthGuard +// enforces authorization (including "this user cannot be deleted" rules) +// itself. +func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) { + id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) + if err != nil { + writeError(w, http.StatusBadRequest, "invalid user id") + return + } + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + if err := s.authGuard.DeleteManagedUser(r.Context(), s.sessionToken(r), id); err != nil { + writeAuthGuardError(w, err, "user could not be deleted") + return + } + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +// Signup registers this deployment's first account against AuthGuard's +// POST /api/register. See the package doc comment's "Setup flow" section for +// why this needs a small local claim flag instead of a count-based check. +func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + user := localProfile + writeJSON(w, http.StatusCreated, map[string]any{"user": &user}) + return + } + + var input struct { + Email string `json:"email"` + Username string `json:"username"` + Password string `json:"password"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + email, err := normalizeEmail(input.Email) + if err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + username := strings.TrimSpace(input.Username) + if username == "" { + writeError(w, http.StatusBadRequest, "a username is required") + return + } + if _, err := normalizeUsername(username); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + if err := validatePassword(input.Password); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return + } + + claimed, err := s.tryClaimSetup(r.Context()) + if err != nil { + writeError(w, http.StatusInternalServerError, "internal error") + return + } + if !claimed { + writeError(w, http.StatusConflict, "Setup has already been completed.") + return + } + + // Belt-and-braces: AdminNeeded 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 := s.authGuard.SetupStatus(r.Context()); err != nil || !setupRequired { + if unclaimErr := s.unclaimSetup(r.Context()); unclaimErr != nil { + writeError(w, http.StatusInternalServerError, "internal error") + return + } + if err != nil { + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + writeError(w, http.StatusConflict, "Setup has already been completed.") + return + } + + result, err := s.authGuard.Register(r.Context(), username, email, input.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 := s.unclaimSetup(r.Context()); unclaimErr != nil { + writeError(w, http.StatusInternalServerError, "internal error") + return + } + writeAuthGuardError(w, err, "could not create account") + return + } + + authclient.ForwardCookies(w, result.Cookies) + writeJSON(w, http.StatusCreated, map[string]any{"user": toUser(result.User)}) +} + +func (s *Service) Login(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + user := localProfile + writeJSON(w, http.StatusOK, map[string]any{"user": &user}) + return + } + + var input struct { + Identifier string `json:"identifier"` + Email string `json:"email"` + Password string `json:"password"` + TOTPToken string `json:"totpToken"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + identifier := strings.TrimSpace(input.Identifier) + if identifier == "" { + identifier = strings.TrimSpace(input.Email) + } + if identifier == "" { + writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) + return + } + + result, err := s.authGuard.Login(r.Context(), identifier, input.Password, input.TOTPToken) + if err != nil { + var apiErr *authclient.APIError + if errors.As(err, &apiErr) { + if apiErr.TOTPRequired { + writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true}) + return + } + if apiErr.StatusCode == http.StatusUnauthorized { + writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) + return + } + writeAuthGuardError(w, err, "could not authenticate") + return + } + // A non-APIError here means the call to AuthGuard itself failed + // (transport/connectivity); see errAuthGuardUnavailable. + writeError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error()) + return + } + + authclient.ForwardCookies(w, result.Cookies) + writeJSON(w, http.StatusOK, map[string]any{"user": toUser(result.User)}) +} + +func (s *Service) Logout(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) + return + } + if token := s.sessionToken(r); token != "" { + cookies, err := s.authGuard.Logout(r.Context(), token) + if err != nil { + var apiErr *authclient.APIError + if !errors.As(err, &apiErr) { + writeError(w, http.StatusInternalServerError, "internal error") + return + } + // An already-invalid/expired session is fine to treat as + // "already logged out" rather than an error. + } else { + authclient.ForwardCookies(w, cookies) + } + } + s.clearSessionCookies(w) + writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) +} + +func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "mfaEnabled": false}) + return + } + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled}) +} + +// TOTPInitiate provisions a pending TOTP secret via AuthGuard's POST +// /api/totp/enable (AuthGuard's "enable" is this service's "initiate" step - +// naming differs, the two-step provision-then-confirm flow is identical). +func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + if user.MFAEnabled { + writeError(w, http.StatusConflict, "multi-factor authentication is already enabled") + return + } + result, err := s.authGuard.TOTPEnable(r.Context(), s.sessionToken(r)) + if err != nil { + writeAuthGuardError(w, err, "could not create authenticator secret") + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{ + "secret": result.Secret, "otpauth": result.OTPAuthURL, "otpauthUrl": result.OTPAuthURL, "enabled": result.Enabled, + }}) +} + +// TOTPVerify confirms a generated code via AuthGuard's POST /api/totp/verify, +// activating two-factor authentication (AuthGuard's "verify" is this +// service's "verify" step too; see TOTPInitiate). +func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + var input struct { + Token string `json:"token"` + TOTPToken string `json:"totpToken"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + token := strings.TrimSpace(input.TOTPToken) + if token == "" { + token = strings.TrimSpace(input.Token) + } + if err := s.authGuard.TOTPVerify(r.Context(), s.sessionToken(r), token); err != nil { + writeError(w, http.StatusUnauthorized, "Invalid authenticator code.") + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}}) +} + +func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) { + if !s.enabled() { + writeError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error()) + return + } + user := UserFromContext(r.Context()) + if user == nil { + writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) + return + } + var input struct { + Token string `json:"token"` + TOTPToken string `json:"totpToken"` + } + if err := decodeJSON(r, &input); err != nil { + writeError(w, http.StatusBadRequest, "invalid JSON body") + return + } + token := strings.TrimSpace(input.TOTPToken) + if token == "" { + token = strings.TrimSpace(input.Token) + } + if err := s.authGuard.TOTPDisable(r.Context(), s.sessionToken(r), token); err != nil { + writeError(w, http.StatusUnauthorized, "Invalid authenticator code.") + return + } + writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}}) +} + +// isSetupClaimed/tryClaimSetup/unclaimSetup back the local one-time setup +// flag described in the package doc comment's "Setup flow" section, reusing +// the pre-existing `settings` key/value table (same mechanism as +// LoginRequired's `auth_required` key) rather than a new table. +func (s *Service) isSetupClaimed(ctx context.Context) (bool, error) { + var value string + err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, setupClaimedSettingKey).Scan(&value) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, err + } + return value == "true", nil +} + +func (s *Service) tryClaimSetup(ctx context.Context) (bool, error) { + tag, err := s.db.Exec(ctx, ` + INSERT INTO settings (key, value, updated_at) VALUES ($1, 'true', NOW()) + ON CONFLICT (key) DO NOTHING + `, setupClaimedSettingKey) + if err != nil { + return false, err + } + return tag.RowsAffected() > 0, nil +} + +func (s *Service) unclaimSetup(ctx context.Context) error { + _, err := s.db.Exec(ctx, `DELETE FROM settings WHERE key = $1`, setupClaimedSettingKey) + return err +} + +// --- Moderatable platform users (unrelated to admin login identity) -------- +// +// The methods below (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser) +// back internal/server/admin_storage.go's mountModeratorRoutes +// (adminUsers/adminCreateUser/adminUpdateUser/adminDeleteUser/adminUserActions +// - the ModerationHub service's "manage platform participants" admin panel). +// This is a DIFFERENT concept from "who can log into this service's own +// admin panel" (the Signup/Login/ManagedUsers family above, now proxied to +// AuthGuard): these are content-uploading end users of the media platform +// being moderated, not administrators. They happen to share the local +// `users`/`go_sessions` table's schema from before this migration, but that +// table's role here is now purely "the local platform-user directory" - it +// is no longer consulted for anything related to *this service's own* +// authentication, which is entirely AuthGuard's job now. Left untouched by +// this migration. + type managedAccount struct { ID int64 Email string @@ -398,400 +1044,11 @@ func managedAccountPayload(user *managedAccount) map[string]any { "id": user.ID, "username": user.Username, "email": user.Email, - "role": string(sharedauth.NormalizeRole(user.Role)), + "role": normalizeRole(user.Role), "createdAt": user.CreatedAt, } } -func (s *Service) ManagedUsers(w http.ResponseWriter, r *http.Request) { - rows, err := s.db.Query(r.Context(), ` - SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at - FROM users ORDER BY created_at, id - `) - if err != nil { - writeError(w, http.StatusInternalServerError, "users unavailable") - return - } - defer rows.Close() - users := make([]map[string]any, 0) - for rows.Next() { - var user managedAccount - if err := rows.Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt); err != nil { - writeError(w, http.StatusInternalServerError, "users unavailable") - return - } - users = append(users, managedAccountPayload(&user)) - } - if err := rows.Err(); err != nil { - writeError(w, http.StatusInternalServerError, "users unavailable") - return - } - writeJSON(w, http.StatusOK, users) -} - -func (s *Service) ManagedCreateUser(w http.ResponseWriter, r *http.Request) { - var input struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` - Role string `json:"role"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - actor := UserFromContext(r.Context()) - role := sharedauth.NormalizeRole(input.Role) - if role == sharedauth.RoleSuperAdmin { - writeError(w, http.StatusBadRequest, "a new user cannot be a superadmin") - return - } - if actor == nil || sharedauth.NormalizeRole(actor.Role) != sharedauth.RoleSuperAdmin { - role = sharedauth.RoleUser - } - user, err := s.CreateUser(r.Context(), input.Email, input.Username, input.Password, string(role)) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - created, err := s.managedAccount(r.Context(), user.ID) - if err != nil || created == nil { - writeError(w, http.StatusInternalServerError, "user could not be loaded") - return - } - writeJSON(w, http.StatusCreated, managedAccountPayload(created)) -} - -func (s *Service) ManagedUpdateUser(w http.ResponseWriter, r *http.Request) { - id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid user id") - return - } - target, err := s.managedAccount(r.Context(), id) - if err != nil { - writeError(w, http.StatusInternalServerError, "user could not be loaded") - return - } - if target == nil { - writeError(w, http.StatusNotFound, "user not found") - return - } - var input struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` - Role *string `json:"role"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - actor := UserFromContext(r.Context()) - targetRole := sharedauth.NormalizeRole(target.Role) - role := targetRole - if targetRole != sharedauth.RoleSuperAdmin && actor != nil && sharedauth.NormalizeRole(actor.Role) == sharedauth.RoleSuperAdmin && input.Role != nil { - requested := sharedauth.NormalizeRole(*input.Role) - if requested == sharedauth.RoleSuperAdmin { - writeError(w, http.StatusBadRequest, "the superadmin role is protected") - return - } - role = requested - } - if err := s.UpdateUser(r.Context(), id, input.Email, input.Username, string(role), nil); err != nil { - writeError(w, http.StatusBadRequest, "user could not be updated") - return - } - if strings.TrimSpace(input.Password) != "" { - if err := s.SetPassword(r.Context(), id, input.Password); err != nil { - writeError(w, http.StatusBadRequest, "password could not be updated") - return - } - } - updated, err := s.managedAccount(r.Context(), id) - if err != nil || updated == nil { - writeError(w, http.StatusInternalServerError, "user could not be loaded") - return - } - writeJSON(w, http.StatusOK, managedAccountPayload(updated)) -} - -func (s *Service) ManagedDeleteUser(w http.ResponseWriter, r *http.Request) { - id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64) - if err != nil { - writeError(w, http.StatusBadRequest, "invalid user id") - return - } - target, err := s.managedAccount(r.Context(), id) - if err != nil { - writeError(w, http.StatusInternalServerError, "user could not be loaded") - return - } - if target == nil { - writeError(w, http.StatusNotFound, "user not found") - return - } - actor := UserFromContext(r.Context()) - if actor == nil || actor.ID == target.ID || sharedauth.NormalizeRole(target.Role) == sharedauth.RoleSuperAdmin { - writeError(w, http.StatusForbidden, "the current or first account cannot be removed") - return - } - if err := s.DeleteUser(r.Context(), id); err != nil { - writeError(w, http.StatusNotFound, "user not found") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Service) Signup(w http.ResponseWriter, r *http.Request) { - var input struct { - Email string `json:"email"` - Username string `json:"username"` - Password string `json:"password"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - email, username, password, err := normalizeCredentials(input.Email, input.Username, input.Password) - if err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - if username == "" { - writeError(w, http.StatusBadRequest, "a username is required") - return - } - hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) - if err != nil { - writeError(w, http.StatusInternalServerError, "could not secure password") - return - } - var user User - err = s.db.QueryRow(r.Context(), ` - INSERT INTO users (email, username, password_hash, role) - SELECT $1, $2, $3, 'superadmin' - WHERE NOT EXISTS (SELECT 1 FROM users) - RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'superadmin') - `, email, username, string(hash)).Scan(&user.ID, &user.Email, &user.Username, &user.Role) - if errors.Is(err, pgx.ErrNoRows) { - writeError(w, http.StatusConflict, "Setup has already been completed.") - return - } - if err != nil { - writeError(w, http.StatusInternalServerError, "could not create account") - return - } - user.CanManageUsers = sharedauth.CanManageUsers(user.Role) - if err := s.startSession(w, r.Context(), user.ID); err != nil { - writeError(w, http.StatusInternalServerError, "could not start session") - return - } - writeJSON(w, http.StatusCreated, map[string]any{"user": user}) -} - -func (s *Service) Login(w http.ResponseWriter, r *http.Request) { - var input struct { - Identifier string `json:"identifier"` - Email string `json:"email"` - Password string `json:"password"` - TOTPToken string `json:"totpToken"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - identifier := strings.TrimSpace(input.Identifier) - if identifier == "" { - identifier = strings.TrimSpace(input.Email) - } - var user storedUser - err := s.db.QueryRow(r.Context(), ` - SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), COALESCE(bio, ''), - COALESCE(avatar_url, ''), password_hash, disabled, COALESCE(mfa_enabled, false), COALESCE(totp_secret, '') - FROM users WHERE LOWER(email) = LOWER($1) OR LOWER(COALESCE(username, '')) = LOWER($1) - LIMIT 1 - `, identifier).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Bio, &user.Avatar, &user.PasswordHash, &user.Disabled, &user.MFAEnabled, &user.TOTPSecret) - if errors.Is(err, pgx.ErrNoRows) { - writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) - return - } - if err != nil { - writeError(w, http.StatusInternalServerError, "could not authenticate") - return - } - user.User.CanManageUsers = sharedauth.CanManageUsers(user.Role) - if user.Disabled || bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(input.Password)) != nil { - writeError(w, http.StatusUnauthorized, ErrInvalidLogin.Error()) - return - } - if user.MFAEnabled && !sharedauth.VerifyTOTP(user.TOTPSecret, strings.TrimSpace(input.TOTPToken), time.Now()) { - writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true}) - return - } - _, _ = s.db.Exec(r.Context(), `UPDATE users SET last_login_at = NOW() WHERE id = $1`, user.ID) - if err := s.startSession(w, r.Context(), user.ID); err != nil { - writeError(w, http.StatusInternalServerError, "could not start session") - return - } - writeJSON(w, http.StatusOK, map[string]any{"user": user.User}) -} - -func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) - return - } - writeJSON(w, http.StatusOK, map[string]any{"enabled": user.MFAEnabled, "mfaEnabled": user.MFAEnabled}) -} - -func (s *Service) TOTPInitiate(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) - return - } - if user.MFAEnabled { - writeError(w, http.StatusConflict, "multi-factor authentication is already enabled") - return - } - secret, err := sharedauth.GenerateTOTPSecret() - if err != nil { - writeError(w, http.StatusInternalServerError, "could not create authenticator secret") - return - } - if _, err := s.db.Exec(r.Context(), `UPDATE users SET totp_secret = $1, mfa_enabled = false WHERE id = $2`, secret, user.ID); err != nil { - writeError(w, http.StatusInternalServerError, "could not save authenticator secret") - return - } - account := user.Username - if account == "" { - account = user.Email - } - uri := sharedauth.TOTPProvisioningURI("MediaCollection", account, secret) - writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"secret": secret, "otpauth": uri, "otpauthUrl": uri, "enabled": false}}) -} - -func (s *Service) TOTPVerify(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) - return - } - var input struct { - Token string `json:"token"` - TOTPToken string `json:"totpToken"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - var secret string - if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, '') FROM users WHERE id = $1`, user.ID).Scan(&secret); err != nil { - writeError(w, http.StatusInternalServerError, "could not load authenticator secret") - return - } - token := strings.TrimSpace(input.TOTPToken) - if token == "" { - token = strings.TrimSpace(input.Token) - } - if !sharedauth.VerifyTOTP(secret, token, time.Now()) { - writeError(w, http.StatusUnauthorized, "Invalid authenticator code.") - return - } - if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = true WHERE id = $1 AND totp_secret <> ''`, user.ID); err != nil { - writeError(w, http.StatusInternalServerError, "could not enable multi-factor authentication") - return - } - writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": true, "enabled": true, "backupCodes": []string{}}}) -} - -func (s *Service) TOTPDisable(w http.ResponseWriter, r *http.Request) { - user := UserFromContext(r.Context()) - if user == nil { - writeError(w, http.StatusUnauthorized, ErrUnauthorized.Error()) - return - } - var input struct { - Token string `json:"token"` - TOTPToken string `json:"totpToken"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - var secret string - var enabled bool - if err := s.db.QueryRow(r.Context(), `SELECT COALESCE(totp_secret, ''), COALESCE(mfa_enabled, false) FROM users WHERE id = $1`, user.ID).Scan(&secret, &enabled); err != nil { - writeError(w, http.StatusInternalServerError, "could not load authenticator state") - return - } - token := strings.TrimSpace(input.TOTPToken) - if token == "" { - token = strings.TrimSpace(input.Token) - } - if !enabled || !sharedauth.VerifyTOTP(secret, token, time.Now()) { - writeError(w, http.StatusUnauthorized, "Invalid authenticator code.") - return - } - if _, err := s.db.Exec(r.Context(), `UPDATE users SET mfa_enabled = false, totp_secret = NULL WHERE id = $1`, user.ID); err != nil { - writeError(w, http.StatusInternalServerError, "could not disable multi-factor authentication") - return - } - writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"mfaEnabled": false, "enabled": false}}) -} - -func (s *Service) Logout(w http.ResponseWriter, r *http.Request) { - if cookie, err := r.Cookie(s.cookieName); err == nil && cookie.Value != "" { - _, _ = s.db.Exec(r.Context(), `DELETE FROM go_sessions WHERE token_hash = $1`, tokenHash(cookie.Value)) - } - http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: "", Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, MaxAge: -1}) - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Service) RequestAdminReset(w http.ResponseWriter, _ *http.Request) { - if _, err := s.resetManager.Request(); err != nil { - writeError(w, http.StatusInternalServerError, "could not create reset code") - return - } - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Service) ConfirmAdminReset(w http.ResponseWriter, r *http.Request) { - var input struct { - Code string `json:"code"` - } - if err := decodeJSON(r, &input); err != nil { - writeError(w, http.StatusBadRequest, "invalid JSON body") - return - } - if !s.resetManager.Confirm(input.Code) { - writeError(w, http.StatusUnauthorized, "Invalid or expired reset code.") - return - } - if _, err := s.db.Exec(r.Context(), `DELETE FROM users`); err != nil { - writeError(w, http.StatusInternalServerError, "could not reset administrator accounts") - return - } - http.SetCookie(w, &http.Cookie{ - Name: s.cookieName, - Value: "", - Path: "/", - HttpOnly: true, - Secure: s.secureCookies, - SameSite: http.SameSiteLaxMode, - MaxAge: -1, - }) - writeJSON(w, http.StatusOK, map[string]bool{"ok": true}) -} - -func (s *Service) CountUsers(ctx context.Context) (int64, error) { - var count int64 - err := s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users`).Scan(&count) - return count, err -} - func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*User, error) { email, username, password, err := normalizeCredentials(email, username, password) if err != nil { @@ -879,38 +1136,62 @@ func (s *Service) SetPassword(ctx context.Context, id int64, password string) er return err } +// writeAuthGuardError translates an authclient error into this service's +// {"error": "..."} response shape. AuthGuard's own httpapi handlers were +// built from this workspace's various local implementations, so their +// status codes and messages already match closely - 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) { + writeError(w, apiErr.StatusCode, apiErr.Message) + return + } + writeError(w, http.StatusInternalServerError, fallbackMessage) +} + +func normalizeUsername(value string) (string, error) { + value = strings.TrimSpace(value) + if value == "" { + return "", nil + } + if len([]rune(value)) > maxUsernameLength { + return "", errors.New("username is too long") + } + return value, nil +} + +func normalizeEmail(value string) (string, error) { + value = strings.ToLower(strings.TrimSpace(value)) + if !strings.Contains(value, "@") || len(value) > maxEmailLength { + return "", errors.New("a valid email is required") + } + return value, nil +} + func validatePassword(password string) error { - if len([]rune(password)) < 8 || len([]rune(password)) > 1024 { - return fmt.Errorf("Password must be at least 8 characters.") + if len([]rune(password)) < minPasswordLength || len([]rune(password)) > 1024 { + return errors.New("Password must be at least 8 characters.") } return nil } -func (s *Service) startSession(w http.ResponseWriter, ctx context.Context, userID int64) error { - token, err := randomToken() - if err != nil { - return err - } - expires := time.Now().Add(s.sessionTTL) - if _, err := s.db.Exec(ctx, `INSERT INTO go_sessions (token_hash, user_id, expires_at) VALUES ($1, $2, $3)`, tokenHash(token), userID, expires); err != nil { - return err - } - _, _ = s.db.Exec(ctx, `DELETE FROM go_sessions WHERE expires_at <= NOW()`) - http.SetCookie(w, &http.Cookie{Name: s.cookieName, Value: token, Path: "/", HttpOnly: true, Secure: s.secureCookies, SameSite: http.SameSiteLaxMode, Expires: expires, MaxAge: int(s.sessionTTL.Seconds())}) - return nil -} - +// normalizeCredentials validates email/password format (username is +// optional here - Signup separately requires it be non-empty; kept this way +// to preserve this package's existing test coverage/contract). func normalizeCredentials(email, username, password string) (string, string, string, error) { - email = strings.ToLower(strings.TrimSpace(email)) - username = strings.TrimSpace(username) - if !strings.Contains(email, "@") || len(email) > 254 { - return "", "", "", fmt.Errorf("a valid email is required") + email, err := normalizeEmail(email) + if err != nil { + return "", "", "", err } - if len([]rune(username)) > 64 { - return "", "", "", fmt.Errorf("username is too long") + username, err = normalizeUsername(username) + if err != nil { + return "", "", "", err } - if len([]rune(password)) < 8 || len([]rune(password)) > 1024 { - return "", "", "", fmt.Errorf("Password must be at least 8 characters.") + if err := validatePassword(password); err != nil { + return "", "", "", err } return email, username, password, nil } @@ -924,19 +1205,6 @@ func normalizeRole(role string) string { } } -func randomToken() (string, error) { - data := make([]byte, 32) - if _, err := rand.Read(data); err != nil { - return "", err - } - return base64.RawURLEncoding.EncodeToString(data), nil -} - -func tokenHash(token string) string { - sum := sha256.Sum256([]byte(token)) - return hex.EncodeToString(sum[:]) -} - func decodeJSON(r *http.Request, target any) error { defer r.Body.Close() decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024)) diff --git a/media-backend/internal/auth/auth_authguard_test.go b/media-backend/internal/auth/auth_authguard_test.go new file mode 100644 index 0000000..a5e18e0 --- /dev/null +++ b/media-backend/internal/auth/auth_authguard_test.go @@ -0,0 +1,252 @@ +package auth + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/jackc/pgx/v5/pgxpool" + + "mediacollection/internal/database" +) + +// testPool returns a connection pool against a real (throwaway) Postgres +// instance, and a cleanup function. DATABASE_URL is expected to point at +// one - these tests are skipped (not failed) when it is unset, mirroring +// the workspace's existing convention for DB-backed test suites (see +// Forks/HordeWorker/tests/conftest.py's identical approach). +func testPool(t *testing.T) *pgxpool.Pool { + t.Helper() + dsn := strings.TrimSpace(os.Getenv("DATABASE_URL")) + if dsn == "" { + t.Skip("DATABASE_URL not set; skipping AuthGuard-proxy auth tests that need a real Postgres") + } + ctx := context.Background() + pool, err := database.Open(ctx, dsn) + if err != nil { + t.Fatalf("open test database: %v", err) + } + if err := database.Migrate(ctx, pool); err != nil { + t.Fatalf("migrate test database: %v", err) + } + if _, err := pool.Exec(ctx, `DELETE FROM settings`); err != nil { + t.Fatalf("reset settings table: %v", err) + } + if _, err := pool.Exec(ctx, `DELETE FROM users`); err != nil { + t.Fatalf("reset users table: %v", err) + } + t.Cleanup(pool.Close) + return pool +} + +// fakeAuthGuard is a minimal stateful in-memory AuthGuard double: enough of +// setup-status/register/login/me/logout to exercise Service's proxy +// behavior end-to-end, mirroring the httptest-server pattern already used +// by shared/backend/authclient's own tests. +type fakeAuthGuard struct { + server *httptest.Server + hasAccount bool + username string + email string + role string + password string + sessions map[string]bool +} + +func newFakeAuthGuard() *fakeAuthGuard { + f := &fakeAuthGuard{sessions: map[string]bool{}} + mux := http.NewServeMux() + mux.HandleFunc("GET /api/setup-status", func(w http.ResponseWriter, r *http.Request) { + writeJSON(w, http.StatusOK, map[string]bool{"setup_required": !f.hasAccount}) + }) + mux.HandleFunc("POST /api/register", func(w http.ResponseWriter, r *http.Request) { + if f.hasAccount { + writeJSON(w, http.StatusConflict, map[string]string{"error": "setup already completed"}) + return + } + var body struct{ Username, Email, Password string } + _ = json.NewDecoder(r.Body).Decode(&body) + f.hasAccount = true + f.username, f.email, f.role, f.password = body.Username, body.Email, "superadmin", body.Password + token := "tok-" + body.Username + f.sessions[token] = true + http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token}) + writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{ + "id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false, + }}) + }) + mux.HandleFunc("POST /api/login", func(w http.ResponseWriter, r *http.Request) { + var body struct { + UsernameOrEmail string `json:"username_or_email"` + Password string `json:"password"` + } + _ = json.NewDecoder(r.Body).Decode(&body) + if !f.hasAccount || body.UsernameOrEmail != f.username && body.UsernameOrEmail != f.email || body.Password != f.password { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "Invalid username or password."}) + return + } + token := "tok-" + f.username + f.sessions[token] = true + http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: token}) + writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{ + "id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false, + }}) + }) + mux.HandleFunc("GET /api/me", func(w http.ResponseWriter, r *http.Request) { + token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if !f.sessions[token] { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid session"}) + return + } + writeJSON(w, http.StatusOK, map[string]any{"user": map[string]any{ + "id": 1, "username": f.username, "email": f.email, "role": f.role, "totp_enabled": false, + }}) + }) + mux.HandleFunc("POST /api/logout", func(w http.ResponseWriter, r *http.Request) { + token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + delete(f.sessions, token) + http.SetCookie(w, &http.Cookie{Name: "auth_session", Value: "", MaxAge: -1}) + writeJSON(w, http.StatusOK, map[string]any{}) + }) + f.server = httptest.NewServer(mux) + return f +} + +func (f *fakeAuthGuard) close() { f.server.Close() } + +func newRequest(method, target string, body string) *http.Request { + var r *http.Request + if body != "" { + r = httptest.NewRequest(method, target, strings.NewReader(body)) + } else { + r = httptest.NewRequest(method, target, nil) + } + return r +} + +func TestCurrentUserDisabledModeReturnsLocalSuperadmin(t *testing.T) { + svc := New(nil, "mediacollection_session", false, "") + user, err := svc.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil)) + if err != nil { + t.Fatalf("CurrentUser() error = %v", err) + } + if user == nil || user.Role != "superadmin" || !user.CanManageUsers { + t.Fatalf("CurrentUser() = %+v, want local superadmin placeholder", user) + } +} + +func TestSignupLoginLogoutProxyToAuthGuard(t *testing.T) { + pool := testPool(t) + guard := newFakeAuthGuard() + defer guard.close() + svc := New(pool, "mediacollection_session", false, guard.server.URL) + ctx := context.Background() + + // Signup + req := newRequest(http.MethodPost, "/auth/signup", `{"email":"a@example.com","username":"admin","password":"correct horse battery staple"}`) + rec := httptest.NewRecorder() + svc.Signup(rec, req) + if rec.Code != http.StatusCreated { + t.Fatalf("Signup() status = %d, body = %s", rec.Code, rec.Body.String()) + } + cookie := firstSetCookie(t, rec) + if cookie == "" { + t.Fatal("Signup() did not forward AuthGuard's Set-Cookie") + } + + claimed, err := svc.isSetupClaimed(ctx) + if err != nil || !claimed { + t.Fatalf("isSetupClaimed() = %v, %v, want true, nil", claimed, err) + } + + // A second signup attempt must be rejected (setup already completed). + req2 := newRequest(http.MethodPost, "/auth/signup", `{"email":"b@example.com","username":"other","password":"correct horse battery staple"}`) + rec2 := httptest.NewRecorder() + svc.Signup(rec2, req2) + if rec2.Code != http.StatusConflict { + t.Fatalf("second Signup() status = %d, want 409", rec2.Code) + } + + // CurrentUser resolves via the forwarded cookie. + authedReq := httptest.NewRequest(http.MethodGet, "/auth/me", nil) + authedReq.Header.Set("Cookie", "auth_session="+cookie) + user, err := svc.CurrentUser(authedReq) + if err != nil { + t.Fatalf("CurrentUser() error = %v", err) + } + if user == nil || user.Username != "admin" || user.Role != "superadmin" { + t.Fatalf("CurrentUser() = %+v, want the AuthGuard-registered admin", user) + } + + // Login with wrong password is rejected. + badLogin := newRequest(http.MethodPost, "/auth/login", `{"identifier":"admin","password":"wrong"}`) + badRec := httptest.NewRecorder() + svc.Login(badRec, badLogin) + if badRec.Code != http.StatusUnauthorized { + t.Fatalf("Login() with wrong password status = %d, want 401", badRec.Code) + } + + // Logout clears the session. + logoutReq := httptest.NewRequest(http.MethodPost, "/auth/logout", nil) + logoutReq.Header.Set("Cookie", "auth_session="+cookie) + logoutRec := httptest.NewRecorder() + svc.Logout(logoutRec, logoutReq) + if logoutRec.Code != http.StatusOK { + t.Fatalf("Logout() status = %d", logoutRec.Code) + } +} + +func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing.T) { + pool := testPool(t) + guard := newFakeAuthGuard() + defer guard.close() + guard.hasAccount = true // simulate a different project (or AuthGuard's own web UI) having already created one + guard.username, guard.email, guard.role, guard.password = "existing", "existing@example.com", "superadmin", "hunter2!!" + + svc := New(pool, "mediacollection_session", false, guard.server.URL) + req := newRequest(http.MethodPost, "/auth/signup", `{"email":"new@example.com","username":"new","password":"correct horse battery staple"}`) + rec := httptest.NewRecorder() + svc.Signup(rec, req) + if rec.Code != http.StatusConflict { + t.Fatalf("Signup() status = %d, body = %s, want 409 (AuthGuard already has an account)", rec.Code, rec.Body.String()) + } + // The local claim must have been released again so a later legitimate flow isn't locked out. + claimed, err := svc.isSetupClaimed(context.Background()) + if err != nil || claimed { + t.Fatalf("isSetupClaimed() = %v, %v, want false after a rejected signup", claimed, err) + } +} + +func TestLoginRequiredToggleIsIndependentOfAuthGuard(t *testing.T) { + pool := testPool(t) + svc := New(pool, "mediacollection_session", false, "") + + required, err := svc.LoginRequired(context.Background()) + if err != nil || !required { + t.Fatalf("LoginRequired() default = %v, %v, want true, nil", required, err) + } + + rec := httptest.NewRecorder() + svc.UpdateAccessSettings(rec, newRequest(http.MethodPut, "/api/auth/access", `{"loginRequired":false}`)) + if rec.Code != http.StatusOK { + t.Fatalf("UpdateAccessSettings() status = %d", rec.Code) + } + required, err = svc.LoginRequired(context.Background()) + if err != nil || required { + t.Fatalf("LoginRequired() after disabling = %v, %v, want false, nil", required, err) + } +} + +func firstSetCookie(t *testing.T, rec *httptest.ResponseRecorder) string { + t.Helper() + for _, raw := range rec.Result().Cookies() { + if raw.Name == "auth_session" && raw.Value != "" { + return raw.Value + } + } + return "" +} diff --git a/media-backend/internal/config/config.go b/media-backend/internal/config/config.go index 0b98295..2f7a183 100644 --- a/media-backend/internal/config/config.go +++ b/media-backend/internal/config/config.go @@ -39,6 +39,11 @@ type Config struct { PublicURL string SessionCookie string SecureCookies bool + // AuthGuardURL is AuthGuard's base URL (see Web/Central/AuthGuard); + // empty means auth-disabled mode (see internal/auth's package doc + // comment). Read raw via os.Getenv rather than envOr since "" is a + // meaningful, distinct value here (not a fallback-worthy blank). + AuthGuardURL string InternalServiceSecret string FFmpeg string FFprobe string @@ -94,6 +99,7 @@ func Load() (*Config, error) { PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"), SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"), SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""), + AuthGuardURL: strings.TrimSpace(os.Getenv("AUTHGUARD_URL")), InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")), FFmpeg: envOr("FFMPEG_PATH", "ffmpeg"), FFprobe: envOr("FFPROBE_PATH", "ffprobe"), diff --git a/media-backend/internal/server/server.go b/media-backend/internal/server/server.go index f3f08db..96d127f 100644 --- a/media-backend/internal/server/server.go +++ b/media-backend/internal/server/server.go @@ -138,7 +138,7 @@ func New(cfg *config.Config, db *pgxpool.Pool) *Server { return &Server{ cfg: cfg, db: db, - auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies), + auth: auth.New(db, cfg.SessionCookie, cfg.SecureCookies, cfg.AuthGuardURL), startedAt: time.Now(), media: make(map[string]MediaRecord), jobs: make(map[string]*WorkflowJob), @@ -167,8 +167,6 @@ func (s *Server) Handler() http.Handler { r.Post("/signup", s.auth.Signup) r.Post("/login", s.auth.Login) r.Post("/logout", s.auth.Logout) - r.Post("/reset/request", s.auth.RequestAdminReset) - r.Post("/reset/confirm", s.auth.ConfirmAdminReset) r.Get("/me", s.auth.Me) r.With(s.auth.Require).Put("/me", s.auth.UpdateMe) r.Get("/status", s.auth.Status) diff --git a/media-webui/src/lib/components/AppShell.svelte b/media-webui/src/lib/components/AppShell.svelte index c20b97a..2929a7e 100644 --- a/media-webui/src/lib/components/AppShell.svelte +++ b/media-webui/src/lib/components/AppShell.svelte @@ -139,13 +139,6 @@ auth = { ...auth, user: data.user, setupRequired: false, loading: false, error: null } } - const requestReset = () => post('/auth/reset/request') - - async function confirmReset(code: string) { - await post('/auth/reset/confirm', { code }) - window.location.reload() - } - async function logout() { try { await post('/auth/logout') @@ -199,8 +192,6 @@ error={auth.error || ''} onLogin={login} onSetup={setup} - onRequestReset={requestReset} - onConfirmReset={confirmReset} /> {:else}
diff --git a/media-webui/src/lib/components/AuthPage.svelte b/media-webui/src/lib/components/AuthPage.svelte index a7edff5..17b0189 100644 --- a/media-webui/src/lib/components/AuthPage.svelte +++ b/media-webui/src/lib/components/AuthPage.svelte @@ -1,43 +1,22 @@ - +