gent-link 0.2.0

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Direct TLS termination on the owner's node. No forwarded-header trust and
//! no request logging: even metadata and tool arguments can be private.
use super::mtls::{self, Peer};
use super::{Registry, Run};
use crate::{managed_file, mcp::GentMcp};
use anyhow::{Context, Result, ensure};
use axum::{
    Router,
    body::Body,
    extract::State,
    http::{HeaderMap, Request, StatusCode, header},
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::any_service,
};
use hyper_util::{
    rt::{TokioIo, TokioTimer},
    service::TowerToHyperService,
};
use rmcp::transport::streamable_http_server::{
    StreamableHttpServerConfig, StreamableHttpService, session::never::NeverSessionManager,
};
use std::{net::SocketAddr, path::PathBuf, sync::Arc, time::Duration};
use tokio::{
    io::{AsyncRead, AsyncWrite},
    net::TcpListener,
    task::JoinSet,
};
use tokio_rustls::{TlsAcceptor, rustls};
use tokio_util::sync::CancellationToken;

const MAX_CONNECTIONS: usize = 64;
const REQUEST_TIME: Duration = Duration::from_secs(30);
const CONNECTION_TIME: Duration = Duration::from_secs(60);
mod oauth;

#[cfg(test)]
mod tests;

#[derive(Clone)]
struct Boundary {
    home: PathBuf,
    registry: Registry,
    host: String,
    origin: String,
    metadata: Arc<super::metadata::runtime::Runtime>,
}

fn one<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    let mut values = headers.get_all(name).iter();
    let first = values.next()?.to_str().ok()?;
    if values.next().is_some() {
        None
    } else {
        Some(first)
    }
}

impl Boundary {
    fn validate(&self, request: &Request<Body>) -> Result<()> {
        ensure!(
            (request.uri().query().is_none()
                || matches!(request.uri().path(), "/oauth/authorize" | "/oauth/continue"))
                && request.uri().scheme().is_none()
                && request.uri().authority().is_none(),
            "invalid request target"
        );
        let headers = request.headers();
        ensure!(
            one(headers, "host") == Some(self.host.as_str()),
            "invalid host"
        );
        ensure!(
            request.uri().path().starts_with("/files/")
                || !headers.contains_key("origin")
                || one(headers, "origin")
                    == Some(
                        url::Url::parse(&self.origin)?
                            .origin()
                            .ascii_serialization()
                            .as_str()
                    ),
            "invalid origin"
        );
        ensure!(
            !headers.keys().any(|h| h == "forwarded"
                || h.as_str().starts_with("x-forwarded-")
                || h == "x-real-ip"),
            "forwarded requests are unsupported"
        );
        Ok(())
    }
}

async fn guard(
    State(boundary): State<Boundary>,
    mut request: Request<Body>,
    next: Next,
) -> Response {
    let response = async {
        if boundary.validate(&request).is_err() {
            return StatusCode::FORBIDDEN.into_response();
        }
        if let Some(token) = request.uri().path().strip_prefix("/files/") {
            return boundary
                .registry
                .downloads
                .handle(
                    &boundary.registry,
                    &boundary.home,
                    token,
                    request.method(),
                    request.headers(),
                )
                .await;
        }
        let url_token =
            gent_protocol::hosted_mcp::capability_token(request.uri().path()).map(str::to_owned);
        if request.uri().path().starts_with("/mcp/") && url_token.is_none() {
            return StatusCode::NOT_FOUND.into_response();
        }
        if url_token.is_none() {
            match boundary.registry.url_only_remote().await {
                // Named connectors authenticate only with their complete URL.
                // Discovery probes must not advertise an unusable OAuth flow.
                Ok(true) => return StatusCode::NOT_FOUND.into_response(),
                Ok(false) => {}
                Err(_) => return oauth::busy(),
            }
        }
        if request.uri().path() != "/mcp" && url_token.is_none() {
            return oauth::handle(&boundary, request).await;
        }
        let by_url = url_token.is_some();
        if by_url && request.headers().contains_key(header::AUTHORIZATION) {
            return StatusCode::BAD_REQUEST.into_response();
        }
        let token = url_token.or_else(|| {
            one(request.headers(), "authorization")
                .and_then(|s| s.strip_prefix("Bearer "))
                .filter(|s| s.len() <= 128)
                .map(str::to_owned)
        });
        // The SDK sees the authorization decision, never the raw bearer.
        request.headers_mut().remove(header::AUTHORIZATION);
        let Some(token) = token else {
            return oauth::challenge(&boundary.origin);
        };
        let permit = if by_url {
            boundary.registry.authenticate_url_remote(token).await
        } else {
            boundary
                .registry
                .authenticate_remote(
                    token,
                    format!("{}/mcp", boundary.origin),
                    request
                        .extensions()
                        .get::<Peer>()
                        .cloned()
                        .unwrap_or_default(),
                )
                .await
        };
        let permit = match permit {
            Ok(permit) => permit,
            Err(error) if error.is::<super::registry::Busy>() => return oauth::busy(),
            Err(_) if by_url => return StatusCode::NOT_FOUND.into_response(),
            Err(_) => return oauth::challenge(&boundary.origin),
        };
        if by_url {
            // Remove the raw URL and axum's original URI/path parameters before
            // handing the request to the MCP SDK or a tool implementation.
            *request.uri_mut() = "/mcp".parse().unwrap();
            request.extensions_mut().clear();
        }
        request.extensions_mut().insert(permit);
        next.run(request).await
    };
    let mut response = tokio::time::timeout(REQUEST_TIME, response)
        .await
        .unwrap_or_else(|_| StatusCode::REQUEST_TIMEOUT.into_response());
    response
        .headers_mut()
        .insert(header::CACHE_CONTROL, "no-store".parse().unwrap());
    response
        .headers_mut()
        .insert("referrer-policy", "no-referrer".parse().unwrap());
    response
        .headers_mut()
        .insert("x-content-type-options", "nosniff".parse().unwrap());
    response
        .headers_mut()
        .entry("content-security-policy")
        .or_insert(
            "default-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"
                .parse()
                .unwrap(),
        );
    response
}

