Skip to content

Commit 4ff621b

Browse files
test(conformance): add a positive control to the WebSocket denial test
The test passed whenever no binary frame reached upstream, whatever the reason. It now first sends the same frame from a sandbox without the provider and requires that it arrives, so the denial check can fail. Unit tests check that WebSocketRecorder sees a binary frame after a long text frame, and none among text frames. Signed-off-by: Matthew Grossman <[email protected]>
1 parent 9ab1be1 commit 4ff621b

3 files changed

Lines changed: 119 additions & 21 deletions

File tree

‎tests/suites/conformance/src/credential_gating.rs‎

Lines changed: 40 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -79,29 +79,29 @@ async fn profile_rest_endpoint_keeps_body_placeholder(cx: &mut Context) -> testk
7979
allow(&mut policy, server.port)
8080
.rest(Access::Full)
8181
.request_body_credential_rewrite(false);
82-
let sandbox = create_sandbox(cx, "rest", policy, &provider).await?;
82+
let sandbox = create_sandbox(cx, "rest", policy, &[&provider]).await?;
8383
run_python(&sandbox, BODY_CLIENT, server.port).await?;
8484
expect_placeholder_body(&server).await
8585
}
8686

8787
/// A provider's WebSocket endpoint completes the handshake but doesn't
8888
/// forward a binary frame, which the supervisor can't inspect for the
89-
/// credential.
89+
/// credential. The same client in a sandbox without the provider gets its
90+
/// binary frame through, which shows the denial comes from the credential.
9091
#[testkit::test]
9192
async fn profile_websocket_endpoint_denies_binary_frames(cx: &mut Context) -> testkit::Result {
9293
let server = HttpRecorder::start("ok").await?;
9394
let websocket = WebSocketRecorder::start().await?;
9495
let provider = install_gating_provider(cx, Some((server.port, websocket.port))).await?;
9596

96-
let mut policy = policy::base();
97-
allow(&mut policy, websocket.port).websocket(Access::ReadWrite);
98-
let sandbox = create_sandbox(cx, "ws", policy, &provider).await?;
99-
run_python(&sandbox, WEBSOCKET_CLIENT, websocket.port).await?;
100-
websocket
101-
.wait_for_handshake()
102-
.await
103-
.context("upstream should receive the WebSocket handshake")?;
104-
let binary_seen = websocket.wait_until_finished().await?;
97+
let control = WebSocketRecorder::start().await?;
98+
let binary_seen = send_binary_frame(cx, "wsctl", &control, &[]).await?;
99+
testkit::ensure!(
100+
binary_seen,
101+
"the binary frame didn't reach upstream from a sandbox without the provider"
102+
);
103+
104+
let binary_seen = send_binary_frame(cx, "ws", &websocket, &[&provider]).await?;
105105
testkit::ensure!(
106106
!binary_seen,
107107
"credentialed WebSocket binary frame reached upstream"
@@ -137,7 +137,7 @@ async fn policy_binding_requires_inspection_or_opt_in(cx: &mut Context) -> testk
137137
allow(&mut opt_in, server.port)
138138
.allow_uninspected_credentials()
139139
.credential_binding(&provider);
140-
let sandbox = create_sandbox(cx, "optin", opt_in, &provider).await?;
140+
let sandbox = create_sandbox(cx, "optin", opt_in, &[&provider]).await?;
141141
sandbox.exec(["true"]).await?.success()?;
142142
Ok(())
143143
}
@@ -156,7 +156,7 @@ async fn policy_binding_rest_body_keeps_placeholder_without_rewrite(
156156
.rest(Access::Full)
157157
.request_body_credential_rewrite(false)
158158
.credential_binding(&provider);
159-
let sandbox = create_sandbox(cx, "body", policy, &provider).await?;
159+
let sandbox = create_sandbox(cx, "body", policy, &[&provider]).await?;
160160
run_python(&sandbox, BODY_CLIENT, server.port).await?;
161161
expect_placeholder_body(&server).await
162162
}
@@ -175,7 +175,7 @@ async fn policy_binding_rest_body_rewrite_sends_secret_upstream(
175175
.rest(Access::Full)
176176
.request_body_credential_rewrite(true)
177177
.credential_binding(&provider);
178-
let sandbox = create_sandbox(cx, "rw", policy, &provider).await?;
178+
let sandbox = create_sandbox(cx, "rw", policy, &[&provider]).await?;
179179
run_python(&sandbox, BODY_CLIENT, server.port).await?;
180180
let request = one_request(&server).await?;
181181
testkit::ensure!(
@@ -205,7 +205,7 @@ async fn policy_binding_updates_provider_environment_live(cx: &mut Context) -> t
205205
};
206206
let (unbound, bound) = (policy_binding(false), policy_binding(true));
207207

208-
let sandbox = create_sandbox(cx, "live", unbound.clone(), &provider).await?;
208+
let sandbox = create_sandbox(cx, "live", unbound.clone(), &[&provider]).await?;
209209
wait_for_token(&sandbox, "TOKEN_ABSENT").await?;
210210

211211
set_policy(cx, &sandbox, &bound)
@@ -219,6 +219,25 @@ async fn policy_binding_updates_provider_environment_live(cx: &mut Context) -> t
219219
wait_for_token(&sandbox, "TOKEN_ABSENT").await
220220
}
221221

222+
/// Run [`WEBSOCKET_CLIENT`] against `server` in a sandbox with `providers`,
223+
/// and return whether its binary frame reached `server`.
224+
async fn send_binary_frame(
225+
cx: &Context,
226+
suffix: &str,
227+
server: &WebSocketRecorder,
228+
providers: &[&str],
229+
) -> Result<bool> {
230+
let mut policy = policy::base();
231+
allow(&mut policy, server.port).websocket(Access::ReadWrite);
232+
let sandbox = create_sandbox(cx, suffix, policy, providers).await?;
233+
run_python(&sandbox, WEBSOCKET_CLIENT, server.port).await?;
234+
server
235+
.wait_for_handshake()
236+
.await
237+
.context("upstream should receive the WebSocket handshake")?;
238+
server.wait_until_finished().await
239+
}
240+
222241
/// Let the image's Python reach `TEST_HOST` on `port`.
223242
fn allow(policy: &mut proto::SandboxPolicy, port: u16) -> &mut proto::NetworkEndpoint {
224243
policy::allow(
@@ -274,26 +293,26 @@ fn sandbox_with(
274293
cx: &Context,
275294
suffix: &str,
276295
policy: proto::SandboxPolicy,
277-
provider: &str,
296+
providers: &[&str],
278297
) -> testkit::SandboxBuilder {
279298
cx.sandbox(suffix)
280299
.policy(policy)
281300
.spec(|spec| {
282301
spec.image = Some(testkit::python_image());
283-
spec.providers = vec![provider.to_string()];
302+
spec.providers = providers.iter().map(ToString::to_string).collect();
284303
})
285304
.command(["sleep", "infinity"])
286305
}
287306

288307
/// Create a long-running sandbox from the Python image with `policy` and
289-
/// `provider`, and wait until it is Ready.
308+
/// `providers`, and wait until it is Ready.
290309
async fn create_sandbox(
291310
cx: &Context,
292311
suffix: &str,
293312
policy: proto::SandboxPolicy,
294-
provider: &str,
313+
providers: &[&str],
295314
) -> Result<Sandbox> {
296-
let sandbox = sandbox_with(cx, suffix, policy, provider).create().await?;
315+
let sandbox = sandbox_with(cx, suffix, policy, providers).create().await?;
297316
sandbox.wait_ready().await?;
298317
Ok(sandbox)
299318
}
@@ -306,7 +325,7 @@ async fn expect_rejected(
306325
policy: proto::SandboxPolicy,
307326
provider: &str,
308327
) -> Result<String> {
309-
match sandbox_with(cx, suffix, policy, provider).create().await {
328+
match sandbox_with(cx, suffix, policy, &[provider]).create().await {
310329
Ok(sandbox) => Err(Error::msg(format!(
311330
"the gateway accepted sandbox {}",
312331
sandbox.name()

‎tests/support/host-server/Cargo.toml‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,6 @@ base64 = "0.22"
1616
openshell-testkit = { path = "../../testkit/testkit" }
1717
sha1 = "0.10"
1818
tokio = { version = "1.43", features = ["io-util", "net", "rt", "time"] }
19+
20+
[dev-dependencies]
21+
tokio = { version = "1.43", features = ["macros", "rt"] }

‎tests/support/host-server/src/lib.rs‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,3 +301,79 @@ fn header(head: &str, name: &str) -> Option<String> {
301301
.then(|| value.trim().to_string())
302302
})
303303
}
304+
305+
#[cfg(test)]
306+
mod tests {
307+
use super::*;
308+
309+
/// Complete a handshake with `recorder`, send `frames`, and close.
310+
async fn send_frames(recorder: &WebSocketRecorder, frames: &[(u8, Vec<u8>)]) {
311+
let mut stream = TcpStream::connect(("127.0.0.1", recorder.port))
312+
.await
313+
.unwrap();
314+
stream.set_nodelay(true).unwrap();
315+
stream
316+
.write_all(
317+
b"GET / HTTP/1.1\r\nHost: test\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\
318+
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n",
319+
)
320+
.await
321+
.unwrap();
322+
let mut response = Vec::new();
323+
while find(&response, b"\r\n\r\n").is_none() {
324+
let mut buffer = [0_u8; 1024];
325+
let read = stream.read(&mut buffer).await.unwrap();
326+
assert!(read > 0, "closed during the handshake");
327+
response.extend_from_slice(&buffer[..read]);
328+
}
329+
let response = String::from_utf8_lossy(&response);
330+
assert!(response.starts_with("HTTP/1.1 101"), "{response}");
331+
// The RFC 6455 sample key's accept value.
332+
assert!(
333+
response.contains("Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo="),
334+
"{response}"
335+
);
336+
for (opcode, payload) in frames {
337+
stream.write_all(&frame(*opcode, payload)).await.unwrap();
338+
}
339+
stream.write_all(&frame(0x08, &[])).await.unwrap();
340+
}
341+
342+
/// A final, masked client frame.
343+
fn frame(opcode: u8, payload: &[u8]) -> Vec<u8> {
344+
let mask = [1_u8, 2, 3, 4];
345+
let mut frame = vec![0x80 | opcode];
346+
match payload.len() {
347+
length @ 0..=125 => frame.push(0x80 | u8::try_from(length).unwrap()),
348+
length => {
349+
frame.push(0x80 | 126);
350+
frame.extend_from_slice(&u16::try_from(length).unwrap().to_be_bytes());
351+
}
352+
}
353+
frame.extend_from_slice(&mask);
354+
frame.extend(payload.iter().enumerate().map(|(i, b)| b ^ mask[i % 4]));
355+
frame
356+
}
357+
358+
#[tokio::test]
359+
async fn websocket_recorder_sees_a_binary_frame_after_a_long_text_frame() {
360+
let recorder = WebSocketRecorder::start().await.unwrap();
361+
send_frames(
362+
&recorder,
363+
&[(0x01, vec![b'x'; 300]), (0x02, b"binary".to_vec())],
364+
)
365+
.await;
366+
assert!(recorder.wait_until_finished().await.unwrap());
367+
}
368+
369+
#[tokio::test]
370+
async fn websocket_recorder_sees_no_binary_frame_in_text_frames() {
371+
let recorder = WebSocketRecorder::start().await.unwrap();
372+
send_frames(
373+
&recorder,
374+
&[(0x01, vec![b'x'; 300]), (0x01, b"text".to_vec())],
375+
)
376+
.await;
377+
assert!(!recorder.wait_until_finished().await.unwrap());
378+
}
379+
}

0 commit comments

Comments
 (0)