Share platform identity across path, network, and sandbox configuration (#46334)

## What changed

- Add `Platform` to `codex-utils-path-uri` with metadata parsing, native platform detection, and path convention mapping. Preserve missing or unrecognized metadata as `Unknown`.
- Replace `NetworkProxyExecutorOs` with the shared type and keep executor-specific socket path validation in the network proxy.
- Extract `effective_sandbox_mode` with explicit platform and Windows sandbox level inputs, preserving the native Windows fallback from `workspace-write` to `read-only` when the sandbox is disabled.

## Testing

Add unit tests for platform metadata, path conventions, native platform detection, and sandbox mode selection across platforms and Windows sandbox levels.

GitOrigin-RevId: 4fe0972e3a91040e35f2a6dfa5bcdf6c9a29be88
This commit is contained in:
Sean Huang
2026-09-18 00:51:34 +00:00
committed by copyberry
parent fd875b188b
commit 3724dc8361
31 changed files with 277 additions and 211 deletions
+1
View File
@@ -4132,6 +4132,7 @@ dependencies = [
"clap",
"codex-utils-absolute-path",
"codex-utils-home-dir",
"codex-utils-path-uri",
"codex-utils-rustls-provider",
"codex-windows-sandbox",
"globset",
+60 -21
View File
@@ -56,6 +56,7 @@ use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_protocol::protocol::AskForApproval;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path::normalize_for_path_comparison;
use codex_utils_path_uri::Platform;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Deserializer;
@@ -749,8 +750,28 @@ pub struct GhostSnapshotToml {
pub disable_warnings: Option<bool>,
}
/// Apply the executor's sandbox availability to an already selected sandbox mode.
///
/// Call this before resolving workspace-write settings so unused writable roots
/// do not affect the read-only fallback. Named permission profiles are resolved
/// separately and must not be downgraded through this helper.
pub fn effective_sandbox_mode(
mode: SandboxMode,
platform: Platform,
windows_sandbox_level: WindowsSandboxLevel,
) -> SandboxMode {
if platform == Platform::Windows
&& windows_sandbox_level == WindowsSandboxLevel::Disabled
&& mode == SandboxMode::WorkspaceWrite
{
SandboxMode::ReadOnly
} else {
mode
}
}
impl ConfigToml {
/// Derive the effective permission profile from legacy sandbox config.
/// Derive the effective permission profile from sandbox config.
///
/// Call this only after ruling out `default_permissions`: named
/// `[permissions]` profiles must be compiled through the permissions
@@ -766,30 +787,17 @@ impl ConfigToml {
let resolved_sandbox_mode = configured_sandbox_mode
.or_else(|| {
// If no sandbox_mode is set but this directory has a trust decision,
// default to workspace-write except on unsandboxed Windows where we
// default to read-only.
// default to workspace-write before applying the platform fallback.
active_project
.filter(|project| project.is_trusted() || project.is_untrusted())
.map(|_| {
if cfg!(target_os = "windows")
&& windows_sandbox_level == WindowsSandboxLevel::Disabled
{
SandboxMode::ReadOnly
} else {
SandboxMode::WorkspaceWrite
}
})
.map(|_| SandboxMode::WorkspaceWrite)
})
.unwrap_or_default();
let effective_sandbox_mode = if cfg!(target_os = "windows")
// If the experimental Windows sandbox is enabled, do not force a downgrade.
&& windows_sandbox_level == WindowsSandboxLevel::Disabled
&& matches!(resolved_sandbox_mode, SandboxMode::WorkspaceWrite)
{
SandboxMode::ReadOnly
} else {
resolved_sandbox_mode
};
let effective_sandbox_mode = effective_sandbox_mode(
resolved_sandbox_mode,
Platform::native(),
windows_sandbox_level,
);
let permission_profile = match effective_sandbox_mode {
SandboxMode::ReadOnly => PermissionProfile::read_only(),
@@ -1000,6 +1008,37 @@ mod tests {
const WORKSPACE_ID_A: &str = "123e4567-e89b-42d3-a456-426614174000";
const WORKSPACE_ID_B: &str = "123e4567-e89b-42d3-a456-426614174001";
#[test]
fn sandbox_mode_uses_executor_platform_and_sandbox_level() {
use Platform::Linux;
use Platform::Macos;
use Platform::Unknown;
use Platform::Windows;
use SandboxMode::DangerFullAccess;
use SandboxMode::ReadOnly;
use SandboxMode::WorkspaceWrite;
use WindowsSandboxLevel::Disabled;
use WindowsSandboxLevel::Elevated;
use WindowsSandboxLevel::RestrictedToken;
for (mode, platform, level, expected) in [
(WorkspaceWrite, Windows, Disabled, ReadOnly),
(WorkspaceWrite, Windows, RestrictedToken, WorkspaceWrite),
(WorkspaceWrite, Windows, Elevated, WorkspaceWrite),
(WorkspaceWrite, Linux, Disabled, WorkspaceWrite),
(WorkspaceWrite, Macos, Disabled, WorkspaceWrite),
(WorkspaceWrite, Unknown, Disabled, WorkspaceWrite),
(ReadOnly, Windows, Disabled, ReadOnly),
(DangerFullAccess, Windows, Disabled, DangerFullAccess),
] {
assert_eq!(
effective_sandbox_mode(mode, platform, level),
expected,
"{mode:?}, {platform:?}, {level:?}"
);
}
}
#[test]
fn thread_unload_delay_requires_nonnegative_seconds() {
for value in ["-1", "1.5", "\"60\""] {
+1
View File
@@ -128,6 +128,7 @@ pub use config_requirements::WebSearchModeRequirement;
pub use config_requirements::WindowsRequirementsToml;
pub use config_requirements::WindowsSandboxImplementationToml;
pub use config_requirements::sandbox_mode_requirement_for_permission_profile;
pub use config_toml::effective_sandbox_mode;
pub use constraint::Constrained;
pub use constraint::ConstraintError;
pub use constraint::ConstraintResult;
+2 -2
View File
@@ -15,8 +15,8 @@ use codex_features::FeatureToml;
use codex_features::FeaturesToml;
use codex_network_proxy::EnvironmentNetworkPolicy;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::NetworkProxyExecutorOs;
use codex_protocol::models::PermissionProfile;
use codex_utils_path_uri::Platform;
use super::NetworkProxySpec;
use super::permissions::apply_network_proxy_feature_config;
@@ -60,7 +60,7 @@ pub fn project_environment_profile_network(
pub fn validate_environment_network_policy(
policy: &EnvironmentNetworkPolicy,
permission_profile: &PermissionProfile,
executor_os: NetworkProxyExecutorOs,
executor_os: Platform,
) -> Result<(), EnvironmentNetworkConfigError> {
NetworkProxySpec::for_environment(
/*controller*/ None,
@@ -42,10 +42,10 @@ fn environment_policy_presence_keeps_selected_and_managed_denials() {
#[test]
fn attachment_projection_preserves_policy_and_drops_listener_addresses() {
for executor_os in [
NetworkProxyExecutorOs::Linux,
NetworkProxyExecutorOs::Macos,
NetworkProxyExecutorOs::Windows,
NetworkProxyExecutorOs::Unknown,
Platform::Linux,
Platform::Macos,
Platform::Windows,
Platform::Unknown,
] {
for (raw, windows_only) in [
("", false),
@@ -76,11 +76,8 @@ allow_local_binding = false
),
] {
let expected: NetworkToml = toml::from_str(raw).unwrap();
let accepted = !windows_only
|| matches!(
executor_os,
NetworkProxyExecutorOs::Windows | NetworkProxyExecutorOs::Unknown
);
let accepted =
!windows_only || matches!(executor_os, Platform::Windows | Platform::Unknown);
assert_eq!(
build_config_state(
expected.to_network_proxy_config(),
@@ -165,7 +162,7 @@ action = ['redact']
validate_environment_network_policy(
&policy,
&PermissionProfile::read_only(),
NetworkProxyExecutorOs::Unknown,
Platform::Unknown,
),
Err(EnvironmentNetworkConfigError),
"{raw}"
@@ -202,7 +199,7 @@ action = ['redact']
validate_environment_network_policy(
&policy,
&PermissionProfile::read_only(),
NetworkProxyExecutorOs::Unknown,
Platform::Unknown,
),
Ok(()),
"{raw}"
+6 -10
View File
@@ -12,7 +12,6 @@ use codex_network_proxy::NetworkProxy;
use codex_network_proxy::NetworkProxyAuditMetadata;
use codex_network_proxy::NetworkProxyConfig;
use codex_network_proxy::NetworkProxyConstraints;
use codex_network_proxy::NetworkProxyExecutorOs;
use codex_network_proxy::NetworkProxyHandle;
use codex_network_proxy::NetworkProxyState;
use codex_network_proxy::build_config_state;
@@ -22,6 +21,7 @@ use codex_network_proxy::managed_proxy_ports;
use codex_network_proxy::normalize_host;
use codex_network_proxy::validate_policy_against_constraints;
use codex_protocol::models::PermissionProfile;
use codex_utils_path_uri::Platform;
use std::collections::HashSet;
use std::sync::Arc;
@@ -197,10 +197,7 @@ impl NetworkProxySpec {
enable_network_approval_flow: bool,
audit_metadata: NetworkProxyAuditMetadata,
) -> std::io::Result<StartedNetworkProxy> {
let state = self.build_state_with_audit_metadata(
audit_metadata,
NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
)?;
let state = self.build_state_with_audit_metadata(audit_metadata, Platform::native())?;
let mut builder = NetworkProxy::builder()
.state(Arc::new(state))
.managed_proxy_routing(managed_proxy_routing);
@@ -341,9 +338,8 @@ impl NetworkProxySpec {
&self,
started_proxy: &StartedNetworkProxy,
) -> std::io::Result<()> {
let state = self.build_config_state_for_spec(NetworkProxyExecutorOs::from_platform_os(
Some(std::env::consts::OS),
))?;
let state = self
.build_config_state_for_spec(Platform::from_platform_os(Some(std::env::consts::OS)))?;
started_proxy
.proxy()
.replace_config_state(state)
@@ -356,7 +352,7 @@ impl NetworkProxySpec {
pub(crate) fn build_state_with_audit_metadata(
&self,
audit_metadata: NetworkProxyAuditMetadata,
executor_os: NetworkProxyExecutorOs,
executor_os: Platform,
) -> std::io::Result<NetworkProxyState> {
let state = self.build_config_state_for_spec(executor_os)?;
let reloader = Arc::new(StaticNetworkProxyReloader::new(state.clone()));
@@ -369,7 +365,7 @@ impl NetworkProxySpec {
pub(super) fn build_config_state_for_spec(
&self,
executor_os: NetworkProxyExecutorOs,
executor_os: Platform,
) -> std::io::Result<ConfigState> {
build_config_state(self.config.clone(), self.constraints.clone(), executor_os).map_err(
|err| std::io::Error::other(format!("failed to build network proxy state: {err}")),
@@ -84,11 +84,9 @@ async fn attachment_socket_grants_respect_configured_restrictions_at_remote_laun
Some(expected),
"{name}"
);
let state =
Arc::new(controller.build_state_with_audit_metadata(
Default::default(),
NetworkProxyExecutorOs::Linux,
)?);
let state = Arc::new(
controller.build_state_with_audit_metadata(Default::default(), Platform::Linux)?,
);
let proxy = NetworkProxy::builder()
.state(Arc::clone(&state))
.managed_by_codex(false)
@@ -142,9 +140,7 @@ async fn attachment_socket_grants_respect_configured_restrictions_at_remote_laun
&profile,
)?;
proxy
.replace_config_state(
restricted.build_config_state_for_spec(NetworkProxyExecutorOs::Linux)?,
)
.replace_config_state(restricted.build_config_state_for_spec(Platform::Linux)?)
.await?;
assert!(
!scoped
@@ -175,7 +171,7 @@ fn build_state_with_audit_metadata_threads_metadata_to_state() {
};
let state = spec
.build_state_with_audit_metadata(metadata.clone(), NetworkProxyExecutorOs::Linux)
.build_state_with_audit_metadata(metadata.clone(), Platform::Linux)
.expect("state should build");
assert_eq!(state.audit_metadata(), &metadata);
}
@@ -258,14 +254,14 @@ fn environment_policy_replaces_soft_controller_allowlist_and_preserves_denials()
let owner_policy =
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false);
assert_eq!(
validate_environment_network_policy(&owner_policy, &profile, NetworkProxyExecutorOs::Linux),
validate_environment_network_policy(&owner_policy, &profile, Platform::Linux),
Ok(())
);
assert_eq!(
validate_environment_network_policy(
&owner_policy,
&PermissionProfile::Disabled,
NetworkProxyExecutorOs::Linux
Platform::Linux
),
Err(EnvironmentNetworkConfigError)
);
@@ -334,22 +330,14 @@ fn environment_policy_replaces_soft_controller_allowlist_and_preserves_denials()
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false);
assert!(compose(Some(&spec), &wildcard_policy, &profile, &empty).is_err());
assert_eq!(
validate_environment_network_policy(
&wildcard_policy,
&profile,
NetworkProxyExecutorOs::Linux
),
validate_environment_network_policy(&wildcard_policy, &profile, Platform::Linux),
Err(EnvironmentNetworkConfigError)
);
owner.set_allowed_domains(vec!["[".to_string()]);
let malformed_policy =
EnvironmentNetworkPolicy::from_config(&owner, /*managed_allowed_domains_only*/ false);
assert_eq!(
validate_environment_network_policy(
&malformed_policy,
&profile,
NetworkProxyExecutorOs::Linux
),
validate_environment_network_policy(&malformed_policy, &profile, Platform::Linux),
Err(EnvironmentNetworkConfigError)
);
}
+2 -6
View File
@@ -521,9 +521,7 @@ async fn inactive_profiles_keep_snapshots_but_active_brokers_require_sandbox() -
.replace_config_state(codex_network_proxy::build_config_state(
config,
codex_network_proxy::NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(
std::env::consts::OS,
)),
codex_utils_path_uri::Platform::native(),
)?)
.await?;
assert_eq!(
@@ -572,9 +570,7 @@ async fn inactive_profiles_keep_snapshots_but_active_brokers_require_sandbox() -
.replace_config_state(codex_network_proxy::build_config_state(
config,
codex_network_proxy::NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(
std::env::consts::OS,
)),
codex_utils_path_uri::Platform::native(),
)?)
.await?;
fs::write(dir.path().join("finish-startup"), "").await?;
+2 -2
View File
@@ -18,7 +18,6 @@ use codex_network_proxy::NetworkPolicyDecider;
use codex_network_proxy::NetworkPolicyRequest;
use codex_network_proxy::NetworkProtocol;
use codex_network_proxy::NetworkProxy;
use codex_network_proxy::NetworkProxyExecutorOs;
use codex_network_proxy::NetworkRequestCancellation;
use codex_network_proxy::NetworkRequestCancellationReason;
use codex_network_proxy::NetworkRequestDisconnect;
@@ -33,6 +32,7 @@ use codex_protocol::protocol::ReviewDecision;
use codex_protocol::protocol::WarningEvent;
use codex_sandboxing::record_network_sandbox_violation;
use codex_tools::ToolName;
use codex_utils_path_uri::Platform;
use indexmap::IndexMap;
use std::collections::HashMap;
use std::collections::HashSet;
@@ -1152,7 +1152,7 @@ pub(crate) async fn begin_network_approval(
})?
} else {
// This carrier never listens: the executor starts the real per-command proxy.
let executor_os = NetworkProxyExecutorOs::from_platform_os(
let executor_os = Platform::from_platform_os(
environments
.turn_environments()
.find(|environment| environment.selection.environment_id == environment_id)
@@ -79,7 +79,7 @@ async fn test_network_proxy_with_config(
let state = codex_network_proxy::build_config_state(
config,
NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
codex_utils_path_uri::Platform::native(),
)?;
NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
+1 -3
View File
@@ -1819,9 +1819,7 @@ mod tests {
.expect("build remote network proxy config");
let state = NetworkProxyState::from_remote_launch_config(
RemoteNetworkProxyLaunchConfig::new(proxy_config),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(
std::env::consts::OS,
)),
codex_utils_path_uri::Platform::native(),
)
.expect("build network proxy state");
let proxy = NetworkProxy::builder()
+1 -1
View File
@@ -350,7 +350,7 @@ async fn prepare_managed_network(
};
let mut state = NetworkProxyState::from_remote_launch_config(
network_proxy,
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
codex_utils_path_uri::Platform::native(),
)
.map_err(|err| invalid_params(format!("invalid network proxy config: {err}")))?;
if let Some(observer) = network_policy_audit_observer {
@@ -143,9 +143,7 @@ for family in (socket.AF_NETLINK, getattr(socket, 'AF_VSOCK', 40)):
let state = build_config_state(
config,
NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(
std::env::consts::OS,
)),
codex_network_proxy::Platform::native(),
)
.expect("valid managed network configuration");
let network = NetworkProxy::builder()
+1
View File
@@ -19,6 +19,7 @@ clap = { workspace = true, features = ["derive"] }
chrono = { workspace = true }
codex-utils-absolute-path = { workspace = true }
codex-utils-home-dir = { workspace = true }
codex-utils-path-uri = { workspace = true }
codex-utils-rustls-provider = { workspace = true }
globset = { workspace = true }
opentelemetry = { workspace = true }
@@ -175,7 +175,7 @@ impl TestProxy {
let config_state = build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.unwrap();
let state = Arc::new(NetworkProxyState::with_reloader(
+15 -27
View File
@@ -14,7 +14,7 @@ use std::path::Path;
use tracing::warn;
use url::Url;
use crate::NetworkProxyExecutorOs;
use crate::Platform;
use crate::mitm_hook::MitmHookConfig;
use crate::policy::normalize_host;
@@ -497,21 +497,19 @@ impl ValidatedUnixSocketPath {
pub(crate) fn validate_unix_socket_allowlist_paths(
cfg: &NetworkProxyConfig,
executor_os: NetworkProxyExecutorOs,
executor_os: Platform,
) -> Result<()> {
for (index, socket_path) in cfg.allow_unix_sockets().iter().enumerate() {
anyhow::ensure!(
executor_os.socket_path_is_absolute(socket_path) && !socket_path.contains('\0'),
crate::socket_path::socket_path_is_absolute(executor_os, socket_path)
&& !socket_path.contains('\0'),
"invalid network.allow_unix_sockets[{index}]: expected a NUL-free absolute path for {executor_os:?}, got {socket_path:?}"
);
}
Ok(())
}
pub fn resolve_runtime(
cfg: &NetworkProxyConfig,
executor_os: NetworkProxyExecutorOs,
) -> Result<RuntimeConfig> {
pub fn resolve_runtime(cfg: &NetworkProxyConfig, executor_os: Platform) -> Result<RuntimeConfig> {
validate_unix_socket_allowlist_paths(cfg, executor_os)?;
let http_addr = resolve_addr(&cfg.proxy_url, /*default_port*/ 3128)
@@ -528,10 +526,7 @@ pub fn resolve_runtime(
/// Returns the sorted loopback ports used by the configured managed proxy listeners.
pub fn managed_proxy_ports(cfg: &NetworkProxyConfig) -> Result<Vec<u16>> {
let runtime = resolve_runtime(
cfg,
NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
)?;
let runtime = resolve_runtime(cfg, Platform::native())?;
if runtime.http_addr.port() == 0 {
bail!("network.proxy_url must use a fixed non-zero port for managed proxy provisioning");
}
@@ -1117,13 +1112,10 @@ mod tests {
] {
let cfg = settings_with_unix_sockets(&[path]);
for (executor_os, accepted) in [
(NetworkProxyExecutorOs::Linux, unix_absolute),
(NetworkProxyExecutorOs::Macos, unix_absolute),
(NetworkProxyExecutorOs::Windows, windows_absolute),
(
NetworkProxyExecutorOs::Unknown,
unix_absolute || windows_absolute,
),
(Platform::Linux, unix_absolute),
(Platform::Macos, unix_absolute),
(Platform::Windows, windows_absolute),
(Platform::Unknown, unix_absolute || windows_absolute),
] {
assert_eq!(
resolve_runtime(&cfg, executor_os).is_ok(),
@@ -1134,11 +1126,7 @@ mod tests {
// Each platform's CI compares the portable implementation to native
// Core acceptance, with the deliberate shared NUL rejection.
assert_eq!(
resolve_runtime(
&cfg,
NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS))
)
.is_ok(),
resolve_runtime(&cfg, Platform::native()).is_ok(),
(Path::new(path).is_absolute() || path.starts_with('/')) && !path.contains('\0'),
"native parity: {path:?}"
);
@@ -1161,10 +1149,10 @@ mod tests {
}
for executor_os in [
NetworkProxyExecutorOs::Linux,
NetworkProxyExecutorOs::Macos,
NetworkProxyExecutorOs::Windows,
NetworkProxyExecutorOs::Unknown,
Platform::Linux,
Platform::Macos,
Platform::Windows,
Platform::Unknown,
] {
assert!(
resolve_runtime(&cfg, executor_os).is_ok(),
-54
View File
@@ -1,54 +0,0 @@
//! Executor path semantics for policy validation, independent of the controller OS.
//! Socket support and native path normalization remain executor runtime concerns.
/// OS of the executor whose network policy is being validated.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NetworkProxyExecutorOs {
Linux,
Macos,
Windows,
/// Legacy executors may omit their OS. Accept absolute syntax supported by
/// either platform here; the executor validates against its own OS at launch.
Unknown,
}
impl NetworkProxyExecutorOs {
/// Uses executor metadata, never the OS of the process doing the validation.
pub fn from_platform_os(platform_os: Option<&str>) -> Self {
match platform_os {
Some("linux") => Self::Linux,
Some("macos") => Self::Macos,
Some("windows") => Self::Windows,
Some(_) | None => Self::Unknown,
}
}
pub(crate) fn socket_path_is_absolute(self, path: &str) -> bool {
// Core also accepts Unix-style absolute paths on Windows, for portability.
path.starts_with('/')
|| match self {
Self::Linux | Self::Macos => false,
Self::Windows | Self::Unknown => windows_path_is_absolute(path),
}
}
}
// Match std::path's Windows absolute-path syntax without consulting the host.
// Non-drive prefixes have an implicit root, including device and verbatim paths.
fn windows_path_is_absolute(path: &str) -> bool {
let bytes = path.as_bytes();
if matches!(bytes, [drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic()) {
return true;
}
let [b'\\' | b'/', b'\\' | b'/', rest @ ..] = bytes else {
return false;
};
if path.starts_with(r"\\?\") || matches!(rest, [b'.', b'\\' | b'/', ..]) {
return true;
}
let mut components = rest.split(|byte| matches!(byte, b'\\' | b'/'));
matches!(
(components.next(), components.next()),
(Some(server), Some(share)) if !server.is_empty() && !share.is_empty()
)
}
+2 -2
View File
@@ -9,7 +9,6 @@ mod connect_policy;
mod connection_lifecycle;
mod credential_broker;
mod environment_policy;
mod executor_os;
mod http_proxy;
mod mitm;
mod mitm_hook;
@@ -24,6 +23,7 @@ mod request_cancellation;
mod request_disconnect;
mod responses;
mod runtime;
mod socket_path;
mod socks5;
mod state;
#[cfg(target_os = "macos")]
@@ -38,6 +38,7 @@ pub use attribution::PROXY_ATTRIBUTION_TOKEN_ENV_KEY;
pub use attribution::write_attribution_frame;
pub use certs::CUSTOM_CA_ENV_KEYS;
pub use certs::is_managed_mitm_ca_trust_bundle_path;
pub use codex_utils_path_uri::Platform;
pub use config::NetworkDomainPermission;
pub use config::NetworkDomainPermissionEntry;
pub use config::NetworkDomainPermissions;
@@ -61,7 +62,6 @@ pub use credential_broker::credential_broker_provider_context_env_keys;
pub use credential_broker::credential_broker_provider_sources_allowed;
pub use credential_broker::is_credential_broker_provider_env_key;
pub use environment_policy::EnvironmentNetworkPolicy;
pub use executor_os::NetworkProxyExecutorOs;
pub use mitm_hook::InjectedHeaderConfig;
pub use mitm_hook::MitmHookActionsConfig;
pub use mitm_hook::MitmHookBodyConfig;
+1 -1
View File
@@ -677,7 +677,7 @@ mod tests {
let state = build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.unwrap();
let reloader = Arc::new(StaticReloader {
+3 -3
View File
@@ -1820,7 +1820,7 @@ mod tests {
let replacement = crate::state::build_config_state(
config.clone(),
Default::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)?;
proxy.replace_config_state(replacement).await?;
let expected_unix_sockets = if cfg!(target_os = "windows") {
@@ -2091,7 +2091,7 @@ mod tests {
..NetworkProxyConfig::default()
},
Default::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.expect("replacement config state");
proxy
@@ -2177,7 +2177,7 @@ mod tests {
let replacement = crate::state::build_config_state(
config.clone(),
Default::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)?;
proxy.replace_config_state(replacement).await?;
let prepared = proxy
@@ -7,8 +7,8 @@ use crate::NetworkMode;
use crate::NetworkProxy;
use crate::NetworkProxyAuditMetadata;
use crate::NetworkProxyConfig;
use crate::NetworkProxyExecutorOs;
use crate::NetworkProxyState;
use crate::Platform;
use std::sync::Arc;
#[test]
@@ -44,10 +44,10 @@ fn optional_socket_policy_preserves_input_and_resolves_at_remote_boundary() {
#[tokio::test]
async fn round_trip_preserves_supported_effective_settings() {
for (executor_os, socket) in [
(NetworkProxyExecutorOs::Linux, "/var/run/example.sock"),
(NetworkProxyExecutorOs::Macos, "/var/run/example.sock"),
(NetworkProxyExecutorOs::Windows, r"C:\example.sock"),
(NetworkProxyExecutorOs::Unknown, r"C:\example.sock"),
(Platform::Linux, "/var/run/example.sock"),
(Platform::Macos, "/var/run/example.sock"),
(Platform::Windows, r"C:\example.sock"),
(Platform::Unknown, r"C:\example.sock"),
] {
let mut config = NetworkProxyConfig {
enabled: true,
@@ -185,7 +185,7 @@ fn launch_config_materializes_audit_and_execution_attribution() {
execution_id: Some("execution-1".to_string()),
policy_decision_timeout_ms: None,
},
NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
Platform::native(),
)
.expect("remote launch state");
+15 -30
View File
@@ -169,7 +169,7 @@ fn blocked_request_violation_log_line(entry: &BlockedRequest) -> String {
#[derive(Clone)]
pub struct ConfigState {
/// Preserve the target when policy edits rebuild state on a controller.
pub(crate) executor_os: crate::NetworkProxyExecutorOs,
pub(crate) executor_os: crate::Platform,
pub config: NetworkProxyConfig,
pub(crate) brokerage_created_default_allowlist: bool,
pub allow_set: GlobSet,
@@ -290,7 +290,7 @@ impl NetworkProxyState {
/// The launching executor supplies its own OS; the wire policy cannot override it.
pub fn from_remote_launch_config(
launch: crate::RemoteNetworkProxyLaunchConfig,
executor_os: crate::NetworkProxyExecutorOs,
executor_os: crate::Platform,
) -> Result<Self> {
let crate::RemoteNetworkProxyLaunchConfig {
proxy,
@@ -584,7 +584,7 @@ impl NetworkProxyState {
pub(crate) async fn current_cfg_with_brokerage_provenance(
&self,
) -> Result<(NetworkProxyConfig, bool, crate::NetworkProxyExecutorOs)> {
) -> Result<(NetworkProxyConfig, bool, crate::Platform)> {
// Callers treat `NetworkProxyState` as a live view of policy. We reload-on-demand so edits to
// `config.toml` (including Codex-managed writes) take effect without a restart.
self.reload_if_needed().await?;
@@ -1188,7 +1188,7 @@ pub(crate) fn network_proxy_state_for_policy(
config.set_allowed_domains(vec!["*".to_string()]);
}
let state = ConfigState {
executor_os: crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
executor_os: crate::Platform::native(),
allow_set: crate::policy::compile_allowlist_globset(
&config.allowed_domains().unwrap_or_default(),
)
@@ -1296,7 +1296,7 @@ mod tests {
let initial_state = build_config_state(
config.clone(),
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.unwrap();
let mut reloaded_config = config;
@@ -1304,7 +1304,7 @@ mod tests {
let reloaded_state = build_config_state(
reloaded_config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.unwrap();
let state = NetworkProxyState::with_reloader(
@@ -1333,7 +1333,7 @@ mod tests {
enabled: Some(false),
..NetworkProxyConstraints::default()
},
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.expect("managed-disabled credential broker should fail open");
let state = NetworkProxyState::with_reloader(config_state, Arc::new(NoopReloader));
@@ -1384,7 +1384,7 @@ mod tests {
let config_state = build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.expect("valid credential-broker configuration");
assert_eq!(config_state.brokerage_created_default_allowlist, !enabled);
@@ -1472,12 +1472,7 @@ mod tests {
..NetworkProxyConstraints::default()
};
let state = NetworkProxyState::with_reloader(
build_config_state(
config,
constraints,
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
)
.unwrap(),
build_config_state(config, constraints, crate::Platform::native()).unwrap(),
Arc::new(NoopReloader),
);
@@ -1504,12 +1499,7 @@ mod tests {
..NetworkProxyConstraints::default()
};
let state = NetworkProxyState::with_reloader(
build_config_state(
config,
constraints,
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
)
.unwrap(),
build_config_state(config, constraints, crate::Platform::native()).unwrap(),
Arc::new(NoopReloader),
);
@@ -1534,12 +1524,7 @@ mod tests {
..NetworkProxyConstraints::default()
};
let state = NetworkProxyState::with_reloader(
build_config_state(
config,
constraints,
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
)
.unwrap(),
build_config_state(config, constraints, crate::Platform::native()).unwrap(),
Arc::new(NoopReloader),
);
@@ -2211,7 +2196,7 @@ mod tests {
build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS))
crate::Platform::native()
)
.is_ok()
);
@@ -2226,7 +2211,7 @@ mod tests {
build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS))
crate::Platform::native()
)
.is_ok()
);
@@ -2241,7 +2226,7 @@ mod tests {
build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS))
crate::Platform::native()
)
.is_err()
);
@@ -2256,7 +2241,7 @@ mod tests {
build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS))
crate::Platform::native()
)
.is_err()
);
+36
View File
@@ -0,0 +1,36 @@
//! Executor-specific absolute socket path validation, independent of the controller OS.
//! Socket support and native path normalization remain executor runtime concerns.
use codex_utils_path_uri::PathConvention;
use codex_utils_path_uri::Platform;
pub(crate) fn socket_path_is_absolute(platform: Platform, path: &str) -> bool {
// Core also accepts Unix-style absolute paths on Windows, for portability.
path.starts_with('/')
|| match platform.path_convention() {
Some(PathConvention::Posix) => false,
// Legacy executors without OS metadata validate against their own
// platform at launch; accept either absolute syntax here.
Some(PathConvention::Windows) | None => windows_path_is_absolute(path),
}
}
// Match std::path's Windows absolute-path syntax without consulting the host.
// Non-drive prefixes have an implicit root, including device and verbatim paths.
fn windows_path_is_absolute(path: &str) -> bool {
let bytes = path.as_bytes();
if matches!(bytes, [drive, b':', b'\\' | b'/', ..] if drive.is_ascii_alphabetic()) {
return true;
}
let [b'\\' | b'/', b'\\' | b'/', rest @ ..] = bytes else {
return false;
};
if path.starts_with(r"\\?\") || matches!(rest, [b'.', b'\\' | b'/', ..]) {
return true;
}
let mut components = rest.split(|byte| matches!(byte, b'\\' | b'/'));
matches!(
(components.next(), components.next()),
(Some(server), Some(share)) if !server.is_empty() && !share.is_empty()
)
}
+1 -1
View File
@@ -905,7 +905,7 @@ mod tests {
let state = build_config_state(
config,
NetworkProxyConstraints::default(),
crate::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
crate::Platform::native(),
)
.unwrap();
let reloader = Arc::new(StaticReloader {
+1 -1
View File
@@ -62,7 +62,7 @@ pub struct PartialNetworkProxyConfig {
pub fn build_config_state(
mut config: NetworkProxyConfig,
constraints: NetworkProxyConstraints,
executor_os: crate::NetworkProxyExecutorOs,
executor_os: crate::Platform,
) -> anyhow::Result<ConfigState> {
if constraints.enabled == Some(false) {
config.credential_broker = false;
@@ -305,7 +305,7 @@ async fn build_proxy(
let config_state = build_config_state(
config,
Default::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
codex_network_proxy::Platform::native(),
)?;
let reloader = Arc::new(StaticReloader(config_state.clone()));
let state = Arc::new(NetworkProxyState::with_reloader(config_state, reloader));
+1 -1
View File
@@ -541,7 +541,7 @@ async fn linux_unix_socket_grant_uses_effective_managed_policy() -> anyhow::Resu
..Default::default()
},
NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
codex_utils_path_uri::Platform::native(),
)?;
let network = NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
+2 -2
View File
@@ -819,7 +819,7 @@ async fn prepared_managed_network_context_takes_precedence_over_live_proxy_socke
let state = build_config_state(
network_config,
NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
codex_utils_path_uri::Platform::native(),
)?;
let network_proxy = NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
@@ -1531,7 +1531,7 @@ async fn create_seatbelt_args_merges_proxy_and_explicit_unix_socket_paths() -> a
let state = build_config_state(
network_config,
NetworkProxyConstraints::default(),
codex_network_proxy::NetworkProxyExecutorOs::from_platform_os(Some(std::env::consts::OS)),
codex_utils_path_uri::Platform::native(),
)?;
let network_proxy = NetworkProxy::builder()
.state(Arc::new(NetworkProxyState::with_reloader(
+2
View File
@@ -26,11 +26,13 @@ mod absolute_path_normalization;
mod api_path_string;
mod config_path;
mod native_path_bytes;
mod platform;
use absolute_path_normalization::path_uri_from_segments;
pub use api_path_string::LegacyAppPathString;
pub use api_path_string::LegacyAppPathStringError;
pub use platform::Platform;
pub const FILE_SCHEME: &str = "file";
const BAD_PATH_URI_PREFIX: &str = "file:///%00/bad/path/";
+51
View File
@@ -0,0 +1,51 @@
//! Platform identity and its path convention, independent of the resolving host.
use crate::PathConvention;
/// Operating system whose paths and execution configuration are being resolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Platform {
Linux,
Macos,
Windows,
/// Missing or unrecognized platform metadata carries no path convention.
Unknown,
}
impl Platform {
/// Read platform metadata without substituting the current host's platform.
pub fn from_platform_os(platform_os: Option<&str>) -> Self {
match platform_os {
Some("linux") => Self::Linux,
Some("macos") => Self::Macos,
Some("windows") => Self::Windows,
Some(_) | None => Self::Unknown,
}
}
/// Return the platform of the current process.
pub const fn native() -> Self {
if cfg!(target_os = "linux") {
Self::Linux
} else if cfg!(target_os = "macos") {
Self::Macos
} else if cfg!(target_os = "windows") {
Self::Windows
} else {
Self::Unknown
}
}
/// Derive path grammar from platform identity while preserving unknown metadata.
pub const fn path_convention(self) -> Option<PathConvention> {
match self {
Self::Linux | Self::Macos => Some(PathConvention::Posix),
Self::Windows => Some(PathConvention::Windows),
Self::Unknown => None,
}
}
}
#[cfg(test)]
#[path = "platform_tests.rs"]
mod tests;
@@ -0,0 +1,43 @@
//! Coverage for platform metadata and platform-derived path conventions.
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn platform_metadata_preserves_missing_and_unrecognized_values() {
for (metadata, expected) in [
(Some("linux"), Platform::Linux),
(Some("macos"), Platform::Macos),
(Some("windows"), Platform::Windows),
(None, Platform::Unknown),
(Some("freebsd"), Platform::Unknown),
(Some("Windows"), Platform::Unknown),
(Some(""), Platform::Unknown),
] {
assert_eq!(
Platform::from_platform_os(metadata),
expected,
"{metadata:?}"
);
}
}
#[test]
fn path_convention_is_derived_from_platform() {
for (platform, expected) in [
(Platform::Linux, Some(PathConvention::Posix)),
(Platform::Macos, Some(PathConvention::Posix)),
(Platform::Windows, Some(PathConvention::Windows)),
(Platform::Unknown, None),
] {
assert_eq!(platform.path_convention(), expected, "{platform:?}");
}
}
#[test]
fn native_platform_matches_current_process_metadata() {
assert_eq!(
Platform::native(),
Platform::from_platform_os(Some(std::env::consts::OS)),
);
}