// Package authclient is how any Go service in this workspace adopts a // centralized AuthServer (see the AuthServer project, a sibling of this // shared/backend module) instead of embedding shared/backend/auth's // Store directly against its own private database. // // A service that switches to AuthServer trades "its own local user table" // for "one HTTP call per request to AuthServer's /api/session/validate", // gaining a single shared identity across every project that does the // same. This package is additive: it does not change how // shared/backend/auth works, and no project in this workspace is wired up // to use it yet — that migration is a deliberate per-project decision, not // something this package does automatically. See AuthServer/README.md's // "Migration notes" section. package authclient import ( "bytes" "context" "encoding/json" "errors" "fmt" "io" "net" "net/http" "strings" "sync" "time" ) // User is the account AuthServer resolved for a validated session. It // mirrors the fields returned by GET /api/session/validate. type User struct { ID int64 `json:"user_id"` Username string `json:"username"` Role string `json:"role"` } // ErrInvalidSession is returned by Validate when AuthServer reports the // token/cookie as not currently valid (expired, unknown, or missing). var ErrInvalidSession = errors.New("authclient: invalid or missing session") // DefaultCookieName is the session cookie AuthServer sets and reads // (AuthServer's own httpapi.SessionCookieName). A service that forwards // AuthServer's Set-Cookie header straight through to its own browser client // (see the "Cookie forwarding" note below) ends up reading this same cookie // name back off incoming requests, so it is exported here rather than left // as an unexported default only Middleware can see. const DefaultCookieName = "auth_session" // Client calls a centralized AuthServer instance over HTTP. type Client struct { // baseURLMu guards baseURL so SetBaseURL can be called concurrently with // Validate/Middleware/the rest of the API surface - see SetBaseURL. baseURLMu sync.RWMutex // baseURL is AuthServer's base URL, e.g. "https://auth.example.com" (no // trailing slash required). Read/written only through getBaseURL/ // SetBaseURL once construction is done. baseURL string // HTTPClient is used for every request; defaults to a client with a // short timeout suitable for a per-request auth check. httpClient *http.Client // CookieName is the cookie this client looks for on incoming requests // when Middleware has no Authorization header to use. Defaults to // "auth_session", matching AuthServer's SessionCookieName. cookieName string // projectKey identifies the calling project to AuthServer (sent as the // ProjectKeyHeader on every request) so per-user project-access // restrictions can be enforced. Empty means "don't identify" - the // caller is treated as unrestricted; see AuthServer's project-scoping // feature and WithProjectKey. projectKey string validationMu sync.Mutex validationCache map[[32]byte]validationCacheEntry } // ProjectKeyHeader is the header Client attaches to every request identifying // which project is calling, so AuthServer can enforce per-user project-access // restriction (see WithProjectKey). AuthServer treats a missing/empty header // the same as "this caller has no project identity": never restricted. const ProjectKeyHeader = "X-Project-Key" // Option configures optional Client behavior. type Option func(*Client) // WithHTTPClient overrides the default HTTP client (e.g. to tune timeouts // or transport pooling). func WithHTTPClient(hc *http.Client) Option { return func(c *Client) { c.httpClient = hc } } // WithCookieName overrides the cookie name Middleware reads from incoming // requests. Only needed if the AuthServer deployment was configured with a // non-default session cookie name. func WithCookieName(name string) Option { return func(c *Client) { c.cookieName = name } } // WithProjectKey identifies this Client's project to AuthServer (see // ProjectKeyHeader), enabling per-user project-access restriction. key is // normally a project's own lowercase identifier, matching the same key // ProjectConfigurator's Projects workspace registers it under (e.g. // "carriernode", "gamestream", "omnilogger") - see AuthServer's project-scope // admin UI, which assigns users access using these same keys. func WithProjectKey(key string) Option { return func(c *Client) { c.projectKey = strings.ToLower(strings.TrimSpace(key)) } } // New creates a Client for the AuthServer instance at baseURL. baseURL may // be given without a scheme (e.g. "auth.example.com" or "192.168.1.50:8080") // - the scheme is then inferred from the host: a loopback, RFC1918/RFC4193 // private, or link-local address, or a ".local" name, defaults to "http://" // (a plain-HTTP AuthServer on a local network is the common case for those), // anything else defaults to "https://". An explicit "http://" or "https://" // is always left as-is, overriding the inference. func New(baseURL string, opts ...Option) *Client { c := &Client{ baseURL: normalizeBaseURL(baseURL), httpClient: &http.Client{Timeout: 5 * time.Second}, cookieName: DefaultCookieName, validationCache: make(map[[32]byte]validationCacheEntry), } for _, opt := range opts { opt(c) } return c } // SetBaseURL atomically replaces the AuthServer base URL this Client calls, // normalizing it the same way New does. Safe to call concurrently with // Validate/Middleware/any other method on this Client - the intended use is // a service wiring this up as a coreconfig.Store's OnUpdate callback, so a // fresh authguard_url pushed from ProjectConfigurator takes effect on this // Client's very next call with no restart. A blank baseURL is ignored // (leaving the previous value in place) rather than leaving the client // unable to reach AuthServer at all. func (c *Client) SetBaseURL(baseURL string) { normalized := normalizeBaseURL(baseURL) if normalized == "" { return } c.baseURLMu.Lock() c.baseURL = normalized c.baseURLMu.Unlock() c.clearValidationCache() } func (c *Client) getBaseURL() string { c.baseURLMu.RLock() defer c.baseURLMu.RUnlock() return c.baseURL } // setProjectKeyHeader attaches ProjectKeyHeader when this Client was built // with WithProjectKey; a no-op otherwise, so an unconfigured Client behaves // exactly as it did before project scoping existed. func (c *Client) setProjectKeyHeader(req *http.Request) { if c.projectKey != "" { req.Header.Set(ProjectKeyHeader, c.projectKey) } } // ForwardedForHeader carries the end user's address to AuthServer on the // credential calls (see WithClientIP). AuthServer reads it only when the // calling service's own address is listed in its TRUSTED_PROXIES, so sending // it changes nothing for a deployment that has not opted in. const ForwardedForHeader = "X-Forwarded-For" type clientIPKey struct{} // WithClientIP returns a context that makes Login, Register, TOTPVerify, // TOTPDisable and the password-reset calls send ip as X-Forwarded-For, so // AuthServer's per-address limits see the end user instead of this service. // Pass an address the caller has already verified (for example // auth.Service's trusted-proxy-aware client address), never a raw request // header. Anything that is not an IP address is ignored. func WithClientIP(ctx context.Context, ip string) context.Context { return context.WithValue(ctx, clientIPKey{}, strings.TrimSpace(ip)) } // setClientIPHeader attaches ForwardedForHeader when ctx carries a valid // address from WithClientIP; a no-op otherwise. func setClientIPHeader(ctx context.Context, req *http.Request) { ip, _ := ctx.Value(clientIPKey{}).(string) if parsed := net.ParseIP(ip); parsed != nil { req.Header.Set(ForwardedForHeader, parsed.String()) } } func normalizeBaseURL(baseURL string) string { trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/") if trimmed == "" { return trimmed } lower := strings.ToLower(trimmed) if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") { return trimmed } if isPrivateHost(trimmed) { return "http://" + trimmed } return "https://" + trimmed } // isPrivateHost reports whether hostport (a bare "host" or "host:port", no // scheme) names a loopback, RFC1918/RFC4193 private, or link-local address, // or a ".local" mDNS name -- the kind of host a plain-HTTP AuthServer is // typically reachable at on a local network, as opposed to a public hostname // expected to terminate TLS itself. Never performs DNS resolution: only // literal IPs and the "localhost"/".local" names are recognized, so a real // public hostname that merely happens to resolve to a private address still // defaults to https. func isPrivateHost(hostport string) bool { host := hostport if h, _, err := net.SplitHostPort(hostport); err == nil { host = h } host = strings.Trim(host, "[]") lower := strings.ToLower(host) if lower == "localhost" || strings.HasSuffix(lower, ".local") { return true } ip := net.ParseIP(host) if ip == nil { return false } return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() } // Validate calls AuthServer's GET /api/session/validate with token as a // Bearer credential and returns the resolved user. It returns // ErrInvalidSession (wrapped) when AuthServer reports the session as not // valid, and a plain error for any transport/decoding failure. func (c *Client) Validate(ctx context.Context, token string) (*User, error) { if c == nil { return nil, errors.New("authclient: client has no base URL") } baseURL := c.getBaseURL() if baseURL == "" { return nil, errors.New("authclient: client has no base URL") } token = strings.TrimSpace(token) if token == "" { return nil, ErrInvalidSession } if user, cachedErr, ok := c.cachedValidation(token); ok { return user, cachedErr } req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/api/session/validate", nil) if err != nil { return nil, fmt.Errorf("authclient: build request: %w", err) } req.Header.Set("Authorization", "Bearer "+token) c.setProjectKeyHeader(req) resp, err := c.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("authclient: call AuthServer: %w", err) } defer resp.Body.Close() var payload struct { Valid bool `json:"valid"` UserID int64 `json:"user_id"` Username string `json:"username"` Role string `json:"role"` } if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { if resp.StatusCode == http.StatusUnauthorized { c.cacheValidation(token, nil, false) return nil, ErrInvalidSession } return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err) } if resp.StatusCode == http.StatusUnauthorized || (resp.StatusCode == http.StatusOK && !payload.Valid) { c.cacheValidation(token, nil, false) return nil, ErrInvalidSession } if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("authclient: AuthServer returned HTTP %d", resp.StatusCode) } user := &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role} c.cacheValidation(token, user, true) return user, nil } // contextKey is unexported so only this package can set/read the resolved // user on a request context. type contextKey struct{} var userContextKey contextKey // UserFromContext returns the user Middleware attached to the request // context, or nil if none is present (e.g. called outside Middleware). func UserFromContext(ctx context.Context) *User { user, _ := ctx.Value(userContextKey).(*User) return user } // Middleware extracts the session token from an incoming request — the // cookie named by WithCookieName (default "auth_session"), falling back to // an Authorization: Bearer header — validates it against AuthServer, and // either responds 401 or attaches the resolved *User to the request // context (retrieve it with UserFromContext) before calling next. func (c *Client) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { token := c.tokenFromRequest(r) user, err := c.Validate(r.Context(), token) if err != nil { status := http.StatusUnauthorized if !errors.Is(err, ErrInvalidSession) { // A transport/decoding failure talking to AuthServer is not // the same as "this visitor is unauthenticated"; still fail // closed (401) rather than letting the request through, but // keep the two cases distinguishable for callers that want // to log or alert differently. status = http.StatusUnauthorized } http.Error(w, "authentication required", status) return } r = r.WithContext(context.WithValue(r.Context(), userContextKey, user)) next.ServeHTTP(w, r) }) } func (c *Client) tokenFromRequest(r *http.Request) string { if header := r.Header.Get("Authorization"); header != "" { if token, ok := strings.CutPrefix(header, "Bearer "); ok { if token = strings.TrimSpace(token); token != "" { return token } } } if cookie, err := r.Cookie(c.cookieName); err == nil { return cookie.Value } return "" } // --- Full API surface ------------------------------------------------------- // // Validate/Middleware above are all a service needs when it only ever // forwards an already-established AuthServer session to check it's still // valid. A service that used to run its own local register/login/logout/ // TOTP/password-reset/admin-user-management flow (backed by its own copy of // shared/backend/auth's Store) and is migrating that flow onto AuthServer // instead needs to originate those same calls itself — that's what the rest // of this file adds. Every method mirrors one of AuthServer's // internal/httpapi handlers exactly (method, path, request/response JSON // shape); see AuthServer/README.md's HTTP API table and // AuthServer/internal/httpapi/*.go for the source of truth this was written // against. // // # Cookie forwarding // // Register and Login both return the Set-Cookie header(s) AuthServer's // response carried, as SessionResult.Cookies (Logout returns them directly). // A service proxying its own e.g. POST /login to AuthServer's POST // /api/login should generally pass these straight through to its own // http.ResponseWriter with ForwardCookies (or by hand with http.SetCookie): // the browser then transparently holds AuthServer's own auth_session cookie // under whatever Domain/Secure/SameSite/Max-Age AuthServer was configured // with (see AUTH_COOKIE_DOMAIN in AuthServer's README for the cross-project // SSO implications of that Domain scope), and every subsequent request's // session token is that same cookie value — no separate mapping between "the // proxying service's own session cookie" and "the AuthServer token" is // needed anywhere. A service adopting this pattern should stop minting a // session cookie of its own and read/forward the incoming auth_session // cookie the same way Middleware does (see tokenFromRequest). // PublicUser is the account payload register/login/me return: {"id", // "username", "email", "role", "totp_enabled"}. It is deliberately distinct // from the slimmer User type Validate/Middleware use (which mirrors GET // /api/session/validate's {"user_id", "username", "role"} instead, and does // not carry TOTP status at all). type PublicUser struct { ID int64 `json:"id"` Username string `json:"username"` Email string `json:"email"` Role string `json:"role"` TOTPEnabled bool `json:"totp_enabled"` } // ManagedUser is one row of GET /api/admin/users, and the payload returned // by CreateManagedUser. It additionally carries CreatedAt, which PublicUser // does not. type ManagedUser struct { ID int64 `json:"id"` Username string `json:"username"` Email string `json:"email"` Role string `json:"role"` CreatedAt time.Time `json:"created_at"` } // SessionResult is returned by Register and Login: the account AuthServer // resolved, plus the Set-Cookie header(s) its response carried. See the // "Cookie forwarding" note above. type SessionResult struct { User PublicUser Cookies []*http.Cookie } // TOTPEnableResult is returned by TOTPEnable: a freshly provisioned, not yet // active TOTP secret and its otpauth:// URI for a QR code / authenticator // app. Confirm it with TOTPVerify. type TOTPEnableResult struct { Secret string `json:"secret"` OTPAuthURL string `json:"otpauth_url"` Enabled bool `json:"enabled"` } // ManagedUserInput is the body of CreateManagedUser (POST /api/admin/users) // and UpdateManagedUser (PUT /api/admin/users/{id}). On update, a zero-value // Username/Email/Password field means "leave unchanged" (AuthServer applies // only non-empty fields), and Role is only honored when AuthServer's own // authorization rules let the caller reassign it (only a superadmin actor, // and never onto/away from a superadmin target) — see AuthServer's // admin_users.go doc comments for the exact rules, which this client does // not re-implement or pre-validate. type ManagedUserInput struct { Username string `json:"username,omitempty"` Email string `json:"email,omitempty"` Password string `json:"password,omitempty"` Role *string `json:"role,omitempty"` } // APIError is returned when AuthServer responds with a non-2xx status. It // carries the status code and (when AuthServer's JSON body decoded // successfully) its {"error": "..."} message, so a caller can map it back // onto its own service's response shape/status code rather than exposing // AuthServer's wording verbatim. Use errors.As to recover it. type APIError struct { StatusCode int Message string // TOTPRequired is set only by Login, mirroring AuthServer's // {"totp_required": true} flag on a 401 that means "credentials were // correct, but this account has two-factor auth enabled and no (or an // incorrect) code was supplied" — distinct from a plain invalid- // credentials 401. TOTPRequired bool } func (e *APIError) Error() string { return fmt.Sprintf("authclient: authserver responded %d: %s", e.StatusCode, e.Message) } // ForwardCookies re-sets each cookie (typically SessionResult.Cookies or // Logout's return value) on w. This is the mechanical half of the "cookie // forwarding" pattern described above. func ForwardCookies(w http.ResponseWriter, cookies []*http.Cookie) { for _, cookie := range cookies { if cookie != nil { http.SetCookie(w, cookie) } } } // call is the shared request/response plumbing for every method below: it // builds a JSON request (skipped when body is nil), attaches token as a // Bearer credential (skipped when token is ""), and on a 2xx response // decodes the JSON body into out (skipped when out is nil). A non-2xx // response is translated into *APIError. The returned *http.Response (nil // on a transport-level failure) is provided so callers can read Cookies(); // its Body is always already fully read and closed. func (c *Client) call(ctx context.Context, method, path, token string, body, out any) (*http.Response, error) { if c == nil { return nil, errors.New("authclient: client has no base URL") } baseURL := c.getBaseURL() if baseURL == "" { return nil, errors.New("authclient: client has no base URL") } var reader io.Reader if body != nil { data, err := json.Marshal(body) if err != nil { return nil, fmt.Errorf("authclient: encode request body: %w", err) } reader = bytes.NewReader(data) } req, err := http.NewRequestWithContext(ctx, method, baseURL+path, reader) if err != nil { return nil, fmt.Errorf("authclient: build request: %w", err) } if body != nil { req.Header.Set("Content-Type", "application/json") } if token != "" { req.Header.Set("Authorization", "Bearer "+token) } c.setProjectKeyHeader(req) setClientIPHeader(ctx, req) resp, err := c.httpClient.Do(req) if err != nil { return nil, fmt.Errorf("authclient: call AuthServer: %w", err) } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { var payload struct { Error string `json:"error"` TOTPRequired bool `json:"totp_required"` } _ = json.NewDecoder(io.LimitReader(resp.Body, 64*1024)).Decode(&payload) message := payload.Error if message == "" { message = resp.Status } return resp, &APIError{StatusCode: resp.StatusCode, Message: message, TOTPRequired: payload.TOTPRequired} } if out != nil { if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out); err != nil { return resp, fmt.Errorf("authclient: decode AuthServer response: %w", err) } } return resp, nil } // SetupStatus calls GET /api/setup-status, an unauthenticated endpoint that // reports whether AuthServer has any account at all. Accounts are // centralized in AuthServer, so a caller with its own "first launch, create // the initial admin" flow should consult this first: when it reports false, // some account already exists (possibly created by a different project, or // directly against AuthServer), and the caller should show its ordinary // login screen instead of its own account-creation form. func (c *Client) SetupStatus(ctx context.Context) (bool, error) { var out struct { SetupRequired bool `json:"setup_required"` } if _, err := c.call(ctx, http.MethodGet, "/api/setup-status", "", nil, &out); err != nil { return false, err } return out.SetupRequired, nil } // Register calls POST /api/register, creating a new AuthServer account and // starting a session for it. func (c *Client) Register(ctx context.Context, username, email, password string) (*SessionResult, error) { var out struct { User PublicUser `json:"user"` } body := map[string]string{"username": username, "email": email, "password": password} resp, err := c.call(ctx, http.MethodPost, "/api/register", "", body, &out) if err != nil { return nil, err } return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil } // Login calls POST /api/login. totpToken may be empty; AuthServer returns an // *APIError with TOTPRequired set when the account has two-factor auth // enabled and no valid code was supplied. func (c *Client) Login(ctx context.Context, usernameOrEmail, password, totpToken string) (*SessionResult, error) { var out struct { User PublicUser `json:"user"` } body := map[string]string{"username_or_email": usernameOrEmail, "password": password} if totpToken != "" { body["totp_token"] = totpToken } resp, err := c.call(ctx, http.MethodPost, "/api/login", "", body, &out) if err != nil { return nil, err } return &SessionResult{User: out.User, Cookies: resp.Cookies()}, nil } // Logout calls POST /api/logout, deleting the session identified by token // server-side. It returns the (cookie-clearing) Set-Cookie header(s) // AuthServer's response carried; see ForwardCookies. func (c *Client) Logout(ctx context.Context, token string) ([]*http.Cookie, error) { resp, err := c.call(ctx, http.MethodPost, "/api/logout", token, nil, nil) if err != nil { return nil, err } c.invalidateValidation(token) return resp.Cookies(), nil } // Me calls GET /api/me, resolving token to its account. func (c *Client) Me(ctx context.Context, token string) (*PublicUser, error) { var out struct { User PublicUser `json:"user"` } if _, err := c.call(ctx, http.MethodGet, "/api/me", token, nil, &out); err != nil { return nil, err } return &out.User, nil } // TOTPEnable calls POST /api/totp/enable, provisioning (or re-provisioning) // a pending TOTP secret for token's account. The secret is not active until // TOTPVerify confirms a generated code. func (c *Client) TOTPEnable(ctx context.Context, token string) (*TOTPEnableResult, error) { var out TOTPEnableResult if _, err := c.call(ctx, http.MethodPost, "/api/totp/enable", token, nil, &out); err != nil { return nil, err } return &out, nil } // TOTPVerify calls POST /api/totp/verify, confirming code against the // pending secret TOTPEnable provisioned and activating two-factor auth. func (c *Client) TOTPVerify(ctx context.Context, token, code string) error { _, err := c.call(ctx, http.MethodPost, "/api/totp/verify", token, map[string]string{"token": code}, nil) return err } // TOTPDisable calls POST /api/totp/disable, turning two-factor auth off for // token's account. AuthServer requires code to be one last valid TOTP code // as proof of possession. func (c *Client) TOTPDisable(ctx context.Context, token, code string) error { _, err := c.call(ctx, http.MethodPost, "/api/totp/disable", token, map[string]string{"token": code}, nil) return err } // RequestPasswordReset calls POST /api/password-reset/request. See // AuthServer's README for an important caveat: this is not an "email me a // link" flow — AuthServer prints a one-time code to its own process // console, and only an operator with access to that console can relay it to // the user. The response never reveals whether usernameOrEmail matched an // account. func (c *Client) RequestPasswordReset(ctx context.Context, usernameOrEmail string) error { _, err := c.call(ctx, http.MethodPost, "/api/password-reset/request", "", map[string]string{"username_or_email": usernameOrEmail}, nil) return err } // ConfirmPasswordReset calls POST /api/password-reset/confirm with the code // an operator relayed out-of-band (see RequestPasswordReset) and a new // password, and invalidates every existing session for that account. func (c *Client) ConfirmPasswordReset(ctx context.Context, code, newPassword string) error { _, err := c.call(ctx, http.MethodPost, "/api/password-reset/confirm", "", map[string]string{"code": code, "password": newPassword}, nil) return err } // ListManagedUsers calls GET /api/admin/users. token's account must satisfy // AuthServer's CanManageUsers check (admin or superadmin), or this returns // an *APIError with StatusCode 401/403. func (c *Client) ListManagedUsers(ctx context.Context, token string) ([]ManagedUser, error) { var out struct { Users []ManagedUser `json:"users"` } if _, err := c.call(ctx, http.MethodGet, "/api/admin/users", token, nil, &out); err != nil { return nil, err } return out.Users, nil } // CreateManagedUser calls POST /api/admin/users. Only honored when token's // account can manage users; see ManagedUserInput's doc comment for the Role // authorization rule. func (c *Client) CreateManagedUser(ctx context.Context, token string, input ManagedUserInput) (*ManagedUser, error) { var out struct { User ManagedUser `json:"user"` } if _, err := c.call(ctx, http.MethodPost, "/api/admin/users", token, input, &out); err != nil { return nil, err } return &out.User, nil } // UpdateManagedUser calls PUT /api/admin/users/{id}. func (c *Client) UpdateManagedUser(ctx context.Context, token string, id int64, input ManagedUserInput) error { _, err := c.call(ctx, http.MethodPut, fmt.Sprintf("/api/admin/users/%d", id), token, input, nil) if err == nil { c.invalidateValidation(token) } return err } // DeleteManagedUser calls DELETE /api/admin/users/{id}. func (c *Client) DeleteManagedUser(ctx context.Context, token string, id int64) error { _, err := c.call(ctx, http.MethodDelete, fmt.Sprintf("/api/admin/users/%d", id), token, nil, nil) return err }