Repository Public
1package api23import (4 "net/http"5 "net/http/httputil"6 "net/url"7 "os"8 "strings"910 "clustr.spboucher.ai/mcc/internal/httpx"11)1213// Agents reach the control plane through the public origin (macOS Local14// Network Privacy blocks LAN traffic from launchd-started binaries; see15// ADR 0004). control-api only RELAYS /agent/v1/ to telemetry-ingest's16// loopback listener: it does not authenticate agents itself. Ingest verifies17// the per-request signature made with the agent's enrolled certificate key,18// and commands are signed end to end by the orchestrator, so this relay sees19// nothing it could forge.2021const (22 agentPrefix = "/agent/v1/"23 agentMaxBody = 2 << 2024)2526// ingestUpstream is where telemetry-ingest's signed-request listener lives.27func (s *Server) ingestUpstream() string {28 if v := strings.TrimSpace(os.Getenv("MCC_INGEST_UPSTREAM")); v != "" {29 return v30 }31 if v := s.core.Cfg.IngestSignedListen; v != "" {32 return "http://" + v33 }34 return "http://127.0.0.1:8734"35}3637func (s *Server) agentProxy() http.Handler {38 target, err := url.Parse(s.ingestUpstream())39 if err != nil {40 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { httpx.WriteError(w, r, httpx.ErrUnavailable) })41 }42 rp := &httputil.ReverseProxy{43 Rewrite: func(pr *httputil.ProxyRequest) {44 pr.SetURL(target)45 pr.Out.Host = target.Host46 // The client address comes from OUR resolution (trusted proxies only), never from the incoming header.47 pr.Out.Header.Del("X-Forwarded-For")48 pr.Out.Header.Del("Forwarded")49 if ip, ok := httpx.ClientIP(pr.In.Context()); ok {50 pr.Out.Header.Set("X-Forwarded-For", ip.String())51 }52 // Agents never use user credentials; do not relay any.53 pr.Out.Header.Del("Cookie")54 pr.Out.Header.Del("Authorization")55 pr.Out.Header.Set("X-Correlation-Id", httpx.Correlation(pr.In.Context()).String())56 },57 FlushInterval: -1, // long-poll and streamed responses are relayed immediately58 ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {59 if r.Context().Err() != nil {60 return // the agent went away; nothing to answer61 }62 e := *httpx.ErrUnavailable63 e.RetryAfter = 1564 httpx.WriteError(w, r, &e)65 },66 }67 limiter := httpx.NewLimiter(20, 10) // enrollment attempts per IP68 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {69 if r.Header.Get("Origin") != "" || r.Header.Get("Cookie") != "" && r.Header.Get("Sec-Fetch-Site") != "" {70 // Browsers have no business here.71 httpx.WriteError(w, r, httpx.ErrForbidden)72 return73 }74 if strings.HasSuffix(r.URL.Path, "/enroll") {75 ip, _ := httpx.ClientIP(r.Context())76 if ok, wait := limiter.Allow(ip.String()); !ok {77 e := *httpx.ErrRateLimited78 e.RetryAfter = wait79 httpx.WriteError(w, r, &e)80 return81 }82 }83 r.Body = http.MaxBytesReader(w, r.Body, agentMaxBody)84 rp.ServeHTTP(w, r)85 })86}87