Report configured sandbox policy consistently (#41933)

## Why

Sandbox diagnostics could report `read-only` when a configured writable root did not yet exist, because policy labeling used filesystem-aware runtime root resolution.

## What changed

- Derive diagnostic policy labels from configured writable roots without inspecting the filesystem. Runtime sandbox authorization continues to use filesystem-aware resolution.
- Capture sandbox labels once per turn and reuse them for response metadata and tool-result metrics.

## Testing

Add coverage for missing project roots, denied roots, and deny rules on project subpaths.

GitOrigin-RevId: ccbdb8c32a1f44bfa63ae4d2ae1f9cc408e66b9c
This commit is contained in:
Charlie Marsh authored and copyberry committed 2026-08-31 23:29:20 +00:00
1 parent 4ac20a7f74
commit a62ff9a5d4
6 files changed
+146 -61

No files matched your search

+53 -6
View File
@@ -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::config_types::WindowsSandboxLevel;
use codex_protocol::models::PermissionProfile; use codex_protocol::models::PermissionProfile;
use codex_sandboxing::SandboxType; use codex_sandboxing::SandboxType;
@@ -5,7 +9,53 @@ use codex_sandboxing::get_platform_sandbox;
use codex_sandboxing::policy_transforms::should_require_platform_sandbox; use codex_sandboxing::policy_transforms::should_require_platform_sandbox;
use std::path::Path; 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, profile: &PermissionProfile,
windows_sandbox_level: WindowsSandboxLevel, windows_sandbox_level: WindowsSandboxLevel,
enforce_managed_network: bool, enforce_managed_network: bool,
@@ -37,10 +87,7 @@ pub(crate) fn permission_profile_sandbox_tag(
.unwrap_or("none") .unwrap_or("none")
} }
pub(crate) fn permission_profile_policy_tag( fn permission_profile_policy_tag(profile: &PermissionProfile, cwd: &Path) -> &'static str {
profile: &PermissionProfile,
cwd: &Path,
) -> &'static str {
match profile { match profile {
PermissionProfile::Disabled => "danger-full-access", PermissionProfile::Disabled => "danger-full-access",
PermissionProfile::External { .. } => "external-sandbox", PermissionProfile::External { .. } => "external-sandbox",
@@ -48,7 +95,7 @@ pub(crate) fn permission_profile_policy_tag(
let file_system_policy = profile.file_system_sandbox_policy(); let file_system_policy = profile.file_system_sandbox_policy();
if file_system_policy.has_full_disk_write_access() { if file_system_policy.has_full_disk_write_access() {
"danger-full-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" "read-only"
} else { } else {
"workspace-write" "workspace-write"
+46
View File
@@ -8,6 +8,7 @@ use codex_protocol::permissions::FileSystemPath;
use codex_protocol::permissions::FileSystemSandboxEntry; use codex_protocol::permissions::FileSystemSandboxEntry;
use codex_protocol::permissions::FileSystemSandboxKind; use codex_protocol::permissions::FileSystemSandboxKind;
use codex_protocol::permissions::FileSystemSandboxPolicy; use codex_protocol::permissions::FileSystemSandboxPolicy;
use codex_protocol::permissions::FileSystemSpecialPath;
use codex_protocol::permissions::NetworkSandboxPolicy; use codex_protocol::permissions::NetworkSandboxPolicy;
use codex_sandboxing::SandboxType; use codex_sandboxing::SandboxType;
use codex_sandboxing::get_platform_sandbox; use codex_sandboxing::get_platform_sandbox;
@@ -160,3 +161,48 @@ fn profile_policy_tag_reports_closest_legacy_mode() {
"workspace-write" "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);
}
}
+6 -25
View File
@@ -11,8 +11,6 @@ use crate::hook_runtime::run_post_tool_use_hooks;
use crate::hook_runtime::run_pre_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::emit_metric_for_tool_read;
use crate::memory_usage::shell_script_for_invocation; 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::session::Session;
use crate::session::turn_context::TurnContext; use crate::session::turn_context::TurnContext;
use crate::tools::context::FunctionToolOutput; use crate::tools::context::FunctionToolOutput;
@@ -498,27 +496,9 @@ impl ToolRegistry {
let tool_name = invocation.tool_name.clone(); let tool_name = invocation.tool_name.clone();
let call_id_owned = invocation.call_id.clone(); let call_id_owned = invocation.call_id.clone();
let otel = invocation.turn.session_telemetry.clone(); let otel = invocation.turn.session_telemetry.clone();
let permission_profile = invocation.turn.permission_profile();
// TODO(anp): Reconcile these tags with TurnEnvironment::sandbox_context // TODO(anp): Reconcile these tags with TurnEnvironment::sandbox_context
// instead of reporting the thread-wide backend for environment-scoped tools. // instead of reporting the thread-wide backend for environment-scoped tools.
let base_tool_result_tags = [ let sandbox_tags = invocation.turn.turn_metadata_state.sandbox_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 mut active = invocation.session.active_turn.lock().await; let mut active = invocation.session.active_turn.lock().await;
@@ -534,6 +514,8 @@ impl ToolRegistry {
None => { None => {
let message = unsupported_tool_call_message(&invocation.payload, &tool_name); let message = unsupported_tool_call_message(&invocation.payload, &tool_name);
let log_payload = tool_log_payload(&invocation.payload, &invocation.source); 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( otel.tool_result_with_tags(
&tool_name, &tool_name,
&call_id_owned, &call_id_owned,
@@ -541,7 +523,7 @@ impl ToolRegistry {
Duration::ZERO, Duration::ZERO,
/*success*/ false, /*success*/ false,
&message, &message,
&base_tool_result_tags, &tool_result_tags,
/*extra_trace_fields*/ &[], /*extra_trace_fields*/ &[],
); );
let err = FunctionCallError::RespondToModel(message); let err = FunctionCallError::RespondToModel(message);
@@ -550,10 +532,9 @@ impl ToolRegistry {
} }
}; };
let telemetry_tags = tool.telemetry_tags(&invocation); let telemetry_tags = tool.telemetry_tags(&invocation);
let mut tool_result_tags = let mut tool_result_tags = Vec::with_capacity(2 + telemetry_tags.len() + 1);
Vec::with_capacity(base_tool_result_tags.len() + telemetry_tags.len() + 1);
let mut extra_trace_fields = Vec::new(); 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 { for (key, value) in &telemetry_tags {
if matches!(*key, "mcp_server" | "mcp_server_origin") { if matches!(*key, "mcp_server" | "mcp_server_origin") {
extra_trace_fields.push((*key, value.as_str())); extra_trace_fields.push((*key, value.as_str()));
+17 -24
View File
@@ -23,8 +23,8 @@ use crate::responses_metadata::TurnToolNamespacesInfo;
use crate::responses_metadata::filter_extra_metadata; use crate::responses_metadata::filter_extra_metadata;
use crate::responses_metadata::subagent_header_value; use crate::responses_metadata::subagent_header_value;
use crate::responses_metadata::subagent_metadata_kind; use crate::responses_metadata::subagent_metadata_kind;
use crate::sandbox_tags::permission_profile_policy_tag; use crate::sandbox_tags::SandboxTags;
use crate::sandbox_tags::permission_profile_sandbox_tag; use crate::sandbox_tags::record_policy_metadata;
use codex_git_utils::SanitizedGitUrl; use codex_git_utils::SanitizedGitUrl;
use codex_git_utils::get_git_remote_urls_assume_git_repo; use codex_git_utils::get_git_remote_urls_assume_git_repo;
use codex_git_utils::get_git_repo_root; use codex_git_utils::get_git_repo_root;
@@ -87,17 +87,16 @@ pub async fn detached_memory_responses_metadata(
permission_profile: &PermissionProfile, permission_profile: &PermissionProfile,
sandbox: Option<&str>, sandbox: Option<&str>,
) -> CodexResponsesMetadata { ) -> CodexResponsesMetadata {
CodexResponsesMetadata { let mut metadata = CodexResponsesMetadata {
request_kind: Some(CodexResponsesRequestKind::Memory), request_kind: Some(CodexResponsesRequestKind::Memory),
thread_source: Some(ThreadSource::MemoryConsolidation), thread_source: Some(ThreadSource::MemoryConsolidation),
subagent_header: subagent_header_value(session_source), subagent_header: subagent_header_value(session_source),
sandbox: sandbox.map(ToString::to_string), 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, workspaces: memory_workspaces(cwd).await,
..CodexResponsesMetadata::new(installation_id, session_id, thread_id, window_id) ..CodexResponsesMetadata::new(installation_id, session_id, thread_id, window_id)
} };
record_policy_metadata(permission_profile, cwd.as_path(), &mut metadata);
metadata
} }
#[derive(Debug)] #[derive(Debug)]
@@ -119,8 +118,7 @@ pub(crate) struct TurnMetadataState {
turn_id: String, turn_id: String,
// TODO(anp): Derive this cached tag from TurnEnvironment::sandbox_context // TODO(anp): Derive this cached tag from TurnEnvironment::sandbox_context
// so metadata reflects the selected environment's backend. // so metadata reflects the selected environment's backend.
sandbox: Option<String>, pub(crate) sandbox_tags: SandboxTags,
sandbox_mode: Option<String>,
auto_review_enabled: bool, auto_review_enabled: bool,
node_repl_auto_review_required: bool, node_repl_auto_review_required: bool,
node_repl_disabled: bool, node_repl_disabled: bool,
@@ -158,16 +156,12 @@ impl TurnMetadataState {
model_info: &ModelInfo, model_info: &ModelInfo,
) -> Self { ) -> Self {
let repo_root = get_git_repo_root(&cwd); let repo_root = get_git_repo_root(&cwd);
let sandbox = Some( let sandbox_tags = SandboxTags::new(
permission_profile_sandbox_tag( permission_profile,
permission_profile, cwd.as_path(),
windows_sandbox_level, windows_sandbox_level,
enforce_managed_network, enforce_managed_network,
)
.to_string(),
); );
let sandbox_mode =
Some(permission_profile_policy_tag(permission_profile, cwd.as_path()).to_string());
let agent_name = session_source let agent_name = session_source
.get_agent_path() .get_agent_path()
.unwrap_or_else(AgentPath::root) .unwrap_or_else(AgentPath::root)
@@ -188,8 +182,7 @@ impl TurnMetadataState {
thread_source, thread_source,
turn_trigger: OnceLock::new(), turn_trigger: OnceLock::new(),
turn_id, turn_id,
sandbox, sandbox_tags,
sandbox_mode,
auto_review_enabled, auto_review_enabled,
node_repl_auto_review_required: model_info.node_repl_auto_review_required, node_repl_auto_review_required: model_info.node_repl_auto_review_required,
node_repl_disabled: model_info.node_repl_disabled, node_repl_disabled: model_info.node_repl_disabled,
@@ -388,7 +381,7 @@ impl TurnMetadataState {
{ {
extra.remove(key); extra.remove(key);
} }
CodexResponsesMetadata { let mut metadata = CodexResponsesMetadata {
turn_id: Some(self.turn_id.clone()), turn_id: Some(self.turn_id.clone()),
agent_name: Some(self.agent_name.clone()), agent_name: Some(self.agent_name.clone()),
forked_from_thread_id: self.forked_from_thread_id, forked_from_thread_id: self.forked_from_thread_id,
@@ -399,8 +392,6 @@ impl TurnMetadataState {
subagent_kind: self.subagent_kind.clone(), subagent_kind: self.subagent_kind.clone(),
thread_source: self.thread_source.clone(), thread_source: self.thread_source.clone(),
turn_trigger: self.turn_trigger.get().cloned(), 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), auto_review_enabled: Some(self.auto_review_enabled),
node_repl_auto_review_required: Some(self.node_repl_auto_review_required), node_repl_auto_review_required: Some(self.node_repl_auto_review_required),
node_repl_disabled: Some(self.node_repl_disabled), node_repl_disabled: Some(self.node_repl_disabled),
@@ -418,7 +409,9 @@ impl TurnMetadataState {
self.thread_id.clone(), self.thread_id.clone(),
String::new(), String::new(),
) )
} };
self.sandbox_tags.record_metadata(&mut metadata);
metadata
} }
fn current_workspaces(&self) -> BTreeMap<String, TurnMetadataWorkspace> { fn current_workspaces(&self) -> BTreeMap<String, TurnMetadataWorkspace> {
+5 -6
View File
@@ -20,7 +20,6 @@ use crate::responses_metadata::TurnToolSource;
use crate::responses_metadata::WINDOW_ID_KEY; use crate::responses_metadata::WINDOW_ID_KEY;
use crate::responses_metadata::WINDOW_NUMBER_KEY; use crate::responses_metadata::WINDOW_NUMBER_KEY;
use crate::responses_metadata::validate_extra_metadata; use crate::responses_metadata::validate_extra_metadata;
use crate::sandbox_tags::permission_profile_sandbox_tag;
use codex_analytics::CompactionImplementation; use codex_analytics::CompactionImplementation;
use codex_analytics::CompactionPhase; use codex_analytics::CompactionPhase;
use codex_analytics::CompactionReason; 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::SessionSource;
use codex_protocol::protocol::SubAgentSource; use codex_protocol::protocol::SubAgentSource;
use codex_protocol::protocol::ThreadSource; use codex_protocol::protocol::ThreadSource;
use codex_sandboxing::SandboxType;
use codex_sandboxing::get_platform_sandbox;
use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_absolute_path::AbsolutePathBuf;
use core_test_support::PathBufExt; use core_test_support::PathBufExt;
use core_test_support::PathExt; 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); let thread_id = json.get("thread_id").and_then(Value::as_str);
assert!(json.get("request_kind").is_none()); assert!(json.get("request_kind").is_none());
let expected_sandbox = permission_profile_sandbox_tag( let expected_sandbox = get_platform_sandbox(/*windows_sandbox_enabled*/ false)
&permission_profile, .map(SandboxType::as_metric_tag)
WindowsSandboxLevel::Disabled, .unwrap_or("none");
/*enforce_managed_network*/ false,
);
assert_eq!(sandbox_name, Some(expected_sandbox)); assert_eq!(sandbox_name, Some(expected_sandbox));
assert_eq!(sandbox_mode, Some("read-only")); assert_eq!(sandbox_mode, Some("read-only"));
assert_eq!(auto_review_enabled, Some(true)); assert_eq!(auto_review_enabled, Some(true));
+19
View File
@@ -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. /// Returns writable roots without following attacker-mutable path components.
/// ///
/// Trusted top-level aliases such as `/tmp -> /private/tmp` are still /// 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.has_writable_roots_with_cwd(cwd.path()),
!policy.get_writable_roots_with_cwd(cwd.path()).is_empty() !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()
);
} }
} }