Extend authclient with the full AuthGuard API surface
Adds Register/Login/Logout/Me/TOTP(Enable/Verify/Disable)/password-reset/ admin-user-management (List/Create/Update/DeleteManagedUser) methods, APIError, SessionResult, and ForwardCookies - everything a Go service needs to fully retire its own local auth in favor of proxying to AuthGuard, not just validate an existing session. Cookie-forwarding pattern: a service passes AuthGuard's own Set-Cookie straight through via ForwardCookies rather than minting its own session token, so the browser holds one real AuthGuard cookie under whatever AUTH_COOKIE_DOMAIN scope was configured - no double session-mapping, correct cross-project SSO for free. Documented in the package doc comment. First real consumer: GameStream's cutover (separate commit, that repo). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5bf8ec5cee
commit
97a5ecdf83
1 file changed
+321
-1
@@ -14,10 +14,12 @@
|
|||||||
package authclient
|
package authclient
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
@@ -35,6 +37,14 @@ type User struct {
|
|||||||
// token/cookie as not currently valid (expired, unknown, or missing).
|
// token/cookie as not currently valid (expired, unknown, or missing).
|
||||||
var ErrInvalidSession = errors.New("authclient: invalid or missing session")
|
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.
|
// Client calls a centralized AuthServer instance over HTTP.
|
||||||
type Client struct {
|
type Client struct {
|
||||||
// BaseURL is AuthServer's base URL, e.g. "https://auth.example.com"
|
// BaseURL is AuthServer's base URL, e.g. "https://auth.example.com"
|
||||||
@@ -70,7 +80,7 @@ func New(baseURL string, opts ...Option) *Client {
|
|||||||
c := &Client{
|
c := &Client{
|
||||||
baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
|
baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"),
|
||||||
httpClient: &http.Client{Timeout: 5 * time.Second},
|
httpClient: &http.Client{Timeout: 5 * time.Second},
|
||||||
cookieName: "auth_session",
|
cookieName: DefaultCookieName,
|
||||||
}
|
}
|
||||||
for _, opt := range opts {
|
for _, opt := range opts {
|
||||||
opt(c)
|
opt(c)
|
||||||
@@ -175,3 +185,313 @@ func (c *Client) tokenFromRequest(r *http.Request) string {
|
|||||||
}
|
}
|
||||||
return ""
|
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"}. It is deliberately distinct from the slimmer
|
||||||
|
// User type Validate/Middleware use (which mirrors GET
|
||||||
|
// /api/session/validate's {"user_id", "username", "role"} instead).
|
||||||
|
type PublicUser struct {
|
||||||
|
ID int64 `json:"id"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Role string `json:"role"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 || c.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, c.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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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
|
||||||
|
}
|
||||||
|
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)
|
||||||
|
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
|
||||||
|
}
|
||||||
Reference in new issue
Block a user