// 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 ( "context" "encoding/json" "errors" "fmt" "net/http" "strings" "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") // Client calls a centralized AuthServer instance over HTTP. type Client struct { // BaseURL is AuthServer's base URL, e.g. "https://auth.example.com" // (no trailing slash required). 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 } // 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 } } // New creates a Client for the AuthServer instance at baseURL. func New(baseURL string, opts ...Option) *Client { c := &Client{ baseURL: strings.TrimRight(strings.TrimSpace(baseURL), "/"), httpClient: &http.Client{Timeout: 5 * time.Second}, cookieName: "auth_session", } for _, opt := range opts { opt(c) } return c } // 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 || c.baseURL == "" { return nil, errors.New("authclient: client has no base URL") } token = strings.TrimSpace(token) if token == "" { return nil, ErrInvalidSession } req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+"/api/session/validate", nil) if err != nil { return nil, fmt.Errorf("authclient: build request: %w", err) } 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() 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 { return nil, ErrInvalidSession } return nil, fmt.Errorf("authclient: decode AuthServer response: %w", err) } if resp.StatusCode != http.StatusOK || !payload.Valid { return nil, ErrInvalidSession } return &User{ID: payload.UserID, Username: payload.Username, Role: payload.Role}, 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 "" }