diff --git a/codex-rs/network-proxy/src/mitm_forwarding_jwt_tests.rs b/codex-rs/network-proxy/src/mitm_forwarding_jwt_tests.rs new file mode 100644 index 0000000000..6e6aa3f744 --- /dev/null +++ b/codex-rs/network-proxy/src/mitm_forwarding_jwt_tests.rs @@ -0,0 +1,529 @@ +//! Exercise a host-owned JWT refresh and scoped bearer delivery at separate TLS origins. + +#![cfg(test)] + +use super::*; +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use jsonwebtoken::Algorithm; +use jsonwebtoken::DecodingKey; +use jsonwebtoken::EncodingKey; +use jsonwebtoken::Header as JwtHeader; +use jsonwebtoken::Validation; +use pretty_assertions::assert_eq; +use rama_http::body::util::BodyExt; +use rama_tls_rustls::dep::pki_types::CertificateDer; +use rama_tls_rustls::dep::pki_types::ServerName; +use rama_tls_rustls::dep::tokio_rustls::TlsConnector; +use serde_json::json; +use std::sync::atomic::AtomicUsize; +use std::sync::atomic::Ordering; + +const ISSUER_KEY: &[u8; 32] = &[0x42; 32]; +const RESOURCE: &str = "/resource/item"; + +async fn resource_origin( + dir: &Path, + method: &str, +) -> (MitmRequestContext, TcpListener, TlsAcceptor) { + tls_origin_with_hook(dir, "s3", b"http/1.1", |hook, _port| { + hook.matcher.methods = vec![method.to_string()]; + hook.matcher.path_prefixes = vec![RESOURCE.to_string()]; + hook.actions = MitmHookActionsConfig { + strip_request_headers: vec!["authorization".to_string()], + ..Default::default() + }; + }) + .await +} + +// Recompile the declarative hook with the fixture CA and loopback origin roots. +async fn compiled_policy(context: &MitmRequestContext) -> crate::runtime::ConfigState { + let config = context.policy.app_state.current_cfg().await.unwrap(); + let mut policy = crate::certs::TEST_MITM_CA + .scope(Arc::clone(&context.mitm.ca), async { + crate::build_config_state(config, Default::default(), crate::Platform::native()) + .unwrap() + }) + .await; + policy.mitm = Some(Arc::clone(&context.mitm)); + policy +} + +// The fixture issuer and resource verifier share this synthetic HS256 key. +fn issue_token(issuer: &str, serial: usize, expires: i64) -> String { + jsonwebtoken::encode( + &JwtHeader::new(Algorithm::HS256), + &json!({ + "iss": issuer, "aud": "fixture-api", "sub": "private-user", + "display": "shown", "exp": expires, "jti": serial.to_string() + }), + &EncodingKey::from_secret(ISSUER_KEY), + ) + .expect("sign fixture JWT") +} + +// The origin sees only bytes sent over its own TLS connection. +async fn serve_origin( + listener: TcpListener, + acceptor: TlsAcceptor, + mut respond: impl FnMut(ReceivedRequest) -> String, +) { + loop { + let (socket, _) = listener.accept().await.unwrap(); + let mut stream = acceptor.accept(socket).await.unwrap(); + let body = respond(read_request(&mut stream).await); + let len = body.len(); + let response = format!("HTTP/1.1 200 OK\r\nContent-Length: {len}\r\n\r\n{body}"); + stream.write_all(response.as_bytes()).await.unwrap(); + stream.shutdown().await.unwrap(); + } +} + +async fn response_status(stream: &mut (impl AsyncRead + Unpin)) -> StatusCode { + let head = timeout(FORWARD_TIMEOUT, async { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + assert!(head.len() < 16 * 1024); + head.push( + stream + .read_u8() + .await + .expect("complete HTTP response headers"), + ); + } + head + }) + .await + .expect("proxy response deadline"); + let status = std::str::from_utf8(&head) + .unwrap() + .split_whitespace() + .nth(1) + .unwrap(); + StatusCode::from_bytes(status.as_bytes()).unwrap() +} + +async fn send_guest_request( + stream: &mut (impl AsyncRead + tokio::io::AsyncWrite + Unpin), + method: &str, + authority: &str, + path: &str, + bearer: &str, +) -> StatusCode { + let request = format!( + "{method} {path} HTTP/1.1\r\nHost: {authority}\r\nAuthorization: Bearer {bearer}\r\n\r\n" + ); + stream.write_all(request.as_bytes()).await.unwrap(); + response_status(stream).await +} + +#[tokio::test] +async fn refreshes_jwt_only_for_its_attached_https_resource() { + const REFRESH_BODY: &str = "grant_type=refresh_token&refresh_token=issuer-only-fixture"; + let issuer_dir = tempdir().unwrap(); + let (issuer, issuer_listener, issuer_tls) = + tls_origin(issuer_dir.path(), "s3", b"http/1.1").await; + let issuer_origin = format!("https://localhost:{}", issuer.policy.target_port); + let expired = issue_token(&issuer_origin, /*serial*/ 0, /*expires*/ 1); + let expires = time::OffsetDateTime::now_utc().unix_timestamp() + 3600; + let first = issue_token(&issuer_origin, /*serial*/ 1, expires); + let second = issue_token(&issuer_origin, /*serial*/ 2, expires); + let mut issued = [first.clone(), second.clone()].into_iter(); + let mut servers = JoinSet::new(); + servers.spawn(serve_origin(issuer_listener, issuer_tls, move |request| { + assert_eq!(request.path, "/oauth/token"); + assert_eq!(request.body.as_slice(), REFRESH_BODY.as_bytes()); + assert!(!request.headers.contains_key("authorization")); + json!({"access_token": issued.next().expect("unexpected refresh")}).to_string() + })); + + let calls = Arc::new(AtomicUsize::new(0)); + let refresh = { + let calls = Arc::clone(&calls); + let endpoint = format!("{issuer_origin}/oauth/token"); + move || { + calls.fetch_add(1, Ordering::SeqCst); + let upstream = issuer.upstream.clone(); + let request = Request::post(endpoint.as_str()) + .header("content-type", "application/x-www-form-urlencoded") + .header("content-length", REFRESH_BODY.len()) + .body(Body::from(REFRESH_BODY)) + .unwrap(); + async move { + let response = upstream.serve(request).await.ok()?; + if !response.status().is_success() { + return None; + } + let bytes = response.into_body().collect().await.ok()?.to_bytes(); + serde_json::from_slice::(&bytes).ok()?["access_token"] + .as_str() + .map(str::to_owned) + } + } + }; + let grant = Arc::new( + crate::JwtBearerGrant::new(&expired, vec!["display".to_string()], refresh).unwrap(), + ); + let alias = grant.alias(); + assert_eq!( + jsonwebtoken::decode_header(alias).unwrap().alg, + Algorithm::ES256 + ); + let payload = URL_SAFE_NO_PAD + .decode(alias.split('.').nth(1).unwrap()) + .unwrap(); + assert_eq!( + serde_json::from_slice::(&payload).unwrap(), + json!({"display": "shown"}) + ); + let key = DecodingKey::from_secret(ISSUER_KEY); + let mut validation = Validation::new(Algorithm::HS256); + validation.set_required_spec_claims(&["exp", "iss", "aud"]); + validation.leeway = 0; + validation.set_audience(&["fixture-api"]); + validation.set_issuer(&[issuer_origin.as_str()]); + assert!(jsonwebtoken::decode::(alias, &key, &validation).is_err()); + + let resource_dir = tempdir().unwrap(); + let (owner, resource_listener, resource_tls) = + resource_origin(resource_dir.path(), "GET").await; + let state = Arc::clone(&owner.policy.app_state); + state + .replace_config_state(compiled_policy(&owner).await) + .await + .unwrap(); + state.register_execution("owner-frame", "env-a", "owner-command"); + state.register_execution("sibling-frame", "env-b", "sibling-command"); + + let proxy_listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let proxy_addr = proxy_listener.local_addr().unwrap(); + let lifecycle = crate::connection_lifecycle::ConnectionLifecycle::new(); + let guard = lifecycle.guard(); + let ingress_state = Arc::clone(&state); + servers.spawn(async move { + crate::http_proxy::run_http_proxy_with_std_listener( + ingress_state, + proxy_listener.into_std().unwrap(), + /*policy_decider*/ None, + /*environment_id*/ None, + guard, + ) + .await + .unwrap(); + }); + let authority = format!("localhost:{}", owner.policy.target_port); + let mut roots = rustls::RootCertStore::empty(); + roots + .add(CertificateDer::from_pem_file(owner.mitm.ca.certificate_path()).unwrap()) + .unwrap(); + let client = TlsConnector::from(Arc::new( + rustls::ClientConfig::builder() + .with_root_certificates(roots) + .with_no_client_auth(), + )); + let open_tunnel = |frame: &str, target: &str| { + let mut preface = Vec::new(); + crate::attribution::write_attribution_frame(&mut preface, frame).unwrap(); + preface.extend_from_slice( + format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\n\r\n").as_bytes(), + ); + let client = client.clone(); + async move { + let mut socket = tokio::net::TcpStream::connect(proxy_addr).await.unwrap(); + socket.write_all(&preface).await.unwrap(); + assert_eq!(response_status(&mut socket).await, StatusCode::OK); + client + .connect(ServerName::try_from("localhost").unwrap(), socket) + .await + .unwrap() + } + }; + let (observed, mut arrivals) = mpsc::unbounded_channel(); + servers.spawn(serve_origin( + resource_listener, + resource_tls, + move |request| { + assert_eq!(request.path, RESOURCE); + assert!(request.body.is_empty()); + assert!( + request + .headers + .values() + .all(|value| !value.contains("issuer-only-fixture")) + ); + let authorization = request.headers.get("authorization"); + if let Some(header) = authorization { + let bearer = header.strip_prefix("Bearer ").unwrap(); + jsonwebtoken::decode::(bearer, &key, &validation) + .expect("resource accepts a current JWT signed by its issuer for its audience"); + } + observed.send(authorization.cloned()).unwrap(); + String::new() + }, + )); + + // An attachment must preserve an anonymous request that the strip rule already allows. + let anonymous = format!("GET {RESOURCE} HTTP/1.1\r\nHost: {authority}\r\n\r\n"); + let mut guest = open_tunnel("owner-frame", &authority).await; + guest.write_all(anonymous.as_bytes()).await.unwrap(); + assert_eq!(response_status(&mut guest).await, StatusCode::OK); + assert_eq!(arrivals.try_recv().unwrap(), None); + + state + .bind_jwt_bearer_grant("env-a", "localhost", RESOURCE, &grant) + .await + .unwrap(); + guest.write_all(anonymous.as_bytes()).await.unwrap(); + assert_eq!(response_status(&mut guest).await, StatusCode::OK); + assert_eq!(arrivals.try_recv().unwrap(), None); + + let wrong_port = format!("localhost:{}", issuer.policy.target_port); + // This CONNECT and its inner Host agree, but they reach the issuer's port, + // which has no resource grant. There must be no refresh or origin request. + let mut at_wrong_port = open_tunnel("owner-frame", &wrong_port).await; + assert_eq!( + send_guest_request(&mut at_wrong_port, "GET", &wrong_port, RESOURCE, alias).await, + StatusCode::FORBIDDEN + ); + let tampered = format!("{alias}x"); + for (frame, method, host, path, bearer) in [ + ( + "owner-frame", + "GET", + authority.as_str(), + "/resource/item/other", + alias, + ), + ("owner-frame", "POST", &authority, RESOURCE, alias), + ("owner-frame", "GET", "127.0.0.1", RESOURCE, alias), + ("owner-frame", "GET", &wrong_port, RESOURCE, alias), + ("sibling-frame", "GET", &authority, RESOURCE, alias), + ( + "owner-frame", + "GET", + &authority, + RESOURCE, + tampered.as_str(), + ), + ] { + let mut guest = open_tunnel(frame, &authority).await; + let status = send_guest_request(&mut guest, method, host, path, bearer).await; + assert!(status.is_client_error(), "unexpected response {status}"); + } + // Removing hop-by-hop headers must not erase a conflicting guest authority. + let mut confused = open_tunnel("owner-frame", &authority).await; + let request = format!( + "GET https://{authority}{RESOURCE} HTTP/1.1\r\nHost: other.invalid\r\nConnection: Host\r\nAuthorization: Bearer {alias}\r\n\r\n" + ); + confused.write_all(request.as_bytes()).await.unwrap(); + assert!(response_status(&mut confused).await.is_client_error()); + + // A guest cannot use hop-by-hop stripping to turn bad credentials into an anonymous request. + for (presented, extra) in [ + (tampered.as_str(), "Connection: Authorization\r\n"), + (alias, "Authorization: Bearer duplicate\r\n"), + ] { + let mut rejected = open_tunnel("owner-frame", &authority).await; + let request = format!( + "GET {RESOURCE} HTTP/1.1\r\nHost: {authority}\r\nAuthorization: Bearer {presented}\r\n{extra}\r\n" + ); + rejected.write_all(request.as_bytes()).await.unwrap(); + assert_eq!(response_status(&mut rejected).await, StatusCode::FORBIDDEN); + } + + let mut plain = tokio::net::TcpStream::connect(proxy_addr).await.unwrap(); + let mut frame = Vec::new(); + crate::attribution::write_attribution_frame(&mut frame, "owner-frame").unwrap(); + plain.write_all(&frame).await.unwrap(); + let plain_uri = format!("http://{authority}{RESOURCE}"); + assert!( + send_guest_request(&mut plain, "GET", &authority, &plain_uri, alias) + .await + .is_client_error() + ); + assert_eq!(calls.load(Ordering::SeqCst), 0); + assert!(arrivals.try_recv().is_err()); + + // Reuse the same attributed CONNECT/TLS session across expiry, rotation and revocation. + for (index, expected) in [&first, &first, &second].into_iter().enumerate() { + if index == 2 { + grant.invalidate_access_token(); + } + let status = send_guest_request(&mut guest, "GET", &authority, RESOURCE, alias).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + arrivals.try_recv().unwrap(), + Some(format!("Bearer {expected}")) + ); + } + // Without an attachment, the sibling gets the original header-stripping rule. + let mut sibling = open_tunnel("sibling-frame", &authority).await; + let status = send_guest_request(&mut sibling, "GET", &authority, RESOURCE, "ordinary").await; + assert_eq!(status, StatusCode::OK); + assert_eq!(arrivals.try_recv().unwrap(), None); + + let mut previous_attachment: Option> = None; + for serial in [3, 4] { + let token = issue_token(&issuer_origin, serial, expires); + let attached = + Arc::new(crate::JwtBearerGrant::new(&token, vec![], || async { None }).unwrap()); + if let Some(previous) = &previous_attachment { + previous.revoke(); + } + state + .bind_jwt_bearer_grant("env-b", "localhost", RESOURCE, &attached) + .await + .unwrap(); + if let Some(previous) = &previous_attachment { + // Repeating an earlier unlink must leave the replacement live. + previous.revoke(); + let mut rejected = open_tunnel("sibling-frame", &authority).await; + assert_eq!( + send_guest_request(&mut rejected, "GET", &authority, RESOURCE, previous.alias()) + .await, + StatusCode::FORBIDDEN + ); + } + let status = + send_guest_request(&mut sibling, "GET", &authority, RESOURCE, attached.alias()).await; + assert_eq!(status, StatusCode::OK); + assert_eq!( + arrivals.try_recv().unwrap(), + Some(format!("Bearer {token}")) + ); + // The owner's original tunnel still uses its own grant while the sibling's is active. + assert_eq!( + send_guest_request(&mut guest, "GET", &authority, RESOURCE, alias).await, + StatusCode::OK + ); + assert_eq!( + arrivals.try_recv().unwrap(), + Some(format!("Bearer {second}")) + ); + previous_attachment = Some(attached); + } + grant.revoke(); + guest.write_all(anonymous.as_bytes()).await.unwrap(); + assert_eq!(response_status(&mut guest).await, StatusCode::OK); + assert_eq!(arrivals.try_recv().unwrap(), None); + let ordinary = send_guest_request(&mut guest, "GET", &authority, RESOURCE, "ordinary").await; + assert_eq!(ordinary, StatusCode::OK); + assert_eq!(arrivals.try_recv().unwrap(), None); + let status = send_guest_request(&mut guest, "GET", &authority, RESOURCE, alias).await; + assert_eq!(status, StatusCode::FORBIDDEN); + assert_eq!(calls.load(Ordering::SeqCst), 2); + assert!(arrivals.try_recv().is_err()); + + // Reload drops the sibling binding without revoking its grant. Its first unlink + // arrives after the replacement owns the same environment and route. + let previous = previous_attachment.unwrap(); + state + .replace_config_state(compiled_policy(&owner).await) + .await + .unwrap(); + let replacement_token = issue_token(&issuer_origin, /*serial*/ 5, expires); + let replacement = Arc::new( + crate::JwtBearerGrant::new(&replacement_token, vec![], || async { None }).unwrap(), + ); + state + .bind_jwt_bearer_grant("env-b", "localhost", RESOURCE, &replacement) + .await + .unwrap(); + assert!(previous.is_active()); + previous.revoke(); + assert!(!previous.is_active()); + + let mut rejected = open_tunnel("sibling-frame", &authority).await; + assert_eq!( + send_guest_request(&mut rejected, "GET", &authority, RESOURCE, previous.alias()).await, + StatusCode::FORBIDDEN + ); + assert!(arrivals.try_recv().is_err()); + assert_eq!( + send_guest_request( + &mut sibling, + "GET", + &authority, + RESOURCE, + replacement.alias() + ) + .await, + StatusCode::OK + ); + assert_eq!( + arrivals.try_recv().unwrap(), + Some(format!("Bearer {replacement_token}")) + ); +} + +enum Withdrawal { + Revoke, + ReloadPolicy, +} + +#[tokio::test] +async fn revoking_grant_during_resource_tls_handshake_sends_no_http_bytes() { + assert_withdrawal_during_handshake(Withdrawal::Revoke).await; +} + +#[tokio::test] +async fn reloading_policy_during_resource_tls_handshake_sends_no_http_bytes() { + assert_withdrawal_during_handshake(Withdrawal::ReloadPolicy).await; +} + +async fn assert_withdrawal_during_handshake(withdrawal: Withdrawal) { + let dir = tempdir().unwrap(); + let (mut context, listener, acceptor) = resource_origin(dir.path(), "POST").await; + let expires = time::OffsetDateTime::now_utc().unix_timestamp() + 3600; + let token = issue_token("https://issuer.test", /*serial*/ 1, expires); + let grant = Arc::new(crate::JwtBearerGrant::new(&token, vec![], || async { None }).unwrap()); + let state = Arc::clone(&context.policy.app_state); + state + .bind_jwt_bearer_grant("owner", "localhost", RESOURCE, &grant) + .await + .unwrap(); + context.policy.app_state = Arc::new(state.for_environment_id(Some("owner"))); + let body = "resource-request-body"; + let request = Request::post(RESOURCE) + .header(HOST, format!("localhost:{}", context.policy.target_port)) + .header("authorization", format!("Bearer {}", grant.alias())) + .header("content-length", body.len()) + .body(Body::from(body)) + .unwrap(); + + let replacement = compiled_policy(&context).await; + let resource = async { + let (socket, _) = listener.accept().await.unwrap(); + // A ClientHello proves forwarding has started. Leave it queued until after revocation. + let mut record_type = [0]; + assert_eq!(socket.peek(&mut record_type).await.unwrap(), 1); + assert_eq!(record_type, [22]); + match withdrawal { + Withdrawal::Revoke => grant.revoke(), + // Recompilation retains the strip-only hook but removes its host-attached grants. + Withdrawal::ReloadPolicy => state.replace_config_state(replacement).await.unwrap(), + } + let mut tls = acceptor + .accept(socket) + .await + .expect("resource TLS handshake"); + let mut first_byte = [0]; + match tls.read(&mut first_byte).await { + Ok(count) => assert_eq!(count, 0, "revoked request reached the HTTP origin"), + Err(error) => assert!( + matches!( + error.kind(), + std::io::ErrorKind::UnexpectedEof | std::io::ErrorKind::ConnectionReset + ), + "unexpected TLS read error: {error}" + ), + } + }; + let (response, ()) = timeout(FORWARD_TIMEOUT, async { + tokio::join!(handle_mitm_request(request, Arc::new(context)), resource) + }) + .await + .expect("revoked connection closes before forwarding"); + assert_eq!(response.unwrap().status(), StatusCode::FORBIDDEN); +} diff --git a/codex-rs/network-proxy/src/mitm_forwarding_tests.rs b/codex-rs/network-proxy/src/mitm_forwarding_tests.rs index 62421e759e..49ecda6b8d 100644 --- a/codex-rs/network-proxy/src/mitm_forwarding_tests.rs +++ b/codex-rs/network-proxy/src/mitm_forwarding_tests.rs @@ -592,3 +592,6 @@ async fn forwards_substituted_body_before_signing() { ) ); } + +#[path = "mitm_forwarding_jwt_tests.rs"] +mod jwt; diff --git a/codex-rs/network-proxy/src/mitm_hook.rs b/codex-rs/network-proxy/src/mitm_hook.rs index ddbdbc11b1..fd1c0bcec9 100644 --- a/codex-rs/network-proxy/src/mitm_hook.rs +++ b/codex-rs/network-proxy/src/mitm_hook.rs @@ -228,7 +228,6 @@ pub type MitmHooksByHost = BTreeMap>; /// Attach only to an existing rule that strips the guest credential even when a /// policy reload removes this process-local binding. Never create a permission. -#[cfg(test)] pub(crate) fn bind_jwt( hooks: &mut MitmHooksByHost, environment_id: &str, diff --git a/codex-rs/network-proxy/src/runtime.rs b/codex-rs/network-proxy/src/runtime.rs index d441ab39f2..eb6b645a86 100644 --- a/codex-rs/network-proxy/src/runtime.rs +++ b/codex-rs/network-proxy/src/runtime.rs @@ -1214,6 +1214,35 @@ impl NetworkProxyState { } } + /// Binds a trusted provider grant to the current compiled rule on this proxy. + /// Retain the grant handle while attached and revoke it on unlink. A policy + /// replacement requires a fresh binding. Only the attributed environment can + /// present the alias through an intercepted request. + pub async fn bind_jwt_bearer_grant( + &self, + environment_id: &str, + host: &str, + exact_path: &str, + grant: &Arc, + ) -> Result<()> { + self.reload_if_needed().await?; + let mut guard = self.state.write().await; + if !guard.config.enabled + || !guard.config.credential_broker + || !guard.config.mitm + || self.environment_id().is_some_and(|id| id != environment_id) + { + anyhow::bail!("JWT binding requires an active managed proxy for the environment"); + } + crate::mitm_hook::bind_jwt( + &mut guard.mitm_hooks, + environment_id, + host, + exact_path, + grant, + ) + } + pub(crate) async fn host_mitm_requirement( &self, host: &str,