Lightweight coding agent that runs in your terminal
Rust
Add a standalone network proxy binary with JSON configuration (#46573)
viyatb-oai94e3c2090631
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lockindex b3bb45bc1f..d2a9c2babd 100644--- a/codex-rs/Cargo.lock+++ b/codex-rs/Cargo.lock@@ -4165,6 +4165,7 @@ dependencies = ["schemars 0.8.22","security-framework 3.5.1","serde",+ "serde_ignored","serde_json","sha2 0.10.9","tempfile",@@ -4172,6 +4173,7 @@ dependencies = ["time","tokio","tracing",+ "tracing-subscriber","url","windows-sys 0.52.0",]diff --git a/codex-rs/network-proxy/Cargo.toml b/codex-rs/network-proxy/Cargo.tomlindex 6e81390231..4b6e91b617 100644--- a/codex-rs/network-proxy/Cargo.toml+++ b/codex-rs/network-proxy/Cargo.toml@@ -9,6 +9,10 @@ name = "codex_network_proxy"path = "src/lib.rs"doctest = false+[[bin]]+name = "codex-network-proxy"+path = "src/main.rs"+[lints]workspace = true@@ -30,11 +34,13 @@ regex-automata = { workspace = true }regex-syntax = { workspace = true }schemars = { workspace = true }serde = { workspace = true, features = ["derive"] }+serde_ignored = { workspace = true }serde_json = { workspace = true }thiserror = { workspace = true }time = { workspace = true }tokio = { workspace = true, features = ["full"] }tracing = { workspace = true }+tracing-subscriber = { workspace = true, features = ["env-filter"] }url = { workspace = true }rama-core = { version = "=0.3.0-alpha.4" }rama-http = { version = "=0.3.0-alpha.4" }diff --git a/codex-rs/network-proxy/README.md b/codex-rs/network-proxy/README.mdindex a83a0df0d7..00ecdbbf6a 100644--- a/codex-rs/network-proxy/README.md+++ b/codex-rs/network-proxy/README.md@@ -83,8 +83,33 @@ strip_request_headers = ["authorization"]### 2) Run the proxy+The proxy can also run without a full Codex permissions profile. Put the network policy in a+standalone JSON file:++```json+{+ "network": {+ "enabled": true,+ "proxy_url": "http://127.0.0.1:3128",+ "enable_socks5": false,+ "enable_socks5_udp": false,+ "allow_upstream_proxy": false,+ "allow_local_binding": false,+ "mode": "full",+ "mitm": false,+ "domains": {+ "api.example.com": "allow"+ }+ }+}+```++HTTPS MITM is enabled automatically for limited mode or configured `mitm_hooks`. Set `mitm` to+`true` to enable it explicitly. The proxy requires `network.enabled = true` and rejects unknown+fields, including fields nested inside MITM hooks.+```bash-cargo run -p codex-network-proxy --+cargo run -p codex-network-proxy -- --config /path/to/network-proxy.json```### 3) Point a client at itdiff --git a/codex-rs/network-proxy/src/main.rs b/codex-rs/network-proxy/src/main.rsnew file mode 100644index 0000000000..8cbf9b4c46--- /dev/null+++ b/codex-rs/network-proxy/src/main.rs@@ -0,0 +1,114 @@+#![deny(clippy::print_stdout, clippy::print_stderr)]++use anyhow::Context as _;+use anyhow::Result;+use anyhow::ensure;+use clap::Parser;+use codex_network_proxy::ConfigReloader;+use codex_network_proxy::ConfigReloaderFuture;+use codex_network_proxy::ConfigState;+use codex_network_proxy::NetworkMode;+use codex_network_proxy::NetworkProxy;+use codex_network_proxy::NetworkProxyConfig;+use codex_network_proxy::NetworkProxyConstraints;+use codex_network_proxy::NetworkProxyState;+use codex_network_proxy::build_config_state;+use serde::Deserialize;+use std::path::PathBuf;+use std::sync::Arc;+use tracing_subscriber::EnvFilter;++const MAX_CONFIG_BYTES: usize = 1024 * 1024;++#[derive(Debug, Parser)]+#[command(name = "codex-network-proxy", about = "Codex network policy proxy")]+struct Args {+ /// Standalone JSON configuration containing a `network` object.+ #[arg(long, value_name = "PATH")]+ config: PathBuf,+}++#[derive(Debug, Deserialize)]+#[serde(deny_unknown_fields)]+struct StandaloneConfig {+ network: NetworkProxyConfig,+}++fn parse_standalone_config(bytes: &[u8]) -> Result<StandaloneConfig> {+ let mut deserializer = serde_json::Deserializer::from_slice(bytes);+ let mut ignored_fields = Vec::new();+ let mut config: StandaloneConfig = serde_ignored::deserialize(&mut deserializer, |path| {+ ignored_fields.push(path.to_string());+ })?;+ deserializer.end()?;+ ensure!(+ ignored_fields.is_empty(),+ "unknown fields in network proxy config: {}",+ ignored_fields.join(", ")+ );+ config.network.mitm |=+ config.network.mode == NetworkMode::Limited || !config.network.mitm_hooks.is_empty();+ Ok(config)+}++struct StaticConfigReloader {+ state: ConfigState,+}++impl ConfigReloader for StaticConfigReloader {+ fn source_label(&self) -> String {+ "standalone network proxy config".to_string()+ }++ fn maybe_reload(&self) -> ConfigReloaderFuture<'_, Option<ConfigState>> {+ Box::pin(async { Ok(None) })+ }++ fn reload_now(&self) -> ConfigReloaderFuture<'_, ConfigState> {+ Box::pin(async { Ok(self.state.clone()) })+ }+}++#[tokio::main]+async fn main() -> Result<()> {+ tracing_subscriber::fmt()+ .with_env_filter(EnvFilter::from_default_env())+ .init();+ let args = Args::parse();+ let bytes = std::fs::read(&args.config).with_context(|| {+ format!(+ "failed to read network proxy config: {}",+ args.config.display()+ )+ })?;+ ensure!(+ bytes.len() <= MAX_CONFIG_BYTES,+ "network proxy config exceeds {MAX_CONFIG_BYTES} bytes"+ );+ let config = parse_standalone_config(&bytes)+ .with_context(|| format!("invalid network proxy config: {}", args.config.display()))?;+ ensure!(+ config.network.enabled,+ "standalone network proxy requires network.enabled = true"+ );++ let config_state = build_config_state(config.network, NetworkProxyConstraints::default())+ .context("failed to initialize network proxy policy")?;+ let reloader = Arc::new(StaticConfigReloader {+ state: config_state.clone(),+ });+ let state = Arc::new(NetworkProxyState::with_reloader(config_state, reloader));+ NetworkProxy::builder()+ .state(state)+ .managed_by_codex(/*managed_by_codex*/ false)+ .build()+ .await?+ .run()+ .await?+ .wait()+ .await+}++#[cfg(test)]+#[path = "main_tests.rs"]+mod tests;diff --git a/codex-rs/network-proxy/src/main_tests.rs b/codex-rs/network-proxy/src/main_tests.rsnew file mode 100644index 0000000000..b12c31bfb8--- /dev/null+++ b/codex-rs/network-proxy/src/main_tests.rs@@ -0,0 +1,121 @@+use super::parse_standalone_config;+use pretty_assertions::assert_eq;+use serde_json::json;++#[test]+fn enables_mitm_for_limited_mode_and_hooks() {+ for (network, expected_mitm) in [+ (json!({"enabled": true, "mode": "full"}), false),+ (json!({"enabled": true, "mode": "full", "mitm": true}), true),+ (json!({"enabled": true, "mode": "limited"}), true),+ (+ json!({+ "enabled": true,+ "mitm_hooks": [{"host": "api.example.com"}]+ }),+ true,+ ),+ ] {+ let bytes = serde_json::to_vec(&json!({"network": network})).unwrap();+ let config = parse_standalone_config(&bytes).unwrap();+ assert_eq!(config.network.mitm, expected_mitm);+ }+}++#[test]+fn accepts_dynamic_domain_socket_and_hook_matcher_keys() {+ let bytes = serde_json::to_vec(&json!({+ "network": {+ "enabled": true,+ "domains": {"api.example.com": "allow"},+ "unix_sockets": {"/tmp/example.sock": "allow"},+ "mitm_hooks": [{+ "host": "api.example.com",+ "match": {+ "query": {"scope": ["read"]},+ "headers": {"authorization": ["Bearer token"]}+ }+ }]+ }+ }))+ .unwrap();++ let config = parse_standalone_config(&bytes).unwrap();++ assert_eq!(+ config.network.allowed_domains(),+ Some(vec!["api.example.com".to_string()])+ );+ assert_eq!(+ config.network.allow_unix_sockets(),+ vec!["/tmp/example.sock".to_string()]+ );+}++#[test]+fn rejects_unknown_fields_at_every_mitm_hook_level() {+ for (network, unknown_field) in [+ (+ json!({"enabled": true, "unexpected_network": true}),+ "unexpected_network",+ ),+ (+ json!({+ "enabled": true,+ "mitm_hooks": [{+ "host": "api.example.com",+ "unexpected_hook": true+ }]+ }),+ "unexpected_hook",+ ),+ (+ json!({+ "enabled": true,+ "mitm_hooks": [{+ "host": "api.example.com",+ "match": {"unexpected_matcher": true}+ }]+ }),+ "unexpected_matcher",+ ),+ (+ json!({+ "enabled": true,+ "mitm_hooks": [{+ "host": "api.example.com",+ "actions": {"unexpected_action": true}+ }]+ }),+ "unexpected_action",+ ),+ (+ json!({+ "enabled": true,+ "mitm_hooks": [{+ "host": "api.example.com",+ "actions": {+ "inject_request_headers": [{+ "name": "authorization",+ "unexpected_header": true+ }]+ }+ }]+ }),+ "unexpected_header",+ ),+ ] {+ let bytes = serde_json::to_vec(&json!({"network": network})).unwrap();+ let error = parse_standalone_config(&bytes).unwrap_err();+ assert!(+ error.to_string().contains(unknown_field),+ "expected {unknown_field} in {error}"+ );+ }+}++#[test]+fn rejects_trailing_json_values() {+ let error = parse_standalone_config(br#"{"network":{"enabled":true}} {}"#).unwrap_err();+ assert!(error.to_string().contains("trailing characters"));+}diff --git a/codex-rs/network-proxy/src/proxy.rs b/codex-rs/network-proxy/src/proxy.rsindex 16d01ed16f..574dcba407 100644--- a/codex-rs/network-proxy/src/proxy.rs+++ b/codex-rs/network-proxy/src/proxy.rs@@ -1791,6 +1791,42 @@ mod tests {})}+ #[tokio::test]+ async fn wait_fails_fast_when_either_listener_fails() {+ for failing_listener in ["http", "socks"] {+ let http_fails = failing_listener == "http";+ let mut listeners = ProxyListeners::new();+ listeners.spawn(move |_guard| async move {+ if http_fails {+ anyhow::bail!("http proxy listener failed");+ }+ std::future::pending::<Result<()>>().await+ });+ listeners.spawn(move |_guard| async move {+ if !http_fails {+ anyhow::bail!("socks proxy listener failed");+ }+ std::future::pending::<Result<()>>().await+ });+ let handle = NetworkProxyHandle {+ runtime: Some(ProxyRuntime::Listeners(listeners)),+ environment_proxies: Some(Arc::new(Mutex::new(HashMap::new()))),+ #[cfg(target_os = "windows")]+ windows_active_route: None,+ };++ let error = tokio::time::timeout(std::time::Duration::from_secs(1), handle.wait())+ .await+ .expect("proxy wait should not hang when a listener fails")+ .unwrap_err();++ assert_eq!(+ error.to_string(),+ format!("{failing_listener} proxy listener failed")+ );+ }+ }+#[tokio::test]async fn proxy_startup_ignores_macos_unix_socket_permissions_on_windows() -> Result<()> {let unix_sockets = crate::config::NetworkUnixSocketPermissions {