Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

Restrict /health/realtime metrics exposure (MUL-1342) (#1608)

LinYushen99154d97b97f
diff --git a/.env.example b/.env.example
index 47f43aa8db..709663e2ff 100644
--- a/.env.example
+++ b/.env.example
@@ -85,6 +85,16 @@ LOCAL_UPLOAD_BASE_URL=http://localhost:8080
# Example: ALLOWED_ORIGINS=https://app.multica.ai,https://staging.multica.ai
ALLOWED_ORIGINS=
+# Realtime metrics endpoint (/health/realtime) access control. See MUL-1342.
+# When unset, the endpoint only serves direct loopback (127.0.0.1 / ::1)
+# callers with no forwarding headers and returns 404 to everything else —
+# safe for local dev. Any deployment behind a reverse proxy (Caddy / Nginx
+# terminating TLS in front of localhost:8080) MUST set this token, since
+# proxied requests look like loopback at the Go layer; with no token, those
+# requests are refused with 404. Pass the token as
+# `Authorization: Bearer <token>`.
+# REALTIME_METRICS_TOKEN=
+
# Frontend
FRONTEND_PORT=3000
FRONTEND_ORIGIN=http://localhost:3000
diff --git a/server/cmd/server/health_realtime.go b/server/cmd/server/health_realtime.go
new file mode 100644
index 0000000000..2a8748ae7f
--- /dev/null
+++ b/server/cmd/server/health_realtime.go
@@ -0,0 +1,103 @@
+package main
+
+import (
+ "crypto/subtle"
+ "encoding/json"
+ "net"
+ "net/http"
+ "strings"
+
+ "github.com/multica-ai/multica/server/internal/realtime"
+)
+
+// realtimeMetricsHandler returns the HTTP handler for /health/realtime.
+//
+// The endpoint exposes operational counters (per-event / per-scope sends,
+// Redis relay state, etc.) that should not be reachable by anonymous public
+// clients. See MUL-1342.
+//
+// Access policy:
+// - If token != "": require Authorization: Bearer <token>; reject other
+// callers with 401.
+// - If token == "": only allow direct loopback callers (127.0.0.1 / ::1)
+// with no forwarding headers; reject anything else with 404 so the
+// endpoint is not enumerable. This keeps local development workflows
+// working without configuration while ensuring the metrics surface is
+// not exposed on a public listener — including when the server sits
+// behind a reverse proxy (Caddy / Nginx) that terminates TLS on
+// localhost, in which case all requests would otherwise look like
+// loopback (see MUL-1342 review).
+func realtimeMetricsHandler(token string) http.HandlerFunc {
+ token = strings.TrimSpace(token)
+ return func(w http.ResponseWriter, r *http.Request) {
+ if token != "" {
+ if !hasBearerToken(r, token) {
+ w.Header().Set("WWW-Authenticate", `Bearer realm="metrics"`)
+ http.Error(w, "unauthorized", http.StatusUnauthorized)
+ return
+ }
+ } else if !isDirectLoopbackRequest(r) {
+ // Hide the endpoint from non-loopback callers (and from
+ // proxied requests we cannot attribute) when no token is
+ // configured. Returning 404 avoids advertising its
+ // existence to remote scanners.
+ http.NotFound(w, r)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ _ = json.NewEncoder(w).Encode(realtime.M.Snapshot())
+ }
+}
+
+func hasBearerToken(r *http.Request, want string) bool {
+ auth := r.Header.Get("Authorization")
+ const prefix = "Bearer "
+ if len(auth) <= len(prefix) || !strings.EqualFold(auth[:len(prefix)], prefix) {
+ return false
+ }
+ got := strings.TrimSpace(auth[len(prefix):])
+ if got == "" {
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(got), []byte(want)) == 1
+}
+
+func isDirectLoopbackRequest(r *http.Request) bool {
+ // Any indication that the request was relayed by a proxy disqualifies
+ // the loopback shortcut: behind Caddy/Nginx -> localhost:8080, public
+ // callers would otherwise appear as 127.0.0.1 here. We deliberately do
+ // NOT trust these headers to identify the real client — we only use
+ // their presence as a "this is proxied, fail closed" signal.
+ if hasForwardingHeader(r) {
+ return false
+ }
+ host, _, err := net.SplitHostPort(r.RemoteAddr)
+ if err != nil {
+ host = r.RemoteAddr
+ }
+ if host == "" {
+ return false
+ }
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return false
+ }
+ return ip.IsLoopback()
+}
+
+func hasForwardingHeader(r *http.Request) bool {
+ for _, h := range []string{
+ "X-Forwarded-For",
+ "X-Forwarded-Host",
+ "X-Forwarded-Proto",
+ "X-Real-Ip",
+ "Forwarded",
+ } {
+ if strings.TrimSpace(r.Header.Get(h)) != "" {
+ return true
+ }
+ }
+ return false
+}
diff --git a/server/cmd/server/health_realtime_test.go b/server/cmd/server/health_realtime_test.go
new file mode 100644
index 0000000000..3493e56d95
--- /dev/null
+++ b/server/cmd/server/health_realtime_test.go
@@ -0,0 +1,168 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestRealtimeMetricsHandler_TokenRequired(t *testing.T) {
+ const token = "secret-test-token"
+ h := realtimeMetricsHandler(token)
+
+ t.Run("missing auth rejected", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "203.0.113.10:54321"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d", rec.Code)
+ }
+ if got := rec.Header().Get("WWW-Authenticate"); got == "" {
+ t.Fatalf("expected WWW-Authenticate header, got empty")
+ }
+ })
+
+ t.Run("loopback without token rejected when token configured", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "127.0.0.1:1234"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401 even from loopback when token required, got %d", rec.Code)
+ }
+ })
+
+ t.Run("wrong token rejected", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.Header.Set("Authorization", "Bearer not-the-token")
+ req.RemoteAddr = "203.0.113.10:54321"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d", rec.Code)
+ }
+ })
+
+ t.Run("non-bearer scheme rejected", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.Header.Set("Authorization", "Basic "+token)
+ req.RemoteAddr = "203.0.113.10:54321"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusUnauthorized {
+ t.Fatalf("expected 401, got %d", rec.Code)
+ }
+ })
+
+ t.Run("correct bearer token accepted", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.RemoteAddr = "203.0.113.10:54321"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d (%s)", rec.Code, rec.Body.String())
+ }
+ if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
+ t.Fatalf("expected JSON content-type, got %q", ct)
+ }
+ })
+}
+
+func TestRealtimeMetricsHandler_NoToken_LoopbackOnly(t *testing.T) {
+ h := realtimeMetricsHandler("")
+
+ t.Run("loopback ipv4 allowed", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "127.0.0.1:9999"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200 from loopback, got %d", rec.Code)
+ }
+ })
+
+ t.Run("loopback ipv6 allowed", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "[::1]:9999"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200 from ipv6 loopback, got %d", rec.Code)
+ }
+ })
+
+ t.Run("non-loopback returns 404", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "10.0.0.5:1234"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 to hide endpoint, got %d", rec.Code)
+ }
+ })
+
+ t.Run("public ipv6 returns 404", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "[2001:db8::1]:1234"
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("expected 404, got %d", rec.Code)
+ }
+ })
+
+ // MUL-1342 review: when the server is behind a reverse proxy on
+ // localhost (Caddy / Nginx -> 127.0.0.1:8080), public callers reach
+ // the handler with RemoteAddr=127.0.0.1. The presence of forwarding
+ // headers must disqualify the loopback shortcut, otherwise the
+ // metrics surface is fully exposed in self-hosted deployments.
+ proxyHeaders := []struct {
+ name string
+ header string
+ value string
+ }{
+ {"x-forwarded-for", "X-Forwarded-For", "203.0.113.10"},
+ {"x-forwarded-for chain", "X-Forwarded-For", "203.0.113.10, 10.0.0.1"},
+ {"x-real-ip", "X-Real-Ip", "203.0.113.10"},
+ {"x-forwarded-host", "X-Forwarded-Host", "metrics.example.com"},
+ {"x-forwarded-proto", "X-Forwarded-Proto", "https"},
+ {"forwarded rfc7239", "Forwarded", "for=203.0.113.10;proto=https"},
+ }
+ for _, tc := range proxyHeaders {
+ tc := tc
+ t.Run("proxied "+tc.name+" via loopback returns 404", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "127.0.0.1:1234"
+ req.Header.Set(tc.header, tc.value)
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for proxied loopback request (%s), got %d", tc.header, rec.Code)
+ }
+ })
+ }
+
+ t.Run("proxied loopback ipv6 returns 404", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "[::1]:9999"
+ req.Header.Set("X-Forwarded-For", "203.0.113.10")
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusNotFound {
+ t.Fatalf("expected 404 for proxied ::1 request, got %d", rec.Code)
+ }
+ })
+
+ t.Run("empty forwarding header still allows loopback", func(t *testing.T) {
+ req := httptest.NewRequest(http.MethodGet, "/health/realtime", nil)
+ req.RemoteAddr = "127.0.0.1:9999"
+ req.Header.Set("X-Forwarded-For", " ")
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200 when forwarding header is blank, got %d", rec.Code)
+ }
+ })
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 5fc065709c..82e9d6589f 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2,7 +2,6 @@ package main
import (
"context"
- "encoding/json"
"net/http"
"os"
"strings"
@@ -120,10 +119,12 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analytics
// and per-event-type send QPS counters. Exposed as JSON so it can be
// scraped by ops or surfaced in the admin UI without adding a Prometheus
// dependency. See MUL-1138 (Phase 0).
- r.Get("/health/realtime", func(w http.ResponseWriter, r *http.Request) {
- w.Header().Set("Content-Type", "application/json")
- _ = json.NewEncoder(w).Encode(realtime.M.Snapshot())
- })
+ //
+ // Access is restricted (MUL-1342): when REALTIME_METRICS_TOKEN is set,
+ // callers must present it via Authorization: Bearer <token>. When the
+ // env var is unset the handler only serves loopback callers so local
+ // dev keeps working without exposing the metrics on a public listener.
+ r.Get("/health/realtime", realtimeMetricsHandler(os.Getenv("REALTIME_METRICS_TOKEN")))
// WebSocket
mc := &membershipChecker{queries: queries}