Files
CollabTable/shared/backend/auth/proxy.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

1680 lines
65 KiB
Go

// This file holds the shared media-backend family's /auth/... and /api/auth/...
// handlers, proxied to AuthGuard. Promoted from each service's own
// internal/auth into this shared library so all 7 independent media-family
// backends (CarrierNode, ModerationHub, ProjectConfigurator, KioskDisplay,
// MediaViewer, ContentScanner, CraftStudio) use one copy instead of
// duplicating it. Originally its own "mediaauth" package; merged into this
// package (2026-09-13) since it is no longer media-specific - see "Unified
// auth proxy" below - and "auth" is the more accurate name for what it now
// is. ProxyUser/ProxyStore/Service/New/NewWithStore below are this file's
// exports; everything else in this package (Store, User, Role, TOTP,
// password, token, reset) is the lower-level local-account persistence
// layer these proxy against AuthGuard instead of using directly.
//
// Unified auth proxy
// ==================
// This file used to be its own package, specific to the 7 media-family
// backends (each built via New, wired directly to their own shared Postgres
// `settings` table). It is now the ONE shared auth-proxy engine for every
// project in this workspace that centralizes identity through AuthGuard -
// GameStream, Bitmagnet, and OmniLogger, which each used to independently
// reimplement this same session/login/TOTP/admin-user proxy against their
// own storage, now build a Service via NewWithStore against a small
// ProxyStore adapter over whatever local table they already used for their
// "login required" toggle and one-time setup-claim flag (see the ProxyStore
// interface below), instead of duplicating this file's logic. New (the
// original media-family constructor) is unchanged and is really just
// NewWithStore plus pgSettingsStore, the default ProxyStore implementation
// backed by the shared `settings` table.
//
// ProjectKey (New/NewWithStore's last parameter) identifies the calling
// project to AuthGuard on every request (authclient.WithProjectKey), so an
// administrator can restrict which projects a given AuthGuard account may
// authenticate against; see AuthGuard's project-scope admin UI. Leave it ""
// to opt out (every account is then unrestricted for this project, the
// pre-existing behavior).
//
// 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/Core/AuthGuard),
// a centralized identity service other projects in this workspace share,
// via the `authclient` package (Web/Core/shared/backend/authclient). This
// service's own /auth/... and /api/auth/... URL paths and JSON response
// shapes are UNCHANGED - the frontend (webui) was not touched - only
// what backs them changed. This mirrors the migration
// Original/GameStream/backend/cmd/gamestreamd/auth.go and
// Fork/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 "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 ProxyUser type carried
// are dropped entirely: AuthGuard has no such concept, and grepping the
// frontend (webui) confirms neither field was ever actually read
// or set by any UI - they were dead weight even before this migration.
//
// Auth-disabled mode (the Disabled() option)
// -------------------------------------------
// Passing Disabled() to New/NewWithStore turns authentication off entirely
// for a Service: Service.authGuard is nil (Service.enabled() reports false),
// CurrentUser always resolves to adminProfile (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 at all; it is
// not an error condition, and there is no degraded/partial "local auth"
// fallback state.
//
// Without Disabled(), a Service is always "enabled" - including when
// authGuardURL is empty at construction. That used to also mean disabled,
// but made AUTHGUARD_URL a de-facto requirement: a Service built with no URL
// could never start authenticating later, since a live retarget
// (SetAuthGuardBaseURL, wired as ProjectConfigurator's coreconfig push) had
// no client to retarget. Now an empty authGuardURL just means "pending": the
// Service still gates every request, but its calls to AuthGuard fail (with
// errAuthGuardUnavailable, a 401) until a URL arrives - normally within
// ProjectConfigurator's periodic re-push window (coreconfig's doc comment),
// converging on its own with no restart needed, the same way a live
// AuthGuard URL *change* already did before this pending mode existed. A
// project that wants no AuthGuard integration at all (the old meaning of an
// unset AUTHGUARD_URL) must now say so explicitly via Disabled().
//
// 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
// in Disabled() mode (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. In
// pending mode (enabled, but no URL yet) these same calls are attempted for
// real and fail closed with errAuthGuardUnavailable instead, since AuthGuard
// integration genuinely is turned on here - it just isn't reachable yet.
//
// 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"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net"
"net/http"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
authclient "repos.gfranz.ch/Gabriel20xx/shared/backend/authclient"
"repos.gfranz.ch/Gabriel20xx/shared/backend/authproxy"
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
)
// ProxyUser 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. Distinct from User (this package's own
// local-account DB row): ProxyUser is the identity resolved through
// AuthGuard for a proxying project, User is a row this package itself owns
// in a project's local database (AuthGuard's own database, in AuthGuard's
// case).
type ProxyUser struct {
ID int64 `json:"id"`
Email string `json:"email"`
Username string `json:"username,omitempty"`
Role string `json:"role,omitempty"`
CanManageUsers bool `json:"canManageUsers"`
MFAEnabled bool `json:"mfaEnabled"`
}
type proxyContextKey struct{}
var proxyUserContextKey proxyContextKey
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 this Service was
// constructed with Disabled(); see the top-of-file doc comment's
// "Auth-disabled mode" section.
errFeatureRequiresAuthGuard = errors.New("This feature requires AuthGuard to be enabled.")
// 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.")
errSecretNotUsable = fmt.Errorf("SECRET environment variable is unset, shorter than %d characters, or an example placeholder.", coreconfig.MinInternalSecretLength)
errTooManyAttempts = errors.New("Too many attempts. Try again later.")
errSetupRequiresLogin = errors.New("Account setup is only available while login is required.")
errNoLoginRequiredStore = errors.New("the login-required setting has no store to save to")
errCrossSiteRequest = errors.New("cross-site request refused")
errJSONContentType = errors.New("request body must be application/json")
errSelfServiceProfile = errors.New("Self-service profile editing is only available to administrator accounts; ask an administrator to update this account.")
)
const (
loginRequiredSettingKey = "auth_required"
setupClaimedSettingKey = "setup_claimed"
proxyMinPasswordLength = 8
// maxBcryptPasswordBytes is the longest password bcrypt hashes in full.
maxBcryptPasswordBytes = 72
proxyMaxUsernameLength = 64
proxyMaxEmailLength = 254
)
// adminProfile is the fixed placeholder identity used when authentication is
// disabled, either explicitly through Disabled() or through a project's
// ProjectConfigurator "Require Login" toggle. Role is superadmin so all
// application routes see the same administrator identity even though no
// credentials were supplied.
var adminProfile = ProxyUser{ID: 0, Username: "Admin", Email: "", Role: string(RoleSuperAdmin), CanManageUsers: true}
// ProxyStore is the small piece of local, project-owned persistence a
// Service needs beyond AuthGuard itself: the independent "require login"
// toggle (RequireIfLoginRequired/RequireAdminIfLoginRequired predate the
// AuthGuard migration - see the package doc comment's second paragraph) and
// the one-time "has this deployment's setup screen been completed" claim
// flag (see the "Setup flow" section below). pgSettingsStore is the
// implementation New builds automatically over the media family's shared
// `settings` table; NewWithStore accepts any other implementation, letting a
// project with its own storage (GameStream's/Bitmagnet's/OmniLogger's own
// tables) reuse this package without adopting that generic table.
type ProxyStore interface {
LoginRequired(ctx context.Context) (bool, error)
SetLoginRequired(ctx context.Context, required bool) error
IsSetupClaimed(ctx context.Context) (bool, error)
TryClaimSetup(ctx context.Context) (bool, error)
UnclaimSetup(ctx context.Context) error
}
type Service struct {
// db backs only the "moderatable platform users" section at the bottom
// of this file (CreateUser/ListUsers/UpdateUser/SetPassword/DeleteUser),
// a media-family-specific concept unrelated to AuthGuard identity - see
// that section's own doc comment. nil for a Service built via
// NewWithStore; those methods are simply never called by a project with
// no such local platform-user table.
db *pgxpool.Pool
store ProxyStore
cookieName string
secureCookies bool
// authGuard is nil only when this Service was built with Disabled(); see
// the top-of-file doc comment's "Auth-disabled mode" section. A "pending"
// Service (auth turned on, but no URL known yet) still has a non-nil
// client, just one whose calls fail until SetAuthGuardBaseURL supplies a
// real base URL.
authGuard *authclient.Client
configurationError error
// reauthenticateEmailChanges is opt-in because older consumers historically
// allowed email-only edits without the current password. Password changes
// always require current credentials in UpdateMe.
reauthenticateEmailChanges bool
loginCacheMu sync.Mutex
loginCacheValue bool
loginCacheSet bool
loginCacheExpires time.Time
// Attempt counters for the credential endpoints; see ratelimit.go.
loginAccountAttempts *attemptLimiter
loginClientAttempts *attemptLimiter
totpAttempts *attemptLimiter
// trustedProxies are the peers whose X-Forwarded-For header is honoured;
// see clientAddress in clientip.go.
trustedProxies []*net.IPNet
}
// ServiceOption configures optional New/NewWithStore construction behavior.
// Variadic and trailing, so every existing call site keeps compiling
// unchanged; only a project that wants Disabled() needs to pass one.
type ServiceOption func(*serviceOptions)
type serviceOptions struct {
disabled bool
requireSecret bool
reauthenticateEmailChanges bool
trustedProxies []*net.IPNet
}
// Disabled explicitly builds a Service in auth-disabled mode (see the
// package doc comment's "Auth-disabled mode" section): nothing gated, a
// fixed superadmin placeholder identity for every request, regardless of
// authGuardURL. This is the explicit opt-out for a genuine standalone/
// local-dev deployment that doesn't want centralized identity at all -
// without it, an empty authGuardURL now means "pending" (auth integration
// is on, but no URL is known yet), not disabled.
func Disabled() ServiceOption {
return func(o *serviceOptions) { o.disabled = true }
}
// RequireSecret keeps the service available when SECRET is omitted, but makes
// the public auth status/me endpoints report the configuration error so the
// frontend can show it in the auth screen. Internal-service routes remain
// fail-closed until a secret is configured.
func RequireSecret() ServiceOption {
return func(o *serviceOptions) { o.requireSecret = true }
}
// ReauthenticateEmailChanges requires current-password proof, and TOTP when
// enabled, for email changes through UpdateMe. Password changes already
// require the same proof. This is opt-in to preserve existing consumers that
// have not adopted the matching profile-dialog flow.
func ReauthenticateEmailChanges() ServiceOption {
return func(o *serviceOptions) { o.reauthenticateEmailChanges = true }
}
// WithTrustedProxies sets the reverse proxies whose X-Forwarded-For header is
// honoured when a login's client address is taken. Build the list from the
// TRUSTED_PROXIES setting with ParseTrustedProxies. Without it, the TCP peer
// is always the client address.
func WithTrustedProxies(networks []*net.IPNet) ServiceOption {
return func(o *serviceOptions) { o.trustedProxies = networks }
}
// New constructs a Service backed by the media family's shared `settings`
// table (pgSettingsStore) for the login-required toggle and setup-claim
// flag, and by db directly for the unrelated "moderatable platform users"
// section. 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 this project's currently
// known AuthGuard base URL - typically empty at construction now that
// ProjectConfigurator pushes it live (coreconfig.Store.OnUpdate ->
// SetAuthGuardBaseURL); see the "Auth-disabled mode" section for what an
// empty authGuardURL means without Disabled(). projectKey identifies this
// project to AuthGuard for per-user project-access restriction; see the
// "Unified auth proxy" section above.
func New(db *pgxpool.Pool, cookieName string, secureCookies bool, authGuardURL, projectKey string, opts ...ServiceOption) *Service {
service := NewWithStore(pgSettingsStore{db: db}, cookieName, secureCookies, authGuardURL, projectKey, opts...)
service.db = db
return service
}
// NewWithStore constructs a Service against any ProxyStore implementation,
// for a project whose login-required toggle and setup-claim flag live in
// its own storage rather than the media family's shared `settings` table.
// Its resulting Service has no db (the "moderatable platform users" section
// is unavailable - a project adopting this package fresh has no such
// feature to preserve).
func NewWithStore(store ProxyStore, cookieName string, secureCookies bool, authGuardURL, projectKey string, opts ...ServiceOption) *Service {
var options serviceOptions
for _, opt := range opts {
opt(&options)
}
var client *authclient.Client
if !options.disabled {
// authclient.New/SetBaseURL/Validate/call all tolerate an empty base
// URL (every call fails cleanly with "client has no base URL" rather
// than panicking or building a malformed request), which is exactly
// what makes "pending" mode safe: a Service constructed with no URL
// yet still has a real, non-nil client ready to be retargeted the
// moment one arrives.
client = authclient.New(strings.TrimSpace(authGuardURL), authclient.WithProjectKey(projectKey))
}
var configurationError error
if options.requireSecret && !options.disabled && !coreconfig.InternalSecretUsable(strings.TrimSpace(os.Getenv("SECRET"))) {
configurationError = errSecretNotUsable
}
return &Service{
store: store,
cookieName: cookieName,
secureCookies: secureCookies,
authGuard: client,
configurationError: configurationError,
reauthenticateEmailChanges: options.reauthenticateEmailChanges,
loginAccountAttempts: newAttemptLimiter(attemptWindow, loginAccountLimit),
loginClientAttempts: newAttemptLimiter(attemptWindow, loginClientLimit),
totpAttempts: newAttemptLimiter(attemptWindow, totpAttemptLimit),
trustedProxies: options.trustedProxies,
}
}
// pgSettingsStore is the default ProxyStore New builds over the media
// family's shared `settings` key/value table (see mediacore.SettingValue/
// SaveSetting) - unchanged behavior from before this package accepted a
// pluggable ProxyStore.
type pgSettingsStore struct {
db *pgxpool.Pool
}
func (s pgSettingsStore) LoginRequired(ctx context.Context) (bool, error) {
var value string
err := s.db.QueryRow(ctx, `SELECT COALESCE(value, '') FROM settings WHERE key = $1`, loginRequiredSettingKey).Scan(&value)
if errors.Is(err, pgx.ErrNoRows) {
return true, nil
}
if err != nil {
return true, err
}
switch strings.ToLower(strings.TrimSpace(value)) {
case "false", "0", "no", "off":
return false, nil
default:
return true, nil
}
}
func (s pgSettingsStore) SetLoginRequired(ctx context.Context, required bool) error {
_, err := s.db.Exec(ctx, `
INSERT INTO settings (key, value, updated_at) VALUES ($1, $2, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`, loginRequiredSettingKey, strconv.FormatBool(required))
return err
}
func (s pgSettingsStore) 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 pgSettingsStore) 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 pgSettingsStore) UnclaimSetup(ctx context.Context) error {
_, err := s.db.Exec(ctx, `DELETE FROM settings WHERE key = $1`, setupClaimedSettingKey)
return err
}
// enabled reports whether this Service was NOT built with Disabled() - true
// for both a fully-configured Service and a "pending" one still waiting for
// its first AuthGuard URL. See the top-of-file doc comment's "Auth-disabled
// mode" section.
func (s *Service) enabled() bool {
return s.authGuard != nil
}
// SetAuthGuardBaseURL retargets the AuthGuard base URL this Service's
// internal authclient.Client calls, taking effect on its very next call -
// wire it as a coreconfig.Store's OnUpdate callback (see
// ProjectConfigurator/README.md's "Pushing core service info to other
// projects" section) so a live authguard_url push applies without a
// restart, whether it's the very first URL a "pending" Service ever
// receives or a later change to one already configured, the same as a
// project holding its own *authclient.Client directly. A no-op only if this
// Service was constructed with Disabled() (see the "Auth-disabled mode"
// section): there is no client to retarget, and this package has no path to
// start authenticating requests it was explicitly told to always let
// through.
func (s *Service) SetAuthGuardBaseURL(baseURL string) {
if s.authGuard != nil {
s.authGuard.SetBaseURL(baseURL)
}
}
func UserFromContext(ctx context.Context) *ProxyUser {
value, _ := ctx.Value(proxyUserContextKey).(*ProxyUser)
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 {
return authproxy.SessionToken(r)
}
// clearSessionCookies clears both the AuthGuard cookie (as a fallback -
// normally AuthGuard's own Set-Cookie, forwarded via authclient.ForwardCookies,
// already does this) and the pre-migration cookie name.
func (s *Service) clearSessionCookies(w http.ResponseWriter) {
authproxy.ClearSessionCookies(w, s.cookieName, s.secureCookies)
}
// toUser translates AuthGuard's PublicUser into this service's own
// ProxyUser response shape.
func toUser(profile authclient.PublicUser) *ProxyUser {
return &ProxyUser{
ID: profile.ID, Email: profile.Email, Username: profile.Username,
Role: profile.Role, CanManageUsers: 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) (*ProxyUser, error) {
if s.configurationError != nil {
return nil, s.configurationError
}
if !s.enabled() {
user := adminProfile
return &user, nil
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
return nil, err
}
if !loginRequired {
user := adminProfile
return &user, nil
}
profile, err := s.currentProfile(r.Context(), s.sessionToken(r))
if err != nil {
return nil, err
}
if profile == nil {
return nil, 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 {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
if user != nil {
r = r.WithContext(context.WithValue(r.Context(), proxyUserContextKey, user))
}
next.ServeHTTP(w, r)
})
}
func (s *Service) Require(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if UserFromContext(r.Context()) == nil {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
next.ServeHTTP(w, r)
}))
}
// RequireIfLoginRequired protects actions when the application has login
// enabled. When login is disabled, CurrentUser supplies the synthetic Admin
// superadmin identity, so handlers can use the same authenticated code path
// without requiring credentials. 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 {
next.ServeHTTP(w, r)
return
}
// CurrentUser returns no user only when login is required (it returns the
// synthetic admin for every other case), so no second settings read is needed.
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
}))
}
func (s *Service) RequireAdmin(next http.Handler) http.Handler {
return s.Require(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if !IsAdmin(user) {
writeProxyError(w, http.StatusForbidden, ErrForbidden.Error())
return
}
next.ServeHTTP(w, r)
}))
}
// RequireAdminIfLoginRequired keeps administrative actions protected for
// authenticated users. When login is disabled, CurrentUser supplies the
// synthetic Admin superadmin identity so configuration endpoints remain
// available without credentials.
func (s *Service) RequireAdminIfLoginRequired(next http.Handler) http.Handler {
return s.Optional(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := UserFromContext(r.Context())
if user == nil {
// As in RequireIfLoginRequired, a nil user means login is required.
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !IsAdmin(user) {
writeProxyError(w, http.StatusForbidden, ErrForbidden.Error())
return
}
next.ServeHTTP(w, r)
}))
}
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 !CanManageUsers(user.Role) {
writeProxyError(w, http.StatusForbidden, ErrForbidden.Error())
return
}
next.ServeHTTP(w, r)
}))
}
func IsAdmin(user *ProxyUser) bool {
if user == nil {
return false
}
switch strings.ToLower(strings.TrimSpace(user.Role)) {
case "admin", "superadmin", "moderator":
return true
default:
return false
}
}
func (s *Service) Me(w http.ResponseWriter, r *http.Request) {
if s.configurationError != nil {
writeProxyError(w, http.StatusInternalServerError, s.configurationError.Error())
return
}
user, err := s.CurrentUser(r)
if err != nil {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
writeProxyJSON(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) {
if !s.enabled() {
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
current := UserFromContext(r.Context())
if current == nil {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !CanManageUsers(current.Role) {
writeProxyError(w, http.StatusForbidden, errSelfServiceProfile.Error())
return
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
CurrentPassword string `json:"currentPassword"`
TOTPToken string `json:"totpToken"`
}
if err := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
return
}
email, err := normalizeProxyEmail(input.Email)
if err != nil {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
username, err := normalizeProxyUsername(input.Username)
if err != nil {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
managedInput := authclient.ManagedUserInput{Username: username, Email: email}
if input.Password != "" {
if err := validateProxyPassword(input.Password); err != nil {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
}
if input.Password != "" || (s.reauthenticateEmailChanges && email != current.Email) {
if input.CurrentPassword == "" {
writeProxyError(w, http.StatusBadRequest, "currentPassword is required to change email or password")
return
}
if current.MFAEnabled && strings.TrimSpace(input.TOTPToken) == "" {
writeProxyError(w, http.StatusBadRequest, "totpToken is required to change email or password")
return
}
reauthenticated, err := s.authGuard.Login(r.Context(), current.Username, input.CurrentPassword, input.TOTPToken)
if err != nil {
writeAuthGuardError(w, err, "current credentials could not be verified")
return
}
if token := temporarySessionToken(reauthenticated); token != "" {
defer func() {
_, _ = s.authGuard.Logout(context.WithoutCancel(r.Context()), token)
}()
}
if input.Password != "" {
managedInput.Password = input.Password
}
}
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
}
updated, err := s.CurrentUser(r)
if err != nil || updated == nil {
writeProxyError(w, http.StatusInternalServerError, "profile could not be loaded")
return
}
writeProxyJSON(w, http.StatusOK, map[string]any{"user": updated})
}
func temporarySessionToken(session *authclient.SessionResult) string {
if session == nil {
return ""
}
for _, cookie := range session.Cookies {
if cookie != nil && cookie.Name == authclient.DefaultCookieName {
return cookie.Value
}
}
return ""
}
// 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) {
if s.configurationError != nil {
writeProxyError(w, http.StatusInternalServerError, s.configurationError.Error())
return
}
if !s.enabled() {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return
}
claimed, err := s.isSetupClaimed(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if claimed {
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": false})
return
}
setupRequired, err := s.authGuard.SetupStatus(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
writeProxyJSON(w, http.StatusOK, map[string]bool{"adminNeeded": setupRequired})
}
// LoginRequired caches the store's value briefly to avoid a database read for
// every authenticated route. Updates through this Service clear the cache
// immediately; changes made by another replica become visible within two seconds.
func (s *Service) LoginRequired(ctx context.Context) (bool, error) {
if s.store == nil {
return true, nil
}
now := time.Now()
s.loginCacheMu.Lock()
if s.loginCacheSet && now.Before(s.loginCacheExpires) {
value := s.loginCacheValue
s.loginCacheMu.Unlock()
return value, nil
}
s.loginCacheMu.Unlock()
value, err := s.store.LoginRequired(ctx)
if err != nil {
return false, err
}
s.loginCacheMu.Lock()
if s.loginCacheSet && time.Now().Before(s.loginCacheExpires) {
cached := s.loginCacheValue
s.loginCacheMu.Unlock()
return cached, nil
}
s.loginCacheValue = value
s.loginCacheSet = true
s.loginCacheExpires = time.Now().Add(2 * time.Second)
s.loginCacheMu.Unlock()
return value, nil
}
func (s *Service) AccessSettings(w http.ResponseWriter, r *http.Request) {
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "access settings unavailable")
return
}
writeProxyJSON(w, http.StatusOK, map[string]bool{"loginRequired": loginRequired})
}
func (s *Service) UpdateAccessSettings(w http.ResponseWriter, r *http.Request) {
var input struct {
LoginRequired *bool `json:"loginRequired"`
}
if err := decodeProxyJSON(r, &input); err != nil || input.LoginRequired == nil {
writeProxyError(w, http.StatusBadRequest, "loginRequired must be a boolean")
return
}
if err := s.SetLoginRequired(r.Context(), *input.LoginRequired); err != nil {
writeProxyError(w, http.StatusInternalServerError, "access setting could not be saved")
return
}
writeProxyJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired})
}
// SetLoginRequired writes the auth_required flag directly, the same one UpdateAccessSettings
// exposes to a manager-authenticated session - callers reach this from an X-Internal-Auth-gated
// route instead (see each service's own setLoginRequiredInternal), letting ProjectConfigurator's
// central "Require Login" toggle (ConfigWorkspace.svelte's loginControls) apply here without an
// admin session of its own.
func (s *Service) SetLoginRequired(ctx context.Context, required bool) error {
if s.store == nil {
return errNoLoginRequiredStore
}
if err := s.store.SetLoginRequired(ctx, required); err != nil {
return err
}
// Drop the cached value rather than setting it, so the next read comes from the store and a
// store that discards writes cannot leave this process with its own login setting.
s.loginCacheMu.Lock()
s.loginCacheSet = false
s.loginCacheMu.Unlock()
return nil
}
// SetLoginRequiredInternal returns the X-Internal-Auth-gated handler used by
// ProjectConfigurator to apply its per-project "Require Login" setting. It
// lives on the shared service so projects outside the core-service family can
// expose the same propagation endpoint without duplicating its JSON handling.
func (s *Service) SetLoginRequiredInternal(secret string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !coreconfig.InternalSecretMatches(r.Header.Get("X-Internal-Auth"), secret) {
writeProxyError(w, http.StatusUnauthorized, "internal service authentication required")
return
}
var input struct {
LoginRequired *bool `json:"loginRequired"`
}
if err := decodeProxyJSON(r, &input); err != nil || input.LoginRequired == nil {
writeProxyError(w, http.StatusBadRequest, "loginRequired must be a boolean")
return
}
if err := s.SetLoginRequired(r.Context(), *input.LoginRequired); err != nil {
writeProxyError(w, http.StatusInternalServerError, "access setting could not be saved")
return
}
writeProxyJSON(w, http.StatusOK, map[string]bool{"loginRequired": *input.LoginRequired})
})
}
func (s *Service) Status(w http.ResponseWriter, r *http.Request) {
if s.configurationError != nil {
writeProxyError(w, http.StatusInternalServerError, s.configurationError.Error())
return
}
if !s.enabled() {
user := adminProfile
writeProxyJSON(w, http.StatusOK, map[string]any{"setupRequired": false, "authenticated": true, "authRequired": false, "user": &user})
return
}
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
user := adminProfile
writeProxyJSON(w, http.StatusOK, map[string]any{
"setupRequired": false, "authenticated": true, "authRequired": false, "user": &user,
})
return
}
claimed, err := s.isSetupClaimed(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
setupRequired := false
if !claimed {
setupRequired, err = s.authGuard.SetupStatus(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
}
user, err := s.CurrentUser(r)
if err != nil {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
writeProxyJSON(w, http.StatusOK, map[string]any{
"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(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.
writeProxyJSON(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))
}
writeProxyJSON(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() {
writeProxyError(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 := decodeProxyJSON(r, &input); err != nil {
writeProxyError(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
}
writeProxyJSON(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(idURLParam(r), 10, 64)
if err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid user id")
return
}
if !s.enabled() {
writeProxyError(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 := decodeProxyJSON(r, &input); err != nil {
writeProxyError(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 {
writeProxyJSON(w, http.StatusOK, managedUserPayload(user))
return
}
}
writeProxyError(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) {
if refuseCrossSite(w, r) {
return
}
id, err := strconv.ParseInt(idURLParam(r), 10, 64)
if err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid user id")
return
}
if !s.enabled() {
writeProxyError(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
}
writeProxyJSON(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 := adminProfile
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": &user})
return
}
// First-run setup only applies while login is required. With login off, every
// caller already gets the local admin identity, and a fresh AuthGuard would make
// an anonymous signup its superadmin.
loginRequired, err := s.LoginRequired(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "authentication status unavailable")
return
}
if !loginRequired {
writeProxyError(w, http.StatusConflict, errSetupRequiresLogin.Error())
return
}
var input struct {
Email string `json:"email"`
Username string `json:"username"`
Password string `json:"password"`
}
if err := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
return
}
email, err := normalizeProxyEmail(input.Email)
if err != nil {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
username := strings.TrimSpace(input.Username)
if username == "" {
writeProxyError(w, http.StatusBadRequest, "a username is required")
return
}
if _, err := normalizeProxyUsername(username); err != nil {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
if err := validateProxyPassword(input.Password); err != nil {
writeProxyError(w, http.StatusBadRequest, err.Error())
return
}
claimed, err := s.tryClaimSetup(r.Context())
if err != nil {
writeProxyError(w, http.StatusInternalServerError, "internal error")
return
}
if !claimed {
writeProxyError(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 {
writeProxyError(w, http.StatusInternalServerError, "internal error")
return
}
if err != nil {
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
writeProxyError(w, http.StatusConflict, "Setup has already been completed.")
return
}
result, err := s.authGuard.Register(s.withClientIP(r), 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 {
writeProxyError(w, http.StatusInternalServerError, "internal error")
return
}
writeAuthGuardError(w, err, "could not create account")
return
}
authclient.ForwardCookies(w, result.Cookies)
writeProxyJSON(w, http.StatusCreated, map[string]any{"user": toUser(result.User)})
}
func (s *Service) Login(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
user := adminProfile
writeProxyJSON(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 := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
return
}
identifier := strings.TrimSpace(input.Identifier)
if identifier == "" {
identifier = strings.TrimSpace(input.Email)
}
if identifier == "" {
writeProxyError(w, http.StatusUnauthorized, ErrInvalidLogin.Error())
return
}
now := time.Now()
if !s.loginAccountAttempts.allow(strings.ToLower(identifier), now) || !s.loginClientAttempts.allow(s.clientAddress(r), now) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
result, err := s.authGuard.Login(s.withClientIP(r), identifier, input.Password, input.TOTPToken)
if err != nil {
var apiErr *authclient.APIError
if errors.As(err, &apiErr) {
if apiErr.TOTPRequired {
writeProxyJSON(w, http.StatusUnauthorized, map[string]any{"error": "Two-factor authentication code required.", "mfaRequired": true})
return
}
if apiErr.StatusCode == http.StatusUnauthorized {
writeProxyError(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.
writeProxyError(w, http.StatusInternalServerError, errAuthGuardUnavailable.Error())
return
}
authclient.ForwardCookies(w, result.Cookies)
writeProxyJSON(w, http.StatusOK, map[string]any{"user": toUser(result.User)})
}
func (s *Service) Logout(w http.ResponseWriter, r *http.Request) {
if refuseCrossSite(w, r) {
return
}
if !s.enabled() {
writeProxyJSON(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) {
writeProxyError(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)
writeProxyJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Service) TOTPStatus(w http.ResponseWriter, r *http.Request) {
if !s.enabled() {
writeProxyJSON(w, http.StatusOK, map[string]any{"enabled": false, "mfaEnabled": false})
return
}
user := UserFromContext(r.Context())
if user == nil {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
writeProxyJSON(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 refuseCrossSite(w, r) {
return
}
if !s.enabled() {
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
user := UserFromContext(r.Context())
if user == nil {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if user.MFAEnabled {
writeProxyError(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
}
writeProxyJSON(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() {
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
user := UserFromContext(r.Context())
if user == nil {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
}
if err := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
return
}
token := strings.TrimSpace(input.TOTPToken)
if token == "" {
token = strings.TrimSpace(input.Token)
}
if err := s.authGuard.TOTPVerify(s.withClientIP(r), s.sessionToken(r), token); err != nil {
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
writeProxyJSON(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() {
writeProxyError(w, http.StatusConflict, errFeatureRequiresAuthGuard.Error())
return
}
user := UserFromContext(r.Context())
if user == nil {
writeProxyError(w, http.StatusUnauthorized, ErrUnauthorized.Error())
return
}
if !s.totpAttempts.allow(strconv.FormatInt(user.ID, 10), time.Now()) {
writeProxyError(w, http.StatusTooManyRequests, errTooManyAttempts.Error())
return
}
var input struct {
Token string `json:"token"`
TOTPToken string `json:"totpToken"`
}
if err := decodeProxyJSON(r, &input); err != nil {
writeProxyError(w, http.StatusBadRequest, "invalid JSON body")
return
}
token := strings.TrimSpace(input.TOTPToken)
if token == "" {
token = strings.TrimSpace(input.Token)
}
if err := s.authGuard.TOTPDisable(s.withClientIP(r), s.sessionToken(r), token); err != nil {
writeProxyError(w, http.StatusUnauthorized, "Invalid authenticator code.")
return
}
writeProxyJSON(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) {
return s.store.IsSetupClaimed(ctx)
}
func (s *Service) tryClaimSetup(ctx context.Context) (bool, error) {
return s.store.TryClaimSetup(ctx)
}
func (s *Service) unclaimSetup(ctx context.Context) error {
return s.store.UnclaimSetup(ctx)
}
// --- 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. Note these methods are on *Service (the AuthGuard-proxy
// engine), a different receiver type than *Store (this package's own
// local-account persistence) - CreateUser/ListUsers/UpdateUser/DeleteUser
// exist on both with different signatures/purposes; Go's per-type method
// scoping means this is not a naming conflict.
type managedAccount struct {
ID int64
Email string
Username string
Role string
Disabled bool
CreatedAt time.Time
}
func (s *Service) managedAccount(ctx context.Context, id int64) (*managedAccount, error) {
var user managedAccount
err := s.db.QueryRow(ctx, `
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at
FROM users WHERE id = $1
`, id).Scan(&user.ID, &user.Email, &user.Username, &user.Role, &user.Disabled, &user.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
return &user, nil
}
func managedAccountPayload(user *managedAccount) map[string]any {
return map[string]any{
"id": user.ID,
"username": user.Username,
"email": user.Email,
"role": normalizePlatformRole(user.Role),
"createdAt": user.CreatedAt,
}
}
func (s *Service) CreateUser(ctx context.Context, email, username, password, role string) (*ProxyUser, error) {
email, username, password, err := normalizeProxyCredentials(email, username, password)
if err != nil {
return nil, err
}
role = normalizePlatformRole(role)
hash, err := HashPassword(password)
if err != nil {
return nil, err
}
var user ProxyUser
err = s.db.QueryRow(ctx, `
INSERT INTO users (email, username, password_hash, role)
VALUES ($1, $2, $3, $4)
RETURNING id, email, COALESCE(username, ''), COALESCE(role, 'user')
`, email, username, hash, role).Scan(&user.ID, &user.Email, &user.Username, &user.Role)
if err != nil {
return nil, err
}
return &user, nil
}
func (s *Service) ListUsers(ctx context.Context, search string, limit, offset int) ([]map[string]any, int64, error) {
search = strings.TrimSpace(search)
if limit <= 0 || limit > 200 {
limit = 50
}
if offset < 0 {
offset = 0
}
pattern := "%" + search + "%"
rows, err := s.db.Query(ctx, `
SELECT id, email, COALESCE(username, ''), COALESCE(role, 'user'), disabled, created_at, last_login_at
FROM users
WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)
ORDER BY id DESC LIMIT $3 OFFSET $4
`, search, pattern, limit, offset)
if err != nil {
return nil, 0, err
}
defer rows.Close()
users := make([]map[string]any, 0)
for rows.Next() {
var id int64
var email, username, role string
var disabled bool
var created time.Time
var lastLogin *time.Time
if err := rows.Scan(&id, &email, &username, &role, &disabled, &created, &lastLogin); err != nil {
return nil, 0, err
}
users = append(users, map[string]any{"id": id, "email": email, "username": username, "role": role, "disabled": disabled, "createdAt": created, "lastLoginAt": lastLogin})
}
var total int64
err = s.db.QueryRow(ctx, `SELECT COUNT(*) FROM users WHERE ($1 = '' OR email ILIKE $2 OR COALESCE(username, '') ILIKE $2)`, search, pattern).Scan(&total)
return users, total, err
}
func (s *Service) DeleteUser(ctx context.Context, id int64) error {
_, err := s.db.Exec(ctx, `DELETE FROM users WHERE id = $1`, id)
return err
}
func (s *Service) UpdateUser(ctx context.Context, id int64, email, username, role string, disabled *bool) error {
role = strings.ToLower(strings.TrimSpace(role))
if role != "" {
role = normalizePlatformRole(role)
}
_, err := s.db.Exec(ctx, `
UPDATE users SET email = COALESCE(NULLIF($2, ''), email), username = COALESCE(NULLIF($3, ''), username),
role = COALESCE(NULLIF($4, ''), role), disabled = COALESCE($5, disabled) WHERE id = $1
`, id, strings.TrimSpace(email), strings.TrimSpace(username), role, disabled)
return err
}
func (s *Service) SetPassword(ctx context.Context, id int64, password string) error {
if err := validateProxyPassword(password); err != nil {
return err
}
hash, err := HashPassword(password)
if err != nil {
return err
}
_, err = s.db.Exec(ctx, `UPDATE users SET password_hash=$2 WHERE id=$1`, id, hash)
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) {
if statusCode, message, ok := authproxy.APIErrorResponse(err); ok {
writeProxyError(w, statusCode, message)
return
}
writeProxyError(w, http.StatusInternalServerError, fallbackMessage)
}
func normalizeProxyUsername(value string) (string, error) {
value = strings.TrimSpace(value)
if value == "" {
return "", nil
}
if len([]rune(value)) > proxyMaxUsernameLength {
return "", errors.New("username is too long")
}
// An identifier containing "@" could be read as another account's email at login.
if strings.Contains(value, "@") {
return "", errors.New("username cannot contain @")
}
return value, nil
}
func normalizeProxyEmail(value string) (string, error) {
value = strings.ToLower(strings.TrimSpace(value))
if !strings.Contains(value, "@") || len(value) > proxyMaxEmailLength {
return "", errors.New("a valid email is required")
}
return value, nil
}
func validateProxyPassword(password string) error {
if len([]rune(password)) < proxyMinPasswordLength || len([]rune(password)) > 1024 {
return errors.New("Password must be at least 8 characters.")
}
// bcrypt uses only the first 72 bytes, so a longer password would be refused at hashing time.
if len(password) > maxBcryptPasswordBytes {
return errors.New("Password must be at most 72 bytes.")
}
return nil
}
// normalizeProxyCredentials 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 normalizeProxyCredentials(email, username, password string) (string, string, string, error) {
email, err := normalizeProxyEmail(email)
if err != nil {
return "", "", "", err
}
username, err = normalizeProxyUsername(username)
if err != nil {
return "", "", "", err
}
if err := validateProxyPassword(password); err != nil {
return "", "", "", err
}
return email, username, password, nil
}
// normalizePlatformRole normalizes a "moderatable platform user" role (see
// that section's doc comment above) - a different, looser role set
// (moderator included) than the account-login Role type NormalizeRole
// governs elsewhere in this package.
func normalizePlatformRole(role string) string {
switch strings.ToLower(strings.TrimSpace(role)) {
case "admin", "superadmin", "moderator":
return strings.ToLower(strings.TrimSpace(role))
default:
return "user"
}
}
// idURLParam extracts the "{id}" path segment from ManagedUpdateUser's/
// ManagedDeleteUser's route regardless of which router mounted it: chi's
// URLParam for the (7) media-family services that route through chi, or the
// standard library's 1.22+ ServeMux PathValue (what GameStream, OmniLogger,
// and other non-chi consumers of this package use) when chi reports none.
func idURLParam(r *http.Request) string {
if id := chi.URLParam(r, "id"); id != "" {
return id
}
return r.PathValue("id")
}
// decodeProxyJSON reads a JSON request body. It refuses a body that is not sent as
// application/json, which a cross-site HTML form cannot produce, and any request the browser
// marks as cross-site.
// refuseCrossSite answers a state-changing request that carries no JSON body (logout, TOTP
// initiate, user delete) when the browser says it came from another site. Simple cross-site
// forms cannot send a JSON body, so decodeProxyJSON already refuses them; this covers the rest.
func refuseCrossSite(w http.ResponseWriter, r *http.Request) bool {
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
writeProxyError(w, http.StatusForbidden, errCrossSiteRequest.Error())
return true
}
return false
}
func decodeProxyJSON(r *http.Request, target any) error {
defer r.Body.Close()
if r.Header.Get("Sec-Fetch-Site") == "cross-site" {
return errCrossSiteRequest
}
mediaType, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" {
return errJSONContentType
}
decoder := json.NewDecoder(io.LimitReader(r.Body, 128*1024))
return decoder.Decode(target)
}
func writeProxyJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(value)
}
func writeProxyError(w http.ResponseWriter, status int, message string) {
writeProxyJSON(w, status, map[string]string{"error": message, "message": message})
}
func (u ProxyUser) String() string { return strconv.FormatInt(u.ID, 10) }