Something went wrong. Try again.
forked from scottlanoue.com/atmosphere-mail
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183// SPDX-License-Identifier: AGPL-3.0-or-later
// Package adminclient provides a typed HTTP client for cmd/relay's// admin API, consumed by cmd/web over loopback. It implements// http.Handler so it can be a drop-in replacement for the in-process// *admin.API that EnrollHandler/RecoverHandler take today: the same// Cookie/User-Agent/RemoteAddr-bearing request shape that// EnrollHandler.proxyAdminInner constructs in-process is constructed// here, then sent across the loopback boundary instead of dispatched// in-process.//// The contract this client preserves (so the existing handlers don't// have to know which side of the binary split they're on)://// - Authorization: Bearer <AdminToken> is added on every request.// The relay's loopback admin listener gates on this token; it is// the same secret cmd/relay reads from sops.// - X-Forwarded-For carries the inbound RemoteAddr's IP so the// relay's per-IP enroll-start rate limiter sees the real public// client, not 127.0.0.1. Without this, every enrollment shares one// bucket and a single attacker locks out the world.// - Cookie + User-Agent are forwarded verbatim. The enroll-auth// ticket is cookie-bound and UA-bound; both have to survive the// hop or the relay treats every request as unauthenticated.// - On HTTP transport error (relay down, connection refused,// timeout) the response is a 502 with a small text body, never a// panic. The wrapping handler renders an inline error page.// - The body is streamed end-to-end via io.Copy. Buffering would be// correct but pointless; admin payloads are tiny and the contract// is "drop-in for the in-process handler", which streams.//// Phase 5c-0 wires this constructor in cmd/web but does not mount any// routes that use it. Phase 5c-1 onwards passes Client into// EnrollHandler/RecoverHandler in place of *admin.API.package adminclient
import ( "errors" "fmt" "io" "net" "net/http" "net/url" "time")
// defaultTimeout applies when Config.Timeout is zero. Ten seconds is the// same per-request timeout cmd/relay uses for its outbound DID/labeler// calls; it's a known-survivable upper bound on a healthy loopback// admin call (which typically completes in single-digit ms).const defaultTimeout = 10 * time.Second
// Config configures a loopback admin API client for cmd/web.type Config struct { // BaseURL is the loopback URL of the relay's admin listener, // e.g. "http://127.0.0.1:8080". Must include scheme + host; path // is ignored (the inbound request's path is preserved). BaseURL string // AdminToken is the bearer token the relay's admin listener // validates. Same secret cmd/relay reads from sops; cmd/web reads // it from a sibling file in the same secrets path. AdminToken string // Timeout is the per-request timeout. Zero applies defaultTimeout. Timeout time.Duration // Transport overrides the underlying http.RoundTripper. Tests use // this to intercept; production leaves it nil and gets // http.DefaultTransport. Transport http.RoundTripper}
// Client is an HTTP-backed admin API client. It implements// http.Handler so EnrollHandler and RecoverHandler can take it// wherever they take an in-process *admin.API today.type Client struct { baseURL *url.URL adminToken string httpClient *http.Client}
// New constructs a Client. Returns an error if BaseURL is missing,// unparseable, or AdminToken is empty — these are configuration bugs// that should fail at startup, not silently produce 401s on every// inbound request.func New(cfg Config) (*Client, error) { if cfg.BaseURL == "" { return nil, errors.New("adminclient: BaseURL is required") } if cfg.AdminToken == "" { return nil, errors.New("adminclient: AdminToken is required") } parsed, err := url.Parse(cfg.BaseURL) if err != nil { return nil, fmt.Errorf("adminclient: parse BaseURL: %w", err) } if parsed.Scheme == "" || parsed.Host == "" { return nil, fmt.Errorf("adminclient: BaseURL must include scheme and host, got %q", cfg.BaseURL) } timeout := cfg.Timeout if timeout <= 0 { timeout = defaultTimeout } httpClient := &http.Client{Timeout: timeout} if cfg.Transport != nil { httpClient.Transport = cfg.Transport } return &Client{ baseURL: parsed, adminToken: cfg.AdminToken, httpClient: httpClient, }, nil}
// ServeHTTP rewrites the inbound request to target the loopback admin// API, forwards the body+headers that the relay's auth and rate-limit// machinery cares about, and copies the response back. Transport errors// produce a 502; everything else passes through.//// The inbound request's path + query are preserved verbatim — the relay// expects "/api/admin/enroll/start" etc., and the wrapping handler// already routes by path. We never rewrite the path here.func (c *Client) ServeHTTP(w http.ResponseWriter, r *http.Request) { target := *c.baseURL target.Path = r.URL.Path target.RawQuery = r.URL.RawQuery
outBody := r.Body // safe — http.NewRequestWithContext copies the io.Reader outReq, err := http.NewRequestWithContext(r.Context(), r.Method, target.String(), outBody) if err != nil { http.Error(w, "adminclient: build request", http.StatusBadGateway) return }
// Forward headers the relay's admin handlers depend on. We do NOT // blanket-copy r.Header — that would forward the inbound // Authorization (if any), and the relay only trusts the bearer we // add below. Forwarding too much is a safety hazard; forwarding // too little breaks cookie-based enrollment auth. if ct := r.Header.Get("Content-Type"); ct != "" { outReq.Header.Set("Content-Type", ct) } if cookie := r.Header.Get("Cookie"); cookie != "" { outReq.Header.Set("Cookie", cookie) } if ua := r.UserAgent(); ua != "" { outReq.Header.Set("User-Agent", ua) } outReq.Header.Set("Authorization", "Bearer "+c.adminToken)
// X-Forwarded-For carries the IP component of the inbound // RemoteAddr so the relay's per-IP enroll-start rate limiter sees // the real client. RemoteAddr is "host:port"; we strip the port. // On parse failure we still send the raw value — better imperfect // rate-limit signal than none. if r.RemoteAddr != "" { host, _, splitErr := net.SplitHostPort(r.RemoteAddr) if splitErr != nil { host = r.RemoteAddr } if host != "" { outReq.Header.Set("X-Forwarded-For", host) } }
resp, err := c.httpClient.Do(outReq) if err != nil { http.Error(w, "adminclient: upstream unreachable", http.StatusBadGateway) return } defer resp.Body.Close()
// Copy response headers before WriteHeader; once status is written, // header mutations are silently dropped. for k, vs := range resp.Header { for _, v := range vs { w.Header().Add(k, v) } } w.WriteHeader(resp.StatusCode) // io.Copy streams; admin responses are small but the contract is // "drop-in for in-process handler" which streams. _, _ = io.Copy(w, resp.Body)}