core: carry parent tool item id for network approvals

Remove the synthetic network approval token and carry parent_tool_item_id directly through the managed proxy attribution path.

Co-authored-by: Codex <noreply@openai.com>
This commit is contained in:
Charles Cunningham
2026-03-23 17:38:01 -07:00
co-authored by Codex
parent 58b860f1bb
commit da3dc36b63
32 changed files with 243 additions and 282 deletions
@@ -1690,7 +1690,7 @@ impl CodexMessageProcessor {
network: started_network_proxy
.as_ref()
.map(codex_core::config::StartedNetworkProxy::proxy),
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level,
windows_sandbox_private_desktop: self
+2 -2
View File
@@ -732,7 +732,7 @@ mod tests {
cwd: PathBuf::from("."),
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
expiration: ExecExpiration::DefaultTimeout,
capture_policy: codex_core::exec::ExecCapturePolicy::ShellTool,
sandbox: SandboxType::WindowsRestrictedToken,
@@ -846,7 +846,7 @@ mod tests {
cwd: PathBuf::from("."),
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
expiration: ExecExpiration::Cancellation(CancellationToken::new()),
capture_policy: codex_core::exec::ExecCapturePolicy::ShellTool,
sandbox: SandboxType::None,
+2 -2
View File
@@ -4813,7 +4813,7 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() {
capture_policy: ExecCapturePolicy::ShellTool,
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions,
windows_sandbox_level: turn_context.windows_sandbox_level,
windows_sandbox_private_desktop: turn_context
@@ -4832,7 +4832,7 @@ async fn rejects_escalated_permissions_when_policy_not_on_request() {
capture_policy: ExecCapturePolicy::ShellTool,
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
windows_sandbox_level: turn_context.windows_sandbox_level,
windows_sandbox_private_desktop: turn_context
.config
+1 -1
View File
@@ -128,7 +128,7 @@ async fn guardian_allows_shell_additional_permissions_requests_past_policy_valid
capture_policy: ExecCapturePolicy::ShellTool,
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::WithAdditionalPermissions,
windows_sandbox_level: turn_context.windows_sandbox_level,
windows_sandbox_private_desktop: turn_context
+12 -10
View File
@@ -81,7 +81,9 @@ pub struct ExecParams {
pub capture_policy: ExecCapturePolicy,
pub env: HashMap<String, String>,
pub network: Option<NetworkProxy>,
pub network_owner_id: Option<String>,
/// Parent tool item id to propagate through managed proxy settings so
/// blocked requests can be attributed back to the originating tool call.
pub parent_tool_item_id: Option<String>,
pub sandbox_permissions: SandboxPermissions,
pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel,
pub windows_sandbox_private_desktop: bool,
@@ -264,7 +266,7 @@ pub fn build_exec_request(
expiration,
capture_policy,
network,
network_owner_id,
parent_tool_item_id,
sandbox_permissions,
windows_sandbox_level,
windows_sandbox_private_desktop,
@@ -272,7 +274,7 @@ pub fn build_exec_request(
arg0: _,
} = params;
if let Some(network) = network.as_ref() {
network.apply_to_env_for_owner(&mut env, network_owner_id.as_deref());
network.apply_to_env_for_parent_tool_item(&mut env, parent_tool_item_id.as_deref());
}
let (program, args) = command.split_first().ok_or_else(|| {
CodexErr::Io(io::Error::new(
@@ -303,7 +305,7 @@ pub fn build_exec_request(
sandbox: sandbox_type,
enforce_managed_network,
network: network.as_ref(),
network_owner_id: network_owner_id.as_deref(),
parent_tool_item_id: parent_tool_item_id.as_deref(),
sandbox_policy_cwd: sandbox_cwd,
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions: None,
@@ -327,7 +329,7 @@ pub(crate) async fn execute_exec_request(
cwd,
env,
network,
network_owner_id,
parent_tool_item_id,
expiration,
capture_policy,
sandbox,
@@ -349,7 +351,7 @@ pub(crate) async fn execute_exec_request(
capture_policy,
env,
network: network.clone(),
network_owner_id,
parent_tool_item_id,
sandbox_permissions,
windows_sandbox_level,
windows_sandbox_private_desktop,
@@ -453,7 +455,7 @@ async fn exec_windows_sandbox(
cwd,
mut env,
network,
network_owner_id,
parent_tool_item_id,
expiration,
capture_policy,
windows_sandbox_level,
@@ -461,7 +463,7 @@ async fn exec_windows_sandbox(
..
} = params;
if let Some(network) = network.as_ref() {
network.apply_to_env_for_owner(&mut env, network_owner_id.as_deref());
network.apply_to_env_for_parent_tool_item(&mut env, parent_tool_item_id.as_deref());
}
// TODO(iceweasel-oai): run_windows_sandbox_capture should support all
@@ -844,7 +846,7 @@ async fn exec(
cwd,
mut env,
network,
network_owner_id,
parent_tool_item_id,
arg0,
expiration,
capture_policy,
@@ -852,7 +854,7 @@ async fn exec(
..
} = params;
if let Some(network) = network.as_ref() {
network.apply_to_env_for_owner(&mut env, network_owner_id.as_deref());
network.apply_to_env_for_parent_tool_item(&mut env, parent_tool_item_id.as_deref());
}
let (program, args) = command.split_first().ok_or_else(|| {
+5 -5
View File
@@ -259,7 +259,7 @@ async fn exec_full_buffer_capture_ignores_expiration() -> Result<()> {
capture_policy: ExecCapturePolicy::FullBuffer,
env,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -299,7 +299,7 @@ async fn exec_full_buffer_capture_keeps_io_drain_timeout_when_descendant_holds_p
capture_policy: ExecCapturePolicy::FullBuffer,
env: std::env::vars().collect(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -350,7 +350,7 @@ async fn process_exec_tool_call_preserves_full_buffer_capture_policy() -> Result
capture_policy: ExecCapturePolicy::FullBuffer,
env: std::env::vars().collect(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -591,7 +591,7 @@ async fn kill_child_process_group_kills_grandchildren_on_timeout() -> Result<()>
capture_policy: ExecCapturePolicy::ShellTool,
env,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -650,7 +650,7 @@ async fn process_exec_tool_call_respects_cancellation_token() -> Result<()> {
capture_policy: ExecCapturePolicy::ShellTool,
env,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -156,7 +156,7 @@ fn denied_network_policy_message_requires_deny_decision() {
let blocked = BlockedRequest {
host: "example.com".to_string(),
reason: "not_allowed".to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: None,
method: Some("GET".to_string()),
mode: None,
@@ -174,7 +174,7 @@ fn denied_network_policy_message_for_denylist_block_is_explicit() {
let blocked = BlockedRequest {
host: "example.com".to_string(),
reason: "denied".to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: None,
method: Some("GET".to_string()),
mode: None,
+9 -4
View File
@@ -68,7 +68,9 @@ pub struct ExecRequest {
pub cwd: PathBuf,
pub env: HashMap<String, String>,
pub network: Option<NetworkProxy>,
pub network_owner_id: Option<String>,
/// Parent tool item id propagated into child process proxy settings for
/// blocked-request attribution.
pub parent_tool_item_id: Option<String>,
pub expiration: ExecExpiration,
pub capture_policy: ExecCapturePolicy,
pub sandbox: SandboxType,
@@ -95,7 +97,10 @@ pub(crate) struct SandboxTransformRequest<'a> {
// TODO(viyatb): Evaluate switching this to Option<Arc<NetworkProxy>>
// to make shared ownership explicit across runtime/sandbox plumbing.
pub network: Option<&'a NetworkProxy>,
pub network_owner_id: Option<&'a str>,
/// Parent tool item id for the current tool call. This is threaded into
/// managed proxy credentials so the proxy can report blocked requests
/// against the exact originating call.
pub parent_tool_item_id: Option<&'a str>,
pub sandbox_policy_cwd: &'a Path,
#[cfg(target_os = "macos")]
pub macos_seatbelt_profile_extensions: Option<&'a MacOsSeatbeltProfileExtensions>,
@@ -594,7 +599,7 @@ impl SandboxManager {
sandbox,
enforce_managed_network,
network,
network_owner_id,
parent_tool_item_id,
sandbox_policy_cwd,
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions,
@@ -712,7 +717,7 @@ impl SandboxManager {
cwd: spec.cwd,
env,
network: network.cloned(),
network_owner_id: network_owner_id.map(ToString::to_string),
parent_tool_item_id: parent_tool_item_id.map(ToString::to_string),
expiration: spec.expiration,
capture_policy: spec.capture_policy,
sandbox,
+3 -3
View File
@@ -171,7 +171,7 @@ fn transform_preserves_unrestricted_file_system_policy_for_restricted_network()
sandbox: SandboxType::None,
enforce_managed_network: false,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_policy_cwd: cwd.as_path(),
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions: None,
@@ -542,7 +542,7 @@ fn transform_additional_permissions_enable_network_for_external_sandbox() {
sandbox: SandboxType::None,
enforce_managed_network: false,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_policy_cwd: cwd.as_path(),
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions: None,
@@ -617,7 +617,7 @@ fn transform_additional_permissions_preserves_denied_entries() {
sandbox: SandboxType::None,
enforce_managed_network: false,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_policy_cwd: cwd.as_path(),
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions: None,
+1 -1
View File
@@ -163,7 +163,7 @@ pub(crate) async fn execute_user_shell_command(
Some(session.conversation_id),
),
network: turn_context.network.clone(),
network_owner_id: None,
parent_tool_item_id: None,
// TODO(zhao-oai): Now that we have ExecExpiration::Cancellation, we
// should use that instead of an "arbitrarily large" timeout here.
expiration: USER_SHELL_TIMEOUT_MS.into(),
@@ -215,7 +215,6 @@ impl ToolHandler for ApplyPatchHandler {
session: session.clone(),
turn: turn.clone(),
call_id: call_id.clone(),
network_approval_owner_id: None,
tool_name: tool_name.to_string(),
};
let out = orchestrator
@@ -320,7 +319,6 @@ pub(crate) async fn intercept_apply_patch(
session: session.clone(),
turn: turn.clone(),
call_id: call_id.to_string(),
network_approval_owner_id: None,
tool_name: tool_name.to_string(),
};
let out = orchestrator
+2 -3
View File
@@ -74,7 +74,7 @@ impl ShellHandler {
capture_policy: ExecCapturePolicy::ShellTool,
env: create_env(&turn_context.shell_environment_policy, Some(thread_id)),
network: turn_context.network.clone(),
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: params.sandbox_permissions.unwrap_or_default(),
windows_sandbox_level: turn_context.windows_sandbox_level,
windows_sandbox_private_desktop: turn_context
@@ -130,7 +130,7 @@ impl ShellCommandHandler {
capture_policy: ExecCapturePolicy::ShellTool,
env: create_env(&turn_context.shell_environment_policy, Some(thread_id)),
network: turn_context.network.clone(),
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: params.sandbox_permissions.unwrap_or_default(),
windows_sandbox_level: turn_context.windows_sandbox_level,
windows_sandbox_private_desktop: turn_context
@@ -476,7 +476,6 @@ impl ShellHandler {
session: session.clone(),
turn: turn.clone(),
call_id: call_id.clone(),
network_approval_owner_id: None,
tool_name,
};
let out = orchestrator
+1 -1
View File
@@ -1067,7 +1067,7 @@ impl JsReplManager {
sandbox: sandbox_type,
enforce_managed_network: has_managed_network_requirements,
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_policy_cwd: &turn.cwd,
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions: None,
+54 -65
View File
@@ -28,7 +28,6 @@ use tokio::sync::Mutex;
use tokio::sync::Notify;
use tokio::sync::RwLock;
use tracing::warn;
use uuid::Uuid;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum NetworkApprovalMode {
@@ -44,18 +43,18 @@ pub(crate) struct NetworkApprovalSpec {
#[derive(Clone, Debug)]
pub(crate) struct DeferredNetworkApproval {
registration_id: String,
parent_tool_item_id: String,
}
impl DeferredNetworkApproval {
pub(crate) fn registration_id(&self) -> &str {
&self.registration_id
pub(crate) fn parent_tool_item_id(&self) -> &str {
&self.parent_tool_item_id
}
}
#[derive(Debug)]
pub(crate) struct ActiveNetworkApproval {
registration_id: Option<String>,
parent_tool_item_id: Option<String>,
mode: NetworkApprovalMode,
}
@@ -64,14 +63,12 @@ impl ActiveNetworkApproval {
self.mode
}
pub(crate) fn owner_id(&self) -> Option<&str> {
self.registration_id.as_deref()
}
pub(crate) fn into_deferred(self) -> Option<DeferredNetworkApproval> {
match (self.mode, self.registration_id) {
(NetworkApprovalMode::Deferred, Some(registration_id)) => {
Some(DeferredNetworkApproval { registration_id })
match (self.mode, self.parent_tool_item_id) {
(NetworkApprovalMode::Deferred, Some(parent_tool_item_id)) => {
Some(DeferredNetworkApproval {
parent_tool_item_id,
})
}
_ => None,
}
@@ -164,7 +161,6 @@ impl PendingHostApproval {
}
struct ActiveNetworkApprovalCall {
registration_id: String,
turn_id: String,
parent_tool_item_id: String,
}
@@ -199,38 +195,32 @@ impl NetworkApprovalService {
other_approved_hosts.extend(approved_hosts.iter().cloned());
}
async fn register_call(
&self,
registration_id: String,
turn_id: String,
parent_tool_item_id: String,
) {
async fn register_call(&self, turn_id: String, parent_tool_item_id: String) {
let mut active_calls = self.active_calls.lock().await;
let key = registration_id.clone();
let key = parent_tool_item_id.clone();
active_calls.insert(
key,
Arc::new(ActiveNetworkApprovalCall {
registration_id,
turn_id,
parent_tool_item_id,
}),
);
}
pub(crate) async fn unregister_call(&self, registration_id: &str) {
pub(crate) async fn unregister_call(&self, parent_tool_item_id: &str) {
let mut active_calls = self.active_calls.lock().await;
active_calls.shift_remove(registration_id);
active_calls.shift_remove(parent_tool_item_id);
let mut call_outcomes = self.call_outcomes.lock().await;
call_outcomes.remove(registration_id);
call_outcomes.remove(parent_tool_item_id);
}
async fn resolve_owner_call(
async fn resolve_active_call(
&self,
network_owner_id: Option<&str>,
parent_tool_item_id: Option<&str>,
) -> Option<Arc<ActiveNetworkApprovalCall>> {
if let Some(network_owner_id) = network_owner_id {
if let Some(parent_tool_item_id) = parent_tool_item_id {
let active_calls = self.active_calls.lock().await;
return active_calls.get(network_owner_id).cloned();
return active_calls.get(parent_tool_item_id).cloned();
}
self.resolve_single_active_call().await
@@ -259,32 +249,36 @@ impl NetworkApprovalService {
(created, true)
}
async fn record_outcome_for_owner_call(
async fn record_outcome_for_active_call(
&self,
network_owner_id: Option<&str>,
parent_tool_item_id: Option<&str>,
outcome: NetworkApprovalOutcome,
) {
let Some(owner_call) = self.resolve_owner_call(network_owner_id).await else {
let Some(active_call) = self.resolve_active_call(parent_tool_item_id).await else {
return;
};
self.record_call_outcome(&owner_call.registration_id, outcome)
self.record_call_outcome(&active_call.parent_tool_item_id, outcome)
.await;
}
async fn take_call_outcome(&self, registration_id: &str) -> Option<NetworkApprovalOutcome> {
async fn take_call_outcome(&self, parent_tool_item_id: &str) -> Option<NetworkApprovalOutcome> {
let mut call_outcomes = self.call_outcomes.lock().await;
call_outcomes.remove(registration_id)
call_outcomes.remove(parent_tool_item_id)
}
async fn record_call_outcome(&self, registration_id: &str, outcome: NetworkApprovalOutcome) {
async fn record_call_outcome(
&self,
parent_tool_item_id: &str,
outcome: NetworkApprovalOutcome,
) {
let mut call_outcomes = self.call_outcomes.lock().await;
if matches!(
call_outcomes.get(registration_id),
call_outcomes.get(parent_tool_item_id),
Some(NetworkApprovalOutcome::DeniedByUser)
) {
return;
}
call_outcomes.insert(registration_id.to_string(), outcome);
call_outcomes.insert(parent_tool_item_id.to_string(), outcome);
}
pub(crate) async fn record_blocked_request(&self, blocked: BlockedRequest) {
@@ -292,8 +286,8 @@ impl NetworkApprovalService {
return;
};
self.record_outcome_for_owner_call(
blocked.network_owner_id.as_deref(),
self.record_outcome_for_active_call(
blocked.parent_tool_item_id.as_deref(),
NetworkApprovalOutcome::DeniedByPolicy(message),
)
.await;
@@ -358,8 +352,8 @@ impl NetworkApprovalService {
pending.set_decision(PendingApprovalDecision::Deny).await;
let mut pending_approvals = self.pending_host_approvals.lock().await;
pending_approvals.remove(&key);
self.record_outcome_for_owner_call(
request.network_owner_id.as_deref(),
self.record_outcome_for_active_call(
request.parent_tool_item_id.as_deref(),
NetworkApprovalOutcome::DeniedByPolicy(policy_denial_message),
)
.await;
@@ -369,8 +363,8 @@ impl NetworkApprovalService {
pending.set_decision(PendingApprovalDecision::Deny).await;
let mut pending_approvals = self.pending_host_approvals.lock().await;
pending_approvals.remove(&key);
self.record_outcome_for_owner_call(
request.network_owner_id.as_deref(),
self.record_outcome_for_active_call(
request.parent_tool_item_id.as_deref(),
NetworkApprovalOutcome::DeniedByPolicy(policy_denial_message),
)
.await;
@@ -381,21 +375,21 @@ impl NetworkApprovalService {
host: request.host.clone(),
protocol,
};
let owner_call = self
.resolve_owner_call(request.network_owner_id.as_deref())
let active_call = self
.resolve_active_call(request.parent_tool_item_id.as_deref())
.await;
let approval_decision = if routes_approval_to_guardian(&turn_context) {
// TODO(ccunningham): Attach guardian network reviews to the reviewed tool item
// lifecycle instead of this temporary standalone network approval id.
// lifecycle instead of this temporary standalone network review id.
review_approval_request(
&session,
&turn_context,
GuardianApprovalRequest::NetworkAccess {
id: Self::approval_id_for_key(&key),
turn_id: owner_call
turn_id: active_call
.as_ref()
.map_or_else(|| turn_context.sub_id.clone(), |call| call.turn_id.clone()),
parent_tool_item_id: owner_call
parent_tool_item_id: active_call
.as_ref()
.map(|call| call.parent_tool_item_id.clone()),
target,
@@ -494,9 +488,9 @@ impl NetworkApprovalService {
.await;
}
}
if let Some(owner_call) = owner_call.as_ref() {
if let Some(active_call) = active_call.as_ref() {
self.record_call_outcome(
&owner_call.registration_id,
&active_call.parent_tool_item_id,
NetworkApprovalOutcome::DeniedByUser,
)
.await;
@@ -507,18 +501,18 @@ impl NetworkApprovalService {
},
ReviewDecision::Denied | ReviewDecision::Abort => {
if routes_approval_to_guardian(&turn_context) {
if let Some(owner_call) = owner_call.as_ref() {
if let Some(active_call) = active_call.as_ref() {
self.record_call_outcome(
&owner_call.registration_id,
&active_call.parent_tool_item_id,
NetworkApprovalOutcome::DeniedByPolicy(
GUARDIAN_REJECTION_MESSAGE.to_string(),
),
)
.await;
}
} else if let Some(owner_call) = owner_call.as_ref() {
} else if let Some(active_call) = active_call.as_ref() {
self.record_call_outcome(
&owner_call.registration_id,
&active_call.parent_tool_item_id,
NetworkApprovalOutcome::DeniedByUser,
)
.await;
@@ -594,19 +588,14 @@ pub(crate) async fn begin_network_approval(
return None;
}
let registration_id = Uuid::new_v4().to_string();
session
.services
.network_approval
.register_call(
registration_id.clone(),
turn_id.to_string(),
parent_tool_item_id.to_string(),
)
.register_call(turn_id.to_string(), parent_tool_item_id.to_string())
.await;
Some(ActiveNetworkApproval {
registration_id: Some(registration_id),
parent_tool_item_id: Some(parent_tool_item_id.to_string()),
mode: spec.mode,
})
}
@@ -615,20 +604,20 @@ pub(crate) async fn finish_immediate_network_approval(
session: &Session,
active: ActiveNetworkApproval,
) -> Result<(), ToolError> {
let Some(registration_id) = active.registration_id.as_deref() else {
let Some(parent_tool_item_id) = active.parent_tool_item_id.as_deref() else {
return Ok(());
};
let approval_outcome = session
.services
.network_approval
.take_call_outcome(registration_id)
.take_call_outcome(parent_tool_item_id)
.await;
session
.services
.network_approval
.unregister_call(registration_id)
.unregister_call(parent_tool_item_id)
.await;
match approval_outcome {
@@ -650,7 +639,7 @@ pub(crate) async fn finish_deferred_network_approval(
session
.services
.network_approval
.unregister_call(deferred.registration_id())
.unregister_call(deferred.parent_tool_item_id())
.await;
}
@@ -180,14 +180,17 @@ fn only_never_policy_disables_network_approval_flow() {
}
fn denied_blocked_request(host: &str) -> BlockedRequest {
denied_blocked_request_with_owner(host, None)
denied_blocked_request_with_parent_tool_item(host, None)
}
fn denied_blocked_request_with_owner(host: &str, network_owner_id: Option<&str>) -> BlockedRequest {
fn denied_blocked_request_with_parent_tool_item(
host: &str,
parent_tool_item_id: Option<&str>,
) -> BlockedRequest {
BlockedRequest::new(BlockedRequestArgs {
host: host.to_string(),
reason: "not_allowed".to_string(),
network_owner_id: network_owner_id.map(ToString::to_string),
parent_tool_item_id: parent_tool_item_id.map(ToString::to_string),
client: None,
method: None,
mode: None,
@@ -199,14 +202,10 @@ fn denied_blocked_request_with_owner(host: &str, network_owner_id: Option<&str>)
}
#[tokio::test]
async fn record_blocked_request_sets_policy_outcome_for_owner_call() {
async fn record_blocked_request_sets_policy_outcome_for_active_call() {
let service = NetworkApprovalService::default();
service
.register_call(
"registration-1".to_string(),
"turn-1".to_string(),
"command-1".to_string(),
)
.register_call("turn-1".to_string(), "command-1".to_string())
.await;
service
@@ -214,7 +213,7 @@ async fn record_blocked_request_sets_policy_outcome_for_owner_call() {
.await;
assert_eq!(
service.take_call_outcome("registration-1").await,
service.take_call_outcome("command-1").await,
Some(NetworkApprovalOutcome::DeniedByPolicy(
"Network access to \"example.com\" was blocked: domain is not on the allowlist for the current sandbox mode.".to_string()
))
@@ -225,22 +224,18 @@ async fn record_blocked_request_sets_policy_outcome_for_owner_call() {
async fn blocked_request_policy_does_not_override_user_denial_outcome() {
let service = NetworkApprovalService::default();
service
.register_call(
"registration-1".to_string(),
"turn-1".to_string(),
"command-1".to_string(),
)
.register_call("turn-1".to_string(), "command-1".to_string())
.await;
service
.record_call_outcome("registration-1", NetworkApprovalOutcome::DeniedByUser)
.record_call_outcome("command-1", NetworkApprovalOutcome::DeniedByUser)
.await;
service
.record_blocked_request(denied_blocked_request("example.com"))
.await;
assert_eq!(
service.take_call_outcome("registration-1").await,
service.take_call_outcome("command-1").await,
Some(NetworkApprovalOutcome::DeniedByUser)
);
}
@@ -249,84 +244,59 @@ async fn blocked_request_policy_does_not_override_user_denial_outcome() {
async fn record_blocked_request_ignores_ambiguous_unattributed_blocked_requests() {
let service = NetworkApprovalService::default();
service
.register_call(
"registration-1".to_string(),
"turn-1".to_string(),
"command-1".to_string(),
)
.register_call("turn-1".to_string(), "command-1".to_string())
.await;
service
.register_call(
"registration-2".to_string(),
"turn-1".to_string(),
"command-2".to_string(),
)
.register_call("turn-1".to_string(), "command-2".to_string())
.await;
service
.record_blocked_request(denied_blocked_request("example.com"))
.await;
assert_eq!(service.take_call_outcome("registration-1").await, None);
assert_eq!(service.take_call_outcome("registration-2").await, None);
assert_eq!(service.take_call_outcome("command-1").await, None);
assert_eq!(service.take_call_outcome("command-2").await, None);
}
#[tokio::test]
async fn resolve_owner_call_uses_network_owner_id_when_multiple_calls_are_active() {
async fn resolve_active_call_uses_parent_tool_item_id_when_multiple_calls_are_active() {
let service = NetworkApprovalService::default();
service
.register_call(
"registration-1".to_string(),
"turn-1".to_string(),
"command-1".to_string(),
)
.register_call("turn-1".to_string(), "command-1".to_string())
.await;
service
.register_call(
"registration-2".to_string(),
"turn-2".to_string(),
"command-2".to_string(),
)
.register_call("turn-2".to_string(), "command-2".to_string())
.await;
let owner_call = service
.resolve_owner_call(Some("registration-2"))
let active_call = service
.resolve_active_call(Some("command-2"))
.await
.expect("owner call should resolve");
.expect("active call should resolve");
assert_eq!(owner_call.registration_id, "registration-2");
assert_eq!(owner_call.turn_id, "turn-2");
assert_eq!(owner_call.parent_tool_item_id, "command-2");
assert_eq!(active_call.turn_id, "turn-2");
assert_eq!(active_call.parent_tool_item_id, "command-2");
}
#[tokio::test]
async fn record_blocked_request_uses_network_owner_id_when_multiple_calls_are_active() {
async fn record_blocked_request_uses_parent_tool_item_id_when_multiple_calls_are_active() {
let service = NetworkApprovalService::default();
service
.register_call(
"registration-1".to_string(),
"turn-1".to_string(),
"command-1".to_string(),
)
.register_call("turn-1".to_string(), "command-1".to_string())
.await;
service
.register_call(
"registration-2".to_string(),
"turn-2".to_string(),
"command-2".to_string(),
)
.register_call("turn-2".to_string(), "command-2".to_string())
.await;
service
.record_blocked_request(denied_blocked_request_with_owner(
.record_blocked_request(denied_blocked_request_with_parent_tool_item(
"example.com",
Some("registration-2"),
Some("command-2"),
))
.await;
assert_eq!(service.take_call_outcome("registration-1").await, None);
assert_eq!(service.take_call_outcome("command-1").await, None);
assert_eq!(
service.take_call_outcome("registration-2").await,
service.take_call_outcome("command-2").await,
Some(NetworkApprovalOutcome::DeniedByPolicy(
"Network access to \"example.com\" was blocked: domain is not on the allowlist for the current sandbox mode.".to_string()
))
+1 -14
View File
@@ -13,7 +13,6 @@ use crate::guardian::GUARDIAN_REJECTION_MESSAGE;
use crate::guardian::routes_approval_to_guardian;
use crate::network_policy_decision::network_approval_context_from_payload;
use crate::sandboxing::SandboxManager;
use crate::tools::network_approval::ActiveNetworkApproval;
use crate::tools::network_approval::DeferredNetworkApproval;
use crate::tools::network_approval::NetworkApprovalMode;
use crate::tools::network_approval::begin_network_approval;
@@ -66,19 +65,7 @@ impl ToolOrchestrator {
tool.network_approval_spec(req, tool_ctx),
)
.await;
let network_approval_owner_id = network_approval
.as_ref()
.and_then(ActiveNetworkApproval::owner_id)
.map(ToString::to_string);
let attempt_tool_ctx = ToolCtx {
session: tool_ctx.session.clone(),
turn: tool_ctx.turn.clone(),
call_id: tool_ctx.call_id.clone(),
network_approval_owner_id,
tool_name: tool_ctx.tool_name.clone(),
};
let run_result = tool.run(req, attempt, &attempt_tool_ctx).await;
let run_result = tool.run(req, attempt, tool_ctx).await;
let Some(network_approval) = network_approval else {
return (run_result, None);
@@ -208,7 +208,9 @@ impl ToolRuntime<ApplyPatchRequest, ExecToolCallOutput> for ApplyPatchRuntime {
) -> Result<ExecToolCallOutput, ToolError> {
let spec = Self::build_command_spec(req, &ctx.turn.config.codex_home)?;
let env = attempt
.env_for(spec, /*network*/ None, /*network_owner_id*/ None)
.env_for(
spec, /*network*/ None, /*parent_tool_item_id*/ None,
)
.map_err(|err| ToolError::Codex(err.into()))?;
let out = execute_env(env, Self::stdout_stream(ctx))
.await
+1 -5
View File
@@ -253,11 +253,7 @@ impl ToolRuntime<ShellRequest, ExecToolCallOutput> for ShellRuntime {
req.justification.clone(),
)?;
let env = attempt
.env_for(
spec,
req.network.as_ref(),
ctx.network_approval_owner_id.as_deref(),
)
.env_for(spec, req.network.as_ref(), Some(ctx.call_id.as_str()))
.map_err(|err| ToolError::Codex(err.into()))?;
let out = execute_env(env, Self::stdout_stream(ctx))
.await
@@ -117,18 +117,14 @@ pub(super) async fn try_run_zsh_fork(
req.justification.clone(),
)?;
let sandbox_exec_request = attempt
.env_for(
spec,
req.network.as_ref(),
ctx.network_approval_owner_id.as_deref(),
)
.env_for(spec, req.network.as_ref(), Some(ctx.call_id.as_str()))
.map_err(|err| ToolError::Codex(err.into()))?;
let crate::sandboxing::ExecRequest {
command,
cwd: sandbox_cwd,
env: sandbox_env,
network: sandbox_network,
network_owner_id,
parent_tool_item_id,
expiration: _sandbox_expiration,
capture_policy: _capture_policy,
sandbox,
@@ -158,7 +154,7 @@ pub(super) async fn try_run_zsh_fork(
sandbox,
env: sandbox_env,
network: sandbox_network,
network_owner_id,
parent_tool_item_id,
windows_sandbox_level,
sandbox_permissions,
justification,
@@ -265,7 +261,7 @@ pub(crate) async fn prepare_unified_exec_zsh_fork(
sandbox: exec_request.sandbox,
env: exec_request.env.clone(),
network: exec_request.network.clone(),
network_owner_id: exec_request.network_owner_id.clone(),
parent_tool_item_id: exec_request.parent_tool_item_id.clone(),
windows_sandbox_level: exec_request.windows_sandbox_level,
sandbox_permissions: exec_request.sandbox_permissions,
justification: exec_request.justification.clone(),
@@ -863,7 +859,7 @@ struct CoreShellCommandExecutor {
sandbox: SandboxType,
env: HashMap<String, String>,
network: Option<codex_network_proxy::NetworkProxy>,
network_owner_id: Option<String>,
parent_tool_item_id: Option<String>,
windows_sandbox_level: WindowsSandboxLevel,
sandbox_permissions: SandboxPermissions,
justification: Option<String>,
@@ -912,7 +908,7 @@ impl ShellCommandExecutor for CoreShellCommandExecutor {
cwd: self.cwd.clone(),
env: exec_env,
network: self.network.clone(),
network_owner_id: self.network_owner_id.clone(),
parent_tool_item_id: self.parent_tool_item_id.clone(),
expiration: ExecExpiration::Cancellation(cancel_rx),
capture_policy: ExecCapturePolicy::ShellTool,
sandbox: self.sandbox,
@@ -1069,7 +1065,7 @@ impl CoreShellCommandExecutor {
sandbox,
enforce_managed_network: self.network.is_some(),
network: self.network.as_ref(),
network_owner_id: self.network_owner_id.as_deref(),
parent_tool_item_id: self.parent_tool_item_id.as_deref(),
sandbox_policy_cwd: &self.sandbox_policy_cwd,
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions,
@@ -1079,9 +1075,9 @@ impl CoreShellCommandExecutor {
windows_sandbox_private_desktop: false,
})?;
if let Some(network) = exec_request.network.as_ref() {
network.apply_to_env_for_owner(
network.apply_to_env_for_parent_tool_item(
&mut exec_request.env,
exec_request.network_owner_id.as_deref(),
exec_request.parent_tool_item_id.as_deref(),
);
}
@@ -655,7 +655,7 @@ async fn prepare_escalated_exec_turn_default_preserves_macos_seatbelt_extensions
cwd: cwd.to_path_buf(),
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox: SandboxType::None,
sandbox_policy: SandboxPolicy::new_read_only_policy(),
file_system_sandbox_policy: read_only_file_system_sandbox_policy(),
@@ -708,7 +708,7 @@ async fn prepare_escalated_exec_permissions_preserve_macos_seatbelt_extensions()
cwd: cwd.to_path_buf(),
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox: SandboxType::None,
sandbox_policy: SandboxPolicy::DangerFullAccess,
file_system_sandbox_policy: unrestricted_file_system_sandbox_policy(),
@@ -784,7 +784,7 @@ async fn prepare_escalated_exec_permission_profile_unions_turn_and_requested_mac
cwd: cwd.to_path_buf(),
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox: SandboxType::None,
sandbox_policy: sandbox_policy.clone(),
file_system_sandbox_policy: read_only_file_system_sandbox_policy(),
@@ -207,7 +207,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
let mut env = req.env.clone();
if let Some(network) = req.network.as_ref() {
network.apply_to_env_for_owner(&mut env, ctx.network_approval_owner_id.as_deref());
network.apply_to_env_for_parent_tool_item(&mut env, Some(ctx.call_id.as_str()));
}
if let UnifiedExecShellMode::ZshFork(zsh_fork_config) = &self.shell_mode {
let spec = build_command_spec(
@@ -221,11 +221,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
)
.map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?;
let exec_env = attempt
.env_for(
spec,
req.network.as_ref(),
ctx.network_approval_owner_id.as_deref(),
)
.env_for(spec, req.network.as_ref(), Some(ctx.call_id.as_str()))
.map_err(|err| ToolError::Codex(err.into()))?;
match zsh_fork_backend::maybe_prepare_unified_exec(
req,
@@ -273,11 +269,7 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
)
.map_err(|_| ToolError::Rejected("missing command line for PTY".to_string()))?;
let exec_env = attempt
.env_for(
spec,
req.network.as_ref(),
ctx.network_approval_owner_id.as_deref(),
)
.env_for(spec, req.network.as_ref(), Some(ctx.call_id.as_str()))
.map_err(|err| ToolError::Codex(err.into()))?;
self.manager
.open_session_with_exec_env(&exec_env, req.tty, Box::new(NoopSpawnLifecycle))
+2 -3
View File
@@ -300,7 +300,6 @@ pub(crate) struct ToolCtx {
pub session: Arc<Session>,
pub turn: Arc<TurnContext>,
pub call_id: String,
pub network_approval_owner_id: Option<String>,
pub tool_name: String,
}
@@ -342,7 +341,7 @@ impl<'a> SandboxAttempt<'a> {
&self,
spec: CommandSpec,
network: Option<&NetworkProxy>,
network_owner_id: Option<&str>,
parent_tool_item_id: Option<&str>,
) -> Result<crate::sandboxing::ExecRequest, SandboxTransformError> {
self.manager
.transform(crate::sandboxing::SandboxTransformRequest {
@@ -353,7 +352,7 @@ impl<'a> SandboxAttempt<'a> {
sandbox: self.sandbox,
enforce_managed_network: self.enforce_managed_network,
network,
network_owner_id,
parent_tool_item_id,
sandbox_policy_cwd: self.sandbox_cwd,
#[cfg(target_os = "macos")]
macos_seatbelt_profile_extensions: None,
@@ -198,7 +198,7 @@ impl UnifiedExecProcessManager {
if process_started_alive {
let network_approval_id = deferred_network_approval
.as_ref()
.map(|deferred| deferred.registration_id().to_string());
.map(|deferred| deferred.parent_tool_item_id().to_string());
self.store_process(
Arc::clone(&process),
context,
@@ -627,7 +627,6 @@ impl UnifiedExecProcessManager {
session: context.session.clone(),
turn: context.turn.clone(),
call_id: context.call_id.clone(),
network_approval_owner_id: None,
tool_name: "exec_command".to_string(),
};
orchestrator
+1 -1
View File
@@ -41,7 +41,7 @@ async fn run_test_cmd(tmp: TempDir, cmd: Vec<&str>) -> Result<ExecToolCallOutput
capture_policy: ExecCapturePolicy::ShellTool,
env: HashMap::new(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -120,7 +120,7 @@ async fn run_cmd_result_with_policies(
capture_policy: ExecCapturePolicy::ShellTool,
env: create_env_from_core_vars(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
@@ -381,7 +381,7 @@ async fn assert_network_blocked(cmd: &[&str]) {
capture_policy: ExecCapturePolicy::ShellTool,
env: create_env_from_core_vars(),
network: None,
network_owner_id: None,
parent_tool_item_id: None,
sandbox_permissions: SandboxPermissions::UseDefault,
windows_sandbox_level: WindowsSandboxLevel::Disabled,
windows_sandbox_private_desktop: false,
+14 -14
View File
@@ -151,7 +151,7 @@ async fn run_http_proxy_with_listener(
Ok(())
}
fn proxy_authorization_network_owner_id<T>(req: &Request<T>) -> Option<String> {
fn proxy_authorization_parent_tool_item_id<T>(req: &Request<T>) -> Option<String> {
req.headers()
.typed_get::<ProxyAuthorization<Basic>>()
.map(|header| header.0.username().to_string())
@@ -181,7 +181,7 @@ async fn http_connect_accept(
}
let client = client_addr(&req);
let network_owner_id = proxy_authorization_network_owner_id(&req);
let parent_tool_item_id = proxy_authorization_parent_tool_item_id(&req);
let enabled = app_state
.enabled()
.await
@@ -194,7 +194,7 @@ async fn http_connect_accept(
host,
authority.port,
client_addr(&req),
network_owner_id,
parent_tool_item_id,
Some("CONNECT".to_string()),
NetworkProtocol::HttpsConnect,
/*audit_endpoint_override*/ None,
@@ -206,7 +206,7 @@ async fn http_connect_accept(
protocol: NetworkProtocol::HttpsConnect,
host: host.clone(),
port: authority.port,
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client_addr: client.clone(),
method: Some("CONNECT".to_string()),
command: None,
@@ -231,7 +231,7 @@ async fn http_connect_accept(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: reason.clone(),
network_owner_id,
parent_tool_item_id,
client: client.clone(),
method: Some("CONNECT".to_string()),
mode: None,
@@ -295,7 +295,7 @@ async fn http_connect_accept(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: REASON_MITM_REQUIRED.to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: client.clone(),
method: Some("CONNECT".to_string()),
mode: Some(NetworkMode::Limited),
@@ -445,7 +445,7 @@ async fn http_plain_proxy(
}
};
let client = client_addr(&req);
let network_owner_id = proxy_authorization_network_owner_id(&req);
let parent_tool_item_id = proxy_authorization_parent_tool_item_id(&req);
let method_allowed = match app_state
.method_allowed(req.method().as_str())
.await
@@ -485,7 +485,7 @@ async fn http_plain_proxy(
socket_path,
/*port*/ 0,
client_addr(&req),
network_owner_id.clone(),
parent_tool_item_id.clone(),
Some(req.method().as_str().to_string()),
NetworkProtocol::Http,
Some(("unix-socket", 0)),
@@ -631,7 +631,7 @@ async fn http_plain_proxy(
host,
port,
client_addr(&req),
network_owner_id.clone(),
parent_tool_item_id.clone(),
Some(req.method().as_str().to_string()),
NetworkProtocol::Http,
/*audit_endpoint_override*/ None,
@@ -643,7 +643,7 @@ async fn http_plain_proxy(
protocol: NetworkProtocol::Http,
host: host.clone(),
port,
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client_addr: client.clone(),
method: Some(req.method().as_str().to_string()),
command: None,
@@ -668,7 +668,7 @@ async fn http_plain_proxy(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: reason.clone(),
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client: client.clone(),
method: Some(req.method().as_str().to_string()),
mode: None,
@@ -714,7 +714,7 @@ async fn http_plain_proxy(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: REASON_METHOD_NOT_ALLOWED.to_string(),
network_owner_id,
parent_tool_item_id,
client: client.clone(),
method: Some(req.method().as_str().to_string()),
mode: Some(NetworkMode::Limited),
@@ -908,7 +908,7 @@ async fn proxy_disabled_response(
host: String,
port: u16,
client: Option<String>,
network_owner_id: Option<String>,
parent_tool_item_id: Option<String>,
method: Option<String>,
protocol: NetworkProtocol,
audit_endpoint_override: Option<(&str, u16)>,
@@ -933,7 +933,7 @@ async fn proxy_disabled_response(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: blocked_host,
reason: REASON_PROXY_DISABLED.to_string(),
network_owner_id,
parent_tool_item_id,
client,
method,
mode: None,
+2 -2
View File
@@ -289,7 +289,7 @@ async fn mitm_blocking_response(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: policy.target_host.clone(),
reason: reason.to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: client.clone(),
method: Some(method.clone()),
mode: Some(policy.mode),
@@ -312,7 +312,7 @@ async fn mitm_blocking_response(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: policy.target_host.clone(),
reason: REASON_METHOD_NOT_ALLOWED.to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: client.clone(),
method: Some(method.clone()),
mode: Some(policy.mode),
+14 -9
View File
@@ -79,7 +79,10 @@ pub struct NetworkPolicyRequest {
pub protocol: NetworkProtocol,
pub host: String,
pub port: u16,
pub network_owner_id: Option<String>,
/// Parent tool item id forwarded from the originating tool call. Core uses
/// this to resolve blocked requests back to the exact active call instead
/// of guessing by session state.
pub parent_tool_item_id: Option<String>,
pub client_addr: Option<String>,
pub method: Option<String>,
pub command: Option<String>,
@@ -90,7 +93,9 @@ pub struct NetworkPolicyRequestArgs {
pub protocol: NetworkProtocol,
pub host: String,
pub port: u16,
pub network_owner_id: Option<String>,
/// Parent tool item id forwarded from the originating tool call for later
/// attribution.
pub parent_tool_item_id: Option<String>,
pub client_addr: Option<String>,
pub method: Option<String>,
pub command: Option<String>,
@@ -103,7 +108,7 @@ impl NetworkPolicyRequest {
protocol,
host,
port,
network_owner_id,
parent_tool_item_id,
client_addr,
method,
command,
@@ -113,7 +118,7 @@ impl NetworkPolicyRequest {
protocol,
host,
port,
network_owner_id,
parent_tool_item_id,
client_addr,
method,
command,
@@ -629,7 +634,7 @@ mod tests {
protocol: NetworkProtocol::Http,
host: "example.com".to_string(),
port: 80,
network_owner_id: None,
parent_tool_item_id: None,
client_addr: None,
method: None,
command: None,
@@ -690,7 +695,7 @@ mod tests {
protocol: NetworkProtocol::Http,
host: "blocked.com".to_string(),
port: 80,
network_owner_id: None,
parent_tool_item_id: None,
client_addr: Some("127.0.0.1:1234".to_string()),
method: Some("GET".to_string()),
command: None,
@@ -732,7 +737,7 @@ mod tests {
protocol: NetworkProtocol::Http,
host: "example.com".to_string(),
port: 80,
network_owner_id: None,
parent_tool_item_id: None,
client_addr: None,
method: Some("GET".to_string()),
command: None,
@@ -783,7 +788,7 @@ mod tests {
protocol: NetworkProtocol::Http,
host: "example.com".to_string(),
port: 80,
network_owner_id: None,
parent_tool_item_id: None,
client_addr: None,
method: Some("GET".to_string()),
command: None,
@@ -867,7 +872,7 @@ mod tests {
protocol: NetworkProtocol::Http,
host: "127.0.0.1".to_string(),
port: 80,
network_owner_id: None,
parent_tool_item_id: None,
client_addr: None,
method: Some("GET".to_string()),
command: None,
+7 -4
View File
@@ -7,16 +7,16 @@ use rama_net::user::authority::AuthorizeResult;
use rama_net::user::authority::Authorizer;
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct ProxyOwnerAuthorizer;
pub(crate) struct ProxyParentToolItemAuthorizer;
impl AuthoritySync<Basic, ()> for ProxyOwnerAuthorizer {
impl AuthoritySync<Basic, ()> for ProxyParentToolItemAuthorizer {
fn authorized(&self, ext: &mut Extensions, credentials: &Basic) -> bool {
ext.insert(UserId::Username(credentials.username().to_string()));
true
}
}
impl Authorizer<Basic> for ProxyOwnerAuthorizer {
impl Authorizer<Basic> for ProxyParentToolItemAuthorizer {
type Error = std::convert::Infallible;
async fn authorize(&self, credentials: Basic) -> AuthorizeResult<Basic, Self::Error> {
@@ -29,7 +29,10 @@ impl Authorizer<Basic> for ProxyOwnerAuthorizer {
}
}
pub(crate) fn network_owner_id<T: ExtensionsRef>(input: &T) -> Option<String> {
/// Extract the parent tool item id from proxy auth/user extensions. Managed
/// proxy callbacks carry the parent tool item id as the proxy auth username so
/// core can attribute blocked requests back to the originating tool call.
pub(crate) fn extract_parent_tool_item_id<T: ExtensionsRef>(input: &T) -> Option<String> {
match input.extensions().get::<UserId>() {
Some(UserId::Username(username)) => Some(username.clone()),
Some(UserId::Token(token)) => String::from_utf8(token.clone()).ok(),
+29 -15
View File
@@ -15,6 +15,7 @@ use std::sync::Arc;
use std::sync::Mutex;
use tokio::task::JoinHandle;
use tracing::warn;
use url::Url;
#[derive(Debug, Clone, Parser)]
#[command(name = "codex-network-proxy", about = "Codex network sandbox proxy")]
@@ -305,11 +306,22 @@ fn set_env_keys(env: &mut HashMap<String, String>, keys: &[&str], value: &str) {
}
}
fn proxy_url(scheme: &str, addr: SocketAddr, network_owner_id: Option<&str>) -> String {
match network_owner_id {
Some(network_owner_id) => format!("{scheme}://{network_owner_id}@{addr}"),
None => format!("{scheme}://{addr}"),
fn proxy_url(scheme: &str, addr: SocketAddr, parent_tool_item_id: Option<&str>) -> String {
let base = format!("{scheme}://{addr}");
let mut url = match Url::parse(&base) {
Ok(url) => url,
Err(err) => panic!("failed to build proxy URL for {base}: {err}"),
};
if let Some(parent_tool_item_id) = parent_tool_item_id
&& let Err(()) = url.set_username(parent_tool_item_id)
{
panic!("failed to encode parent tool item id in proxy URL");
}
let mut proxy_url = url.to_string();
if proxy_url.ends_with('/') {
proxy_url.pop();
}
proxy_url
}
fn apply_proxy_env_overrides(
@@ -318,10 +330,10 @@ fn apply_proxy_env_overrides(
socks_addr: SocketAddr,
socks_enabled: bool,
allow_local_binding: bool,
network_owner_id: Option<&str>,
parent_tool_item_id: Option<&str>,
) {
let http_proxy_url = proxy_url("http", http_addr, network_owner_id);
let socks_proxy_url = proxy_url("socks5h", socks_addr, network_owner_id);
let http_proxy_url = proxy_url("http", http_addr, parent_tool_item_id);
let socks_proxy_url = proxy_url("socks5h", socks_addr, parent_tool_item_id);
env.insert(
ALLOW_LOCAL_BINDING_ENV_KEY.to_string(),
if allow_local_binding {
@@ -422,13 +434,15 @@ impl NetworkProxy {
}
pub fn apply_to_env(&self, env: &mut HashMap<String, String>) {
self.apply_to_env_for_owner(env, /*network_owner_id*/ None);
self.apply_to_env_for_parent_tool_item(env, /*parent_tool_item_id*/ None);
}
pub fn apply_to_env_for_owner(
/// Apply managed proxy environment variables, optionally tagging them with
/// the originating parent tool item id for blocked-request attribution.
pub fn apply_to_env_for_parent_tool_item(
&self,
env: &mut HashMap<String, String>,
network_owner_id: Option<&str>,
parent_tool_item_id: Option<&str>,
) {
// Enforce proxying for child processes. We intentionally override existing values so
// command-level environment cannot bypass the managed proxy endpoint.
@@ -438,7 +452,7 @@ impl NetworkProxy {
self.socks_addr,
self.socks_enabled,
self.allow_local_binding,
network_owner_id,
parent_tool_item_id,
);
}
@@ -713,7 +727,7 @@ mod tests {
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081),
true,
false,
/*network_owner_id*/ None,
/*parent_tool_item_id*/ None,
);
assert_eq!(
@@ -764,7 +778,7 @@ mod tests {
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081),
false,
true,
/*network_owner_id*/ None,
/*parent_tool_item_id*/ None,
);
assert_eq!(
@@ -783,7 +797,7 @@ mod tests {
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081),
true,
false,
/*network_owner_id*/ None,
/*parent_tool_item_id*/ None,
);
assert_eq!(
@@ -829,7 +843,7 @@ mod tests {
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 8081),
true,
false,
/*network_owner_id*/ None,
/*parent_tool_item_id*/ None,
);
assert_eq!(
+12 -7
View File
@@ -84,8 +84,11 @@ pub enum HostBlockDecision {
pub struct BlockedRequest {
pub host: String,
pub reason: String,
/// Parent tool item id carried alongside the blocked request for
/// attribution in core. This is internal-only and is intentionally omitted
/// from serialized logs/snapshots.
#[serde(skip_serializing)]
pub network_owner_id: Option<String>,
pub parent_tool_item_id: Option<String>,
pub client: Option<String>,
pub method: Option<String>,
pub mode: Option<NetworkMode>,
@@ -102,7 +105,9 @@ pub struct BlockedRequest {
pub struct BlockedRequestArgs {
pub host: String,
pub reason: String,
pub network_owner_id: Option<String>,
/// Parent tool item id carried alongside the blocked request for
/// attribution in core.
pub parent_tool_item_id: Option<String>,
pub client: Option<String>,
pub method: Option<String>,
pub mode: Option<NetworkMode>,
@@ -117,7 +122,7 @@ impl BlockedRequest {
let BlockedRequestArgs {
host,
reason,
network_owner_id,
parent_tool_item_id,
client,
method,
mode,
@@ -129,7 +134,7 @@ impl BlockedRequest {
Self {
host,
reason,
network_owner_id,
parent_tool_item_id,
client,
method,
mode,
@@ -999,7 +1004,7 @@ mod tests {
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: "google.com".to_string(),
reason: "not_allowed".to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: None,
method: Some("GET".to_string()),
mode: None,
@@ -1040,7 +1045,7 @@ mod tests {
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: format!("example{idx}.com"),
reason: "not_allowed".to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: None,
method: Some("GET".to_string()),
mode: None,
@@ -1063,7 +1068,7 @@ mod tests {
let entry = BlockedRequest {
host: "google.com".to_string(),
reason: "not_allowed".to_string(),
network_owner_id: None,
parent_tool_item_id: None,
client: Some("127.0.0.1".to_string()),
method: Some("GET".to_string()),
mode: Some(NetworkMode::Full),
+13 -13
View File
@@ -9,8 +9,8 @@ use crate::network_policy::NetworkPolicyRequestArgs;
use crate::network_policy::NetworkProtocol;
use crate::network_policy::emit_block_decision_audit_event;
use crate::network_policy::evaluate_host_policy;
use crate::owner_identity::ProxyOwnerAuthorizer;
use crate::owner_identity::network_owner_id as extract_network_owner_id;
use crate::owner_identity::ProxyParentToolItemAuthorizer;
use crate::owner_identity::extract_parent_tool_item_id;
use crate::policy::normalize_host;
use crate::reasons::REASON_METHOD_NOT_ALLOWED;
use crate::reasons::REASON_PROXY_DISABLED;
@@ -111,7 +111,7 @@ async fn run_socks5_with_listener(
base.set_auth_optional(true);
let base = base
.with_connector(socks_connector)
.with_authorizer(ProxyOwnerAuthorizer);
.with_authorizer(ProxyParentToolItemAuthorizer);
if enable_socks5_udp {
let udp_state = state.clone();
@@ -156,7 +156,7 @@ async fn handle_socks5_tcp(
.extensions()
.get::<SocketInfo>()
.map(|info| info.peer_addr().to_string());
let network_owner_id = extract_network_owner_id(&req);
let parent_tool_item_id = extract_parent_tool_item_id(&req);
match app_state.enabled().await {
Ok(true) => {}
@@ -182,7 +182,7 @@ async fn handle_socks5_tcp(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: REASON_PROXY_DISABLED.to_string(),
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client: client.clone(),
method: None,
mode: None,
@@ -225,7 +225,7 @@ async fn handle_socks5_tcp(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: REASON_METHOD_NOT_ALLOWED.to_string(),
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client: client.clone(),
method: None,
mode: Some(NetworkMode::Limited),
@@ -252,7 +252,7 @@ async fn handle_socks5_tcp(
protocol: NetworkProtocol::Socks5Tcp,
host: host.clone(),
port,
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client_addr: client.clone(),
method: None,
command: None,
@@ -277,7 +277,7 @@ async fn handle_socks5_tcp(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: reason.clone(),
network_owner_id,
parent_tool_item_id,
client: client.clone(),
method: None,
mode: None,
@@ -325,7 +325,7 @@ async fn inspect_socks5_udp(
let client = extensions
.get::<SocketInfo>()
.map(|info| info.peer_addr().to_string());
let network_owner_id = extract_network_owner_id(&extensions);
let parent_tool_item_id = extract_parent_tool_item_id(&extensions);
match state.enabled().await {
Ok(true) => {}
@@ -351,7 +351,7 @@ async fn inspect_socks5_udp(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: REASON_PROXY_DISABLED.to_string(),
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client: client.clone(),
method: None,
mode: None,
@@ -394,7 +394,7 @@ async fn inspect_socks5_udp(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: REASON_METHOD_NOT_ALLOWED.to_string(),
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client: client.clone(),
method: None,
mode: Some(NetworkMode::Limited),
@@ -417,7 +417,7 @@ async fn inspect_socks5_udp(
protocol: NetworkProtocol::Socks5Udp,
host: host.clone(),
port,
network_owner_id: network_owner_id.clone(),
parent_tool_item_id: parent_tool_item_id.clone(),
client_addr: client.clone(),
method: None,
command: None,
@@ -442,7 +442,7 @@ async fn inspect_socks5_udp(
.record_blocked(BlockedRequest::new(BlockedRequestArgs {
host: host.clone(),
reason: reason.clone(),
network_owner_id,
parent_tool_item_id,
client: client.clone(),
method: None,
mode: None,