fn origin(options: &Run, bound: SocketAddr) -> Result<(String, String)> {
    ensure!(
        options.tls_cert.is_some() == options.tls_key.is_some()
            && options.tls_cert.is_some() == options.origin.is_some(),
        "direct TLS needs --tls-cert, --tls-key and --origin"
    );
    if let Some(origin) = &options.origin {
        let url = url::Url::parse(origin).context("invalid gateway HTTPS origin")?;
        ensure!(
            url.scheme() == "https"
                && url.host_str().is_some()
                && url.username().is_empty()
                && url.password().is_none()
                && url.path() == "/"
                && url.query().is_none()
                && url.fragment().is_none(),
            "gateway origin must be an HTTPS origin without credentials, path, query or fragment"
        );
        let canonical = url.origin().ascii_serialization();
        ensure!(
            *origin == canonical,
            "use the canonical HTTPS origin without a trailing slash"
        );
        Ok((
            url[url::Position::BeforeHost..url::Position::AfterPort].to_string(),
            canonical,
        ))
    } else {
        ensure!(
            bound.ip().is_loopback(),
            "non-loopback listeners require direct TLS"
        );
        Ok((bound.to_string(), format!("http://{bound}")))
    }
}

fn tls(options: &Run, policies: &[mtls::Policy]) -> Result<Option<TlsAcceptor>> {
    let (Some(cert), Some(key)) = (&options.tls_cert, &options.tls_key) else {
        return Ok(None);
    };
    let cert = managed_file::Snapshot::read(cert)?;
    let key = managed_file::Snapshot::read(key)?;
    key.private()?;
    let cert_text = cert
        .text
        .as_deref()
        .context("TLS certificate file is missing")?;
    let key_text = key.text.as_deref().context("TLS key file is missing")?;
    ensure!(
        cert_text.len() <= 64 * 1024 && key_text.len() <= 64 * 1024,
        "TLS PEM file is too large"
    );
    let certs =
        rustls_pemfile::certs(&mut cert_text.as_bytes()).collect::<std::io::Result<Vec<_>>>()?;
    let key_der = rustls_pemfile::private_key(&mut key_text.as_bytes())?
        .context("missing TLS private key")?;
    let builder = rustls::ServerConfig::builder_with_provider(mtls::provider())
        .with_safe_default_protocol_versions()?;
    let builder = if policies.is_empty() {
        builder.with_no_client_auth()
    } else {
        builder.with_client_cert_verifier(mtls::verifier(policies)?)
    };
    let mut config = builder.with_single_cert(certs, key_der)?;
    config.alpn_protocols = vec![b"http/1.1".to_vec()];
    cert.verify()?;
    key.verify()?;
    Ok(Some(TlsAcceptor::from(Arc::new(config))))
}

pub(super) fn router(
    home: PathBuf,
    registry: Registry,
    host: String,
    origin: String,
    stop: CancellationToken,
    metadata: Arc<super::metadata::runtime::Runtime>,
) -> Router {
    let config = StreamableHttpServerConfig::default()
        .with_legacy_session_mode(false)
        .with_json_response(true)
        .with_max_request_body_bytes(gent_protocol::MAX_FRAME_BYTES)
        .with_allowed_hosts([host.clone()])
        .with_allowed_origins([url::Url::parse(&origin)
            .expect("validated origin")
            .origin()
            .ascii_serialization()])
        .enforce_origin_validation()
        .with_cancellation_token(stop);
    let binding = registry.clone();
    let gateway_home = home.clone();
    let service = StreamableHttpService::new(
        move || Ok(GentMcp::remote(home.clone(), binding.clone())),
        Arc::new(NeverSessionManager::default()),
        config,
    );
    Router::new()
        .route_service("/mcp", any_service(service.clone()))
        .route_service("/mcp/{credential}", any_service(service))
        .layer(middleware::from_fn_with_state(
            Boundary {
                home: gateway_home,
                registry,
                host,
                origin,
                metadata,
            },
            guard,
        ))
}

