package server import ( "context" "net" "net/http" "strings" "git.a-wan.net/alan/pipelines/internal/protocol" "git.a-wan.net/alan/pipelines/internal/servertoken" ) // requestBoundary is the server's HTTP front door, applied before any route // (docs/notes/security-boundary.md): // // - Host: a connection that arrived on a loopback address must name a // loopback literal (127.0.0.1, localhost, [::1]) with the port it reached, // so a DNS-rebinding page (Host: rebind.example:8080) is refused with 421. // A connection that arrived on another interface exists only when the // server was explicitly bound beyond loopback; its Host is not checked. // - Origin: /connect refuses any request carrying Origin. Browsers always // send it on a WebSocket upgrade; the web proxy strips it and the CLI, the // TUI and the native app send none. // - Token: when the server is configured with the shared secret, every // request must carry it in servertoken.Header, except the chat-tools MCP // endpoint (its own per-chat token, loopback and no-Origin checks) and // /healthz (a bare liveness boolean). // - Session: protocol.SessionHeader names the web session a proxied request // belongs to (an opaque id the proxy derives from the verified cookie). It // is trusted only on a request that carried the configured token; it is // always removed from the request and, when trusted, reaches handlers // through the context (trustedSession). type requestBoundary struct { next http.Handler token string } func guardRequests(next http.Handler, token string) http.Handler { return requestBoundary{next: next, token: token} } func (b requestBoundary) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !allowedHost(r) { http.Error(w, "misdirected request: this server answers only its own loopback address", http.StatusMisdirectedRequest) return } if r.URL.Path == "/connect" && r.Header.Get("Origin") != "" { http.Error(w, "browser origins may not connect directly; use the web proxy", http.StatusForbidden) return } if b.token != "" && !tokenExempt(r.URL.Path) && !servertoken.Equal(r.Header.Get(servertoken.Header), b.token) { http.Error(w, "server token required", http.StatusUnauthorized) return } // The secret never reaches a handler, a log line or a forwarded request. r.Header.Del(servertoken.Header) session := r.Header.Get(protocol.SessionHeader) r.Header.Del(protocol.SessionHeader) if b.token != "" && validSessionID(session) { r = r.WithContext(context.WithValue(r.Context(), sessionContextKey{}, session)) } b.next.ServeHTTP(w, r) } type sessionContextKey struct{} // trustedSession is the web session id the token-authenticated proxy reported // for r, or "" (no server token configured, a direct client, or no header). func trustedSession(r *http.Request) string { session, _ := r.Context().Value(sessionContextKey{}).(string) return session } // validSessionID bounds the proxy's opaque id: 16 to 128 URL-safe characters. func validSessionID(value string) bool { if len(value) < 16 || len(value) > 128 { return false } for _, c := range value { if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_') { return false } } return true } func tokenExempt(path string) bool { return path == "/healthz" || strings.HasPrefix(path, chatToolPath) } // allowedHost applies the loopback Host rule. A request with no recorded local // address (an in-process test handler) has no listener to compare against. func allowedHost(r *http.Request) bool { local, ok := r.Context().Value(http.LocalAddrContextKey).(net.Addr) if !ok || local == nil { return true } localHost, localPort, err := net.SplitHostPort(local.String()) if err != nil { return false } if ip := net.ParseIP(localHost); ip == nil || !ip.IsLoopback() { return true } host, port, err := net.SplitHostPort(r.Host) if err != nil { // No port: only the default HTTP port could match. host, port = strings.TrimSuffix(strings.TrimPrefix(r.Host, "["), "]"), "80" } if port != localPort { return false } if strings.EqualFold(host, "localhost") { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() && !strings.Contains(host, "%") }