fix(core): harden runtime workspace updates

This commit is contained in:
Felipe Coury
2026-06-12 00:18:43 -07:00
parent cb72ac4e89
commit 4ad972321e
22 changed files with 428 additions and 10 deletions
@@ -279,6 +279,35 @@
}
},
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
}
},
"properties": {
@@ -314,6 +343,16 @@
},
"turnId": {
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -1754,6 +1754,16 @@
],
"title": "RequestPermissionsGuardianApprovalReviewActionType",
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -5380,6 +5390,35 @@
"samplePaths"
],
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
}
},
"description": "Notification sent from the server to the client.",
@@ -1619,6 +1619,16 @@
},
"turnId": {
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -1759,6 +1769,35 @@
"question"
],
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
}
},
"description": "Request initiated from the server and sent to the client.",
@@ -3859,6 +3859,16 @@
},
"turnId": {
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/v2/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -10084,6 +10094,16 @@
],
"title": "RequestPermissionsGuardianApprovalReviewActionType",
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/v2/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -19707,6 +19727,35 @@
"title": "WindowsWorldWritableWarningNotification",
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/v2/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/v2/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/v2/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
},
"WriteStatus": {
"enum": [
"ok",
@@ -6508,6 +6508,16 @@
],
"title": "RequestPermissionsGuardianApprovalReviewActionType",
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -17515,6 +17525,35 @@
"title": "WindowsWorldWritableWarningNotification",
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
},
"WriteStatus": {
"enum": [
"ok",
@@ -484,6 +484,16 @@
],
"title": "RequestPermissionsGuardianApprovalReviewActionType",
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -567,6 +577,35 @@
}
},
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
}
},
"description": "[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.",
@@ -477,6 +477,16 @@
],
"title": "RequestPermissionsGuardianApprovalReviewActionType",
"type": "string"
},
"workspaceMutation": {
"anyOf": [
{
"$ref": "#/definitions/WorkspaceMutationApprovalRequest"
},
{
"type": "null"
}
]
}
},
"required": [
@@ -560,6 +570,35 @@
}
},
"type": "object"
},
"WorkspaceMutationApprovalRequest": {
"properties": {
"operation": {
"$ref": "#/definitions/WorkspaceMutationOperation"
},
"resultingWorkspaceRoots": {
"items": {
"$ref": "#/definitions/AbsolutePathBuf"
},
"type": "array"
},
"target": {
"$ref": "#/definitions/AbsolutePathBuf"
}
},
"required": [
"operation",
"resultingWorkspaceRoots",
"target"
],
"type": "object"
},
"WorkspaceMutationOperation": {
"enum": [
"setWorkingDirectory",
"addWorkspaceRoot"
],
"type": "string"
}
},
"description": "[UNSTABLE] Temporary notification payload for approval auto-review. This shape is expected to change soon.",
@@ -5,5 +5,6 @@ import type { AbsolutePathBuf } from "../AbsolutePathBuf";
import type { GuardianCommandSource } from "./GuardianCommandSource";
import type { NetworkApprovalProtocol } from "./NetworkApprovalProtocol";
import type { RequestPermissionProfile } from "./RequestPermissionProfile";
import type { WorkspaceMutationApprovalRequest } from "./WorkspaceMutationApprovalRequest";
export type GuardianApprovalReviewAction = { "type": "command", source: GuardianCommandSource, command: string, cwd: AbsolutePathBuf, } | { "type": "execve", source: GuardianCommandSource, program: string, argv: Array<string>, cwd: AbsolutePathBuf, } | { "type": "applyPatch", cwd: AbsolutePathBuf, files: Array<AbsolutePathBuf>, } | { "type": "networkAccess", target: string, host: string, protocol: NetworkApprovalProtocol, port: number, } | { "type": "mcpToolCall", server: string, toolName: string, connectorId: string | null, connectorName: string | null, toolTitle: string | null, } | { "type": "requestPermissions", reason: string | null, permissions: RequestPermissionProfile, };
export type GuardianApprovalReviewAction = { "type": "command", source: GuardianCommandSource, command: string, cwd: AbsolutePathBuf, } | { "type": "execve", source: GuardianCommandSource, program: string, argv: Array<string>, cwd: AbsolutePathBuf, } | { "type": "applyPatch", cwd: AbsolutePathBuf, files: Array<AbsolutePathBuf>, } | { "type": "networkAccess", target: string, host: string, protocol: NetworkApprovalProtocol, port: number, } | { "type": "mcpToolCall", server: string, toolName: string, connectorId: string | null, connectorName: string | null, toolTitle: string | null, } | { "type": "requestPermissions", reason: string | null, permissions: RequestPermissionProfile, workspaceMutation: WorkspaceMutationApprovalRequest | null, };
@@ -3,9 +3,10 @@
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
import type { RequestPermissionProfile } from "./RequestPermissionProfile";
import type { WorkspaceMutationApprovalRequest } from "./WorkspaceMutationApprovalRequest";
export type PermissionsRequestApprovalParams = { threadId: string, turnId: string, itemId: string, environmentId: string | null,
/**
* Unix timestamp (in milliseconds) when this approval request started.
*/
startedAtMs: number, cwd: AbsolutePathBuf, reason: string | null, permissions: RequestPermissionProfile, };
startedAtMs: number, cwd: AbsolutePathBuf, reason: string | null, permissions: RequestPermissionProfile, workspaceMutation: WorkspaceMutationApprovalRequest | null, };
@@ -0,0 +1,7 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
import type { AbsolutePathBuf } from "../AbsolutePathBuf";
import type { WorkspaceMutationOperation } from "./WorkspaceMutationOperation";
export type WorkspaceMutationApprovalRequest = { operation: WorkspaceMutationOperation, target: AbsolutePathBuf, resultingWorkspaceRoots: Array<AbsolutePathBuf>, };
@@ -0,0 +1,5 @@
// GENERATED CODE! DO NOT MODIFY BY HAND!
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
export type WorkspaceMutationOperation = "setWorkingDirectory" | "addWorkspaceRoot";
@@ -479,4 +479,6 @@ export type { WindowsSandboxSetupMode } from "./WindowsSandboxSetupMode";
export type { WindowsSandboxSetupStartParams } from "./WindowsSandboxSetupStartParams";
export type { WindowsSandboxSetupStartResponse } from "./WindowsSandboxSetupStartResponse";
export type { WindowsWorldWritableWarningNotification } from "./WindowsWorldWritableWarningNotification";
export type { WorkspaceMutationApprovalRequest } from "./WorkspaceMutationApprovalRequest";
export type { WorkspaceMutationOperation } from "./WorkspaceMutationOperation";
export type { WriteStatus } from "./WriteStatus";
+9
View File
@@ -2403,6 +2403,7 @@ impl Session {
tx_response,
requested_permissions: requested_permissions.clone(),
environment: environment.clone(),
workspace_mutation: workspace_mutation.is_some(),
},
)
}
@@ -2565,6 +2566,14 @@ impl Session {
};
match entry {
Some(entry) => {
let response = if entry.workspace_mutation {
RequestPermissionsResponse {
scope: PermissionGrantScope::Session,
..response
}
} else {
response
};
let response = Self::normalize_request_permissions_response(
entry.requested_permissions,
response,
@@ -293,7 +293,7 @@ pub(crate) fn runtime_workspace_baseline_from_initial_history(
reconstruct_rollout_metadata(rollout_items).reference_context_item?;
Some(RuntimeWorkspaceBaseline {
cwd: AbsolutePathBuf::try_from(reference_context_item.cwd).ok()?,
workspace_roots: reference_context_item.workspace_roots?,
workspace_roots: reference_context_item.workspace_roots.unwrap_or_default(),
})
}
+74
View File
@@ -5881,6 +5881,80 @@ async fn request_permissions_response_materializes_session_cwd_grants_before_rec
);
}
#[tokio::test]
async fn workspace_mutation_permission_response_forces_session_scope() {
let (session, turn_context, rx) = make_session_and_context_with_rx().await;
*session.active_turn.lock().await = Some(ActiveTurn::default());
let session = Arc::new(session);
let turn_context = Arc::new(turn_context);
#[allow(deprecated)]
let cwd = turn_context.cwd.clone();
let requested_permissions = RequestPermissionProfile {
file_system: Some(FileSystemPermissions::from_read_write_roots(
/*read*/ None,
Some(vec![cwd.clone()]),
)),
..Default::default()
};
let handle = tokio::spawn({
let session = Arc::clone(&session);
let turn_context = Arc::clone(&turn_context);
let cwd = cwd.clone();
let requested_permissions = requested_permissions.clone();
async move {
session
.request_workspace_permissions_for_cwd(
&turn_context,
"workspace-mutation".to_string(),
codex_protocol::request_permissions::RequestPermissionsArgs {
reason: Some("persist workspace mutation".to_string()),
permissions: requested_permissions,
},
cwd.clone(),
codex_protocol::request_permissions::WorkspaceMutationApprovalRequest {
operation:
codex_protocol::request_permissions::WorkspaceMutationOperation::SetWorkingDirectory,
target: cwd.clone(),
resulting_workspace_roots: vec![cwd],
},
CancellationToken::new(),
)
.await
}
});
let request_event = tokio::time::timeout(StdDuration::from_secs(1), rx.recv())
.await
.expect("request_permissions event timed out")
.expect("request_permissions event missing");
let EventMsg::RequestPermissions(request) = request_event.msg else {
panic!("expected request_permissions event");
};
session
.notify_request_permissions_response(
&request.call_id,
codex_protocol::request_permissions::RequestPermissionsResponse {
permissions: request.permissions,
scope: PermissionGrantScope::Turn,
strict_auto_review: false,
},
)
.await;
let response = tokio::time::timeout(StdDuration::from_secs(1), handle)
.await
.expect("workspace mutation request timed out")
.expect("workspace mutation request join error")
.expect("workspace mutation response");
assert_eq!(response.scope, PermissionGrantScope::Session);
assert_eq!(
session.granted_session_permissions().await,
Some(requested_permissions.into())
);
assert_eq!(session.granted_turn_permissions().await, None);
}
#[tokio::test]
async fn request_permissions_is_auto_denied_when_granular_policy_blocks_tool_requests() {
let (session, mut turn_context, rx) = make_session_and_context_with_rx().await;
+1
View File
@@ -103,6 +103,7 @@ pub(crate) struct PendingRequestPermissions {
pub(crate) tx_response: oneshot::Sender<RequestPermissionsResponse>,
pub(crate) requested_permissions: RequestPermissionProfile,
pub(crate) environment: TurnEnvironmentSelection,
pub(crate) workspace_mutation: bool,
}
impl TurnState {
+24
View File
@@ -205,6 +205,30 @@ async fn hydrate_runtime_workspace_from_history_restores_persisted_baseline() {
assert_eq!(config.permissions.workspace_roots(), persisted_roots);
}
#[tokio::test]
async fn hydrate_runtime_workspace_from_history_restores_cwd_with_empty_roots() {
let (_session, turn_context) = make_session_and_context().await;
let persisted_cwd = PathBuf::from("/workspace/updated").abs();
let mut context_item = turn_context.to_turn_context_item();
context_item.cwd = persisted_cwd.to_path_buf();
context_item.workspace_roots = None;
let history = InitialHistory::Forked(vec![
RolloutItem::ResponseItem(user_msg("mutate workspace")),
RolloutItem::TurnContext(context_item),
]);
let mut config = test_config().await;
hydrate_runtime_workspace_from_history(
&mut config,
&history,
RuntimeWorkspaceReplayOverrides::default(),
);
assert_eq!(config.cwd, persisted_cwd);
assert_eq!(config.workspace_roots, Vec::new());
assert_eq!(config.permissions.workspace_roots(), Vec::new());
}
#[tokio::test]
async fn hydrate_runtime_workspace_from_history_preserves_explicit_replacements() {
let (_session, turn_context) = make_session_and_context().await;
@@ -283,7 +283,12 @@ impl ExecCommandHandler {
yield_time_ms,
max_output_tokens,
cwd,
sandbox_cwd: turn_environment.cwd.clone(),
sandbox_cwd: if turn.environments.turn_environments.len() == 1 {
runtime_workspace.cwd
} else {
turn_environment.cwd.clone()
},
permission_profile: runtime_workspace.permission_profile,
environment,
shell_mode,
network: context.turn.network.clone(),
+8 -5
View File
@@ -148,7 +148,10 @@ impl ToolOrchestrator {
// 1) Approval
let mut already_approved = false;
let file_system_sandbox_policy = turn_ctx.file_system_sandbox_policy();
let runtime_workspace = turn_ctx.runtime_workspace.snapshot().await;
let file_system_sandbox_policy = runtime_workspace
.permission_profile
.file_system_sandbox_policy();
let network_sandbox_policy = turn_ctx.network_sandbox_policy();
let requirement = tool.exec_approval_requirement(req).unwrap_or_else(|| {
default_exec_approval_requirement(approval_policy, &file_system_sandbox_policy)
@@ -238,11 +241,11 @@ impl ToolOrchestrator {
// Platform-specific flag gating is handled by SandboxManager::select_initial.
let use_legacy_landlock = turn_ctx.features.use_legacy_landlock();
#[allow(deprecated)]
let sandbox_cwd = tool.sandbox_cwd(req).unwrap_or(&turn_ctx.cwd);
let workspace_roots = turn_ctx.config.effective_workspace_roots();
let sandbox_cwd = tool.sandbox_cwd(req).unwrap_or(&runtime_workspace.cwd);
let workspace_roots = runtime_workspace.workspace_roots;
let initial_attempt = SandboxAttempt {
sandbox: initial_sandbox,
permissions: &turn_ctx.permission_profile,
permissions: &runtime_workspace.permission_profile,
enforce_managed_network: managed_network_active,
manager: &self.sandbox,
sandbox_cwd,
@@ -415,7 +418,7 @@ impl ToolOrchestrator {
};
let retry_attempt = SandboxAttempt {
sandbox: retry_sandbox,
permissions: &turn_ctx.permission_profile,
permissions: &runtime_workspace.permission_profile,
enforce_managed_network: managed_network_active,
manager: &self.sandbox,
sandbox_cwd,
+2
View File
@@ -30,6 +30,7 @@ use std::sync::Weak;
use codex_exec_server::Environment;
use codex_network_proxy::NetworkProxy;
use codex_protocol::models::AdditionalPermissionProfile;
use codex_protocol::models::PermissionProfile;
use codex_tools::UnifiedExecShellMode;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_output_truncation::TruncationPolicy;
@@ -97,6 +98,7 @@ pub(crate) struct ExecCommandRequest {
pub max_output_tokens: Option<usize>,
pub cwd: AbsolutePathBuf,
pub sandbox_cwd: AbsolutePathBuf,
pub permission_profile: PermissionProfile,
pub environment: Arc<Environment>,
pub shell_mode: UnifiedExecShellMode,
pub network: Option<NetworkProxy>,
@@ -1050,7 +1050,7 @@ impl UnifiedExecProcessManager {
.create_exec_approval_requirement_for_command(ExecApprovalRequest {
command: &request.command,
approval_policy: context.turn.approval_policy.value(),
permission_profile: context.turn.permission_profile(),
permission_profile: request.permission_profile.clone(),
windows_sandbox_level: context.turn.windows_sandbox_level,
sandbox_permissions: if request.additional_permissions_preapproved {
crate::sandboxing::SandboxPermissions::UseDefault
@@ -175,6 +175,7 @@ async fn failed_initial_end_for_unstored_process_uses_fallback_output() {
cwd: turn.cwd.clone(),
#[allow(deprecated)]
sandbox_cwd: turn.cwd.clone(),
permission_profile: turn.permission_profile(),
environment: turn
.environments
.primary_environment()