Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/cli/src/gateway/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,9 @@ pub(crate) fn post_verified(
.map(|byte| format!("{byte:02x}"))
.collect::<String>();
let authority = loopback_authority(&host, port);
let client_token = key.client_token();
let tunnel = format!(
"GET /bootstrap/tunnel HTTP/1.1\r\nHost: {authority}\r\nX-NeMo-Relay-Bootstrap-Fingerprint: {bootstrap_fingerprint}\r\nX-NeMo-Relay-Bootstrap-Nonce: {nonce}\r\nConnection: upgrade\r\nUpgrade: nemo-relay-tls\r\n\r\n"
"GET /bootstrap/tunnel HTTP/1.1\r\nHost: {authority}\r\nX-NeMo-Relay-Bootstrap-Fingerprint: {bootstrap_fingerprint}\r\nX-NeMo-Relay-Bootstrap-Nonce: {nonce}\r\n{BOOTSTRAP_CLIENT_TOKEN_HEADER}: {client_token}\r\nConnection: upgrade\r\nUpgrade: nemo-relay-tls\r\n\r\n"
Comment thread
willkill07 marked this conversation as resolved.
);
stream.write_all(tunnel.as_bytes()).map_err(|error| {
VerifiedHttpError::before_payload(format!(
Expand Down
41 changes: 19 additions & 22 deletions crates/cli/src/server/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ const HTTP_READ_TIMEOUT: Duration = Duration::from_secs(300);
#[derive(Clone)]
pub(crate) struct AppState {
pub(crate) config: GatewayConfig,
#[allow(dead_code)]
pub(crate) bootstrap_fingerprint: Option<String>,
pub(crate) bootstrap_challenge_key: Option<BootstrapChallengeKey>,
pub(crate) require_provider_client_token: bool,
Expand Down Expand Up @@ -668,25 +669,25 @@ async fn bootstrap_tls_tunnel(
else {
return StatusCode::FORBIDDEN.into_response();
};
let fingerprint_matches = state
.bootstrap_fingerprint
.as_deref()
.is_some_and(|actual| bool::from(actual.as_bytes().ct_eq(fingerprint.as_bytes())));
let (Some(key), Some(tls), Some(local_address)) = (
state.bootstrap_challenge_key.as_ref(),
state.bootstrap_tls.clone(),
state.local_address,
) else {
let Some(key) = state.bootstrap_challenge_key.as_ref() else {
return StatusCode::NOT_FOUND.into_response();
};
if !fingerprint_matches
let token_is_valid = headers
.get(BOOTSTRAP_CLIENT_TOKEN_HEADER)
Comment thread
willkill07 marked this conversation as resolved.
.and_then(|value| value.to_str().ok())
.is_some_and(|token| key.verify_client_token(token));
if !token_is_valid
|| headers
.get(http::header::UPGRADE)
.and_then(|value| value.to_str().ok())
!= Some("nemo-relay-tls")
{
return StatusCode::FORBIDDEN.into_response();
}
let (Some(tls), Some(local_address)) = (state.bootstrap_tls.clone(), state.local_address)
else {
return StatusCode::NOT_FOUND.into_response();
};
let proof = key.proof(fingerprint, nonce);
let upgrade = hyper::upgrade::on(&mut request);
tokio::spawn(async move {
Expand Down Expand Up @@ -762,24 +763,20 @@ async fn healthz(State(state): State<AppState>, headers: HeaderMap) -> Response
let mut response_headers = HeaderMap::new();
let compatible = match presented_fingerprint {
None => true,
Some(expected) => {
let fingerprint_matches = state
.bootstrap_fingerprint
.as_deref()
.is_some_and(|actual| bool::from(actual.as_bytes().ct_eq(expected.as_bytes())));
Some(fingerprint) => {
// Persistent configuration does not determine whether an existing
// gateway can serve this MCP connection. Bind the caller's
// fingerprint into the proof without requiring it to match the
// gateway's configuration fingerprint.
let nonce = headers
.get("x-nemo-relay-bootstrap-nonce")
.and_then(|value| value.to_str().ok())
.filter(|nonce| {
nonce.len() == 64 && nonce.bytes().all(|byte| byte.is_ascii_hexdigit())
});
match (
fingerprint_matches,
nonce,
state.bootstrap_challenge_key.as_ref(),
) {
(true, Some(nonce), Some(key)) => {
let proof = key.proof(expected, nonce);
match (nonce, state.bootstrap_challenge_key.as_ref()) {
(Some(nonce), Some(key)) => {
let proof = key.proof(fingerprint, nonce);
response_headers.insert(
"x-nemo-relay-bootstrap-proof",
HeaderValue::from_str(&proof).expect("bootstrap proof is an ASCII value"),
Expand Down
12 changes: 10 additions & 2 deletions crates/cli/tests/coverage/shared/gateway_client_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ fn verified_hook_payload_is_not_sent_before_the_tls_tunnel_is_authenticated() {
("XDG_CONFIG_HOME", Some(temp.path().as_os_str())),
("HOME", Some(temp.path().as_os_str())),
]);
crate::configuration::BootstrapChallengeKey::load().unwrap();
let key = crate::configuration::BootstrapChallengeKey::load().unwrap();
crate::gateway::tls::RelayTlsIdentity::load_or_create().unwrap();
let (url, request, server) = serve_once(
b"HTTP/1.1 101 Switching Protocols\r\nConnection: upgrade\r\nUpgrade: nemo-relay-tls\r\nContent-Length: 0\r\n\r\n",
Expand All @@ -413,9 +413,17 @@ fn verified_hook_payload_is_not_sent_before_the_tls_tunnel_is_authenticated() {
)
.unwrap_err();

let request = request.recv_timeout(Duration::from_secs(2)).unwrap();
let request = String::from_utf8(request.recv_timeout(Duration::from_secs(2)).unwrap()).unwrap();
assert_eq!(
header(
&request,
crate::configuration::BOOTSTRAP_CLIENT_TOKEN_HEADER
),
key.client_token()
);
assert!(
!request
.as_bytes()
.windows(19)
.any(|window| window == b"secret-hook-payload")
);
Expand Down
11 changes: 6 additions & 5 deletions crates/cli/tests/coverage/shared/mcp_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,7 @@ async fn mcp_session_serves_stdio_and_stops_heartbeat_on_eof() {
}

#[tokio::test]
async fn heartbeat_keeps_a_compatible_gateway_session_alive() {
async fn heartbeat_keeps_a_differently_configured_gateway_session_alive() {
let _plugin_guard = crate::test_support::PLUGIN_CONFIG_TEST_LOCK.lock().await;
let temp = tempfile::tempdir().unwrap();
let _bootstrap_home = BootstrapConfigHome::enter(&temp.path().join("xdg"));
Expand All @@ -316,19 +316,20 @@ async fn heartbeat_keeps_a_compatible_gateway_session_alive() {
..crate::configuration::GatewayConfig::default()
};
let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel();
let fingerprint = "test-fingerprint";
let gateway_fingerprint = "existing-gateway-fingerprint";
let client_fingerprint = "new-client-fingerprint";
let gateway = tokio::spawn(crate::server::serve_listener_with_bootstrap(
listener,
config,
fingerprint.into(),
gateway_fingerprint.into(),
Some(shutdown_rx),
));
let url = format!("http://{bind}");
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let probe_url = url.clone();
if tokio::task::spawn_blocking(move || {
crate::gateway::client::healthz_compatible(&probe_url, fingerprint)
crate::gateway::client::healthz_compatible(&probe_url, client_fingerprint)
})
.await
.unwrap()
Expand All @@ -355,7 +356,7 @@ async fn heartbeat_keeps_a_compatible_gateway_session_alive() {
let observed_tx = observed_tx.clone();
async move {
let healthy = tokio::task::spawn_blocking(move || {
crate::gateway::client::healthz_compatible(&url, fingerprint)
crate::gateway::client::healthz_compatible(&url, client_fingerprint)
})
.await
.map_err(|error| {
Expand Down
128 changes: 125 additions & 3 deletions crates/cli/tests/coverage/shared/server_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@ use tower::ServiceExt;
use super::*;
use crate::configuration::BootstrapChallengeKey;
use crate::error::CliError;
use crate::gateway::tls::RelayTlsIdentity;
use crate::plugins::lifecycle::ActiveDynamicPluginComponent;
use crate::test_support::PLUGIN_CONFIG_TEST_LOCK;
use crate::test_support::{EnvScope, PLUGIN_CONFIG_TEST_LOCK};

const GENERIC_TEST_PLUGIN_KIND: &str = "cli-test-generic-plugin";
static GENERIC_TEST_PLUGIN_REGISTRATIONS: AtomicUsize = AtomicUsize::new(0);
Expand Down Expand Up @@ -483,7 +484,56 @@ async fn healthz_returns_ok() {
}

#[tokio::test]
async fn healthz_rejects_a_different_persistent_gateway_fingerprint() {
async fn healthz_accepts_a_different_persistent_gateway_fingerprint() {
let challenge_key = BootstrapChallengeKey::from_bytes(b"test challenge key");
let app = router_with_state(AppState::new_with_bootstrap(
test_config(),
Some("expected-fingerprint".into()),
Some(challenge_key.clone()),
false,
None,
None,
));
let response = app
.oneshot(
Request::builder()
.method("GET")
.uri("/healthz")
.header(
"x-nemo-relay-bootstrap-fingerprint",
"different-fingerprint",
)
.header(
"x-nemo-relay-bootstrap-nonce",
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
)
.body(Body::empty())
.unwrap(),
Comment thread
willkill07 marked this conversation as resolved.
)
.await
.unwrap();

assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response
.headers()
.get("x-nemo-relay-bootstrap-proof")
.unwrap(),
challenge_key
.proof(
"different-fingerprint",
"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
)
.as_str()
);
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["status"], json!("ok"));
assert!(body.get("bootstrap_fingerprint").is_none());
}

#[tokio::test]
async fn healthz_rejects_a_missing_bootstrap_nonce() {
let app = router_with_state(AppState::new_with_bootstrap(
test_config(),
Some("expected-fingerprint".into()),
Expand All @@ -508,10 +558,82 @@ async fn healthz_rejects_a_different_persistent_gateway_fingerprint() {
.unwrap();

assert_eq!(response.status(), StatusCode::CONFLICT);
assert!(
response
.headers()
.get("x-nemo-relay-bootstrap-proof")
.is_none()
);
let bytes = response.into_body().collect().await.unwrap().to_bytes();
let body: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(body["status"], json!("incompatible"));
assert!(body.get("bootstrap_fingerprint").is_none());
}

#[tokio::test]
async fn bootstrap_tls_tunnel_requires_a_client_token_for_a_different_fingerprint() {
let temp = tempfile::tempdir().unwrap();
let _environment = EnvScope::set(&[
("XDG_CONFIG_HOME", Some(temp.path().as_os_str())),
("HOME", Some(temp.path().as_os_str())),
]);
let key = BootstrapChallengeKey::from_bytes(b"test challenge key");
let identity = RelayTlsIdentity::load_or_create().unwrap();
let mut state = AppState::new_with_bootstrap(
test_config(),
Some("gateway-fingerprint".into()),
Some(key.clone()),
false,
None,
None,
);
state.bootstrap_tls = Some(identity.server_config().unwrap());
state.local_address = Some("127.0.0.1:1".parse().unwrap());
let app = router_with_state(state);
let nonce = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";

let response = app
.clone()
.oneshot(
Request::builder()
.method("GET")
.uri("/bootstrap/tunnel")
.header("x-nemo-relay-bootstrap-fingerprint", "caller-fingerprint")
.header("x-nemo-relay-bootstrap-nonce", nonce)
.header(header::CONNECTION, "upgrade")
.header(header::UPGRADE, "nemo-relay-tls")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::FORBIDDEN);

let response = app
.oneshot(
Request::builder()
.method("GET")
.uri("/bootstrap/tunnel")
.header("x-nemo-relay-bootstrap-fingerprint", "caller-fingerprint")
.header("x-nemo-relay-bootstrap-nonce", nonce)
.header(
crate::configuration::BOOTSTRAP_CLIENT_TOKEN_HEADER,
key.client_token(),
)
.header(header::CONNECTION, "upgrade")
.header(header::UPGRADE, "nemo-relay-tls")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS);
assert_eq!(
response
.headers()
.get("x-nemo-relay-bootstrap-proof")
.unwrap(),
key.proof("caller-fingerprint", nonce).as_str()
);
}

#[tokio::test]
Expand Down
Loading