diff --git a/codex-rs/core/src/sandbox_tags.rs b/codex-rs/core/src/sandbox_tags.rs index 29d520e2d1..7c453996f4 100644 --- a/codex-rs/core/src/sandbox_tags.rs +++ b/codex-rs/core/src/sandbox_tags.rs @@ -1,3 +1,7 @@ +//! Captures configuration-derived sandbox labels and writes them to diagnostics. +//! Labels never inspect the filesystem and must not be used for authorization. + +use crate::responses_metadata::CodexResponsesMetadata; use codex_protocol::config_types::WindowsSandboxLevel; use codex_protocol::models::PermissionProfile; use codex_sandboxing::SandboxType; @@ -5,7 +9,53 @@ use codex_sandboxing::get_platform_sandbox; use codex_sandboxing::policy_transforms::should_require_platform_sandbox; use std::path::Path; -pub(crate) fn permission_profile_sandbox_tag( +/// Diagnostic labels captured with a turn's permission configuration. +/// These labels must never be used to authorize filesystem access. +#[derive(Clone, Copy, Debug)] +pub(crate) struct SandboxTags { + sandbox: &'static str, + policy: &'static str, +} + +impl SandboxTags { + pub(crate) fn new( + profile: &PermissionProfile, + cwd: &Path, + windows_sandbox_level: WindowsSandboxLevel, + enforce_managed_network: bool, + ) -> Self { + Self { + sandbox: permission_profile_sandbox_tag( + profile, + windows_sandbox_level, + enforce_managed_network, + ), + policy: permission_profile_policy_tag(profile, cwd), + } + } + + /// Adds the captured labels to a tool's metric attributes. + pub(crate) fn append_metric_tags(&self, tags: &mut Vec<(&str, &str)>) { + tags.extend([("sandbox", self.sandbox), ("sandbox_policy", self.policy)]); + } + + /// Records the same captured labels in model and MCP request metadata. + pub(crate) fn record_metadata(&self, metadata: &mut CodexResponsesMetadata) { + metadata.sandbox = Some(self.sandbox.to_string()); + metadata.sandbox_mode = Some(self.policy.to_string()); + } +} + +/// Records policy metadata for detached requests without selecting a sandbox backend. +pub(crate) fn record_policy_metadata( + profile: &PermissionProfile, + cwd: &Path, + metadata: &mut CodexResponsesMetadata, +) { + metadata.sandbox_mode = Some(permission_profile_policy_tag(profile, cwd).to_string()); +} + +fn permission_profile_sandbox_tag( profile: &PermissionProfile, windows_sandbox_level: WindowsSandboxLevel, enforce_managed_network: bool, @@ -37,10 +87,7 @@ pub(crate) fn permission_profile_sandbox_tag( .unwrap_or("none") } -pub(crate) fn permission_profile_policy_tag( - profile: &PermissionProfile, - cwd: &Path, -) -> &'static str { +fn permission_profile_policy_tag(profile: &PermissionProfile, cwd: &Path) -> &'static str { match profile { PermissionProfile::Disabled => "danger-full-access", PermissionProfile::External { .. } => "external-sandbox", @@ -48,7 +95,7 @@ pub(crate) fn permission_profile_policy_tag( let file_system_policy = profile.file_system_sandbox_policy(); if file_system_policy.has_full_disk_write_access() { "danger-full-access" - } else if !file_system_policy.has_writable_roots_with_cwd(cwd) { + } else if !file_system_policy.has_configured_writable_roots_with_cwd(cwd) { "read-only" } else { "workspace-write" diff --git a/codex-rs/core/src/sandbox_tags_tests.rs b/codex-rs/core/src/sandbox_tags_tests.rs index b4feee5b2f..1a22a52eb5 100644 --- a/codex-rs/core/src/sandbox_tags_tests.rs +++ b/codex-rs/core/src/sandbox_tags_tests.rs @@ -8,6 +8,7 @@ use codex_protocol::permissions::FileSystemPath; use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSandboxKind; use codex_protocol::permissions::FileSystemSandboxPolicy; +use codex_protocol::permissions::FileSystemSpecialPath; use codex_protocol::permissions::NetworkSandboxPolicy; use codex_sandboxing::SandboxType; use codex_sandboxing::get_platform_sandbox; @@ -160,3 +161,48 @@ fn profile_policy_tag_reports_closest_legacy_mode() { "workspace-write" ); } + +#[test] +fn policy_labels_follow_configured_roots_and_deny_rules() { + let workspace = tempfile::tempdir().expect("workspace"); + let cwd = workspace.path().join("not-created"); + let denied_root = AbsolutePathBuf::from_absolute_path(&cwd).expect("absolute root"); + let project_root = FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::ProjectRoots { subpath: None }, + }, + FileSystemAccessMode::Write, + ); + let cases = [ + (vec![project_root.clone()], "workspace-write"), + ( + vec![ + project_root.clone(), + FileSystemSandboxEntry::new(denied_root.into(), FileSystemAccessMode::Deny), + ], + "read-only", + ), + ( + vec![ + project_root, + FileSystemSandboxEntry::new( + FileSystemPath::Special { + value: FileSystemSpecialPath::ProjectRoots { + subpath: Some("private".to_string()), + }, + }, + FileSystemAccessMode::Deny, + ), + ], + "workspace-write", + ), + ]; + + for (entries, expected) in cases { + let profile = PermissionProfile::from_runtime_permissions( + &FileSystemSandboxPolicy::restricted(entries), + NetworkSandboxPolicy::Restricted, + ); + assert_eq!(permission_profile_policy_tag(&profile, &cwd), expected); + } +} diff --git a/codex-rs/core/src/tools/registry.rs b/codex-rs/core/src/tools/registry.rs index 6564a22d1f..8e19ece6bc 100644 --- a/codex-rs/core/src/tools/registry.rs +++ b/codex-rs/core/src/tools/registry.rs @@ -11,8 +11,6 @@ use crate::hook_runtime::run_post_tool_use_hooks; use crate::hook_runtime::run_pre_tool_use_hooks; use crate::memory_usage::emit_metric_for_tool_read; use crate::memory_usage::shell_script_for_invocation; -use crate::sandbox_tags::permission_profile_policy_tag; -use crate::sandbox_tags::permission_profile_sandbox_tag; use crate::session::session::Session; use crate::session::turn_context::TurnContext; use crate::tools::context::FunctionToolOutput; @@ -498,27 +496,9 @@ impl ToolRegistry { let tool_name = invocation.tool_name.clone(); let call_id_owned = invocation.call_id.clone(); let otel = invocation.turn.session_telemetry.clone(); - let permission_profile = invocation.turn.permission_profile(); // TODO(anp): Reconcile these tags with TurnEnvironment::sandbox_context // instead of reporting the thread-wide backend for environment-scoped tools. - let base_tool_result_tags = [ - ( - "sandbox", - permission_profile_sandbox_tag( - &permission_profile, - invocation.turn.windows_sandbox_level, - invocation.turn.network.is_some(), - ), - ), - ( - "sandbox_policy", - permission_profile_policy_tag( - &permission_profile, - #[allow(deprecated)] - invocation.turn.cwd.as_path(), - ), - ), - ]; + let sandbox_tags = invocation.turn.turn_metadata_state.sandbox_tags; { let mut active = invocation.session.active_turn.lock().await; @@ -534,6 +514,8 @@ impl ToolRegistry { None => { let message = unsupported_tool_call_message(&invocation.payload, &tool_name); let log_payload = tool_log_payload(&invocation.payload, &invocation.source); + let mut tool_result_tags = Vec::with_capacity(2); + sandbox_tags.append_metric_tags(&mut tool_result_tags); otel.tool_result_with_tags( &tool_name, &call_id_owned, @@ -541,7 +523,7 @@ impl ToolRegistry { Duration::ZERO, /*success*/ false, &message, - &base_tool_result_tags, + &tool_result_tags, /*extra_trace_fields*/ &[], ); let err = FunctionCallError::RespondToModel(message); @@ -550,10 +532,9 @@ impl ToolRegistry { } }; let telemetry_tags = tool.telemetry_tags(&invocation); - let mut tool_result_tags = - Vec::with_capacity(base_tool_result_tags.len() + telemetry_tags.len() + 1); + let mut tool_result_tags = Vec::with_capacity(2 + telemetry_tags.len() + 1); let mut extra_trace_fields = Vec::new(); - tool_result_tags.extend_from_slice(&base_tool_result_tags); + sandbox_tags.append_metric_tags(&mut tool_result_tags); for (key, value) in &telemetry_tags { if matches!(*key, "mcp_server" | "mcp_server_origin") { extra_trace_fields.push((*key, value.as_str())); diff --git a/codex-rs/core/src/turn_metadata.rs b/codex-rs/core/src/turn_metadata.rs index 2f7b540d06..ec63cfa7d9 100644 --- a/codex-rs/core/src/turn_metadata.rs +++ b/codex-rs/core/src/turn_metadata.rs @@ -23,8 +23,8 @@ use crate::responses_metadata::TurnToolNamespacesInfo; use crate::responses_metadata::filter_extra_metadata; use crate::responses_metadata::subagent_header_value; use crate::responses_metadata::subagent_metadata_kind; -use crate::sandbox_tags::permission_profile_policy_tag; -use crate::sandbox_tags::permission_profile_sandbox_tag; +use crate::sandbox_tags::SandboxTags; +use crate::sandbox_tags::record_policy_metadata; use codex_git_utils::SanitizedGitUrl; use codex_git_utils::get_git_remote_urls_assume_git_repo; use codex_git_utils::get_git_repo_root; @@ -87,17 +87,16 @@ pub async fn detached_memory_responses_metadata( permission_profile: &PermissionProfile, sandbox: Option<&str>, ) -> CodexResponsesMetadata { - CodexResponsesMetadata { + let mut metadata = CodexResponsesMetadata { request_kind: Some(CodexResponsesRequestKind::Memory), thread_source: Some(ThreadSource::MemoryConsolidation), subagent_header: subagent_header_value(session_source), sandbox: sandbox.map(ToString::to_string), - sandbox_mode: Some( - permission_profile_policy_tag(permission_profile, cwd.as_path()).to_string(), - ), workspaces: memory_workspaces(cwd).await, ..CodexResponsesMetadata::new(installation_id, session_id, thread_id, window_id) - } + }; + record_policy_metadata(permission_profile, cwd.as_path(), &mut metadata); + metadata } #[derive(Debug)] @@ -119,8 +118,7 @@ pub(crate) struct TurnMetadataState { turn_id: String, // TODO(anp): Derive this cached tag from TurnEnvironment::sandbox_context // so metadata reflects the selected environment's backend. - sandbox: Option, - sandbox_mode: Option, + pub(crate) sandbox_tags: SandboxTags, auto_review_enabled: bool, node_repl_auto_review_required: bool, node_repl_disabled: bool, @@ -158,16 +156,12 @@ impl TurnMetadataState { model_info: &ModelInfo, ) -> Self { let repo_root = get_git_repo_root(&cwd); - let sandbox = Some( - permission_profile_sandbox_tag( - permission_profile, - windows_sandbox_level, - enforce_managed_network, - ) - .to_string(), + let sandbox_tags = SandboxTags::new( + permission_profile, + cwd.as_path(), + windows_sandbox_level, + enforce_managed_network, ); - let sandbox_mode = - Some(permission_profile_policy_tag(permission_profile, cwd.as_path()).to_string()); let agent_name = session_source .get_agent_path() .unwrap_or_else(AgentPath::root) @@ -188,8 +182,7 @@ impl TurnMetadataState { thread_source, turn_trigger: OnceLock::new(), turn_id, - sandbox, - sandbox_mode, + sandbox_tags, auto_review_enabled, node_repl_auto_review_required: model_info.node_repl_auto_review_required, node_repl_disabled: model_info.node_repl_disabled, @@ -388,7 +381,7 @@ impl TurnMetadataState { { extra.remove(key); } - CodexResponsesMetadata { + let mut metadata = CodexResponsesMetadata { turn_id: Some(self.turn_id.clone()), agent_name: Some(self.agent_name.clone()), forked_from_thread_id: self.forked_from_thread_id, @@ -399,8 +392,6 @@ impl TurnMetadataState { subagent_kind: self.subagent_kind.clone(), thread_source: self.thread_source.clone(), turn_trigger: self.turn_trigger.get().cloned(), - sandbox: self.sandbox.clone(), - sandbox_mode: self.sandbox_mode.clone(), auto_review_enabled: Some(self.auto_review_enabled), node_repl_auto_review_required: Some(self.node_repl_auto_review_required), node_repl_disabled: Some(self.node_repl_disabled), @@ -418,7 +409,9 @@ impl TurnMetadataState { self.thread_id.clone(), String::new(), ) - } + }; + self.sandbox_tags.record_metadata(&mut metadata); + metadata } fn current_workspaces(&self) -> BTreeMap { diff --git a/codex-rs/core/src/turn_metadata_tests.rs b/codex-rs/core/src/turn_metadata_tests.rs index 132bd644be..82137c25b6 100644 --- a/codex-rs/core/src/turn_metadata_tests.rs +++ b/codex-rs/core/src/turn_metadata_tests.rs @@ -20,7 +20,6 @@ use crate::responses_metadata::TurnToolSource; use crate::responses_metadata::WINDOW_ID_KEY; use crate::responses_metadata::WINDOW_NUMBER_KEY; use crate::responses_metadata::validate_extra_metadata; -use crate::sandbox_tags::permission_profile_sandbox_tag; use codex_analytics::CompactionImplementation; use codex_analytics::CompactionPhase; use codex_analytics::CompactionReason; @@ -32,6 +31,8 @@ use codex_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig; use codex_protocol::protocol::SessionSource; use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::ThreadSource; +use codex_sandboxing::SandboxType; +use codex_sandboxing::get_platform_sandbox; use codex_utils_absolute_path::AbsolutePathBuf; use core_test_support::PathBufExt; use core_test_support::PathExt; @@ -249,11 +250,9 @@ fn turn_metadata_state_includes_sandbox_metadata() { let thread_id = json.get("thread_id").and_then(Value::as_str); assert!(json.get("request_kind").is_none()); - let expected_sandbox = permission_profile_sandbox_tag( - &permission_profile, - WindowsSandboxLevel::Disabled, - /*enforce_managed_network*/ false, - ); + let expected_sandbox = get_platform_sandbox(/*windows_sandbox_enabled*/ false) + .map(SandboxType::as_metric_tag) + .unwrap_or("none"); assert_eq!(sandbox_name, Some(expected_sandbox)); assert_eq!(sandbox_mode, Some("read-only")); assert_eq!(auto_review_enabled, Some(true)); diff --git a/codex-rs/protocol/src/permissions.rs b/codex-rs/protocol/src/permissions.rs index dcdae60f28..7327a5177d 100644 --- a/codex-rs/protocol/src/permissions.rs +++ b/codex-rs/protocol/src/permissions.rs @@ -1447,6 +1447,21 @@ impl FileSystemSandboxPolicy { }) } + /// Reports configured writable roots for diagnostics without inspecting the filesystem. + /// + /// Unlike runtime root resolution, this includes configured roots even if they + /// do not currently exist (including `/tmp`). Do not use this result to authorize + /// filesystem access or replace the resolution needed for sandbox enforcement. + pub fn has_configured_writable_roots_with_cwd(&self, cwd: &Path) -> bool { + !self.has_full_disk_write_access() + && with_local_policy_context(cwd, cwd, |_, context| { + self.resolved_entries(context) + .into_iter() + .any(|(path, access)| access.can_write() && self.can_write_path(&path, context)) + }) + .unwrap_or(false) + } + /// Returns writable roots without following attacker-mutable path components. /// /// Trusted top-level aliases such as `/tmp -> /private/tmp` are still @@ -2521,6 +2536,10 @@ mod tests { policy.has_writable_roots_with_cwd(cwd.path()), !policy.get_writable_roots_with_cwd(cwd.path()).is_empty() ); + assert_eq!( + policy.has_configured_writable_roots_with_cwd(cwd.path()), + !policy.get_writable_roots_with_cwd(cwd.path()).is_empty() + ); } }