From 568d411082f69ca88292cbd2d1fcd2e2b90a1593 Mon Sep 17 00:00:00 2001 From: Abhinav Vedmala Date: Mon, 15 Jun 2026 22:24:59 +0000 Subject: [PATCH] Use keyed shell environment rules --- .../codex_app_server_protocol.schemas.json | 35 ++++--- .../codex_app_server_protocol.v2.schemas.json | 35 ++++--- .../v2/ConfigRequirementsReadResponse.json | 35 ++++--- .../v2/ShellEnvironmentPolicyRequirements.ts | 3 +- .../v2/ShellEnvironmentPolicyRule.ts | 9 ++ .../schema/typescript/v2/index.ts | 1 + .../src/protocol/v2/config.rs | 4 +- codex-rs/app-server/README.md | 2 +- .../request_processors/config_processor.rs | 29 +++--- codex-rs/config/src/config_requirements.rs | 38 ++++---- codex-rs/config/src/merge.rs | 92 +++++++++++++------ codex-rs/config/src/merge_tests.rs | 85 +++++++++++------ .../src/requirements_layers/stack_tests.rs | 36 +++----- codex-rs/config/src/types.rs | 75 +++++---------- codex-rs/config/src/types_tests.rs | 50 ++++++++-- codex-rs/core/config.schema.json | 56 ++++++----- codex-rs/core/src/config/config_tests.rs | 23 ++--- codex-rs/core/src/config/requirements.rs | 54 +++++++---- codex-rs/protocol/src/config_types.rs | 10 ++ 19 files changed, 375 insertions(+), 297 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRule.ts diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index a5d803bac8..496fc16328 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -15572,15 +15572,6 @@ }, "ShellEnvironmentPolicyRequirements": { "properties": { - "exclude": { - "additionalProperties": { - "type": "boolean" - }, - "type": [ - "object", - "null" - ] - }, "experimental_use_profile": { "type": [ "boolean", @@ -15593,15 +15584,6 @@ "null" ] }, - "include_only": { - "additionalProperties": { - "type": "boolean" - }, - "type": [ - "object", - "null" - ] - }, "inherit": { "anyOf": [ { @@ -15612,6 +15594,15 @@ } ] }, + "rules": { + "additionalProperties": { + "$ref": "#/definitions/v2/ShellEnvironmentPolicyRule" + }, + "type": [ + "object", + "null" + ] + }, "set": { "additionalProperties": { "type": "string" @@ -15624,6 +15615,14 @@ }, "type": "object" }, + "ShellEnvironmentPolicyRule": { + "description": "Assigns a shell environment variable pattern to the include-only or exclude set. Includes do not re-add variables removed by another exclude pattern.", + "enum": [ + "include", + "exclude" + ], + "type": "string" + }, "SkillDependencies": { "properties": { "tools": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 280f4b887f..6e4a91291a 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -13380,15 +13380,6 @@ }, "ShellEnvironmentPolicyRequirements": { "properties": { - "exclude": { - "additionalProperties": { - "type": "boolean" - }, - "type": [ - "object", - "null" - ] - }, "experimental_use_profile": { "type": [ "boolean", @@ -13401,15 +13392,6 @@ "null" ] }, - "include_only": { - "additionalProperties": { - "type": "boolean" - }, - "type": [ - "object", - "null" - ] - }, "inherit": { "anyOf": [ { @@ -13420,6 +13402,15 @@ } ] }, + "rules": { + "additionalProperties": { + "$ref": "#/definitions/ShellEnvironmentPolicyRule" + }, + "type": [ + "object", + "null" + ] + }, "set": { "additionalProperties": { "type": "string" @@ -13432,6 +13423,14 @@ }, "type": "object" }, + "ShellEnvironmentPolicyRule": { + "description": "Assigns a shell environment variable pattern to the include-only or exclude set. Includes do not re-add variables removed by another exclude pattern.", + "enum": [ + "include", + "exclude" + ], + "type": "string" + }, "SkillDependencies": { "properties": { "tools": { diff --git a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json index 5393162f06..41e2b4e3aa 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json +++ b/codex-rs/app-server-protocol/schema/json/v2/ConfigRequirementsReadResponse.json @@ -680,15 +680,6 @@ }, "ShellEnvironmentPolicyRequirements": { "properties": { - "exclude": { - "additionalProperties": { - "type": "boolean" - }, - "type": [ - "object", - "null" - ] - }, "experimental_use_profile": { "type": [ "boolean", @@ -701,15 +692,6 @@ "null" ] }, - "include_only": { - "additionalProperties": { - "type": "boolean" - }, - "type": [ - "object", - "null" - ] - }, "inherit": { "anyOf": [ { @@ -720,6 +702,15 @@ } ] }, + "rules": { + "additionalProperties": { + "$ref": "#/definitions/ShellEnvironmentPolicyRule" + }, + "type": [ + "object", + "null" + ] + }, "set": { "additionalProperties": { "type": "string" @@ -732,6 +723,14 @@ }, "type": "object" }, + "ShellEnvironmentPolicyRule": { + "description": "Assigns a shell environment variable pattern to the include-only or exclude set. Includes do not re-add variables removed by another exclude pattern.", + "enum": [ + "include", + "exclude" + ], + "type": "string" + }, "WebSearchMode": { "enum": [ "disabled", diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRequirements.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRequirements.ts index d58b3ac9c6..ce953373b2 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRequirements.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRequirements.ts @@ -2,5 +2,6 @@ // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. import type { ShellEnvironmentPolicyInherit } from "./ShellEnvironmentPolicyInherit"; +import type { ShellEnvironmentPolicyRule } from "./ShellEnvironmentPolicyRule"; -export type ShellEnvironmentPolicyRequirements = { inherit: ShellEnvironmentPolicyInherit | null, ignore_default_excludes: boolean | null, exclude: { [key in string]?: boolean } | null, set: { [key in string]?: string } | null, include_only: { [key in string]?: boolean } | null, experimental_use_profile: boolean | null, }; +export type ShellEnvironmentPolicyRequirements = { inherit: ShellEnvironmentPolicyInherit | null, ignore_default_excludes: boolean | null, set: { [key in string]?: string } | null, rules: { [key in string]?: ShellEnvironmentPolicyRule } | null, experimental_use_profile: boolean | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRule.ts b/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRule.ts new file mode 100644 index 0000000000..059095db21 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/ShellEnvironmentPolicyRule.ts @@ -0,0 +1,9 @@ +// 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. + +/** + * Assigns a shell environment variable pattern to the include-only or exclude + * set. Includes do not re-add variables removed by another exclude pattern. + */ +export type ShellEnvironmentPolicyRule = "include" | "exclude"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index 5790000c5d..204728eef2 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -347,6 +347,7 @@ export type { SessionMigration } from "./SessionMigration"; export type { SessionSource } from "./SessionSource"; export type { ShellEnvironmentPolicyInherit } from "./ShellEnvironmentPolicyInherit"; export type { ShellEnvironmentPolicyRequirements } from "./ShellEnvironmentPolicyRequirements"; +export type { ShellEnvironmentPolicyRule } from "./ShellEnvironmentPolicyRule"; export type { SkillDependencies } from "./SkillDependencies"; export type { SkillErrorInfo } from "./SkillErrorInfo"; export type { SkillInterface } from "./SkillInterface"; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/config.rs b/codex-rs/app-server-protocol/src/protocol/v2/config.rs index 7ffe2e2042..47ce838bd4 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -9,6 +9,7 @@ use codex_protocol::config_types::AutoCompactTokenLimitScope; use codex_protocol::config_types::ForcedLoginMethod; use codex_protocol::config_types::ReasoningSummary; use codex_protocol::config_types::ShellEnvironmentPolicyInherit; +use codex_protocol::config_types::ShellEnvironmentPolicyRule; use codex_protocol::config_types::Verbosity; use codex_protocol::config_types::WebSearchMode; use codex_protocol::config_types::WebSearchToolConfig; @@ -424,9 +425,8 @@ pub struct FeedbackRequirements { pub struct ShellEnvironmentPolicyRequirements { pub inherit: Option, pub ignore_default_excludes: Option, - pub exclude: Option>, pub r#set: Option>, - pub include_only: Option>, + pub rules: Option>, pub experimental_use_profile: Option, } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index bf2a51139f..d3e555ab4f 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -234,7 +234,7 @@ Example with notification opt-out: - `externalAgentConfig/import` — apply selected external-agent migration items by passing explicit `migrationItems` with `cwd` (`null` for home) and any plugin/session `details` returned by detect. When a request includes migration items, the server emits `externalAgentConfig/import/completed` once after the full import finishes (immediately after the response when everything completed synchronously, or after background imports finish). - `config/value/write` — write a single config key/value to the user's config.toml on disk; dotted paths such as `desktop.someKey` use the same generic write surface. - `config/batchWrite` — apply multiple config edits atomically to the user's config.toml on disk, with optional `reloadUserConfig: true` to hot-reload loaded threads, including multiple `desktop.*` edits. -- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`, `allowedLoginMethods`, `allowedChatgptWorkspaces`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`, and pinned runtime settings such as credential storage, ChatGPT base URL, state/log/model-catalog paths, update checks, login-shell and environment policy, feedback, Windows private-desktop use, and OTEL configuration. Shell environment `exclude` and `include_only` requirements are boolean maps whose `false` entries are preserved as tombstones; OTEL exporter responses include their complete headers map. +- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`, `allowedLoginMethods`, `allowedChatgptWorkspaces`), the layered permission-profile allow map (`allowedPermissionProfiles`), the managed permission-profile default (`defaultPermissions`), lifecycle hook lockdown (`allowManagedHooksOnly`), remote-control policy (`allowRemoteControl`; `false` force-disables remote control while `true` or `null` preserves existing behavior), computer use policy (`computerUse`), pinned feature values (`featureRequirements`), managed lifecycle hooks (`hooks`), `enforceResidency`, `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`, and pinned runtime settings such as credential storage, ChatGPT base URL, state/log/model-catalog paths, update checks, login-shell and environment policy, feedback, Windows private-desktop use, and OTEL configuration. Shell environment requirements expose pattern-to-action `rules` whose values are `include` or `exclude`; OTEL exporter responses include their complete headers map. ### Example: Start or resume a thread diff --git a/codex-rs/app-server/src/request_processors/config_processor.rs b/codex-rs/app-server/src/request_processors/config_processor.rs index ba08859c72..0a8775f357 100644 --- a/codex-rs/app-server/src/request_processors/config_processor.rs +++ b/codex-rs/app-server/src/request_processors/config_processor.rs @@ -410,17 +410,15 @@ fn map_shell_environment_policy_requirements_to_api( let ShellEnvironmentPolicyRequirementsToml { inherit, ignore_default_excludes, - exclude, r#set, - include_only, + rules, experimental_use_profile, } = policy; ShellEnvironmentPolicyRequirements { inherit, ignore_default_excludes, - exclude, r#set, - include_only, + rules, experimental_use_profile, } } @@ -618,6 +616,7 @@ mod tests { use codex_config::ConfigRequirementsToml; use codex_config::WindowsRequirementsToml; use codex_protocol::config_types::ShellEnvironmentPolicyInherit; + use codex_protocol::config_types::ShellEnvironmentPolicyRule; use pretty_assertions::assert_eq; use serde_json::json; use std::collections::BTreeMap; @@ -736,13 +735,10 @@ inherit = "core" ignore_default_excludes = false experimental_use_profile = false -[shell_environment_policy.exclude] -"*OLD*" = false -"*SECRET*" = true - -[shell_environment_policy.include_only] -"HOME" = true -"PATH" = false +[shell_environment_policy.rules] +"*SECRET*" = "exclude" +"HOME" = "include" +"PATH" = "exclude" [shell_environment_policy.set] MANAGED = "true" @@ -763,16 +759,13 @@ MANAGED = "true" Some(ShellEnvironmentPolicyRequirements { inherit: Some(ShellEnvironmentPolicyInherit::Core), ignore_default_excludes: Some(false), - exclude: Some(BTreeMap::from([ - ("*OLD*".to_string(), false), - ("*SECRET*".to_string(), true), - ])), r#set: Some(HashMap::from([ ("MANAGED".to_string(), "true".to_string(),) ])), - include_only: Some(BTreeMap::from([ - ("HOME".to_string(), true), - ("PATH".to_string(), false), + rules: Some(BTreeMap::from([ + ("*SECRET*".to_string(), ShellEnvironmentPolicyRule::Exclude,), + ("HOME".to_string(), ShellEnvironmentPolicyRule::Include,), + ("PATH".to_string(), ShellEnvironmentPolicyRule::Exclude,), ])), experimental_use_profile: Some(false), }) diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index dce2011a24..e4ca833aa7 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -1,6 +1,7 @@ use codex_protocol::config_types::ApprovalsReviewer; use codex_protocol::config_types::SandboxMode; use codex_protocol::config_types::ShellEnvironmentPolicyInherit; +use codex_protocol::config_types::ShellEnvironmentPolicyRule; use codex_protocol::config_types::WebSearchMode; use codex_protocol::models::PermissionProfile; use codex_protocol::protocol::AskForApproval; @@ -893,17 +894,17 @@ pub struct ConfigRequirementsToml { /// Managed shell environment policy fields accepted by `requirements.toml`. /// -/// Unlike ordinary `config.toml`, requirements intentionally accept only -/// boolean maps for list-like fields. This keeps tombstones composable by key +/// Unlike ordinary `config.toml`, requirements intentionally accept only the +/// keyed `rules` form. This makes include/exclude actions compose by pattern, /// while config arrays remain a migration-only compatibility path that can be /// deprecated independently later. #[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)] +#[serde(deny_unknown_fields)] pub struct ShellEnvironmentPolicyRequirementsToml { pub inherit: Option, pub ignore_default_excludes: Option, - pub exclude: Option>, pub r#set: Option>, - pub include_only: Option>, + pub rules: Option>, pub experimental_use_profile: Option, } @@ -1760,29 +1761,21 @@ mod tests { } #[test] - fn shell_environment_policy_requires_boolean_maps_for_list_fields() -> Result<()> { + fn shell_environment_policy_requires_rules_for_list_fields() -> Result<()> { let requirements: ConfigRequirementsToml = from_str( r#" -[shell_environment_policy.exclude] -"ADD_*" = true -"REMOVE_*" = false - -[shell_environment_policy.include_only] -"HOME" = true -"PATH" = false +[shell_environment_policy.rules] +"HOME" = "include" +"SECRET_*" = "exclude" "#, )?; assert_eq!( requirements.shell_environment_policy, Some(ShellEnvironmentPolicyRequirementsToml { - exclude: Some(BTreeMap::from([ - ("ADD_*".to_string(), true), - ("REMOVE_*".to_string(), false), - ])), - include_only: Some(BTreeMap::from([ - ("HOME".to_string(), true), - ("PATH".to_string(), false), + rules: Some(BTreeMap::from([ + ("HOME".to_string(), ShellEnvironmentPolicyRule::Include,), + ("SECRET_*".to_string(), ShellEnvironmentPolicyRule::Exclude,), ])), ..Default::default() }) @@ -1792,9 +1785,14 @@ mod tests { let error = from_str::(&format!( "[shell_environment_policy]\n{field} = [\"LEGACY_*\"]\n" )) - .expect_err("requirements.toml arrays should be rejected"); + .expect_err("legacy requirements.toml arrays should be rejected"); assert!(error.to_string().contains(field)); } + let error = from_str::( + "[shell_environment_policy.rules]\n\"PATH\" = \"keep\"\n", + ) + .expect_err("unknown rule actions should be rejected"); + assert!(error.to_string().contains("keep")); Ok(()) } diff --git a/codex-rs/config/src/merge.rs b/codex-rs/config/src/merge.rs index e0845f2cac..f2cb510345 100644 --- a/codex-rs/config/src/merge.rs +++ b/codex-rs/config/src/merge.rs @@ -9,14 +9,7 @@ pub fn merge_toml_values(base: &mut TomlValue, overlay: &TomlValue) { } fn merge_toml_values_at_path(base: &mut TomlValue, overlay: &TomlValue, path: &mut Vec) { - // Ordinary config temporarily accepts legacy arrays and keyed boolean maps - // for these fields. Promote a lower array only when a map overlays it so - // tombstones can remove individual entries. Keeping this migration rule - // narrow preserves legacy array replacement and makes arrays easy to - // deprecate later without changing the general TOML merge semantics. - if is_shell_environment_pattern_list_path(path) && overlay.is_table() { - promote_string_array_to_bool_map(base); - } + prepare_shell_environment_policy_merge(base, overlay, path); if let TomlValue::Table(overlay_table) = overlay && let TomlValue::Table(base_table) = base @@ -43,32 +36,73 @@ fn merge_toml_values_at_path(base: &mut TomlValue, overlay: &TomlValue, path: &m } } -fn is_shell_environment_pattern_list_path(path: &[String]) -> bool { - matches!( - path, - [policy, field] - if policy == "shell_environment_policy" - && (field == "exclude" || field == "include_only") - ) +fn prepare_shell_environment_policy_merge( + base: &mut TomlValue, + overlay: &TomlValue, + path: &[String], +) { + if !matches!(path, [policy] if policy == "shell_environment_policy") { + return; + } + let TomlValue::Table(base) = base else { + return; + }; + let TomlValue::Table(overlay) = overlay else { + return; + }; + + // Ordinary config keeps accepting legacy arrays while `rules` is the + // canonical keyed form. Reconcile the two shapes only at this boundary so + // layer precedence remains correct and array compatibility can be removed + // cleanly after the migration. + for (legacy_field, opposite_field, action) in [ + ("exclude", "include_only", "exclude"), + ("include_only", "exclude", "include"), + ] { + let Some(patterns) = overlay + .get(legacy_field) + .and_then(TomlValue::as_array) + .and_then(|items| { + items + .iter() + .map(TomlValue::as_str) + .collect::>>() + }) + else { + continue; + }; + + if let Some(base_rules) = base.get_mut("rules").and_then(TomlValue::as_table_mut) { + base_rules.retain(|pattern, value| { + value.as_str() != Some(action) && !patterns.contains(&pattern) + }); + } + remove_patterns_from_legacy_array(base, opposite_field, &patterns); + } + + let Some(overlay_rules) = overlay.get("rules").and_then(TomlValue::as_table) else { + return; + }; + let patterns = overlay_rules.keys().map(String::as_str).collect::>(); + remove_patterns_from_legacy_array(base, "exclude", &patterns); + remove_patterns_from_legacy_array(base, "include_only", &patterns); } -fn promote_string_array_to_bool_map(value: &mut TomlValue) { - let TomlValue::Array(items) = value else { +fn remove_patterns_from_legacy_array( + table: &mut toml::map::Map, + field: &str, + patterns: &[&str], +) { + let Some(items) = table.get_mut(field).and_then(TomlValue::as_array_mut) else { return; }; - let Some(patterns) = items - .iter() - .map(TomlValue::as_str) - .collect::>>() - else { + if !items.iter().all(|item| item.as_str().is_some()) { return; - }; - *value = TomlValue::Table( - patterns - .into_iter() - .map(|pattern| (pattern.to_string(), TomlValue::Boolean(true))) - .collect(), - ); + } + items.retain(|item| { + item.as_str() + .is_none_or(|pattern| !patterns.contains(&pattern)) + }); } fn is_permission_network_domains_path(path: &[String]) -> bool { diff --git a/codex-rs/config/src/merge_tests.rs b/codex-rs/config/src/merge_tests.rs index f667d88dec..271f6c75dc 100644 --- a/codex-rs/config/src/merge_tests.rs +++ b/codex-rs/config/src/merge_tests.rs @@ -147,19 +147,19 @@ exclude = ["HIGH_*"] } #[test] -fn shell_environment_policy_bool_map_overlay_merges_by_key() { +fn shell_environment_policy_rules_overlay_merges_by_key() { let mut base = parse_toml( r#" -[shell_environment_policy.exclude] -"KEEP_*" = true -"REMOVE_*" = true +[shell_environment_policy.rules] +"FLIP_*" = "exclude" +"KEEP_*" = "include" "#, ); let overlay = parse_toml( r#" -[shell_environment_policy.exclude] -"ADD_*" = true -"REMOVE_*" = false +[shell_environment_policy.rules] +"ADD_*" = "exclude" +"FLIP_*" = "include" "#, ); @@ -169,28 +169,30 @@ fn shell_environment_policy_bool_map_overlay_merges_by_key() { base, parse_toml( r#" -[shell_environment_policy.exclude] -"ADD_*" = true -"KEEP_*" = true -"REMOVE_*" = false +[shell_environment_policy.rules] +"ADD_*" = "exclude" +"FLIP_*" = "include" +"KEEP_*" = "include" "#, ) ); } #[test] -fn shell_environment_policy_bool_map_overlay_promotes_lower_legacy_array() { +fn shell_environment_policy_rules_override_lower_legacy_arrays_by_pattern() { let mut base = parse_toml( r#" [shell_environment_policy] -include_only = ["HOME", "PATH"] +exclude = ["FLIP_TO_INCLUDE", "KEEP_EXCLUDED"] +include_only = ["FLIP_TO_EXCLUDE", "KEEP_INCLUDED"] "#, ); let overlay = parse_toml( r#" -[shell_environment_policy.include_only] -"PATH" = false -"USER" = true +[shell_environment_policy.rules] +"ADD_INCLUDED" = "include" +"FLIP_TO_EXCLUDE" = "exclude" +"FLIP_TO_INCLUDE" = "include" "#, ); @@ -200,40 +202,65 @@ include_only = ["HOME", "PATH"] base, parse_toml( r#" -[shell_environment_policy.include_only] -"HOME" = true -"PATH" = false -"USER" = true +[shell_environment_policy] +exclude = ["KEEP_EXCLUDED"] +include_only = ["KEEP_INCLUDED"] + +[shell_environment_policy.rules] +"ADD_INCLUDED" = "include" +"FLIP_TO_EXCLUDE" = "exclude" +"FLIP_TO_INCLUDE" = "include" "#, ) ); let config: ConfigToml = base.try_into().expect("merged config should deserialize"); assert_eq!( - config.shell_environment_policy, - ShellEnvironmentPolicyToml { - include_only: Some(vec!["HOME".to_string(), "USER".to_string()]), + codex_protocol::config_types::ShellEnvironmentPolicy::from(config.shell_environment_policy), + codex_protocol::config_types::ShellEnvironmentPolicy::from(ShellEnvironmentPolicyToml { + exclude: Some(vec![ + "KEEP_EXCLUDED".to_string(), + "FLIP_TO_EXCLUDE".to_string(), + ]), + include_only: Some(vec![ + "KEEP_INCLUDED".to_string(), + "ADD_INCLUDED".to_string(), + "FLIP_TO_INCLUDE".to_string(), + ]), ..Default::default() - } + }) ); } #[test] -fn shell_environment_policy_legacy_array_overlay_replaces_lower_bool_map() { +fn shell_environment_policy_legacy_array_replaces_lower_rules_for_its_action() { let mut base = parse_toml( r#" -[shell_environment_policy.exclude] -"LOW_*" = true +[shell_environment_policy.rules] +"FLIP_TO_EXCLUDE" = "include" +"LOW_EXCLUDED" = "exclude" +"KEEP_INCLUDED" = "include" "#, ); let overlay = parse_toml( r#" [shell_environment_policy] -exclude = ["HIGH_*"] +exclude = ["FLIP_TO_EXCLUDE", "HIGH_EXCLUDED"] "#, ); merge_toml_values(&mut base, &overlay); - assert_eq!(base, overlay); + assert_eq!( + base, + parse_toml( + r#" +[shell_environment_policy] +exclude = ["FLIP_TO_EXCLUDE", "HIGH_EXCLUDED"] + +[shell_environment_policy.rules] +"KEEP_INCLUDED" = "include" +"#, + ) + ); } diff --git a/codex-rs/config/src/requirements_layers/stack_tests.rs b/codex-rs/config/src/requirements_layers/stack_tests.rs index 7126cdd384..8438889cc7 100644 --- a/codex-rs/config/src/requirements_layers/stack_tests.rs +++ b/codex-rs/config/src/requirements_layers/stack_tests.rs @@ -8,6 +8,7 @@ use crate::ConfigRequirementsWithSources; use crate::RequirementSource; use crate::ShellEnvironmentPolicyRequirementsToml; use crate::Sourced; +use codex_protocol::config_types::ShellEnvironmentPolicyRule; use codex_protocol::protocol::AskForApproval; use codex_utils_absolute_path::AbsolutePathBuf; use pretty_assertions::assert_eq; @@ -348,7 +349,7 @@ api = false } #[test] -fn shell_environment_pattern_maps_compose_by_key_with_tombstones() { +fn shell_environment_rules_compose_by_pattern() { let high_source = RequirementSource::EnterpriseManaged { id: "req_high".to_string(), name: "High".to_string(), @@ -362,25 +363,17 @@ fn shell_environment_pattern_maps_compose_by_key_with_tombstones() { RequirementsLayerEntry::from_toml( low_source.clone(), r#" -[shell_environment_policy.exclude] -"KEEP_*" = true -"REMOVE_*" = true - -[shell_environment_policy.include_only] -"HOME" = true -"PATH" = true +[shell_environment_policy.rules] +"FLIP_*" = "exclude" +"KEEP_*" = "include" "#, ), RequirementsLayerEntry::from_toml( high_source.clone(), r#" -[shell_environment_policy.exclude] -"ADD_*" = true -"REMOVE_*" = false - -[shell_environment_policy.include_only] -"PATH" = false -"USER" = true +[shell_environment_policy.rules] +"ADD_*" = "exclude" +"FLIP_*" = "include" "#, ), ], @@ -393,15 +386,10 @@ fn shell_environment_pattern_maps_compose_by_key_with_tombstones() { composed.shell_environment_policy, Some(Sourced::new( ShellEnvironmentPolicyRequirementsToml { - exclude: Some(BTreeMap::from([ - ("ADD_*".to_string(), true), - ("KEEP_*".to_string(), true), - ("REMOVE_*".to_string(), false), - ])), - include_only: Some(BTreeMap::from([ - ("HOME".to_string(), true), - ("PATH".to_string(), false), - ("USER".to_string(), true), + rules: Some(BTreeMap::from([ + ("ADD_*".to_string(), ShellEnvironmentPolicyRule::Exclude,), + ("FLIP_*".to_string(), ShellEnvironmentPolicyRule::Include,), + ("KEEP_*".to_string(), ShellEnvironmentPolicyRule::Include,), ])), ..Default::default() }, diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index f39d3863cf..e0c2a91057 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -20,6 +20,7 @@ pub use codex_protocol::config_types::Personality; pub use codex_protocol::config_types::ServiceTier; use codex_protocol::config_types::ShellEnvironmentPolicy; use codex_protocol::config_types::ShellEnvironmentPolicyInherit; +use codex_protocol::config_types::ShellEnvironmentPolicyRule; pub use codex_protocol::config_types::WebSearchMode; use codex_utils_absolute_path::AbsolutePathBuf; use std::collections::BTreeMap; @@ -913,41 +914,6 @@ impl From for codex_app_server_protocol::SandboxSettings } } -// Compatibility input for list-like shell environment policy fields. -// -// Ordinary `config.toml` accepts both the legacy array form and the keyed -// boolean-map form while the latter rolls out. Keeping that compatibility in -// this input-only type lets requirements stay map-only and gives us a single -// seam where arrays can be deprecated and removed later. -#[derive(Deserialize, JsonSchema)] -#[serde(untagged)] -enum ShellEnvironmentPatternListInput { - List(Vec), - Map(BTreeMap), -} - -impl ShellEnvironmentPatternListInput { - fn into_enabled_patterns(self) -> Vec { - match self { - Self::List(patterns) => patterns, - Self::Map(patterns) => patterns - .into_iter() - .filter_map(|(pattern, enabled)| enabled.then_some(pattern)) - .collect(), - } - } -} - -fn deserialize_optional_shell_environment_pattern_list<'de, D>( - deserializer: D, -) -> Result>, D::Error> -where - D: serde::Deserializer<'de>, -{ - Option::::deserialize(deserializer) - .map(|value| value.map(ShellEnvironmentPatternListInput::into_enabled_patterns)) -} - /// Policy for building the `env` when spawning a process via shell-like tools. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] @@ -956,24 +922,21 @@ pub struct ShellEnvironmentPolicyToml { pub ignore_default_excludes: Option, - /// List or boolean map of regular expressions. - #[serde( - default, - deserialize_with = "deserialize_optional_shell_environment_pattern_list" - )] - #[schemars(with = "Option")] + /// Legacy list of regular expressions to exclude. pub exclude: Option>, pub r#set: Option>, - /// List or boolean map of regular expressions. - #[serde( - default, - deserialize_with = "deserialize_optional_shell_environment_pattern_list" - )] - #[schemars(with = "Option")] + /// Legacy list of regular expressions to include. pub include_only: Option>, + /// Pattern actions used by the canonical table representation. + /// + /// Ordinary config keeps accepting the legacy arrays above during the + /// migration. Requirements accept only this keyed form, keeping array + /// compatibility isolated so the legacy fields can be deprecated later. + pub rules: Option>, + pub experimental_use_profile: Option, } @@ -982,16 +945,22 @@ impl From for ShellEnvironmentPolicy { // Default to inheriting the full environment when not specified. let inherit = toml.inherit.unwrap_or(ShellEnvironmentPolicyInherit::All); let ignore_default_excludes = toml.ignore_default_excludes.unwrap_or(true); - let exclude = toml - .exclude - .unwrap_or_default() + let mut exclude = toml.exclude.unwrap_or_default(); + let mut include_only = toml.include_only.unwrap_or_default(); + for (pattern, rule) in toml.rules.unwrap_or_default() { + exclude.retain(|candidate| candidate != &pattern); + include_only.retain(|candidate| candidate != &pattern); + match rule { + ShellEnvironmentPolicyRule::Include => include_only.push(pattern), + ShellEnvironmentPolicyRule::Exclude => exclude.push(pattern), + } + } + let exclude = exclude .into_iter() .map(|s| EnvironmentVariablePattern::new_case_insensitive(&s)) .collect(); let r#set = toml.r#set.unwrap_or_default(); - let include_only = toml - .include_only - .unwrap_or_default() + let include_only = include_only .into_iter() .map(|s| EnvironmentVariablePattern::new_case_insensitive(&s)) .collect(); diff --git a/codex-rs/config/src/types_tests.rs b/codex-rs/config/src/types_tests.rs index 92cc4d41e1..ac1b1bcb5a 100644 --- a/codex-rs/config/src/types_tests.rs +++ b/codex-rs/config/src/types_tests.rs @@ -2,7 +2,7 @@ use super::*; use pretty_assertions::assert_eq; #[test] -fn shell_environment_policy_accepts_legacy_lists_and_bool_maps() { +fn shell_environment_policy_accepts_legacy_lists_and_rules() { let legacy: ShellEnvironmentPolicyToml = toml::from_str( r#" exclude = ["LEGACY_*", "SHARED_*"] @@ -19,21 +19,55 @@ include_only = ["PATH", "HOME"] } ); - let mapped: ShellEnvironmentPolicyToml = toml::from_str( + let ruled: ShellEnvironmentPolicyToml = toml::from_str( r#" -exclude = { "DISABLED_*" = false, "ENABLED_*" = true } -include_only = { "HOME" = true, "PATH" = false } +exclude = ["KEEP_EXCLUDED", "FLIP_TO_INCLUDE"] +include_only = ["KEEP_INCLUDED", "FLIP_TO_EXCLUDE"] + +[rules] +"FLIP_TO_EXCLUDE" = "exclude" +"FLIP_TO_INCLUDE" = "include" "#, ) - .expect("boolean maps should be valid in config.toml"); + .expect("rules should be valid in config.toml"); assert_eq!( - mapped, + ruled, ShellEnvironmentPolicyToml { - exclude: Some(vec!["ENABLED_*".to_string()]), - include_only: Some(vec!["HOME".to_string()]), + exclude: Some(vec![ + "KEEP_EXCLUDED".to_string(), + "FLIP_TO_INCLUDE".to_string(), + ]), + include_only: Some(vec![ + "KEEP_INCLUDED".to_string(), + "FLIP_TO_EXCLUDE".to_string(), + ]), + rules: Some(BTreeMap::from([ + ( + "FLIP_TO_EXCLUDE".to_string(), + ShellEnvironmentPolicyRule::Exclude, + ), + ( + "FLIP_TO_INCLUDE".to_string(), + ShellEnvironmentPolicyRule::Include, + ), + ])), ..Default::default() } ); + assert_eq!( + ShellEnvironmentPolicy::from(ruled), + ShellEnvironmentPolicy::from(ShellEnvironmentPolicyToml { + exclude: Some(vec![ + "KEEP_EXCLUDED".to_string(), + "FLIP_TO_EXCLUDE".to_string(), + ]), + include_only: Some(vec![ + "KEEP_INCLUDED".to_string(), + "FLIP_TO_INCLUDE".to_string(), + ]), + ..Default::default() + }) + ); } #[test] diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index a1299b6be5..7adff89e44 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -2592,22 +2592,6 @@ ], "type": "string" }, - "ShellEnvironmentPatternListInput": { - "anyOf": [ - { - "items": { - "type": "string" - }, - "type": "array" - }, - { - "additionalProperties": { - "type": "boolean" - }, - "type": "object" - } - ] - }, "ShellEnvironmentPolicyInherit": { "oneOf": [ { @@ -2633,18 +2617,24 @@ } ] }, + "ShellEnvironmentPolicyRule": { + "description": "Assigns a shell environment variable pattern to the include-only or exclude set. Includes do not re-add variables removed by another exclude pattern.", + "enum": [ + "include", + "exclude" + ], + "type": "string" + }, "ShellEnvironmentPolicyToml": { "additionalProperties": false, "description": "Policy for building the `env` when spawning a process via shell-like tools.", "properties": { "exclude": { - "allOf": [ - { - "$ref": "#/definitions/ShellEnvironmentPatternListInput" - } - ], - "default": null, - "description": "List or boolean map of regular expressions." + "description": "Legacy list of regular expressions to exclude.", + "items": { + "type": "string" + }, + "type": "array" }, "experimental_use_profile": { "type": "boolean" @@ -2653,17 +2643,22 @@ "type": "boolean" }, "include_only": { - "allOf": [ - { - "$ref": "#/definitions/ShellEnvironmentPatternListInput" - } - ], - "default": null, - "description": "List or boolean map of regular expressions." + "description": "Legacy list of regular expressions to include.", + "items": { + "type": "string" + }, + "type": "array" }, "inherit": { "$ref": "#/definitions/ShellEnvironmentPolicyInherit" }, + "rules": { + "additionalProperties": { + "$ref": "#/definitions/ShellEnvironmentPolicyRule" + }, + "description": "Pattern actions used by the canonical table representation.\n\nOrdinary config keeps accepting the legacy arrays above during the migration. Requirements accept only this keyed form, keeping array compatibility isolated so the legacy fields can be deprecated later.", + "type": "object" + }, "set": { "additionalProperties": { "type": "string" @@ -5217,6 +5212,7 @@ "ignore_default_excludes": null, "include_only": null, "inherit": null, + "rules": null, "set": null } }, diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 05d8450114..e42a0b1ec9 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -9338,8 +9338,8 @@ allow_login_shell = true [shell_environment_policy] ignore_default_excludes = true -exclude = ["USER_*", "REMOVE_*"] -include_only = ["HOME", "PATH"] +exclude = ["USER_*", "FLIP_TO_INCLUDE"] +include_only = ["HOME", "FLIP_TO_EXCLUDE"] [shell_environment_policy.set] CONFIGURED = "kept" @@ -9382,13 +9382,10 @@ api = false ignore_default_excludes = false experimental_use_profile = true -[shell_environment_policy.exclude] -"MANAGED_*" = true -"REMOVE_*" = false - -[shell_environment_policy.include_only] -"PATH" = false -"USER" = true +[shell_environment_policy.rules] +"FLIP_TO_EXCLUDE" = "exclude" +"FLIP_TO_INCLUDE" = "include" +"MANAGED_*" = "exclude" [shell_environment_policy.set] MANAGED = "required" @@ -9415,8 +9412,12 @@ sandbox_private_desktop = false let expected_shell_environment_policy: ShellEnvironmentPolicy = codex_config::types::ShellEnvironmentPolicyToml { ignore_default_excludes: Some(false), - exclude: Some(vec!["USER_*".to_string(), "MANAGED_*".to_string()]), - include_only: Some(vec!["HOME".to_string(), "USER".to_string()]), + exclude: Some(vec![ + "USER_*".to_string(), + "FLIP_TO_EXCLUDE".to_string(), + "MANAGED_*".to_string(), + ]), + include_only: Some(vec!["HOME".to_string(), "FLIP_TO_INCLUDE".to_string()]), experimental_use_profile: Some(true), r#set: Some(HashMap::from([ ("CONFIGURED".to_string(), "kept".to_string()), diff --git a/codex-rs/core/src/config/requirements.rs b/codex-rs/core/src/config/requirements.rs index 745eff7f85..335d5090d9 100644 --- a/codex-rs/core/src/config/requirements.rs +++ b/codex-rs/core/src/config/requirements.rs @@ -7,6 +7,7 @@ use codex_config::types::AuthCredentialsStoreMode; use codex_config::types::FeedbackConfigToml; use codex_config::types::ShellEnvironmentPolicyToml; use codex_protocol::config_types::ForcedLoginMethod; +use codex_protocol::config_types::ShellEnvironmentPolicyRule; use std::collections::BTreeMap; use super::otel; @@ -147,9 +148,8 @@ fn apply_shell_environment_policy_requirement( let ShellEnvironmentPolicyRequirementsToml { inherit, ignore_default_excludes, - exclude, r#set: required_set, - include_only, + rules, experimental_use_profile, } = value; let mut conflict = false; @@ -159,8 +159,7 @@ fn apply_shell_environment_policy_requirement( &mut configured.ignore_default_excludes, ignore_default_excludes, ); - conflict |= apply_required_pattern_map(&mut configured.exclude, exclude); - conflict |= apply_required_pattern_map(&mut configured.include_only, include_only); + conflict |= apply_required_pattern_rules(configured, rules); conflict |= replace_required_leaf( &mut configured.experimental_use_profile, experimental_use_profile, @@ -184,26 +183,47 @@ fn apply_shell_environment_policy_requirement( ); } -fn apply_required_pattern_map( - configured: &mut Option>, - required: &Option>, +fn apply_required_pattern_rules( + configured: &mut ShellEnvironmentPolicyToml, + required: &Option>, ) -> bool { let Some(required) = required else { return false; }; - let configured = configured.get_or_insert_default(); - // Adding an enabled pattern is additive; removing a configured pattern is - // the only case that overrides the user's effective list. - let conflict = required - .iter() - .any(|(pattern, enabled)| !enabled && configured.contains(pattern)); + let conflict = required.iter().any(|(pattern, required_action)| { + let configured_action = configured + .rules + .as_ref() + .and_then(|rules| rules.get(pattern).copied()) + .or_else(|| { + configured + .exclude + .as_ref() + .is_some_and(|patterns| patterns.contains(pattern)) + .then_some(ShellEnvironmentPolicyRule::Exclude) + }) + .or_else(|| { + configured + .include_only + .as_ref() + .is_some_and(|patterns| patterns.contains(pattern)) + .then_some(ShellEnvironmentPolicyRule::Include) + }); + configured_action.is_some_and(|action| action != *required_action) + }); - configured.retain(|pattern| required.get(pattern).copied().unwrap_or(true)); - for (pattern, enabled) in required { - if *enabled && !configured.contains(pattern) { - configured.push(pattern.clone()); + for pattern in required.keys() { + if let Some(exclude) = configured.exclude.as_mut() { + exclude.retain(|candidate| candidate != pattern); + } + if let Some(include_only) = configured.include_only.as_mut() { + include_only.retain(|candidate| candidate != pattern); } } + configured + .rules + .get_or_insert_default() + .extend(required.clone()); conflict } diff --git a/codex-rs/protocol/src/config_types.rs b/codex-rs/protocol/src/config_types.rs index e2434726d4..9d992cd12a 100644 --- a/codex-rs/protocol/src/config_types.rs +++ b/codex-rs/protocol/src/config_types.rs @@ -217,6 +217,16 @@ pub enum ShellEnvironmentPolicyInherit { None, } +/// Assigns a shell environment variable pattern to the include-only or exclude +/// set. Includes do not re-add variables removed by another exclude pattern. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "lowercase")] +#[ts(export_to = "v2/")] +pub enum ShellEnvironmentPolicyRule { + Include, + Exclude, +} + pub type EnvironmentVariablePattern = WildMatchPattern<'*', '?'>; /// Deriving the `env` based on this policy works as follows: