Forward executor network policy decisions for auditing (#38670)

## What changed

- Add a best-effort `network/policyDecision` notification for final domain and non-domain policy decisions made by executor-local proxies.
- Validate notifications against the active process on the controller and emit audit events with controller-trusted session and execution metadata.
- Reserve outbound RPC capacity so audit notifications cannot block control messages, and expose valid `chatgpt-account-id` header values for audit attribution.

## Testing

- Cover notification serialization, proxy decision capture, executor-to-controller delivery, trusted metadata handling, and reserved RPC capacity.

GitOrigin-RevId: a39f96a6b3d9401c03d54eaef5b9a6d3fe0da78b
This commit is contained in:
viyatb-oai
2026-08-14 23:42:40 +00:00
committed by copyberry
parent a186f5484d
commit 15fde8c1f2
15 changed files with 655 additions and 19 deletions
@@ -1,7 +1,9 @@
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
use codex_exec_server_protocol::JSONRPCMessage;
use codex_exec_server_protocol::JSONRPCNotification;
use codex_exec_server_protocol::JSONRPCRequest;
use codex_exec_server_protocol::JSONRPCResponse;
use codex_exec_server_protocol::RequestId;
@@ -10,15 +12,21 @@ use codex_http_client::OutboundProxyPolicy;
use codex_network_proxy::NetworkDecision;
use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkPolicyRequest;
use codex_network_proxy::NetworkProxyAuditMetadata;
use codex_utils_path_uri::PathUri;
use pretty_assertions::assert_eq;
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use tokio::time::timeout;
use tracing::instrument::WithSubscriber;
use tracing_subscriber::prelude::*;
use super::super::LazyRemoteExecServerClient;
use super::super::NetworkPolicyAuditContext;
use super::super::NetworkPolicyDecisionController;
use super::super::SessionState;
use super::super::handle_server_notification;
use super::accept_websocket;
use super::complete_websocket_initialize;
use super::read_jsonrpc_websocket;
@@ -31,7 +39,9 @@ use crate::protocol::ExecParams;
use crate::protocol::ExecServerNetworkPolicyDecision;
use crate::protocol::ExecServerNetworkPolicyRequest;
use crate::protocol::ExecServerNetworkProtocol;
use crate::protocol::NETWORK_POLICY_DECISION_METHOD;
use crate::protocol::NETWORK_POLICY_REQUEST_METHOD;
use crate::protocol::NetworkPolicyDecisionNotification;
use crate::protocol::NetworkPolicyRequestParams;
use crate::protocol::NetworkPolicyRequestResponse;
use crate::rpc_server_requests::MAX_IN_FLIGHT_SERVER_CALLS;
@@ -76,6 +86,129 @@ async fn read_decision(
.decision
}
#[tokio::test(flavor = "current_thread")]
async fn policy_decisions_reject_forged_process_and_use_trusted_controller_metadata() {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("listener should bind");
let websocket_url = format!("ws://{}", listener.local_addr().expect("listener address"));
let (release_tx, release_rx) = oneshot::channel();
let (initialized_tx, initialized_rx) = oneshot::channel();
let server = tokio::spawn(async move {
let mut websocket = accept_websocket(&listener).await;
complete_websocket_initialize(
&mut websocket,
"audit-session",
/*expected_resume_session_id*/ None,
)
.await;
initialized_tx
.send(())
.expect("client should await completed WebSocket initialization");
release_rx.await.expect("server should be released");
});
let logs = Arc::new(Mutex::new(Vec::new()));
let writer_logs = Arc::clone(&logs);
let subscriber = tracing_subscriber::registry().with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_writer(move || AuditLogWriter(Arc::clone(&writer_logs))),
);
async move {
let client = LazyRemoteExecServerClient::new(
ExecServerTransportParams::websocket_url(websocket_url, Duration::from_secs(1)),
HttpClientFactory::new(OutboundProxyPolicy::ReqwestDefault),
)
.get()
.await
.expect("client should connect");
initialized_rx
.await
.expect("server should complete WebSocket initialization");
let mut state = SessionState::new(/*recoverable*/ true);
state.network_policy.audit = Some(NetworkPolicyAuditContext {
metadata: NetworkProxyAuditMetadata {
conversation_id: Some("trusted-conversation".to_string()),
user_account_id: Some("trusted-account".to_string()),
..NetworkProxyAuditMetadata::default()
},
execution_id: Some("trusted-execution".to_string()),
});
client
.inner
.insert_session(&ProcessId::from("trusted-process"), Arc::new(state))
.expect("trusted process should register");
for (process_id, host) in [
("forged-process", "forged.example"),
("trusted-process", "trusted.example"),
] {
handle_server_notification(
&client.inner,
JSONRPCNotification {
method: NETWORK_POLICY_DECISION_METHOD.to_string(),
params: Some(
serde_json::to_value(NetworkPolicyDecisionNotification {
process_id: ProcessId::from(process_id),
timestamp: "2026-08-11T12:00:00.000Z".to_string(),
scope: "domain".to_string(),
decision: "deny".to_string(),
source: "baseline_policy".to_string(),
reason: "not_allowed".to_string(),
protocol: ExecServerNetworkProtocol::HttpsConnect,
host: host.to_string(),
port: 443,
method: None,
client: None,
policy_override: false,
})
.expect("network policy decision should serialize"),
),
},
)
.await
.expect("controller should handle network policy notification");
}
let output = String::from_utf8(
logs.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone(),
)
.expect("audit log should be UTF-8");
assert!(!output.contains("forged.example"));
for expected in [
"trusted-conversation",
"trusted-account",
"trusted-execution",
] {
assert!(
output.contains(expected),
"missing `{expected}` in {output}"
);
}
release_tx.send(()).expect("server should be released");
}
.with_subscriber(subscriber)
.await;
server.await.expect("server should finish");
}
struct AuditLogWriter(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for AuditLogWriter {
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.extend_from_slice(bytes);
Ok(bytes.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[tokio::test]
async fn abandoned_process_start_unregisters_and_cleans_up() {
let listener = TcpListener::bind("127.0.0.1:0")
@@ -155,7 +288,8 @@ async fn abandoned_process_start_unregisters_and_cleans_up() {
Arc::new(|_request: NetworkPolicyRequest| async { NetworkDecision::Allow });
let decider_weak = Arc::downgrade(&decider);
state
.network_policy_controller
.network_policy
.controller
.store(Some(Arc::new(NetworkPolicyDecisionController {
decider,
timeout: Duration::from_secs(30),
@@ -163,7 +297,7 @@ async fn abandoned_process_start_unregisters_and_cleans_up() {
start.abort();
assert!(start.await.is_err_and(|error| error.is_cancelled()));
assert!(state.network_policy_cancelled.is_cancelled());
assert!(state.network_policy.cancelled.is_cancelled());
assert!(client.inner.get_session(&process_id).is_none());
assert!(decider_weak.upgrade().is_none());
@@ -305,7 +439,7 @@ async fn policy_requests_use_process_decider_and_cancel_on_unregister() {
}
}
});
session.state.network_policy_controller.store(Some(Arc::new(
session.state.network_policy.controller.store(Some(Arc::new(
NetworkPolicyDecisionController {
decider,
timeout: Duration::from_secs(30),