async fn connection<T: AsyncRead + AsyncWrite + Unpin + Send + 'static>(
    io: T,
    app: Router,
    stop: CancellationToken,
) {
    let mut builder = hyper::server::conn::http1::Builder::new();
    builder
        .timer(TokioTimer::new())
        .header_read_timeout(Duration::from_secs(10))
        .max_headers(64)
        .max_buf_size(16 * 1024);
    // Connection failures carry no useful user action and may include private
    // request data; deliberately do not print errors from peers.
    let connection = builder.serve_connection(TokioIo::new(io), TowerToHyperService::new(app));
    tokio::pin!(connection);
    tokio::select! {
        _ = &mut connection => {},
        _ = stop.cancelled() => {
            connection.as_mut().graceful_shutdown();
            let _ = connection.await;
        }
    }
}

async fn serve(
    listener: TcpListener,
    app: Router,
    tls: Option<TlsAcceptor>,
    stop: CancellationToken,
) -> Result<()> {
    let mut tasks = JoinSet::new();
    loop {
        tokio::select! {
            biased;
            _=stop.cancelled()=>break,
            Some(_)=tasks.join_next(), if !tasks.is_empty()=>{},
            accepted=listener.accept()=> {
                let (socket,_)=accepted?;
                if tasks.len()>=MAX_CONNECTIONS {continue;}
                let app=app.clone();
                let tls=tls.clone();
                let drain = stop.clone();
                tasks.spawn(async move {
                    let _=tokio::time::timeout(CONNECTION_TIME,async move {
                        if let Some(tls)=tls {
                            if let Ok(Ok(stream))=tokio::time::timeout(Duration::from_secs(10),tls.accept(socket)).await
                                && let Ok(peer)=Peer::from_tls(stream.get_ref().1.peer_certificates()) {
                                connection(stream,app.layer(axum::Extension(peer)),drain).await;
                            }
                        } else {connection(socket,app,drain).await;}
                    }).await;
                });
            }
        }
    }
    drop(listener);
    while tasks.join_next().await.is_some() {}
    Ok(())
}

pub(super) async fn run(home: PathBuf, options: Run, drain: CancellationToken) -> Result<()> {
    if options.hosted.is_some() {
        return super::hosted::run_until(home, options, drain).await;
    }
    let registry = Registry::open(&home)?.with_file_origins(&options.file_origin)?;
    let _lock = managed_file::lock(&home.join("gateway/runtime.lock"))?;
    // Validate exposure before binding any non-loopback socket.
    origin(&options, options.listen)?;
    let tls = tls(&options, &registry.tls_policies()?)?;
    let listener = TcpListener::bind(options.listen).await?;
    let address = listener.local_addr()?;
    let (host, origin) = origin(&options, address)?;
    let registry = registry.with_file_downloads(&options.file_downloads, &origin)?;
    let stop = CancellationToken::new();
    let metadata = super::metadata::runtime::Runtime::new(
        registry.clone(),
        format!("{origin}/mcp"),
        &options.client_metadata,
    )
    .await?;
    let control = super::control::Server::bind(&home)?;
    let app = router(home, registry, host, origin.clone(), stop.clone(), metadata);
    let mut terminate = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
    eprintln!("Gent gateway: {origin}/mcp (user-controlled endpoint, listening on {address})");
    let serving = serve(listener, app, tls, drain.clone());
    tokio::pin!(serving);
    let result = tokio::select! {
        result=&mut serving => result,
        result=control.serve(address,&origin)=>result,
        result=tokio::signal::ctrl_c()=>{ result?; drain.cancel(); serving.await },
        _=terminate.recv()=>{ drain.cancel(); serving.await },
    };
    stop.cancel();
    result
}

/// Check every saved capability before writing or restarting a service.
pub(super) async fn validate(home: &std::path::Path, options: &Run) -> Result<()> {
    if options.hosted.is_some() {
        return super::hosted::validate(home, options).await;
    }
    let (_, origin) = origin(options, options.listen)?;
    let registry = Registry::open(home)?.with_file_origins(&options.file_origin)?;
    tls(options, &registry.tls_policies()?)?;
    let registry = registry.with_file_downloads(&options.file_downloads, &origin)?;
    super::metadata::runtime::Runtime::new(
        registry,
        format!("{origin}/mcp"),
        &options.client_metadata,
    )
    .await?;
    Ok(())
}