mirror of
https://github.com/openai/codex.git
synced 2026-12-04 00:51:02 +00:00
Verify Guardian network approvals against a mock origin (#64653)
## Why The routing test needs to verify that Guardian's decision controls whether a request reaches its destination. Loopback addresses are covered by `NO_PROXY`, so the probe must explicitly use the managed proxy. ## What changed Send both probes through `HTTP_PROXY` to a local mock origin. Assert that the approved command exits successfully and receives the origin's response, and that the denied command reports Guardian's denial without sending a second request to the origin. Collect output across the initial `exec_command` response and subsequent polls so the test can check stdout even when it arrives before the process exits. GitOrigin-RevId: aa32a588e9ad9a049621242d8b8a567462237cca
This commit is contained in:
@@ -142,6 +142,14 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
skip_if_sandbox!(Ok(()));
|
||||
|
||||
let server = start_mock_server().await;
|
||||
let origin = server.uri();
|
||||
let upstream = wiremock::Mock::given(wiremock::matchers::method("GET"))
|
||||
.and(wiremock::matchers::path("/guardian-network-probe"))
|
||||
.respond_with(
|
||||
wiremock::ResponseTemplate::new(200).set_body_string("guardian-upstream-reached"),
|
||||
)
|
||||
.mount_as_scoped(&server)
|
||||
.await;
|
||||
let test = managed_network_unified_exec_builder(&[])?
|
||||
.with_cloud_config_bundle(
|
||||
CloudConfigBundleFixture::loader_with_enterprise_requirement(format!(
|
||||
@@ -153,16 +161,25 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
assert!(test.config.managed_network_requirements_enabled());
|
||||
assert!(test.config.permissions.network.is_some());
|
||||
assert!(test.session_configured.network_proxy.is_some());
|
||||
let local_cwd = test.cwd.path().abs();
|
||||
let first_call_id = "guardian-network-approved";
|
||||
let second_call_id = "guardian-network-denied";
|
||||
let first_command = network_fetch_args(LOCAL_ENVIRONMENT_ID)["cmd"]
|
||||
.as_str()
|
||||
.context("expected network command")?
|
||||
.to_string();
|
||||
let second_command = first_command.clone();
|
||||
// NO_PROXY includes loopback. Send the absolute URL to the managed proxy explicitly
|
||||
// so both requests require Guardian's decision before the origin can see them.
|
||||
let command = format!(
|
||||
"python3 -c \"import http.client, os, urllib.parse; \
|
||||
proxy = urllib.parse.urlsplit(os.environ['HTTP_PROXY']); \
|
||||
conn = http.client.HTTPConnection(proxy.hostname, proxy.port); \
|
||||
conn.request('GET', '{origin}/guardian-network-probe'); \
|
||||
r = conn.getresponse(); \
|
||||
print('%d:%s' % (r.status, r.read().decode())); \
|
||||
raise SystemExit(r.status != 200)\""
|
||||
);
|
||||
let mut fetch_args = network_exec_args(&command);
|
||||
fetch_args["environment_id"] = json!(LOCAL_ENVIRONMENT_ID);
|
||||
let expected_command = get_shell(ShellType::Sh)
|
||||
.context("expected local sh")?
|
||||
.derive_exec_args(&first_command, /*use_login_shell*/ false);
|
||||
.derive_exec_args(&command, /*use_login_shell*/ false);
|
||||
let denial = "The destination is outside the approved test boundary.";
|
||||
let mut actions = Vec::new();
|
||||
let mut outputs = Vec::new();
|
||||
@@ -186,7 +203,7 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
ev_function_call(
|
||||
call_id,
|
||||
"exec_command",
|
||||
&serde_json::to_string(&network_fetch_args(LOCAL_ENVIRONMENT_ID))?,
|
||||
&serde_json::to_string(&fetch_args)?,
|
||||
),
|
||||
ev_completed(&format!("{call_id}-start")),
|
||||
]),
|
||||
@@ -212,7 +229,7 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
.await;
|
||||
|
||||
// Process startup can outlast exec_command's first yield. Follow the returned
|
||||
// session until its final output instead of consuming Guardian's next response.
|
||||
// session and keep every chunk. Polling drains output before the process exits.
|
||||
let (output_tx, output_rx) = std::sync::mpsc::channel();
|
||||
let parent = wiremock::Mock::given(wiremock::matchers::method("POST"))
|
||||
.and(wiremock::matchers::path("/v1/responses"))
|
||||
@@ -231,6 +248,9 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
.find(|item| item["type"] == "function_call_output")
|
||||
.and_then(|item| item["output"].as_str())
|
||||
.expect("network command or poll output");
|
||||
output_tx
|
||||
.send(output.to_string())
|
||||
.expect("save network output");
|
||||
let response_id = format!("{call_id}-{}", input.len());
|
||||
let event = if let Some(session_id) = output
|
||||
.lines()
|
||||
@@ -247,9 +267,6 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
.to_string(),
|
||||
)
|
||||
} else {
|
||||
output_tx
|
||||
.send(output.to_string())
|
||||
.expect("save final output");
|
||||
ev_assistant_message(&response_id, "done")
|
||||
};
|
||||
sse_response(sse(vec![event, ev_completed(&response_id)]))
|
||||
@@ -259,18 +276,35 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
submit_managed_network_turn(
|
||||
&test,
|
||||
prompt,
|
||||
vec![local(test.config.cwd.clone())],
|
||||
vec![local(local_cwd.clone())],
|
||||
ApprovalsReviewer::AutoReview,
|
||||
AskForApproval::OnRequest,
|
||||
)
|
||||
.await?;
|
||||
wait_for_completion_without_network_prompt(&test).await;
|
||||
let chunks = output_rx.try_iter().collect::<Vec<_>>();
|
||||
let last = chunks.last().context("expected network output")?;
|
||||
if outcome == "allow" {
|
||||
assert!(
|
||||
last.lines()
|
||||
.any(|line| line == "Process exited with code 0"),
|
||||
"approved network command did not exit successfully: {last}"
|
||||
);
|
||||
}
|
||||
outputs.push(
|
||||
output_rx
|
||||
.try_recv()
|
||||
.context("expected final network output")?,
|
||||
chunks
|
||||
.iter()
|
||||
.map(|chunk| {
|
||||
// Tool errors have no header. Strip each exec header before joining stdout.
|
||||
chunk
|
||||
.split_once("\nOutput:\n")
|
||||
.map_or(chunk.as_str(), |(_, body)| body)
|
||||
})
|
||||
.collect::<String>(),
|
||||
);
|
||||
actions.extend(guardian_network_actions(&guardian)?);
|
||||
// The first allow must reach the origin, and the following denial must not.
|
||||
assert_eq!(upstream.received_requests().await.len(), 1);
|
||||
drop(parent);
|
||||
}
|
||||
|
||||
@@ -278,16 +312,16 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
assert_eq!(
|
||||
actions[0],
|
||||
json!({
|
||||
"host": NETWORK_TEST_HOST,
|
||||
"port": 80,
|
||||
"host": server.address().ip().to_string(),
|
||||
"port": server.address().port(),
|
||||
"protocol": "http",
|
||||
"target": NETWORK_TEST_TARGET,
|
||||
"target": origin,
|
||||
"tool": "network_access",
|
||||
"environment_id": LOCAL_ENVIRONMENT_ID,
|
||||
"trigger": {
|
||||
"callId": first_call_id,
|
||||
"command": expected_command,
|
||||
"cwd": test.config.cwd,
|
||||
"cwd": local_cwd,
|
||||
"sandboxPermissions": "use_default",
|
||||
"toolName": "exec_command",
|
||||
"tty": false,
|
||||
@@ -304,10 +338,17 @@ async fn guardian_network_approval_preserves_action_and_outcome_routing(
|
||||
actions[1]
|
||||
.pointer("/trigger/command/2")
|
||||
.and_then(Value::as_str),
|
||||
Some(second_command.as_str())
|
||||
Some(command.as_str())
|
||||
);
|
||||
|
||||
assert!(!outputs[0].contains("rejected"));
|
||||
assert!(
|
||||
outputs[0]
|
||||
.lines()
|
||||
.any(|line| line == "200:guardian-upstream-reached"),
|
||||
"expected the approved request to receive the origin's response; got: {}",
|
||||
outputs[0]
|
||||
);
|
||||
assert!(outputs[1].contains(denial));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user