Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-3123 fix(realtime): support X-Forwarded-Host in WebSocket checkOrigin
xiaoyue2610076ae773e5
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex b5d8aaf33d..ce97c8acf7 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -399,6 +399,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// Share allowed origins with WebSocket origin checker.realtime.SetAllowedOrigins(origins)+ // Share the same trusted-proxy CIDRs (MULTICA_TRUSTED_PROXIES) so the+ // WebSocket origin check honors X-Forwarded-Host only from trusted proxies,+ // using one config source instead of a parallel one.+ realtime.SetTrustedProxies(signupConfig.TrustedProxies)+r.Use(cors.Handler(cors.Options{AllowedOrigins: origins,AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},diff --git a/server/internal/realtime/hub.go b/server/internal/realtime/hub.goindex 79b04d4304..2cba7c30e8 100644--- a/server/internal/realtime/hub.go+++ b/server/internal/realtime/hub.go@@ -4,7 +4,9 @@ import ("context""encoding/json""log/slog"+ "net""net/http"+ "net/netip""net/url""os""strings"@@ -40,9 +42,11 @@ type ScopeAuthorizer interface {}var allowedWSOrigins atomic.Value // holds []string+var trustedProxies atomic.Value // holds []netip.Prefixfunc init() {allowedWSOrigins.Store(loadAllowedOrigins())+ trustedProxies.Store(loadTrustedProxies())}func loadAllowedOrigins() []string {@@ -72,11 +76,85 @@ func loadAllowedOrigins() []string {return origins}+// loadTrustedProxies reads the same MULTICA_TRUSTED_PROXIES env var the rest of+// the server uses (see cmd/server/router.go and handler.Config.TrustedProxies),+// parsing it as a comma-separated list of CIDR prefixes. Invalid entries are+// dropped with a warn-line rather than crashing. Empty input returns nil, which+// means "trust no proxy" — X-Forwarded-Host is then never honored. The router+// overrides this at startup via SetTrustedProxies so both share one config.+func loadTrustedProxies() []netip.Prefix {+ raw := strings.TrimSpace(os.Getenv("MULTICA_TRUSTED_PROXIES"))+ if raw == "" {+ return nil+ }+ var prefixes []netip.Prefix+ for _, part := range strings.Split(raw, ",") {+ s := strings.TrimSpace(part)+ if s == "" {+ continue+ }+ p, err := netip.ParsePrefix(s)+ if err != nil {+ slog.Warn("ws: ignoring invalid trusted proxy CIDR", "value", s, "error", err)+ continue+ }+ prefixes = append(prefixes, p)+ }+ return prefixes+}+// SetAllowedOrigins overrides the WebSocket origin whitelist.func SetAllowedOrigins(origins []string) {allowedWSOrigins.Store(origins)}+// SetTrustedProxies overrides the trusted proxy CIDR list. The server wires the+// shared MULTICA_TRUSTED_PROXIES value in here at startup.+func SetTrustedProxies(proxies []netip.Prefix) {+ trustedProxies.Store(proxies)+}++// isTrustedProxy reports whether the request's remote address falls within one+// of the configured trusted proxy CIDRs.+func isTrustedProxy(remoteAddr string) bool {+ proxies := trustedProxies.Load().([]netip.Prefix)+ if len(proxies) == 0 {+ return false+ }+ addr, err := netip.ParseAddr(remoteHost(remoteAddr))+ if err != nil {+ return false+ }+ addr = addr.Unmap()+ for _, p := range proxies {+ if p.Contains(addr) {+ return true+ }+ }+ return false+}++// remoteHost extracts the host/IP from an http.Request.RemoteAddr, which is+// normally "host:port". It handles bracketed IPv6 ("[::1]:443") via+// net.SplitHostPort and falls back to the raw value (sans brackets) when no+// port is present.+func remoteHost(remoteAddr string) string {+ if host, _, err := net.SplitHostPort(remoteAddr); err == nil {+ return host+ }+ return strings.Trim(remoteAddr, "[]")+}++// firstForwardedHost returns the first host from a (possibly comma-separated)+// X-Forwarded-Host header. Proxy chains append values left-to-right, so the+// first entry is the original client-facing host we compare against Origin.+func firstForwardedHost(h string) string {+ if i := strings.IndexByte(h, ','); i >= 0 {+ h = h[:i]+ }+ return strings.TrimSpace(h)+}+func checkOrigin(r *http.Request) bool {origin := r.Header.Get("Origin")if origin == "" {@@ -92,13 +170,23 @@ func checkOrigin(r *http.Request) bool {if u, err := url.Parse(origin); err == nil && strings.EqualFold(u.Host, r.Host) {return true}+ // Reverse-proxy support: when sitting behind a proxy the Host header+ // contains the internal address. X-Forwarded-Host carries the original+ // public host seen by the client, so we treat a matching origin as+ // same-origin in that case too. SECURITY: Only trust X-Forwarded-Host+ // if the request comes from a trusted proxy to prevent header spoofing.+ if fwdHost := firstForwardedHost(r.Header.Get("X-Forwarded-Host")); fwdHost != "" && isTrustedProxy(r.RemoteAddr) {+ if u, err := url.Parse(origin); err == nil && strings.EqualFold(u.Host, fwdHost) {+ return true+ }+ }origins := allowedWSOrigins.Load().([]string)for _, allowed := range origins {if origin == allowed {return true}}- slog.Warn("ws: rejected origin", "origin", origin)+ slog.Warn("ws: rejected origin", "origin", origin, "remote_addr", r.RemoteAddr)return false}diff --git a/server/internal/realtime/hub_test.go b/server/internal/realtime/hub_test.goindex ebd13fa6c0..10dcdc8131 100644--- a/server/internal/realtime/hub_test.go+++ b/server/internal/realtime/hub_test.go@@ -8,6 +8,7 @@ import ("log/slog""net/http""net/http/httptest"+ "net/netip""strings""sync""testing"@@ -360,31 +361,55 @@ func TestCheckOrigin(t *testing.T) {})t.Cleanup(func() { SetAllowedOrigins(prev) })+ prevProxies := trustedProxies.Load().([]netip.Prefix)+ SetTrustedProxies([]netip.Prefix{+ netip.MustParsePrefix("127.0.0.1/32"),+ netip.MustParsePrefix("10.0.0.0/8"),+ netip.MustParsePrefix("::1/128"),+ })+ t.Cleanup(func() { SetTrustedProxies(prevProxies) })+cases := []struct {- name string- host string- origin string- want bool+ name string+ host string+ origin string+ fwdHost string+ remoteAddr string+ want bool}{- {"empty origin allowed", "api.multica.ai", "", true},- {"same-origin allowed (native client default)", "localhost:8080", "http://localhost:8080", true},- {"same-origin allowed (https)", "api.multica.ai", "https://api.multica.ai", true},- {"same-origin allowed (case-insensitive host, RFC 7230)", "API.Multica.AI", "https://api.multica.ai", true},- {"whitelisted origin allowed (web cross-origin)", "localhost:8080", "http://localhost:3000", true},- {"whitelisted origin allowed (prod web)", "api.multica.ai", "https://multica.ai", true},- {"unknown origin rejected (CSWSH defense)", "api.multica.ai", "https://evil.com", false},- {"different port rejected", "localhost:8080", "http://localhost:9999", false},+ {"empty origin allowed", "api.multica.ai", "", "", "1.2.3.4:5678", true},+ {"same-origin allowed (native client default)", "localhost:8080", "http://localhost:8080", "", "1.2.3.4:5678", true},+ {"same-origin allowed (https)", "api.multica.ai", "https://api.multica.ai", "", "1.2.3.4:5678", true},+ {"same-origin allowed (case-insensitive host, RFC 7230)", "API.Multica.AI", "https://api.multica.ai", "", "1.2.3.4:5678", true},+ {"whitelisted origin allowed (web cross-origin)", "localhost:8080", "http://localhost:3000", "", "1.2.3.4:5678", true},+ {"whitelisted origin allowed (prod web)", "api.multica.ai", "https://multica.ai", "", "1.2.3.4:5678", true},+ {"unknown origin rejected (CSWSH defense)", "api.multica.ai", "https://evil.com", "", "1.2.3.4:5678", false},+ {"different port rejected", "localhost:8080", "http://localhost:9999", "", "1.2.3.4:5678", false},+ {"X-Forwarded-Host from trusted proxy matches origin", "internal.proxy", "https://multica.ai", "multica.ai", "127.0.0.1:5678", true},+ {"X-Forwarded-Host from trusted proxy case-insensitive", "internal.proxy", "https://Multica.AI", "multica.ai", "10.0.0.1:5678", true},+ {"X-Forwarded-Host from untrusted source rejected", "internal.proxy", "https://example.com", "example.com", "1.2.3.4:5678", false},+ {"X-Forwarded-Host from trusted proxy but evil origin rejected", "internal.proxy", "https://evil.com", "multica.ai", "127.0.0.1:5678", false},+ {"X-Forwarded-Host present but origin matches direct Host", "multica.ai", "https://multica.ai", "other.host", "1.2.3.4:5678", true},+ {"X-Forwarded-Host spoofed by attacker rejected", "internal.proxy", "https://evil.com", "evil.com", "1.2.3.4:5678", false},+ {"X-Forwarded-Host from trusted CIDR range matches origin", "internal.proxy", "https://multica.ai", "multica.ai", "10.5.6.7:5678", true},+ {"X-Forwarded-Host from trusted IPv6 proxy matches origin", "internal.proxy", "https://multica.ai", "multica.ai", "[::1]:5678", true},+ {"X-Forwarded-Host comma list uses first (client-facing) value", "internal.proxy", "https://multica.ai", "multica.ai, proxy.internal", "127.0.0.1:5678", true},+ {"X-Forwarded-Host comma list ignores trailing values", "internal.proxy", "https://app.multica.ai", "proxy.internal, app.multica.ai", "127.0.0.1:5678", false},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {r := httptest.NewRequest(http.MethodGet, "/ws", nil)r.Host = tc.host+ r.RemoteAddr = tc.remoteAddrif tc.origin != "" {r.Header.Set("Origin", tc.origin)}+ if tc.fwdHost != "" {+ r.Header.Set("X-Forwarded-Host", tc.fwdHost)+ }if got := checkOrigin(r); got != tc.want {- t.Fatalf("checkOrigin(host=%q, origin=%q) = %v, want %v", tc.host, tc.origin, got, tc.want)+ t.Fatalf("checkOrigin(host=%q, origin=%q, X-Forwarded-Host=%q, remoteAddr=%q) = %v, want %v", tc.host, tc.origin, tc.fwdHost, tc.remoteAddr, got, tc.want)}})}