// Package httpx holds the transport-level middleware streamd wraps around its // mux: real-client-IP resolution behind a trusted reverse proxy, security // headers, a strict CORS policy and an access log. package httpx import ( "log/slog" "net" "net/http" "strings" "time" ) // ParseCIDRs turns a comma-separated list of CIDRs or bare IPs into networks. // Bare IPs become single-host networks, so --trusted-proxies 10.0.0.5 works. func ParseCIDRs(list string) ([]*net.IPNet, error) { var out []*net.IPNet for _, raw := range strings.Split(list, ",") { raw = strings.TrimSpace(raw) if raw == "" { continue } if _, n, err := net.ParseCIDR(raw); err == nil { out = append(out, n) continue } ip := net.ParseIP(raw) if ip == nil { return nil, &net.ParseError{Type: "CIDR or IP address", Text: raw} } bits := 32 if ip.To4() == nil { bits = 128 } out = append(out, &net.IPNet{IP: ip, Mask: net.CIDRMask(bits, bits)}) } return out, nil } // Trust decides whether forwarded headers may be believed. type Trust struct { Proxies []*net.IPNet } func (t Trust) trusted(ip net.IP) bool { if ip == nil { return false } for _, n := range t.Proxies { if n.Contains(ip) { return true } } return false } // ClientIP returns the caller's address. X-Forwarded-For is honoured only when // the immediate peer is a configured trusted proxy; otherwise the peer address // wins, so a stranger cannot spoof their IP to dodge a rate limit. func (t Trust) ClientIP(r *http.Request) string { peer := peerIP(r) if !t.trusted(net.ParseIP(peer)) { return peer } // Right-most entry is the one our trusted proxy appended; walk from the // right to the first address that is not itself a trusted proxy. xff := r.Header.Get("X-Forwarded-For") parts := strings.Split(xff, ",") for i := len(parts) - 1; i >= 0; i-- { cand := strings.TrimSpace(parts[i]) if cand == "" { continue } ip := net.ParseIP(cand) if ip == nil { continue } if !t.trusted(ip) { return ip.String() } } if real := strings.TrimSpace(r.Header.Get("X-Real-IP")); real != "" { if ip := net.ParseIP(real); ip != nil { return ip.String() } } return peer } // IsHTTPS reports whether the original client request used TLS, trusting // X-Forwarded-Proto only from a trusted proxy. func (t Trust) IsHTTPS(r *http.Request) bool { if r.TLS != nil { return true } if !t.trusted(net.ParseIP(peerIP(r))) { return false } proto := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Forwarded-Proto"))) // A proxy chain may append, e.g. "https, http". if i := strings.IndexByte(proto, ','); i >= 0 { proto = strings.TrimSpace(proto[:i]) } return proto == "https" } func peerIP(r *http.Request) string { host, _, err := net.SplitHostPort(r.RemoteAddr) if err != nil { return strings.TrimSpace(r.RemoteAddr) } return host } // SecurityHeaders sets conservative defaults on every response. The CSP is // default-src 'self' throughout, which is why hls.js is vendored into the // embedded assets rather than loaded from a CDN. func SecurityHeaders(trust Trust, next http.Handler) http.Handler { const csp = "default-src 'self'; " + "script-src 'self'; " + "style-src 'self' 'unsafe-inline'; " + "img-src 'self' data:; " + "media-src 'self' blob:; " + "connect-src 'self' ws: wss:; " + "font-src 'self'; " + "object-src 'none'; " + "base-uri 'none'; " + "form-action 'self'; " + "frame-ancestors 'none'" return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() // Media responses are served to players and must stay cacheable and // embeddable; the policy above is for the dashboard documents. if !isMediaPath(r.URL.Path) { h.Set("Content-Security-Policy", csp) h.Set("X-Frame-Options", "DENY") h.Set("Referrer-Policy", "no-referrer") h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()") } h.Set("X-Content-Type-Options", "nosniff") if trust.IsHTTPS(r) { h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") } next.ServeHTTP(w, r) }) } func isMediaPath(p string) bool { return strings.HasPrefix(p, "/hls/") || strings.HasPrefix(p, "/live/") } // CORS echoes an Origin only when it is explicitly allowed. With no allowed // origins configured the API is same-origin only, which is the default. func CORS(allowed []string, next http.Handler) http.Handler { allow := map[string]bool{} wildcardMedia := false for _, o := range allowed { o = strings.TrimRight(strings.TrimSpace(o), "/") if o == "" { continue } if o == "*" { wildcardMedia = true continue } allow[strings.ToLower(o)] = true } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { origin := strings.TrimRight(strings.TrimSpace(r.Header.Get("Origin")), "/") if origin != "" { switch { case allow[strings.ToLower(origin)]: w.Header().Set("Access-Control-Allow-Origin", origin) w.Header().Set("Access-Control-Allow-Credentials", "true") w.Header().Add("Vary", "Origin") case wildcardMedia && isMediaPath(r.URL.Path): // A wildcard is only ever honoured for media, never for the // API, so credentials can never be read cross-origin. w.Header().Set("Access-Control-Allow-Origin", "*") } w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Streamd-Token, X-CSRF-Token, X-Agent-ID") w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS") w.Header().Set("Access-Control-Max-Age", "600") } if r.Method == http.MethodOptions { w.WriteHeader(http.StatusNoContent) return } next.ServeHTTP(w, r) }) } // StatusRecorder captures the response status and byte count for logging and // for the audit trail. type StatusRecorder struct { http.ResponseWriter Status int Bytes int64 } func (s *StatusRecorder) WriteHeader(code int) { if s.Status == 0 { s.Status = code } s.ResponseWriter.WriteHeader(code) } func (s *StatusRecorder) Write(b []byte) (int, error) { if s.Status == 0 { s.Status = http.StatusOK } n, err := s.ResponseWriter.Write(b) s.Bytes += int64(n) return n, err } // Flush forwards to the underlying writer so SSE and progressive TS keep // streaming through this wrapper. func (s *StatusRecorder) Flush() { if f, ok := s.ResponseWriter.(http.Flusher); ok { f.Flush() } } // Unwrap lets http.ResponseController reach the real writer (needed for // per-write deadlines on long-lived streaming responses). func (s *StatusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter } // AccessLog logs one line per request at debug level, and at info level for // 5xx responses so failures are visible without enabling debug. func AccessLog(lg *slog.Logger, trust Trust, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Media and websocket traffic is far too chatty for a per-request log. if isMediaPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/ws/") { next.ServeHTTP(w, r) return } start := time.Now() rec := &StatusRecorder{ResponseWriter: w} next.ServeHTTP(rec, r) if rec.Status == 0 { rec.Status = http.StatusOK } lvl := slog.LevelDebug if rec.Status >= 500 { lvl = slog.LevelInfo } lg.Log(r.Context(), lvl, "http", "method", r.Method, "path", r.URL.Path, "status", rec.Status, "bytes", rec.Bytes, "dur_ms", time.Since(start).Milliseconds(), "ip", trust.ClientIP(r), ) }) }