mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
feat(network-proxy): attribute Linux requests per command
Register one attribution capability for each managed-network command, pass it only to the trusted Linux bridge, and prepend it on connections to the shared proxy ingress. Approval matching and cleanup follow the command lifecycle. Co-authored-by: Codex noreply@openai.com
This commit is contained in:
co-authored by
Codex noreply@openai.com
parent
5800d3a4b6
commit
329bf3c9a1
@@ -18,6 +18,7 @@ use codex_network_proxy::NetworkPolicyDecider;
|
||||
use codex_network_proxy::NetworkPolicyRequest;
|
||||
use codex_network_proxy::NetworkProtocol;
|
||||
use codex_network_proxy::NetworkProxy;
|
||||
use codex_network_proxy::NetworkProxyExecutionLease;
|
||||
use codex_protocol::approvals::NetworkApprovalContext;
|
||||
use codex_protocol::approvals::NetworkApprovalProtocol;
|
||||
use codex_protocol::approvals::NetworkPolicyRuleAction;
|
||||
@@ -57,6 +58,7 @@ pub(crate) struct NetworkApprovalSpec {
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct DeferredNetworkApproval {
|
||||
registration_id: String,
|
||||
execution_proxy_lease: Option<NetworkProxyExecutionLease>,
|
||||
cancellation_token: CancellationToken,
|
||||
finish_outcome: Arc<OnceCell<Option<NetworkApprovalOutcome>>>,
|
||||
}
|
||||
@@ -80,6 +82,9 @@ impl DeferredNetworkApproval {
|
||||
.get_or_init(|| async { service.finish_call_outcome(&self.registration_id).await })
|
||||
.await
|
||||
.clone();
|
||||
if let Some(execution_proxy_lease) = self.execution_proxy_lease.as_ref() {
|
||||
execution_proxy_lease.close();
|
||||
}
|
||||
network_approval_outcome_to_result(outcome)
|
||||
}
|
||||
}
|
||||
@@ -87,6 +92,7 @@ impl DeferredNetworkApproval {
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ActiveNetworkApproval {
|
||||
registration_id: Option<String>,
|
||||
execution_proxy_lease: Option<NetworkProxyExecutionLease>,
|
||||
mode: NetworkApprovalMode,
|
||||
cancellation_token: CancellationToken,
|
||||
}
|
||||
@@ -100,16 +106,23 @@ impl ActiveNetworkApproval {
|
||||
self.cancellation_token.clone()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub(crate) fn execution_id(&self) -> Option<&str> {
|
||||
self.registration_id.as_deref()
|
||||
}
|
||||
|
||||
pub(crate) fn into_deferred(self) -> Option<DeferredNetworkApproval> {
|
||||
let ActiveNetworkApproval {
|
||||
registration_id,
|
||||
execution_proxy_lease,
|
||||
mode,
|
||||
cancellation_token,
|
||||
} = self;
|
||||
match (mode, registration_id) {
|
||||
(NetworkApprovalMode::Deferred, Some(registration_id)) => {
|
||||
match (mode, registration_id, execution_proxy_lease) {
|
||||
(NetworkApprovalMode::Deferred, Some(registration_id), execution_proxy_lease) => {
|
||||
Some(DeferredNetworkApproval {
|
||||
registration_id,
|
||||
execution_proxy_lease,
|
||||
cancellation_token,
|
||||
finish_outcome: Arc::new(OnceCell::new()),
|
||||
})
|
||||
@@ -305,9 +318,8 @@ impl NetworkApprovalService {
|
||||
|
||||
async fn resolve_single_active_call(&self) -> Option<Arc<ActiveNetworkApprovalCall>> {
|
||||
let calls = self.calls.lock().await;
|
||||
// Blocked proxy requests are not attributed to a specific tool call. Only pick an owner
|
||||
// Older proxy listeners do not carry an execution ID. Only pick an owner for those requests
|
||||
// when there is exactly one candidate; with concurrent calls, canceling one would be a guess.
|
||||
// TODO: Carry blocked-request attribution so concurrent active calls can be handled safely.
|
||||
if calls.active_calls.len() == 1 {
|
||||
return calls.active_calls.values().next().cloned();
|
||||
}
|
||||
@@ -315,6 +327,18 @@ impl NetworkApprovalService {
|
||||
None
|
||||
}
|
||||
|
||||
async fn resolve_active_call_by_execution_id(
|
||||
&self,
|
||||
execution_id: &str,
|
||||
) -> Option<Arc<ActiveNetworkApprovalCall>> {
|
||||
self.calls
|
||||
.lock()
|
||||
.await
|
||||
.active_calls
|
||||
.get(execution_id)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
async fn resolve_active_call_attribution(&self) -> ActiveNetworkApprovalAttribution {
|
||||
let calls = self.calls.lock().await;
|
||||
match calls.active_calls.len() {
|
||||
@@ -393,8 +417,18 @@ impl NetworkApprovalService {
|
||||
return;
|
||||
};
|
||||
|
||||
self.record_outcome_for_single_active_call(NetworkApprovalOutcome::DeniedByPolicy(message))
|
||||
if let Some(execution_id) = blocked.execution_id.as_deref() {
|
||||
self.record_call_outcome(
|
||||
execution_id,
|
||||
NetworkApprovalOutcome::DeniedByPolicy(message),
|
||||
)
|
||||
.await;
|
||||
} else {
|
||||
self.record_outcome_for_single_active_call(NetworkApprovalOutcome::DeniedByPolicy(
|
||||
message,
|
||||
))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn active_turn_context(
|
||||
@@ -431,28 +465,37 @@ impl NetworkApprovalService {
|
||||
NetworkProtocol::Socks5Tcp => NetworkApprovalProtocol::Socks5Tcp,
|
||||
NetworkProtocol::Socks5Udp => NetworkApprovalProtocol::Socks5Udp,
|
||||
};
|
||||
let (owner_call, active_environment_id) =
|
||||
if let Some(environment_id) = request.environment_id.clone() {
|
||||
let owner_call = match self.resolve_active_call_attribution().await {
|
||||
ActiveNetworkApprovalAttribution::Single(call) => {
|
||||
(call.environment_id == environment_id).then_some(call)
|
||||
}
|
||||
ActiveNetworkApprovalAttribution::None
|
||||
| ActiveNetworkApprovalAttribution::Ambiguous => None,
|
||||
};
|
||||
(owner_call, Some(environment_id))
|
||||
} else {
|
||||
match self.resolve_active_call_attribution().await {
|
||||
ActiveNetworkApprovalAttribution::None => (None, None),
|
||||
ActiveNetworkApprovalAttribution::Single(call) => {
|
||||
let environment_id = call.environment_id.clone();
|
||||
(Some(call), Some(environment_id))
|
||||
}
|
||||
ActiveNetworkApprovalAttribution::Ambiguous => {
|
||||
return NetworkDecision::deny(REASON_NOT_ALLOWED);
|
||||
}
|
||||
}
|
||||
let attributed_call = if let Some(execution_id) = request.execution_id.as_deref() {
|
||||
let Some(call) = self.resolve_active_call_by_execution_id(execution_id).await else {
|
||||
return NetworkDecision::deny(REASON_NOT_ALLOWED);
|
||||
};
|
||||
Some(call)
|
||||
} else {
|
||||
match self.resolve_active_call_attribution().await {
|
||||
ActiveNetworkApprovalAttribution::None => None,
|
||||
ActiveNetworkApprovalAttribution::Single(call) => Some(call),
|
||||
ActiveNetworkApprovalAttribution::Ambiguous => {
|
||||
return NetworkDecision::deny(REASON_NOT_ALLOWED);
|
||||
}
|
||||
}
|
||||
};
|
||||
let (owner_call, active_environment_id) = if let Some(environment_id) =
|
||||
request.environment_id.clone()
|
||||
{
|
||||
let owner_call = attributed_call.filter(|call| call.environment_id == environment_id);
|
||||
(owner_call, Some(environment_id))
|
||||
} else {
|
||||
match attributed_call {
|
||||
Some(call) => {
|
||||
let environment_id = call.environment_id.clone();
|
||||
(Some(call), Some(environment_id))
|
||||
}
|
||||
None => (None, None),
|
||||
}
|
||||
};
|
||||
if request.execution_id.is_some() && owner_call.is_none() {
|
||||
return NetworkDecision::deny(REASON_NOT_ALLOWED);
|
||||
}
|
||||
let turn_context = Self::active_turn_context(session.as_ref()).await;
|
||||
let Some(environment_id) = active_environment_id.or_else(|| {
|
||||
turn_context
|
||||
@@ -802,6 +845,14 @@ pub(crate) async fn begin_network_approval(
|
||||
}
|
||||
|
||||
let registration_id = Uuid::new_v4().to_string();
|
||||
let attribution_token = Uuid::new_v4().to_string();
|
||||
let execution_proxy_lease = network.as_ref().map(|network| {
|
||||
network.execution_lease(
|
||||
environment_id.clone(),
|
||||
registration_id.clone(),
|
||||
attribution_token,
|
||||
)
|
||||
});
|
||||
let cancellation_token = CancellationToken::new();
|
||||
session
|
||||
.services
|
||||
@@ -818,6 +869,7 @@ pub(crate) async fn begin_network_approval(
|
||||
|
||||
Some(ActiveNetworkApproval {
|
||||
registration_id: Some(registration_id),
|
||||
execution_proxy_lease,
|
||||
mode,
|
||||
cancellation_token,
|
||||
})
|
||||
@@ -831,11 +883,15 @@ pub(crate) async fn finish_immediate_network_approval(
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
session
|
||||
let result = session
|
||||
.services
|
||||
.network_approval
|
||||
.finish_call(registration_id)
|
||||
.await
|
||||
.await;
|
||||
if let Some(execution_proxy_lease) = active.execution_proxy_lease.as_ref() {
|
||||
execution_proxy_lease.close();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(crate) async fn finish_deferred_network_approval(
|
||||
|
||||
@@ -287,6 +287,12 @@ fn denied_blocked_request(host: &str) -> BlockedRequest {
|
||||
})
|
||||
}
|
||||
|
||||
fn denied_blocked_request_for_execution(host: &str, execution_id: &str) -> BlockedRequest {
|
||||
let mut blocked = denied_blocked_request(host);
|
||||
blocked.execution_id = Some(execution_id.to_string());
|
||||
blocked
|
||||
}
|
||||
|
||||
async fn register_call_with_default_shell_trigger(
|
||||
service: &NetworkApprovalService,
|
||||
registration_id: &str,
|
||||
@@ -429,6 +435,7 @@ async fn deferred_finish_reuses_denial_result_after_first_consumer() {
|
||||
register_call_with_default_shell_trigger(&service, "registration-1").await;
|
||||
let deferred = DeferredNetworkApproval {
|
||||
registration_id: "registration-1".to_string(),
|
||||
execution_proxy_lease: None,
|
||||
cancellation_token,
|
||||
finish_outcome: Arc::new(OnceCell::new()),
|
||||
};
|
||||
@@ -483,3 +490,27 @@ async fn record_blocked_request_ignores_ambiguous_unattributed_blocked_requests(
|
||||
assert_eq!(service.take_call_outcome("registration-1").await, None);
|
||||
assert_eq!(service.take_call_outcome("registration-2").await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn record_blocked_request_targets_attributed_execution_among_concurrent_calls() {
|
||||
let service = NetworkApprovalService::default();
|
||||
let first = register_call_with_default_shell_trigger(&service, "registration-1").await;
|
||||
let second = register_call_with_default_shell_trigger(&service, "registration-2").await;
|
||||
|
||||
service
|
||||
.record_blocked_request(denied_blocked_request_for_execution(
|
||||
"example.com",
|
||||
"registration-2",
|
||||
))
|
||||
.await;
|
||||
|
||||
assert!(!first.is_cancelled());
|
||||
assert!(second.is_cancelled());
|
||||
assert_eq!(service.take_call_outcome("registration-1").await, None);
|
||||
assert_eq!(
|
||||
service.take_call_outcome("registration-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()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -82,6 +82,12 @@ impl ToolOrchestrator {
|
||||
call_id: tool_ctx.call_id.clone(),
|
||||
tool_name: tool_ctx.tool_name.clone(),
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let network_execution_id = network_approval
|
||||
.as_ref()
|
||||
.and_then(ActiveNetworkApproval::execution_id);
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let network_execution_id = None;
|
||||
let attempt_with_network_approval = SandboxAttempt {
|
||||
sandbox: attempt.sandbox,
|
||||
sandbox_requested: attempt.sandbox_requested,
|
||||
@@ -98,6 +104,7 @@ impl ToolOrchestrator {
|
||||
network_denial_cancellation_token: network_approval
|
||||
.as_ref()
|
||||
.map(ActiveNetworkApproval::cancellation_token),
|
||||
network_execution_id,
|
||||
};
|
||||
let run_result = tool
|
||||
.run(req, &attempt_with_network_approval, &attempt_tool_ctx)
|
||||
@@ -274,6 +281,7 @@ impl ToolOrchestrator {
|
||||
.permissions
|
||||
.windows_sandbox_private_desktop,
|
||||
network_denial_cancellation_token: None,
|
||||
network_execution_id: None,
|
||||
};
|
||||
|
||||
let initial_attempt_start = Instant::now();
|
||||
@@ -456,6 +464,7 @@ impl ToolOrchestrator {
|
||||
.permissions
|
||||
.windows_sandbox_private_desktop,
|
||||
network_denial_cancellation_token: None,
|
||||
network_execution_id: None,
|
||||
};
|
||||
|
||||
// Second attempt.
|
||||
|
||||
@@ -232,6 +232,7 @@ async fn file_system_sandbox_context_uses_active_attempt() {
|
||||
windows_sandbox_level: WindowsSandboxLevel::RestrictedToken,
|
||||
windows_sandbox_private_desktop: true,
|
||||
network_denial_cancellation_token: None,
|
||||
network_execution_id: None,
|
||||
};
|
||||
|
||||
let sandbox = ApplyPatchRuntime::file_system_sandbox_context_for_attempt(&req, &attempt)
|
||||
@@ -300,6 +301,7 @@ async fn no_sandbox_attempt_has_no_file_system_context() {
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
windows_sandbox_private_desktop: false,
|
||||
network_denial_cancellation_token: None,
|
||||
network_execution_id: None,
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
|
||||
@@ -118,6 +118,7 @@ async fn explicit_escalation_prepares_exec_without_managed_network() -> anyhow::
|
||||
windows_sandbox_level: WindowsSandboxLevel::Disabled,
|
||||
windows_sandbox_private_desktop: false,
|
||||
network_denial_cancellation_token: None,
|
||||
network_execution_id: None,
|
||||
};
|
||||
|
||||
let exec_request = attempt
|
||||
|
||||
@@ -323,17 +323,23 @@ impl<'a> ToolRuntime<UnifiedExecRequest, UnifiedExecProcess> for UnifiedExecRunt
|
||||
);
|
||||
let mut env = exec_env_for_sandbox_permissions(&req.env, launch_sandbox_permissions);
|
||||
if let Some(network) = managed_network {
|
||||
network
|
||||
.apply_to_env_for_optional_environment(
|
||||
let apply_result = match attempt.network_execution_id {
|
||||
Some(execution_id) => network.apply_to_env_for_execution(
|
||||
&mut env,
|
||||
&req.turn_environment.environment_id,
|
||||
execution_id,
|
||||
),
|
||||
None => network.apply_to_env_for_optional_environment(
|
||||
&mut env,
|
||||
Some(&req.turn_environment.environment_id),
|
||||
)
|
||||
.map_err(|err| {
|
||||
ToolError::Codex(CodexErr::Io(io::Error::other(format!(
|
||||
"failed to prepare network proxy for environment `{}`: {err}",
|
||||
req.turn_environment.environment_id
|
||||
))))
|
||||
})?;
|
||||
),
|
||||
};
|
||||
apply_result.map_err(|err| {
|
||||
ToolError::Codex(CodexErr::Io(io::Error::other(format!(
|
||||
"failed to prepare network proxy for environment `{}`: {err}",
|
||||
req.turn_environment.environment_id
|
||||
))))
|
||||
})?;
|
||||
}
|
||||
let explicit_env_overrides = req.explicit_env_overrides.clone();
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -424,16 +424,24 @@ pub(crate) struct SandboxAttempt<'a> {
|
||||
pub windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel,
|
||||
pub windows_sandbox_private_desktop: bool,
|
||||
pub network_denial_cancellation_token: Option<CancellationToken>,
|
||||
pub network_execution_id: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> SandboxAttempt<'a> {
|
||||
pub fn env_for(
|
||||
&self,
|
||||
command: SandboxCommand,
|
||||
mut command: SandboxCommand,
|
||||
options: ExecOptions,
|
||||
network: Option<&NetworkProxy>,
|
||||
environment_id: Option<&str>,
|
||||
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
|
||||
if let (Some(network), Some(environment_id), Some(execution_id)) =
|
||||
(network, environment_id, self.network_execution_id)
|
||||
{
|
||||
network
|
||||
.apply_to_env_for_execution(&mut command.env, environment_id, execution_id)
|
||||
.map_err(|err| CodexErr::Io(std::io::Error::other(err.to_string())))?;
|
||||
}
|
||||
let request = self
|
||||
.manager
|
||||
.transform(SandboxTransformRequest {
|
||||
@@ -461,11 +469,18 @@ impl<'a> SandboxAttempt<'a> {
|
||||
|
||||
pub fn env_for_exec_server(
|
||||
&self,
|
||||
command: SandboxCommand,
|
||||
mut command: SandboxCommand,
|
||||
options: ExecOptions,
|
||||
network: Option<&NetworkProxy>,
|
||||
environment_id: Option<&str>,
|
||||
) -> Result<crate::sandboxing::ExecRequest, CodexErr> {
|
||||
if let (Some(network), Some(environment_id), Some(execution_id)) =
|
||||
(network, environment_id, self.network_execution_id)
|
||||
{
|
||||
network
|
||||
.apply_to_env_for_execution(&mut command.env, environment_id, execution_id)
|
||||
.map_err(|err| CodexErr::Io(std::io::Error::other(err.to_string())))?;
|
||||
}
|
||||
let exec_server_permissions = effective_permission_profile(
|
||||
self.exec_server_permissions,
|
||||
command.additional_permissions.as_ref(),
|
||||
|
||||
@@ -226,6 +226,7 @@ fn exec_server_env_keeps_command_native_and_carries_sandbox_context() {
|
||||
windows_sandbox_level: codex_protocol::config_types::WindowsSandboxLevel::Disabled,
|
||||
windows_sandbox_private_desktop: false,
|
||||
network_denial_cancellation_token: None,
|
||||
network_execution_id: None,
|
||||
};
|
||||
let command = SandboxCommand {
|
||||
program: "/bin/bash".into(),
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
use codex_sandboxing::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
use codex_sandboxing::write_attribution_frame;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
@@ -83,6 +85,19 @@ pub(crate) fn prepare_host_proxy_route_spec() -> io::Result<String> {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, message));
|
||||
}
|
||||
|
||||
let attribution_token = std::env::var(PROXY_ATTRIBUTION_TOKEN_ENV_KEY).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"managed proxy mode requires an attribution token",
|
||||
)
|
||||
})?;
|
||||
// SAFETY: this helper process is single-threaded before any bridge workers
|
||||
// are forked. Removing the token here keeps it out of the command's
|
||||
// environment and out of the serialized inner route specification.
|
||||
unsafe {
|
||||
std::env::remove_var(PROXY_ATTRIBUTION_TOKEN_ENV_KEY);
|
||||
}
|
||||
|
||||
let socket_parent_dir = proxy_socket_parent_dir();
|
||||
let _ = cleanup_stale_proxy_socket_dirs_in(socket_parent_dir.as_path());
|
||||
|
||||
@@ -100,7 +115,11 @@ pub(crate) fn prepare_host_proxy_route_spec() -> io::Result<String> {
|
||||
|
||||
let mut host_bridge_pids = Vec::with_capacity(socket_by_endpoint.len());
|
||||
for (endpoint, socket_path) in &socket_by_endpoint {
|
||||
host_bridge_pids.push(spawn_host_bridge(*endpoint, socket_path)?);
|
||||
host_bridge_pids.push(spawn_host_bridge(
|
||||
*endpoint,
|
||||
socket_path,
|
||||
&attribution_token,
|
||||
)?);
|
||||
}
|
||||
spawn_proxy_socket_dir_cleanup_worker(socket_dir, host_bridge_pids)?;
|
||||
|
||||
@@ -438,7 +457,11 @@ fn cleanup_proxy_socket_dir(socket_dir: &Path) -> io::Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_host_bridge(endpoint: SocketAddr, uds_path: &Path) -> io::Result<libc::pid_t> {
|
||||
fn spawn_host_bridge(
|
||||
endpoint: SocketAddr,
|
||||
uds_path: &Path,
|
||||
attribution_token: &str,
|
||||
) -> io::Result<libc::pid_t> {
|
||||
let (read_fd, write_fd) = create_ready_pipe()?;
|
||||
let pid = unsafe { libc::fork() };
|
||||
if pid < 0 {
|
||||
@@ -452,7 +475,7 @@ fn spawn_host_bridge(endpoint: SocketAddr, uds_path: &Path) -> io::Result<libc::
|
||||
if close_fd(read_fd).is_err() {
|
||||
unsafe { libc::_exit(1) };
|
||||
}
|
||||
let result = run_host_bridge(endpoint, uds_path, write_fd);
|
||||
let result = run_host_bridge(endpoint, uds_path, write_fd, attribution_token);
|
||||
if result.is_err() {
|
||||
unsafe { libc::_exit(1) };
|
||||
}
|
||||
@@ -471,7 +494,12 @@ fn spawn_host_bridge(endpoint: SocketAddr, uds_path: &Path) -> io::Result<libc::
|
||||
Ok(pid)
|
||||
}
|
||||
|
||||
fn run_host_bridge(endpoint: SocketAddr, uds_path: &Path, ready_fd: libc::c_int) -> io::Result<()> {
|
||||
fn run_host_bridge(
|
||||
endpoint: SocketAddr,
|
||||
uds_path: &Path,
|
||||
ready_fd: libc::c_int,
|
||||
attribution_token: &str,
|
||||
) -> io::Result<()> {
|
||||
harden_bridge_process()?;
|
||||
if uds_path.exists() {
|
||||
std::fs::remove_file(uds_path)?;
|
||||
@@ -482,13 +510,18 @@ fn run_host_bridge(endpoint: SocketAddr, uds_path: &Path, ready_fd: libc::c_int)
|
||||
ready_file.write_all(&[HOST_BRIDGE_READY])?;
|
||||
drop(ready_file);
|
||||
|
||||
let attribution_token = attribution_token.to_string();
|
||||
loop {
|
||||
let (unix_stream, _) = listener.accept()?;
|
||||
let attribution_token = attribution_token.clone();
|
||||
std::thread::spawn(move || {
|
||||
let tcp_stream = match TcpStream::connect(endpoint) {
|
||||
let mut tcp_stream = match TcpStream::connect(endpoint) {
|
||||
Ok(stream) => stream,
|
||||
Err(_) => return,
|
||||
};
|
||||
if write_attribution_frame(&mut tcp_stream, &attribution_token).is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = proxy_bidirectional(tcp_stream, unix_stream);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
use codex_core::exec_env::create_env;
|
||||
use codex_protocol::config_types::ShellEnvironmentPolicy;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_sandboxing::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
@@ -17,6 +18,7 @@ use tokio::process::Command;
|
||||
|
||||
const BWRAP_UNAVAILABLE_ERR: &str = "bubblewrap is unavailable: no system bwrap was found";
|
||||
const NETWORK_TIMEOUT_MS: u64 = 4_000;
|
||||
const TEST_ATTRIBUTION_TOKEN: &str = "test-attribution-token";
|
||||
const MANAGED_PROXY_PERMISSION_ERR_SNIPPETS: &[&str] = &[
|
||||
"loopback: Failed RTM_NEWADDR",
|
||||
"loopback: Failed RTM_NEWLINK",
|
||||
@@ -53,6 +55,14 @@ fn strip_proxy_env(env: &mut HashMap<String, String>) {
|
||||
let lower = key.to_ascii_lowercase();
|
||||
env.remove(lower.as_str());
|
||||
}
|
||||
env.remove(PROXY_ATTRIBUTION_TOKEN_ENV_KEY);
|
||||
}
|
||||
|
||||
fn insert_test_attribution_token(env: &mut HashMap<String, String>) {
|
||||
env.insert(
|
||||
PROXY_ATTRIBUTION_TOKEN_ENV_KEY.to_string(),
|
||||
TEST_ATTRIBUTION_TOKEN.to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
fn is_bwrap_unavailable_output(output: &Output) -> bool {
|
||||
@@ -88,6 +98,7 @@ async fn managed_proxy_skip_reason() -> Option<String> {
|
||||
let mut env = create_env_from_core_vars();
|
||||
strip_proxy_env(&mut env);
|
||||
env.insert("HTTP_PROXY".to_string(), "http://127.0.0.1:9".to_string());
|
||||
insert_test_attribution_token(&mut env);
|
||||
|
||||
let output = run_linux_sandbox_direct(
|
||||
&["bash", "-c", "true"],
|
||||
@@ -176,6 +187,33 @@ async fn managed_proxy_mode_fails_closed_without_proxy_env() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_proxy_mode_fails_closed_without_attribution_token() {
|
||||
if should_skip_bwrap_tests().await {
|
||||
return;
|
||||
}
|
||||
|
||||
let mut env = create_env_from_core_vars();
|
||||
strip_proxy_env(&mut env);
|
||||
env.insert("HTTP_PROXY".to_string(), "http://127.0.0.1:9".to_string());
|
||||
|
||||
let output = run_linux_sandbox_direct(
|
||||
&["bash", "-c", "true"],
|
||||
&PermissionProfile::Disabled,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
env,
|
||||
NETWORK_TIMEOUT_MS,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(output.status.success(), false);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains("managed proxy mode requires an attribution token"),
|
||||
"expected fail-closed attribution message, got stderr: {stderr}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_proxy_mode_routes_through_bridge_and_blocks_direct_egress() {
|
||||
if let Some(skip_reason) = managed_proxy_skip_reason().await {
|
||||
@@ -194,6 +232,21 @@ async fn managed_proxy_mode_routes_through_bridge_and_blocks_direct_egress() {
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.expect("set read timeout");
|
||||
let mut magic = [0_u8; 8];
|
||||
stream
|
||||
.read_exact(&mut magic)
|
||||
.expect("read attribution frame magic");
|
||||
assert_eq!(&magic, b"\0CDXPXY1");
|
||||
let mut token_len = [0_u8; 2];
|
||||
stream
|
||||
.read_exact(&mut token_len)
|
||||
.expect("read attribution token length");
|
||||
let mut token = vec![0_u8; u16::from_be_bytes(token_len) as usize];
|
||||
stream
|
||||
.read_exact(&mut token)
|
||||
.expect("read attribution token");
|
||||
assert_eq!(token, TEST_ATTRIBUTION_TOKEN.as_bytes());
|
||||
|
||||
let mut buf = [0_u8; 4096];
|
||||
let read = stream.read(&mut buf).expect("read proxy request");
|
||||
let request = String::from_utf8_lossy(&buf[..read]).to_string();
|
||||
@@ -209,12 +262,13 @@ async fn managed_proxy_mode_routes_through_bridge_and_blocks_direct_egress() {
|
||||
"HTTP_PROXY".to_string(),
|
||||
format!("http://127.0.0.1:{proxy_port}"),
|
||||
);
|
||||
insert_test_attribution_token(&mut env);
|
||||
|
||||
let routed_output = run_linux_sandbox_direct(
|
||||
&[
|
||||
"bash",
|
||||
"-c",
|
||||
"proxy=\"${HTTP_PROXY#*://}\"; host=\"${proxy%%:*}\"; port=\"${proxy##*:}\"; exec 3<>/dev/tcp/${host}/${port}; printf 'GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n' >&3; IFS= read -r line <&3; printf '%s\\n' \"$line\"",
|
||||
"test -z \"${CODEX_NETWORK_PROXY_ATTRIBUTION+x}\" || exit 42; proxy=\"${HTTP_PROXY#*://}\"; host=\"${proxy%%:*}\"; port=\"${proxy##*:}\"; exec 3<>/dev/tcp/${host}/${port}; printf 'GET http://example.com/ HTTP/1.1\\r\\nHost: example.com\\r\\n\\r\\n' >&3; IFS= read -r line <&3; printf '%s\\n' \"$line\"",
|
||||
],
|
||||
&PermissionProfile::Disabled,
|
||||
/*allow_network_for_proxy*/ true,
|
||||
@@ -278,6 +332,7 @@ async fn managed_proxy_mode_denies_af_unix_socket_but_allows_socketpair() {
|
||||
let mut env = create_env_from_core_vars();
|
||||
strip_proxy_env(&mut env);
|
||||
env.insert("HTTP_PROXY".to_string(), "http://127.0.0.1:9".to_string());
|
||||
insert_test_attribution_token(&mut env);
|
||||
|
||||
let output = run_linux_sandbox_direct(
|
||||
&[
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use crate::network_policy::NetworkRequestContext;
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use rama_core::Service;
|
||||
use rama_core::error::BoxError;
|
||||
use rama_core::extensions::ExtensionsMut;
|
||||
@@ -11,7 +13,7 @@ use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
/// Internal handoff to a trusted proxy bridge.
|
||||
/// Internal handoff from Codex to the trusted Linux proxy bridge.
|
||||
#[doc(hidden)]
|
||||
pub const PROXY_ATTRIBUTION_TOKEN_ENV_KEY: &str = "CODEX_NETWORK_PROXY_ATTRIBUTION";
|
||||
|
||||
@@ -21,31 +23,85 @@ const ATTRIBUTION_FRAME_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct AttributionRegistry {
|
||||
contexts: Arc<Mutex<HashMap<String, NetworkRequestContext>>>,
|
||||
records: Arc<Mutex<HashMap<String, AttributionRecord>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct AttributionRecord {
|
||||
execution_id: String,
|
||||
context: NetworkRequestContext,
|
||||
}
|
||||
|
||||
impl AttributionRegistry {
|
||||
pub(crate) fn register(
|
||||
&self,
|
||||
execution_id: String,
|
||||
token: String,
|
||||
context: NetworkRequestContext,
|
||||
) {
|
||||
let mut records = self
|
||||
.records
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
records.insert(
|
||||
token,
|
||||
AttributionRecord {
|
||||
execution_id,
|
||||
context,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn token_for_execution(
|
||||
&self,
|
||||
execution_id: &str,
|
||||
expected_context: &NetworkRequestContext,
|
||||
) -> Result<String> {
|
||||
let records = self
|
||||
.records
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
let (token, record) = records
|
||||
.iter()
|
||||
.find(|(_, record)| record.execution_id == execution_id)
|
||||
.with_context(|| {
|
||||
format!("network proxy execution `{execution_id}` is not registered")
|
||||
})?;
|
||||
anyhow::ensure!(
|
||||
record.context == *expected_context,
|
||||
"network proxy execution `{execution_id}` was reused with different attribution"
|
||||
);
|
||||
Ok(token.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn context_for_token(&self, token: &str) -> Option<NetworkRequestContext> {
|
||||
self.contexts
|
||||
self.records
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(token)
|
||||
.cloned()
|
||||
.map(|record| record.context.clone())
|
||||
}
|
||||
|
||||
pub(crate) fn remove(&self, execution_id: &str) {
|
||||
self.records
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.retain(|_, record| record.execution_id != execution_id);
|
||||
}
|
||||
|
||||
pub(crate) fn clear(&self) {
|
||||
self.contexts
|
||||
self.records
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.clear();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn register(&self, token: impl Into<String>, context: NetworkRequestContext) {
|
||||
self.contexts
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.records
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.insert(token.into(), context);
|
||||
.len()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,27 @@ use tokio::io::AsyncWriteExt;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
#[test]
|
||||
fn attribution_records_are_removed_by_execution() -> anyhow::Result<()> {
|
||||
let registry = AttributionRegistry::default();
|
||||
let context = NetworkRequestContext::for_execution("local", "execution-1");
|
||||
registry.register(
|
||||
"execution-1".to_string(),
|
||||
"token-1".to_string(),
|
||||
context.clone(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
registry.token_for_execution("execution-1", &context)?,
|
||||
"token-1"
|
||||
);
|
||||
assert_eq!(registry.context_for_token("token-1"), Some(context));
|
||||
|
||||
registry.remove("execution-1");
|
||||
assert_eq!(registry.context_for_token("token-1"), None);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn attribution_frame_has_bounded_binary_prefix() -> io::Result<()> {
|
||||
let mut frame = Vec::new();
|
||||
@@ -28,11 +49,12 @@ fn attribution_frame_has_bounded_binary_prefix() -> io::Result<()> {
|
||||
#[tokio::test]
|
||||
async fn framed_connection_receives_registered_attribution() -> Result<(), BoxError> {
|
||||
let registry = AttributionRegistry::default();
|
||||
let expected = NetworkRequestContext {
|
||||
environment_id: Some("local".to_string()),
|
||||
execution_id: Some("execution-1".to_string()),
|
||||
};
|
||||
registry.register("token-1", expected.clone());
|
||||
let expected = NetworkRequestContext::for_execution("local", "execution-1");
|
||||
registry.register(
|
||||
"execution-1".to_string(),
|
||||
"token-1".to_string(),
|
||||
expected.clone(),
|
||||
);
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let addr = listener.local_addr()?;
|
||||
|
||||
@@ -1234,10 +1234,7 @@ mod tests {
|
||||
|
||||
let (response, _request) = http_connect_accept(
|
||||
Some(decider),
|
||||
NetworkRequestContext {
|
||||
environment_id: Some("remote".to_string()),
|
||||
execution_id: Some("execution-1".to_string()),
|
||||
},
|
||||
NetworkRequestContext::for_execution("remote", "execution-1"),
|
||||
req,
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -53,6 +53,7 @@ pub use proxy::DEFAULT_NO_PROXY_VALUE;
|
||||
pub use proxy::NO_PROXY_ENV_KEYS;
|
||||
pub use proxy::NetworkProxy;
|
||||
pub use proxy::NetworkProxyBuilder;
|
||||
pub use proxy::NetworkProxyExecutionLease;
|
||||
pub use proxy::NetworkProxyHandle;
|
||||
pub use proxy::PROXY_ACTIVE_ENV_KEY;
|
||||
pub use proxy::PROXY_ENV_KEYS;
|
||||
|
||||
@@ -32,6 +32,16 @@ impl NetworkRequestContext {
|
||||
execution_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn for_execution(
|
||||
environment_id: impl Into<String>,
|
||||
execution_id: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
environment_id: Some(environment_id.into()),
|
||||
execution_id: Some(execution_id.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::attribution::AttributionRegistry;
|
||||
use crate::attribution::ConnectionAttribution;
|
||||
use crate::attribution::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
use crate::config;
|
||||
use crate::http_proxy;
|
||||
use crate::network_policy::NetworkPolicyDecider;
|
||||
@@ -19,6 +20,8 @@ use std::net::TcpListener as StdTcpListener;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tokio::task::JoinHandle;
|
||||
use tracing::warn;
|
||||
|
||||
@@ -334,6 +337,7 @@ struct EnvironmentProxyAddrs {
|
||||
|
||||
struct EnvironmentProxy {
|
||||
addrs: EnvironmentProxyAddrs,
|
||||
request_context: NetworkRequestContext,
|
||||
http_task: JoinHandle<Result<()>>,
|
||||
socks_task: Option<JoinHandle<Result<()>>>,
|
||||
}
|
||||
@@ -352,6 +356,48 @@ pub struct NetworkProxy {
|
||||
execution_proxies: AttributionRegistry,
|
||||
}
|
||||
|
||||
/// Keeps an execution-scoped proxy attribution alive until the command tree exits.
|
||||
///
|
||||
/// Clones share one lease. Calling [`Self::close`] or dropping the final clone
|
||||
/// removes its attribution record.
|
||||
#[derive(Clone)]
|
||||
pub struct NetworkProxyExecutionLease {
|
||||
inner: Arc<NetworkProxyExecutionLeaseInner>,
|
||||
}
|
||||
|
||||
struct NetworkProxyExecutionLeaseInner {
|
||||
proxy: NetworkProxy,
|
||||
execution_id: String,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NetworkProxyExecutionLease {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("NetworkProxyExecutionLease")
|
||||
.field("execution_id", &self.inner.execution_id)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkProxyExecutionLease {
|
||||
/// Removes the execution-scoped route immediately.
|
||||
pub fn close(&self) {
|
||||
if !self.inner.closed.swap(true, Ordering::AcqRel) {
|
||||
self.inner
|
||||
.proxy
|
||||
.release_execution_proxy(&self.inner.execution_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NetworkProxyExecutionLeaseInner {
|
||||
fn drop(&mut self) {
|
||||
if !self.closed.swap(true, Ordering::AcqRel) {
|
||||
self.proxy.release_execution_proxy(&self.execution_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for NetworkProxy {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
// Avoid logging internal state (config contents, derived globsets, etc.) which can be noisy
|
||||
@@ -401,6 +447,7 @@ const NODE_USE_ENV_PROXY_ENV_KEY: &str = "NODE_USE_ENV_PROXY";
|
||||
const GIT_SSH_COMMAND_ENV_KEY: &str = "GIT_SSH_COMMAND";
|
||||
pub const PROXY_ENV_KEYS: &[&str] = &[
|
||||
PROXY_ACTIVE_ENV_KEY,
|
||||
PROXY_ATTRIBUTION_TOKEN_ENV_KEY,
|
||||
ALLOW_LOCAL_BINDING_ENV_KEY,
|
||||
ELECTRON_GET_USE_PROXY_ENV_KEY,
|
||||
NODE_USE_ENV_PROXY_ENV_KEY,
|
||||
@@ -615,6 +662,29 @@ impl NetworkProxy {
|
||||
NetworkProxyBuilder::default()
|
||||
}
|
||||
|
||||
/// Registers and leases a command's execution-scoped proxy attribution.
|
||||
pub fn execution_lease(
|
||||
&self,
|
||||
environment_id: impl Into<String>,
|
||||
execution_id: impl Into<String>,
|
||||
token: impl Into<String>,
|
||||
) -> NetworkProxyExecutionLease {
|
||||
let environment_id = environment_id.into();
|
||||
let execution_id = execution_id.into();
|
||||
self.execution_proxies.register(
|
||||
execution_id.clone(),
|
||||
token.into(),
|
||||
NetworkRequestContext::for_execution(environment_id, execution_id.clone()),
|
||||
);
|
||||
NetworkProxyExecutionLease {
|
||||
inner: Arc::new(NetworkProxyExecutionLeaseInner {
|
||||
proxy: self.clone(),
|
||||
execution_id,
|
||||
closed: AtomicBool::new(false),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn http_addr(&self) -> SocketAddr {
|
||||
self.http_addr
|
||||
}
|
||||
@@ -696,11 +766,41 @@ impl NetworkProxy {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Applies a proxy route whose requests are attributed to one execution tree.
|
||||
pub fn apply_to_env_for_execution(
|
||||
&self,
|
||||
env: &mut HashMap<String, String>,
|
||||
environment_id: &str,
|
||||
execution_id: &str,
|
||||
) -> Result<()> {
|
||||
let request_context = NetworkRequestContext::for_execution(environment_id, execution_id);
|
||||
let token = self
|
||||
.execution_proxies
|
||||
.token_for_execution(execution_id, &request_context)?;
|
||||
self.apply_to_env(env);
|
||||
env.insert(PROXY_ATTRIBUTION_TOKEN_ENV_KEY.to_string(), token);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn apply_to_env_for_optional_environment(
|
||||
&self,
|
||||
env: &mut HashMap<String, String>,
|
||||
environment_id: Option<&str>,
|
||||
) -> Result<()> {
|
||||
if let (Some(environment_id), Some(token)) = (
|
||||
environment_id,
|
||||
env.get(PROXY_ATTRIBUTION_TOKEN_ENV_KEY).cloned(),
|
||||
) {
|
||||
let execution_context = self.execution_proxies.context_for_token(&token);
|
||||
if execution_context
|
||||
.as_ref()
|
||||
.is_some_and(|context| context.environment_id.as_deref() == Some(environment_id))
|
||||
{
|
||||
self.apply_to_env(env);
|
||||
return Ok(());
|
||||
}
|
||||
env.remove(PROXY_ATTRIBUTION_TOKEN_ENV_KEY);
|
||||
}
|
||||
match environment_id {
|
||||
Some(environment_id) => self.apply_to_env_for_environment(env, environment_id),
|
||||
None => {
|
||||
@@ -711,27 +811,42 @@ impl NetworkProxy {
|
||||
}
|
||||
|
||||
fn environment_proxy_addrs(&self, environment_id: &str) -> Result<EnvironmentProxyAddrs> {
|
||||
let mut proxies = self
|
||||
.environment_proxies
|
||||
self.scoped_proxy_addrs(
|
||||
&self.environment_proxies,
|
||||
environment_id,
|
||||
NetworkRequestContext::for_environment(environment_id),
|
||||
format!("environment `{environment_id}`"),
|
||||
)
|
||||
}
|
||||
|
||||
fn scoped_proxy_addrs(
|
||||
&self,
|
||||
proxy_map: &Arc<Mutex<HashMap<String, EnvironmentProxy>>>,
|
||||
key: &str,
|
||||
request_context: NetworkRequestContext,
|
||||
description: String,
|
||||
) -> Result<EnvironmentProxyAddrs> {
|
||||
let mut proxies = proxy_map
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(proxy) = proxies.get(environment_id) {
|
||||
if let Some(proxy) = proxies.get(key) {
|
||||
anyhow::ensure!(
|
||||
proxy.request_context == request_context,
|
||||
"network proxy route `{key}` was reused with different attribution"
|
||||
);
|
||||
return Ok(proxy.addrs);
|
||||
}
|
||||
|
||||
let runtime = tokio::runtime::Handle::try_current().with_context(|| {
|
||||
format!("failed to create network proxy for environment `{environment_id}`")
|
||||
})?;
|
||||
let listeners =
|
||||
reserve_loopback_ephemeral_listeners(self.socks_enabled).with_context(|| {
|
||||
format!("failed to reserve network proxy for environment `{environment_id}`")
|
||||
})?;
|
||||
let http_addr = listeners.http_addr().with_context(|| {
|
||||
format!("failed to read HTTP proxy address for environment `{environment_id}`")
|
||||
})?;
|
||||
let socks_addr = listeners.socks_addr(self.socks_addr).with_context(|| {
|
||||
format!("failed to read SOCKS proxy address for environment `{environment_id}`")
|
||||
})?;
|
||||
let runtime = tokio::runtime::Handle::try_current()
|
||||
.with_context(|| format!("failed to create network proxy for {description}"))?;
|
||||
let listeners = reserve_loopback_ephemeral_listeners(self.socks_enabled)
|
||||
.with_context(|| format!("failed to reserve network proxy for {description}"))?;
|
||||
let http_addr = listeners
|
||||
.http_addr()
|
||||
.with_context(|| format!("failed to read HTTP proxy address for {description}"))?;
|
||||
let socks_addr = listeners
|
||||
.socks_addr(self.socks_addr)
|
||||
.with_context(|| format!("failed to read SOCKS proxy address for {description}"))?;
|
||||
let addrs = EnvironmentProxyAddrs {
|
||||
http_addr,
|
||||
socks_addr,
|
||||
@@ -741,10 +856,10 @@ impl NetworkProxy {
|
||||
socks_listener,
|
||||
} = listeners;
|
||||
|
||||
let environment_id = environment_id.to_string();
|
||||
let stored_request_context = request_context.clone();
|
||||
let http_state = self.state.clone();
|
||||
let http_decider = self.policy_decider.clone();
|
||||
let http_request_context = NetworkRequestContext::for_environment(&environment_id);
|
||||
let http_request_context = request_context.clone();
|
||||
let http_task = runtime.spawn(async move {
|
||||
http_proxy::run_http_proxy_with_std_listener(
|
||||
http_state,
|
||||
@@ -758,7 +873,7 @@ impl NetworkProxy {
|
||||
let socks_task = if self.socks_enabled {
|
||||
let socks_state = self.state.clone();
|
||||
let socks_decider = self.policy_decider.clone();
|
||||
let socks_request_context = NetworkRequestContext::for_environment(&environment_id);
|
||||
let socks_request_context = request_context;
|
||||
let socks5_udp_enabled = self.socks5_udp_enabled;
|
||||
socks_listener.map(|listener| {
|
||||
runtime.spawn(async move {
|
||||
@@ -777,9 +892,10 @@ impl NetworkProxy {
|
||||
};
|
||||
|
||||
proxies.insert(
|
||||
environment_id,
|
||||
key.to_string(),
|
||||
EnvironmentProxy {
|
||||
addrs,
|
||||
request_context: stored_request_context,
|
||||
http_task,
|
||||
socks_task,
|
||||
},
|
||||
@@ -787,6 +903,10 @@ impl NetworkProxy {
|
||||
Ok(addrs)
|
||||
}
|
||||
|
||||
fn release_execution_proxy(&self, execution_id: &str) {
|
||||
self.execution_proxies.remove(execution_id);
|
||||
}
|
||||
|
||||
pub async fn replace_config_state(&self, new_state: ConfigState) -> Result<()> {
|
||||
let current_cfg = self.state.current_cfg().await?;
|
||||
anyhow::ensure!(
|
||||
@@ -1109,6 +1229,71 @@ mod tests {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn execution_proxy_routes_share_ports_and_are_released_independently() -> Result<()> {
|
||||
let state = Arc::new(network_proxy_state_for_policy(
|
||||
NetworkProxySettings::default(),
|
||||
));
|
||||
let proxy = NetworkProxy::builder().state(state).build().await?;
|
||||
let handle = proxy.run().await?;
|
||||
let first_lease = proxy.execution_lease("local", "execution-1", "attribution-token-1");
|
||||
let second_lease = proxy.execution_lease("local", "execution-2", "attribution-token-2");
|
||||
|
||||
let mut first_env = HashMap::new();
|
||||
proxy.apply_to_env_for_execution(&mut first_env, "local", "execution-1")?;
|
||||
let mut second_env = HashMap::new();
|
||||
proxy.apply_to_env_for_execution(&mut second_env, "local", "execution-2")?;
|
||||
let mut repeated_first_env = HashMap::new();
|
||||
proxy.apply_to_env_for_execution(&mut repeated_first_env, "local", "execution-1")?;
|
||||
|
||||
assert_eq!(first_env.get("HTTP_PROXY"), second_env.get("HTTP_PROXY"));
|
||||
assert_eq!(
|
||||
first_env.get("HTTP_PROXY"),
|
||||
repeated_first_env.get("HTTP_PROXY")
|
||||
);
|
||||
assert_eq!(
|
||||
first_env.get("HTTP_PROXY"),
|
||||
Some(&format!("http://{}", proxy.http_addr()))
|
||||
);
|
||||
assert_eq!(
|
||||
first_env.get(PROXY_ATTRIBUTION_TOKEN_ENV_KEY),
|
||||
Some(&"attribution-token-1".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
second_env.get(PROXY_ATTRIBUTION_TOKEN_ENV_KEY),
|
||||
Some(&"attribution-token-2".to_string())
|
||||
);
|
||||
assert_eq!(proxy.execution_proxies.len(), 2);
|
||||
assert_eq!(
|
||||
proxy
|
||||
.execution_proxies
|
||||
.context_for_token("attribution-token-1"),
|
||||
Some(NetworkRequestContext::for_execution("local", "execution-1"))
|
||||
);
|
||||
|
||||
first_lease.close();
|
||||
|
||||
assert_eq!(proxy.execution_proxies.len(), 1);
|
||||
assert_eq!(
|
||||
proxy
|
||||
.execution_proxies
|
||||
.context_for_token("attribution-token-1"),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
proxy
|
||||
.execution_proxies
|
||||
.context_for_token("attribution-token-2"),
|
||||
Some(NetworkRequestContext::for_execution("local", "execution-2"))
|
||||
);
|
||||
|
||||
drop(second_lease);
|
||||
assert_eq!(proxy.execution_proxies.len(), 0);
|
||||
|
||||
handle.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_proxy_builder_does_not_reserve_socks_listener_when_disabled() {
|
||||
let settings = NetworkProxySettings {
|
||||
|
||||
@@ -31,6 +31,11 @@ pub use windows::resolve_windows_restricted_token_filesystem_overrides;
|
||||
pub use windows::unsupported_windows_restricted_token_sandbox_reason;
|
||||
pub use windows::windows_sandbox_uses_elevated_backend;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use codex_network_proxy::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
|
||||
#[cfg(target_os = "linux")]
|
||||
pub use codex_network_proxy::write_attribution_frame;
|
||||
|
||||
use codex_protocol::error::CodexErr;
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
|
||||
Reference in New Issue
Block a user