Skip to content

Commit f37d89b

Browse files
authored
fix(supervisor-network): keep workload bytes read with a mediated CONNECT header (ai-openshell#3745)
The proxy read the synthesized CONNECT header of a mediated open with a full-width read into an 8192-byte buffer through a BufReader of the same size, so the workload's request could arrive in the same read. The CONNECT path never looked past the header, and the request was lost until the workload timed out. Take the header out of the BufReader with fill_buf and consume only through the terminator, so the bytes behind it stay buffered for the relay. Signed-off-by: Davanum Srinivas <dsrinivas@nvidia.com>
1 parent a3ed8c7 commit f37d89b

1 file changed

Lines changed: 155 additions & 5 deletions

File tree

  • crates/openshell-supervisor-network/src

‎crates/openshell-supervisor-network/src/proxy.rs‎

Lines changed: 155 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2455,13 +2455,24 @@ async fn handle_mediated_connection(
24552455
return Ok(());
24562456
}
24572457

2458-
let n = client.read(&mut buf[used..]).await.into_diagnostic()?;
2459-
if n == 0 {
2458+
// A mediated open's first workload bytes follow the synthesized CONNECT header.
2459+
// Take only the header out of the reader so the bytes behind it stay buffered for
2460+
// the relay; overlap three bytes so a terminator split across fills is found.
2461+
let available = client.fill_buf().await.into_diagnostic()?;
2462+
if available.is_empty() {
24602463
return Ok(());
24612464
}
2462-
used += n;
2463-
2464-
if buf[..used].windows(4).any(|win| win == b"\r\n\r\n") {
2465+
let n = available.len().min(buf.len() - used);
2466+
buf[used..used + n].copy_from_slice(&available[..n]);
2467+
let start = used.saturating_sub(3);
2468+
let end = buf[start..used + n]
2469+
.windows(4)
2470+
.position(|window| window == b"\r\n\r\n")
2471+
.map(|position| start + position + 4);
2472+
let consumed = end.map_or(n, |end| end - used);
2473+
client.consume(consumed);
2474+
used += consumed;
2475+
if end.is_some() {
24652476
break;
24662477
}
24672478
}
@@ -7660,6 +7671,145 @@ process: { run_as_user: sandbox, run_as_group: sandbox }
76607671
assert!(response.contains("\"format\":\"yaml\""), "{response}");
76617672
}
76627673

7674+
#[tokio::test]
7675+
async fn mediated_connect_keeps_workload_bytes_read_with_the_synthesized_header() {
7676+
let Some(upstream_ip) = non_loopback_test_ipv4() else {
7677+
eprintln!("skipping: no routable non-loopback IPv4 test address");
7678+
return;
7679+
};
7680+
let upstream = TcpListener::bind((upstream_ip, 0)).await.unwrap();
7681+
let destination = upstream.local_addr().unwrap();
7682+
let (request_tx, request_rx) = tokio::sync::oneshot::channel();
7683+
tokio::spawn(async move {
7684+
let (mut stream, _) = upstream.accept().await.unwrap();
7685+
// Report whatever arrives before the request terminator or EOF, so a
7686+
// swallowed request shows up as an empty read, not as a hang.
7687+
let mut request = Vec::new();
7688+
loop {
7689+
let mut byte = [0_u8; 1];
7690+
match stream.read(&mut byte).await {
7691+
Ok(1) => request.push(byte[0]),
7692+
_ => break,
7693+
}
7694+
if request.ends_with(b"\r\n\r\n") {
7695+
break;
7696+
}
7697+
}
7698+
request_tx.send(request).unwrap();
7699+
stream
7700+
.write_all(b"HTTP/1.1 204 No Content\r\nConnection: close\r\n\r\n")
7701+
.await
7702+
.unwrap();
7703+
});
7704+
let engine = Arc::new(
7705+
OpaEngine::from_strings(
7706+
include_str!("../data/sandbox-policy.rego"),
7707+
&format!(
7708+
r#"
7709+
network_policies:
7710+
allowed:
7711+
name: allowed
7712+
endpoints:
7713+
- host: "{upstream_ip}"
7714+
port: {port}
7715+
tls: skip
7716+
binaries:
7717+
- path: /usr/bin/curl
7718+
"#,
7719+
port = destination.port()
7720+
),
7721+
)
7722+
.unwrap(),
7723+
);
7724+
let cache = Arc::new(BinaryIdentityCache::new());
7725+
let (stream, mut workload) = tokio::io::duplex(4096);
7726+
let (decision, completion) = tokio::sync::oneshot::channel();
7727+
let pending = PendingTcpOpen {
7728+
stream: Box::new(stream),
7729+
binary_identity: Ok(ContractBinaryIdentity {
7730+
executable: ContractExecutableIdentity {
7731+
path: PathBuf::from("/usr/bin/curl"),
7732+
digest: Some("44".repeat(32).parse().unwrap()),
7733+
},
7734+
ancestors: Vec::new(),
7735+
cmdline_paths: Vec::new(),
7736+
}),
7737+
destination,
7738+
socket: openshell_isolation_interface::contract::NetworkSocketMetadata {
7739+
socket_cookie: 7,
7740+
nonblocking: false,
7741+
process_generation: 1,
7742+
},
7743+
policy_generation: engine.current_generation(),
7744+
timing: MediationTiming::default(),
7745+
decision,
7746+
};
7747+
let (stream, supplied_identity, socket_addrs, transparent) =
7748+
preauthorize_transparent_open(pending, None, &engine, &cache, None, None, false, None)
7749+
.await
7750+
.expect("open is admitted");
7751+
assert_eq!(completion.await.unwrap(), TcpOpenDecision::RelayReady);
7752+
// The workload writes before the proxy reads anything, so its request sits
7753+
// right behind the synthesized CONNECT header in the proxy's first read.
7754+
workload
7755+
.write_all(
7756+
format!("GET /ping HTTP/1.1\r\nHost: {destination}\r\nConnection: close\r\n\r\n")
7757+
.as_bytes(),
7758+
)
7759+
.await
7760+
.unwrap();
7761+
workload.shutdown().await.unwrap();
7762+
let handler = tokio::spawn(handle_mediated_connection(
7763+
tokio::io::BufReader::new(stream),
7764+
supplied_identity,
7765+
socket_addrs,
7766+
transparent,
7767+
None,
7768+
engine,
7769+
cache,
7770+
Arc::new(AtomicU32::new(0)),
7771+
None,
7772+
None,
7773+
AgentProposals::new(true),
7774+
Arc::new(None),
7775+
Arc::new(None),
7776+
Arc::new(None),
7777+
None,
7778+
None,
7779+
None,
7780+
None,
7781+
None,
7782+
None,
7783+
));
7784+
let request = tokio::time::timeout(std::time::Duration::from_secs(5), request_rx)
7785+
.await
7786+
.expect("upstream never received the workload's request")
7787+
.unwrap();
7788+
assert!(
7789+
request.starts_with(b"GET /ping HTTP/1.1\r\n"),
7790+
"upstream received {:?} instead of the workload's request",
7791+
String::from_utf8_lossy(&request)
7792+
);
7793+
let mut response = Vec::new();
7794+
tokio::time::timeout(
7795+
std::time::Duration::from_secs(5),
7796+
workload.read_to_end(&mut response),
7797+
)
7798+
.await
7799+
.expect("response timed out")
7800+
.unwrap();
7801+
assert!(
7802+
response.starts_with(b"HTTP/1.1 204 "),
7803+
"{}",
7804+
String::from_utf8_lossy(&response)
7805+
);
7806+
tokio::time::timeout(std::time::Duration::from_secs(5), handler)
7807+
.await
7808+
.expect("handler did not finish")
7809+
.unwrap()
7810+
.unwrap();
7811+
}
7812+
76637813
#[test]
76647814
fn policy_local_route_requires_one_exact_host_and_an_origin_form_target() {
76657815
assert!(valid_policy_local_request(

0 commit comments

Comments
 (0)