package proxy import ( "errors" "io" "log" "github.com/mcp-runtime/mcp-runtime/pkg/transport/httptrace" "net/http" "net/url" "path" "strings" "time" "github.com/mcp-runtime/mcp-runtime/pkg/httpx" "github.com/mcp-runtime/mcp-runtime/pkg/passport" "github.com/mcp-runtime/mcp-runtime/services/ui/internal/session" ) const ( DefaultRuntimeUpstream = "http://mcp-runtime-api.mcp-platform.svc.cluster.local:8084" DefaultAnalyticsUpstream = "http://mcp-analytics-api.mcp-observability.svc.cluster.local:8085" SessionAPIPrefix = "/api/ui/v1" sessionProxyTimeout = 15 * time.Second ) var sessionProxyRuntimePrefixes = []string{ "/dashboard/summary", "/runtime/workspace/teams", "/runtime/workspace/servers", "/runtime/workspace/access", "/admin/overview/directory", "/admin/overview/servers", "/runtime/namespaces", "/runtime/servers", "/runtime/tools", "/runtime/server-events", "/runtime/observability/links", "/runtime/observability/prometheus/query", "/runtime/observability/metrics", "/runtime/observability/logs/query", "/runtime/observability/traces", "/runtime/teams", "/runtime/agents", "/runtime/delegation-recipients", "/runtime/grants", "/runtime/sessions", "/runtime/components", "/runtime/actions/restart", "/runtime/policy", "/admin/operations", "/admin/deployments", } // Platform-api owns identity state, so these routes go to it directly. The // stored platform bearer already has platform-api's audience and is forwarded // unchanged; there is no exchange for the service that issues the exchange. var sessionProxyPlatformPrefixes = []string{ "/user/api-keys", } var sessionProxyAnalyticsPrefixes = []string{ "/events", "/analytics/usage", "/user/analytics/usage", } // State-changing routes are kept separate from the read allowlist. A route is // admitted only for the listed methods and, when Segments is non-zero, the // exact number of path segments after Prefix. var sessionProxyWriteRoutes = []sessionProxyWriteRoute{ {Prefix: "/user/api-keys", Methods: []string{http.MethodPost}}, {Prefix: "/user/api-keys/", Methods: []string{http.MethodDelete}, Segments: 1}, {Prefix: "/runtime/grants/", Methods: []string{http.MethodPatch, http.MethodDelete}, Segments: 2}, {Prefix: "/runtime/grants/", Methods: []string{http.MethodPost}, Segments: 3, Suffixes: []string{"revoke-sessions"}}, {Prefix: "/runtime/grants", Methods: []string{http.MethodPost}}, {Prefix: "/runtime/sessions/", Methods: []string{http.MethodPatch, http.MethodDelete}, Segments: 2}, {Prefix: "/runtime/sessions", Methods: []string{http.MethodPost}}, {Prefix: "/runtime/teams", Methods: []string{http.MethodPost}}, {Prefix: "/runtime/teams/", Methods: []string{http.MethodPost}, Segments: 2, Suffixes: []string{"members", "users"}}, {Prefix: "/runtime/teams/", Methods: []string{http.MethodPost}, Segments: 2, Suffixes: []string{"agents"}}, {Prefix: "/runtime/teams/", Methods: []string{http.MethodPut, http.MethodDelete}, Segments: 3, Suffixes: []string{"members"}, SuffixIndex: 1}, {Prefix: "/runtime/agents/", Methods: []string{http.MethodPatch}, Segments: 1}, {Prefix: "/runtime/agents/", Methods: []string{http.MethodPost}, Segments: 2, Suffixes: []string{"deactivate", "reactivate"}}, {Prefix: "/runtime/actions/restart", Methods: []string{http.MethodPost}}, {Prefix: "/runtime/servers/", Methods: []string{http.MethodDelete}, Segments: 2}, } type sessionProxyWriteRoute struct { Prefix string Methods []string Segments int Suffixes []string SuffixIndex int } func sessionProxyWriteRouteMatches(route sessionProxyWriteRoute, requestPath string) bool { if route.Segments == 0 { return requestPath == route.Prefix } rest, ok := strings.CutPrefix(requestPath, route.Prefix) if !ok || rest == "" || strings.HasPrefix(rest, "/") || strings.HasSuffix(rest, "/") { return false } parts := strings.Split(rest, "/") if len(parts) != route.Segments { return false } if len(route.Suffixes) == 0 { return true } index := len(parts) - 1 if route.SuffixIndex > 0 { index = route.SuffixIndex } for _, suffix := range route.Suffixes { if parts[index] == suffix { return true } } return false } func sessionProxyWriteAllowed(method, requestPath string) bool { for _, route := range sessionProxyWriteRoutes { if !sessionProxyWriteRouteMatches(route, requestPath) { continue } for _, allowed := range route.Methods { if allowed == method { return true } } } return false } func sessionProxyAllowHeader(requestPath string) string { methods := []string{http.MethodGet} for _, route := range sessionProxyWriteRoutes { if sessionProxyWriteRouteMatches(route, requestPath) { methods = append(methods, route.Methods...) } } return strings.Join(methods, ", ") } const sessionProxyMaxWriteBody = 32 * 1024 // NewHTTPClient retains the browser proxy's bounded, non-redirecting transport. func NewHTTPClient() *http.Client { return &http.Client{Timeout: sessionProxyTimeout, Transport: httptrace.TracedTransport(nil), CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} } type SessionProxy struct { platformBase *url.URL runtimeBase *url.URL analyticsBase *url.URL store *session.Store client *http.Client } func ParseUpstream(raw string) (*url.URL, error) { base := strings.TrimSpace(raw) if base == "" { return nil, errors.New("runtime upstream is empty") } u, err := url.Parse(base) if err != nil { return nil, err } if u.Scheme != "http" && u.Scheme != "https" { return nil, errors.New("runtime upstream must use http or https") } if u.Host == "" { return nil, errors.New("runtime upstream must include scheme and host") } if u.User != nil { return nil, errors.New("runtime upstream must not include userinfo") } u.RawQuery = "" u.Fragment = "" return u, nil } func NewSessionProxy(platformBase, runtimeBase, analyticsBase *url.URL, store *session.Store, httpClient *http.Client) *SessionProxy { return &SessionProxy{ platformBase: platformBase, runtimeBase: runtimeBase, analyticsBase: analyticsBase, store: store, client: httpClient, } } func sessionProxyUpstreamPath(requestPath string) (string, bool) { _, upstreamPath, ok := sessionProxyRoute(requestPath) return upstreamPath, ok } func sessionProxyRoute(requestPath string) (*url.URL, string, bool) { cleaned := path.Clean("/" + strings.TrimPrefix(strings.TrimSpace(requestPath), "/")) suffix, ok := strings.CutPrefix(cleaned, SessionAPIPrefix) if !ok || suffix == "" { return nil, "", false } if sessionProxyPathAllowed(suffix, sessionProxyRuntimePrefixes) { return nil, "/api/v1" + suffix, true } if sessionProxyPathAllowed(suffix, sessionProxyAnalyticsPrefixes) { return nil, "/api/v1" + suffix, true } if sessionProxyPathAllowed(suffix, sessionProxyPlatformPrefixes) { return nil, "/api/v1" + suffix, true } return nil, "", false } func sessionProxyPathAllowed(requestPath string, prefixes []string) bool { for _, prefix := range prefixes { if requestPath == prefix || strings.HasPrefix(requestPath, prefix+"/") { return true } } return false } func (p *SessionProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { write := unsafeHTTPMethod(r.Method) _, upstreamPath, ok := sessionProxyRoute(r.URL.Path) if !ok { httpx.WriteJSON(w, http.StatusNotFound, map[string]string{"error": "not_found"}) return } if write { suffix := strings.TrimPrefix(upstreamPath, "/api/v1") if !sessionProxyWriteAllowed(r.Method, suffix) { w.Header().Set("allow", sessionProxyAllowHeader(suffix)) httpx.WriteJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method_not_allowed"}) return } } sess, ok := p.store.FromRequest(r) if !ok { httpx.WriteJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return } authHeader, apiKey, ok := sessionUpstreamCredential(sess) if !ok { httpx.WriteJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"}) return } if status := verifyCSRF(r, sess); status != 0 { // #nosec G706 -- path-only telemetry; no credential or token material. log.Printf("ui session proxy csrf rejection method=%q path=%q", r.Method, r.URL.Path) httpx.WriteJSON(w, status, map[string]string{"error": "csrf_failed"}) return } var body io.Reader if write && r.Body != nil { body = http.MaxBytesReader(w, r.Body, sessionProxyMaxWriteBody) } targetAudience := passport.AudienceRuntime base := p.runtimeBase platformTarget := sessionProxyPathAllowed(strings.TrimPrefix(upstreamPath, "/api/v1"), sessionProxyPlatformPrefixes) switch { case platformTarget: base = p.platformBase case strings.HasPrefix(upstreamPath, "/api/v1/events") || strings.HasPrefix(upstreamPath, "/api/v1/analytics/usage") || strings.HasPrefix(upstreamPath, "/api/v1/user/analytics/usage"): base = p.analyticsBase targetAudience = passport.AudienceAnalytics } upstreamURL, err := resolveSessionProxyURL(base, upstreamPath, r.URL.RawQuery) if err != nil { httpx.WriteJSON(w, http.StatusBadGateway, map[string]string{"error": "upstream_error"}) return } req, err := http.NewRequestWithContext(r.Context(), r.Method, upstreamURL.String(), body) if err != nil { httpx.WriteJSON(w, http.StatusBadGateway, map[string]string{"error": "upstream_error"}) return } if accept := strings.TrimSpace(r.Header.Get("accept")); accept != "" { req.Header.Set("accept", accept) } else { req.Header.Set("accept", "application/json") } if write { contentType := strings.TrimSpace(r.Header.Get("content-type")) if contentType == "" { contentType = "application/json" } req.Header.Set("content-type", contentType) } copySessionProxyOriginHeaders(req, r) req.Header.Set("x-mcp-source", "ui") client := p.client if client == nil { client = NewHTTPClient() } if authHeader != "" && platformTarget { req.Header.Set("authorization", authHeader) } else if authHeader != "" { authHeader, err = passport.ExchangeBearer(r.Context(), client, p.platformBase, authHeader, targetAudience) if err != nil { status := http.StatusBadGateway if errors.Is(err, passport.ErrExchangeUnauthorized) { status = http.StatusUnauthorized } httpx.WriteJSON(w, status, map[string]string{"error": "token_exchange_failed"}) return } req.Header.Set("authorization", authHeader) } else { req.Header.Set("x-api-key", apiKey) } resp, err := client.Do(req) if err != nil { var tooLarge *http.MaxBytesError if errors.As(err, &tooLarge) { httpx.WriteJSON(w, http.StatusRequestEntityTooLarge, map[string]string{"error": "request_too_large"}) return } // #nosec G706 -- path-only telemetry; upstream URL and credentials are omitted. log.Printf("ui session proxy upstream error path=%q", r.URL.Path) httpx.WriteJSON(w, http.StatusBadGateway, map[string]string{"error": "upstream_error"}) return } copySessionProxyResponse(w, resp, true) } func sessionUpstreamCredential(sess session.Session) (authHeader, apiKey string, ok bool) { if header := strings.TrimSpace(sess.UpstreamAuthHeader); header != "" { return header, "", true } if key := strings.TrimSpace(sess.UpstreamAPIKey); key != "" { return "", key, true } return "", "", false } func resolveSessionProxyURL(base *url.URL, upstreamPath, rawQuery string) (*url.URL, error) { if base == nil { return nil, errors.New("runtime upstream is empty") } if !strings.HasPrefix(upstreamPath, "/") || strings.HasPrefix(upstreamPath, "//") { return nil, errors.New("runtime upstream path must be absolute") } // upstreamPath is already decoded. Assign it as a path instead of parsing it // as a URL, otherwise a decoded '?' or '#' would split off a query or // fragment and silently truncate the path the allowlist approved. resolved := *base resolved.Path = upstreamPath resolved.RawPath = "" resolved.RawQuery = rawQuery resolved.Fragment = "" return &resolved, nil } // copySessionProxyOriginHeaders preserves the public origin used by the // runtime API when the dashboard is reached through an ingress or proxy. func copySessionProxyOriginHeaders(dst, src *http.Request) { if forwardedHost := strings.TrimSpace(src.Header.Get("x-forwarded-host")); forwardedHost != "" { dst.Header.Set("x-forwarded-host", forwardedHost) } if forwardedProto := strings.TrimSpace(src.Header.Get("x-forwarded-proto")); forwardedProto != "" { dst.Header.Set("x-forwarded-proto", forwardedProto) } } // copySessionProxyResponse relays an upstream response. With noStore, the // proxied body is credential-adjacent (API keys, sessions, tenant data), so the // upstream's own caching validators are dropped and the response is pinned to // no-store rather than appended to whatever the upstream asked for. func copySessionProxyResponse(w http.ResponseWriter, resp *http.Response, noStore bool) { defer drainAndClose(resp.Body) dst := w.Header() for key, values := range resp.Header { if skipSessionProxyResponseHeader(key) { continue } if noStore { switch http.CanonicalHeaderKey(key) { case "Cache-Control", "Expires", "Pragma", "Etag", "Last-Modified", "Age": continue } } for _, value := range values { dst.Add(key, value) } } if noStore { dst.Set("Cache-Control", "no-store") } w.WriteHeader(resp.StatusCode) _, _ = io.Copy(w, resp.Body) } func skipSessionProxyResponseHeader(key string) bool { switch http.CanonicalHeaderKey(key) { case "Authorization", "Cookie", "Set-Cookie", "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Te", "Trailer", "Trailers", "Transfer-Encoding", "Upgrade": return true default: return false } }