Skip to main content

winx_code_agent/
http_server.rs

1//! Optional remote MCP transport over Streamable HTTP.
2//!
3//! This is what lets a cloud client (e.g. ChatGPT "developer mode" custom
4//! connectors) talk to winx. The default stdio transport is for local clients
5//! (Claude Desktop, Cursor); this one serves the MCP protocol over HTTP at
6//! `/mcp` so it can sit behind an HTTPS tunnel (cloudflared/ngrok).
7//!
8//! # SECURITY
9//! winx exposes arbitrary shell execution and filesystem access. Serving it over
10//! the network is effectively remote code execution on this machine. Therefore:
11//! - a non-empty bearer token is **required**; every request must present it via
12//!   the `Authorization: Bearer <token>` header. A `?token=` query parameter is
13//!   rejected by default (it would leak the secret into proxy/tunnel logs and
14//!   browser history) unless the operator opts in with `--allow-query-token`, the
15//!   escape hatch for URL-only clients like ChatGPT;
16//! - bind to a loopback address and put an authenticated HTTPS tunnel in front —
17//!   never expose this straight to `0.0.0.0` on an untrusted network;
18//! - turn it off when you're done testing.
19
20// Module docs name products (ChatGPT, OAuth, cloudflared) — prose, not code idents.
21#![allow(clippy::doc_markdown)]
22
23use std::net::SocketAddr;
24use std::sync::Arc;
25use std::time::Duration;
26
27use axum::{
28    extract::{ConnectInfo, Request, State},
29    http::StatusCode,
30    middleware::{self, Next},
31    response::{IntoResponse, Response},
32    Router,
33};
34use rmcp::transport::streamable_http_server::{
35    session::local::LocalSessionManager, StreamableHttpServerConfig, StreamableHttpService,
36};
37use tower_http::limit::RequestBodyLimitLayer;
38use tower_http::timeout::TimeoutLayer;
39
40use crate::server::{SessionIsolation, WinxService};
41
42type BoxError = Box<dyn std::error::Error + Send + Sync>;
43
44/// Reject request bodies larger than this — caps an unbounded-POST DoS on the
45/// network-reachable RCE endpoint. Sized above the 50 MB per-file ceiling
46/// (`MAX_FILE_SIZE` in `read_files`/`file_write_or_edit`) so `FileWriteOrEdit`,
47/// which carries the file content inline in the JSON-RPC body, isn't rejected
48/// for large-but-legitimate writes over HTTP — the stdio transport has no such
49/// limit.
50const MAX_BODY_BYTES: usize = 64 * 1024 * 1024;
51
52/// Per-request wall-clock budget. Long-running shell commands run in the
53/// background (BashCommand `is_background`/`status_check`), so the HTTP request
54/// itself is always short-lived; a stuck request shouldn't pin a connection
55/// forever.
56const REQUEST_TIMEOUT: Duration = Duration::from_secs(120);
57
58/// Start the Streamable HTTP MCP server.
59///
60/// - `bind`: socket address to listen on, e.g. `127.0.0.1:8000`.
61/// - `token`: shared secret required on every request (must be non-empty).
62/// - `extra_hosts`: additional `Host` authorities to accept beyond loopback —
63///   add your tunnel hostname here (e.g. `abc.trycloudflare.com`), otherwise the
64///   built-in DNS-rebinding guard rejects requests coming through the tunnel.
65pub async fn start_http_server(
66    bind: &str,
67    token: String,
68    extra_hosts: Vec<String>,
69    allow_query_token: bool,
70) -> Result<(), BoxError> {
71    if token.trim().is_empty() {
72        return Err("refusing to start HTTP transport without a token (RCE exposure)".into());
73    }
74
75    let mut config = StreamableHttpServerConfig::default();
76    config.stateful_mode = true;
77    config.allowed_hosts.extend(extra_hosts);
78
79    // One shared WinxService across every request. Remote clients like ChatGPT
80    // are effectively stateless — they don't reuse the MCP session between tool
81    // calls — so a per-session service would throw away the shell that
82    // `Initialize` created before `BashCommand` runs ("Bash state not
83    // initialized"). Sharing one instance keeps shells alive for the server's
84    // lifetime; isolation between logical sessions is provided per `thread_id`
85    // by the service's internal session registry.
86    //
87    // Strict isolation: with many clients behind one shared token, an empty
88    // `thread_id` must NOT fall back to whoever was last active (that would land
89    // one client in another's shell). Strict mode disables that fallback. Two
90    // clients that deliberately reuse the same explicit `thread_id` still share a
91    // shell — real multi-tenant isolation needs per-client tokens, which the
92    // single shared-token model doesn't provide.
93    let shared = WinxService::with_isolation(SessionIsolation::Strict);
94    let mcp_service = StreamableHttpService::new(
95        move || Ok(shared.clone()),
96        Arc::new(LocalSessionManager::default()),
97        config,
98    );
99
100    // Layer order: the LAST `.layer()` is the outermost, so the body-size limit
101    // runs first (it can reject an oversized POST before auth even looks at it),
102    // then the timeout, then the token check, then the MCP service.
103    let auth = Arc::new(AuthConfig { token, allow_query: allow_query_token });
104    let app = Router::new()
105        .nest_service("/mcp", mcp_service)
106        .layer(middleware::from_fn_with_state(auth, require_token))
107        .layer(TimeoutLayer::with_status_code(StatusCode::REQUEST_TIMEOUT, REQUEST_TIMEOUT))
108        .layer(RequestBodyLimitLayer::new(MAX_BODY_BYTES));
109
110    let listener = tokio::net::TcpListener::bind(bind).await?;
111    tracing::warn!(
112        "winx remote MCP transport on http://{bind}/mcp — shell/file access is now \
113         network-reachable. Keep it behind an HTTPS tunnel and shut it down when done."
114    );
115    if allow_query_token {
116        tracing::warn!(
117            "--allow-query-token is ON: clients may authenticate via ?token=<secret> in the URL. \
118             Convenient for clients that only take a URL (ChatGPT), but the token will appear in \
119             tunnel/proxy access logs and browser history. Use only on ephemeral/trusted tunnels."
120        );
121    }
122    // `into_make_service_with_connect_info` puts the peer address in request
123    // extensions so the auth middleware can log who is hammering the endpoint.
124    axum::serve(listener, app.into_make_service_with_connect_info::<SocketAddr>()).await?;
125    Ok(())
126}
127
128/// Auth state shared with the token middleware.
129#[derive(Clone)]
130struct AuthConfig {
131    token: String,
132    /// When true, also accept the token via a `?token=` query parameter (opt-in,
133    /// for URL-only clients like ChatGPT). Off by default — see [`request_has_token`].
134    allow_query: bool,
135}
136
137/// Reject any request that doesn't carry the shared token.
138async fn require_token(
139    State(auth): State<Arc<AuthConfig>>,
140    ConnectInfo(peer): ConnectInfo<SocketAddr>,
141    request: Request,
142    next: Next,
143) -> Response {
144    if request_has_token(&request, &auth.token, auth.allow_query) {
145        next.run(request).await
146    } else {
147        // Log the peer (never the token) so brute-force attempts on this
148        // RCE-adjacent endpoint are visible.
149        tracing::warn!(
150            "rejected request from {peer} to {} — missing or invalid token",
151            request.uri().path()
152        );
153        (StatusCode::UNAUTHORIZED, "missing or invalid token\n").into_response()
154    }
155}
156
157/// True if the request presents the token via `Authorization: Bearer`, or — only
158/// when `allow_query` is set — via a `?token=` query parameter.
159///
160/// The header is the default and preferred path. A `?token=` query parameter
161/// leaks the secret into proxy/tunnel access logs, browser history, and `Referer`
162/// headers, so it stays OFF unless the operator explicitly opts in with
163/// `--allow-query-token` (the escape hatch for URL-only clients like ChatGPT).
164fn request_has_token(request: &Request, expected: &str, allow_query: bool) -> bool {
165    let header_ok = request
166        .headers()
167        .get(axum::http::header::AUTHORIZATION)
168        .and_then(|value| value.to_str().ok())
169        .and_then(|value| value.strip_prefix("Bearer "))
170        .is_some_and(|presented| constant_time_eq(presented.trim(), expected));
171    if header_ok {
172        return true;
173    }
174    allow_query
175        && query_token(request).is_some_and(|presented| constant_time_eq(presented, expected))
176}
177
178/// Extract the raw `token=` value from the request's query string, if present.
179///
180/// Minimal parser (no percent-decoding): winx tokens are hex (`openssl rand
181/// -hex`), so they never contain reserved characters. Compared constant-time by
182/// the caller.
183fn query_token(request: &Request) -> Option<&str> {
184    request.uri().query()?.split('&').find_map(|pair| pair.strip_prefix("token="))
185}
186
187/// Constant-time token comparison.
188///
189/// Comparing the raw bytes directly leaks the *length* of the expected token: an
190/// early `a.len() != b.len()` return (or a fold whose iteration count depends on
191/// the inputs) lets an attacker time responses to learn how long the secret is,
192/// shrinking the brute-force space. Instead we hash both sides to fixed 32-byte
193/// SHA-256 digests and compare those: the comparison always runs over 32 bytes
194/// regardless of input length, and hashing the (fixed) secret takes constant time.
195/// A digest match implies an input match by collision resistance.
196fn constant_time_eq(a: &str, b: &str) -> bool {
197    use sha2::{Digest, Sha256};
198    let ha = Sha256::digest(a.as_bytes());
199    let hb = Sha256::digest(b.as_bytes());
200    ha.iter().zip(hb.iter()).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
201}
202
203#[cfg(test)]
204mod tests {
205    #![allow(clippy::unwrap_used)]
206    use super::{constant_time_eq, request_has_token};
207    use axum::body::Body;
208    use axum::extract::Request;
209
210    #[test]
211    fn token_comparison() {
212        assert!(constant_time_eq("s3cret", "s3cret"));
213        assert!(!constant_time_eq("s3cret", "s3creT"));
214        assert!(!constant_time_eq("s3cret", "s3cret-longer"));
215        assert!(!constant_time_eq("", "x"));
216    }
217
218    fn req(uri: &str, auth: Option<&str>) -> Request {
219        let mut b = Request::builder().uri(uri);
220        if let Some(a) = auth {
221            b = b.header(axum::http::header::AUTHORIZATION, a);
222        }
223        b.body(Body::empty()).unwrap()
224    }
225
226    #[test]
227    fn accepts_valid_bearer_header() {
228        // Header works regardless of the query-token toggle.
229        assert!(request_has_token(&req("/mcp", Some("Bearer s3cret")), "s3cret", false));
230        assert!(request_has_token(&req("/mcp", Some("Bearer s3cret")), "s3cret", true));
231    }
232
233    #[test]
234    fn rejects_missing_and_wrong_header() {
235        assert!(!request_has_token(&req("/mcp", None), "s3cret", false));
236        assert!(!request_has_token(&req("/mcp", Some("Bearer nope")), "s3cret", false));
237        assert!(!request_has_token(&req("/mcp", Some("s3cret")), "s3cret", false));
238        // no "Bearer "
239    }
240
241    #[test]
242    fn query_token_rejected_when_not_allowed() {
243        // Default (allow_query=false): a `?token=` query param must NOT
244        // authenticate (it would leak the secret into proxy/tunnel logs).
245        assert!(!request_has_token(&req("/mcp?token=s3cret", None), "s3cret", false));
246    }
247
248    #[test]
249    fn query_token_accepted_only_when_opted_in() {
250        // With --allow-query-token, the query param authenticates...
251        assert!(request_has_token(&req("/mcp?token=s3cret", None), "s3cret", true));
252        // ...among other params, and still rejects a wrong value.
253        assert!(request_has_token(&req("/mcp?a=1&token=s3cret&b=2", None), "s3cret", true));
254        assert!(!request_has_token(&req("/mcp?token=nope", None), "s3cret", true));
255        assert!(!request_has_token(&req("/mcp", None), "s3cret", true));
256    }
257}