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 081b4fb4ab..3e4c3e7020 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/config.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/config.rs @@ -335,6 +335,7 @@ pub struct ConfigWriteResponse { #[ts(export_to = "v2/")] pub enum ConfigWriteErrorCode { ConfigLayerReadonly, + ConfigRequirementReadonly, ConfigVersionConflict, ConfigValidationError, ConfigPathNotFound, diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 9188877384..650bc80396 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -230,12 +230,12 @@ Example with notification opt-out: - `mcpServer/tool/call` — call a tool on a thread's configured MCP server by `threadId`, `server`, `tool`, optional `arguments`, and optional `_meta`, returning the MCP tool result. - `windowsSandbox/setupStart` — start Windows sandbox setup for the selected mode (`elevated` or `unelevated`); accepts an optional absolute `cwd` to target setup for a specific workspace, returns `{ started: true }` immediately, and later emits `windowsSandbox/setupCompleted`. - `feedback/upload` — submit a feedback report (classification + optional reason/logs, conversation_id, and optional `extraLogFiles` attachments array); returns the tracking thread id. -- `config/read` — fetch the effective config on disk after resolving config layering, including opaque `desktop` values stored in `config.toml`. +- `config/read` — fetch the runtime-effective config after resolving config layering and managed requirements, including opaque `desktop` values stored in `config.toml`. - `externalAgentConfig/detect` — detect migratable external-agent artifacts with `includeHome` and optional `cwds`; each detected item includes `cwd` (`null` for home), and plugin/session migration items may additionally include structured `details` grouping plugin ids or session metadata. - `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. Returns an `importId` used to correlate the completion notification. When a request includes migration items, the server emits `externalAgentConfig/import/completed` once after the full import finishes with type-level `itemResults` containing each migrated type's success count, error count, successes, and raw errors (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/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. Writes that overlap a managed requirement are rejected with `configRequirementReadonly`. - `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`), 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`, and `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`. +- `configRequirements/read` — fetch loaded requirements constraints from `requirements.toml` and/or MDM (or `null` if none are configured), including exact managed values (`sqliteHome`, `logDir`, `modelCatalogJson`, `checkForUpdateOnStartup`, `allowLoginShell`, `feedback.enabled`, and `windowsSandboxPrivateDesktop`), allow-lists (`allowedApprovalPolicies`, `allowedSandboxModes`, `allowedWebSearchModes`), 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`, and `network` constraints such as canonical domain/socket permissions plus `managedAllowedDomainsOnly` and `dangerFullAccessDenylistOnly`. ### Example: Start or resume a thread diff --git a/codex-rs/app-server/src/config_manager_service.rs b/codex-rs/app-server/src/config_manager_service.rs index 4b42c28aa9..7002746408 100644 --- a/codex-rs/app-server/src/config_manager_service.rs +++ b/codex-rs/app-server/src/config_manager_service.rs @@ -125,9 +125,12 @@ impl ConfigManager { }; let effective = layers.effective_config(); - let effective_config_toml: ConfigToml = effective + let mut effective_config_toml: ConfigToml = effective .try_into() .map_err(|err| ConfigManagerError::toml("invalid configuration", err))?; + layers + .requirements_toml() + .apply_exact_to_config(&mut effective_config_toml); let json_value = serde_json::to_value(&effective_config_toml) .map_err(|err| ConfigManagerError::json("failed to serialize configuration", err))?; @@ -237,6 +240,15 @@ impl ConfigManager { let segments = parse_key_path(&key_path).map_err(|message| { ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message) })?; + if let Some(field) = layers + .requirements_toml() + .exact_requirement_for_config_path(&segments) + { + return Err(ConfigManagerError::write( + ConfigWriteErrorCode::ConfigRequirementReadonly, + format!("`{field}` is managed by requirements and cannot be changed"), + )); + } if !value.is_null() { match segments.as_slice() { [segment] if segment == "profile" => { diff --git a/codex-rs/app-server/src/config_manager_service_tests.rs b/codex-rs/app-server/src/config_manager_service_tests.rs index 8deae8b065..0eeb168750 100644 --- a/codex-rs/app-server/src/config_manager_service_tests.rs +++ b/codex-rs/app-server/src/config_manager_service_tests.rs @@ -742,6 +742,107 @@ personality = true ); } +#[tokio::test] +async fn write_value_rejects_exact_managed_requirement() { + let tmp = tempdir().expect("tempdir"); + let path = tmp.path().join(CONFIG_TOML_FILE); + std::fs::write(&path, "allow_login_shell = true\n").unwrap(); + + let service = ConfigManager::new_for_tests( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides::without_managed_config_for_tests(), + CloudConfigBundleFixture::loader_with_enterprise_requirement("allow_login_shell = false"), + ); + + let error = service + .write_value(ConfigValueWriteParams { + file_path: Some(path.display().to_string()), + key_path: "allow_login_shell".to_string(), + value: serde_json::json!(true), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect_err("managed exact field should be read-only"); + + assert_eq!( + error.write_error_code(), + Some(ConfigWriteErrorCode::ConfigRequirementReadonly) + ); + assert!(error.to_string().contains("`allow_login_shell`")); + assert_eq!( + std::fs::read_to_string(path).unwrap(), + "allow_login_shell = true\n" + ); +} + +#[tokio::test] +async fn read_reflects_exact_managed_requirement() { + let tmp = tempdir().expect("tempdir"); + std::fs::write( + tmp.path().join(CONFIG_TOML_FILE), + "allow_login_shell = true\n", + ) + .unwrap(); + + let service = ConfigManager::new_for_tests( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides::without_managed_config_for_tests(), + CloudConfigBundleFixture::loader_with_enterprise_requirement("allow_login_shell = false"), + ); + + let response = service + .read(ConfigReadParams { + include_layers: false, + cwd: None, + }) + .await + .expect("config read should succeed"); + + assert_eq!( + response.config.additional.get("allow_login_shell"), + Some(&serde_json::json!(false)) + ); +} + +#[tokio::test] +async fn write_value_allows_unmanaged_sibling_of_exact_requirement() { + let tmp = tempdir().expect("tempdir"); + let path = tmp.path().join(CONFIG_TOML_FILE); + std::fs::write(&path, "").unwrap(); + + let service = ConfigManager::new_for_tests( + tmp.path().to_path_buf(), + vec![], + LoaderOverrides::without_managed_config_for_tests(), + CloudConfigBundleFixture::loader_with_enterprise_requirement( + r#" +[windows] +sandbox_private_desktop = false +"#, + ), + ); + + service + .write_value(ConfigValueWriteParams { + file_path: Some(path.display().to_string()), + key_path: "windows.sandbox".to_string(), + value: serde_json::json!("elevated"), + merge_strategy: MergeStrategy::Replace, + expected_version: None, + }) + .await + .expect("unmanaged sibling should remain writable"); + + assert!( + std::fs::read_to_string(path) + .unwrap() + .contains("sandbox = \"elevated\"") + ); +} + #[tokio::test] async fn read_reports_managed_overrides_user_and_session_flags() { let tmp = tempdir().expect("tempdir"); diff --git a/codex-rs/config/src/config_requirements.rs b/codex-rs/config/src/config_requirements.rs index 9871df9c4c..9776e1484f 100644 --- a/codex-rs/config/src/config_requirements.rs +++ b/codex-rs/config/src/config_requirements.rs @@ -18,6 +18,7 @@ use super::requirements_exec_policy::RequirementsExecPolicyToml; use crate::Constrained; use crate::ConstraintError; use crate::ManagedHooksRequirementsToml; +use crate::config_toml::ConfigToml; use crate::mcp_types::AppToolApproval; use crate::permissions_toml::PermissionProfileToml; use crate::types::FeedbackConfigToml; @@ -1208,6 +1209,92 @@ impl ConfigRequirementsToml { .as_deref() .is_none_or(|value| value.trim().is_empty()) } + + /// Applies the requirements whose values replace config values. + /// + /// This projection is shared by config/read and config-lock export so + /// both surfaces describe the same behavior as the final runtime config. + pub fn apply_exact_to_config(&self, config: &mut ConfigToml) { + macro_rules! apply_exact { + ($field:ident) => { + if let Some(value) = self.$field.as_ref() { + config.$field = Some(value.clone()); + } + }; + } + + apply_exact!(sqlite_home); + apply_exact!(log_dir); + apply_exact!(model_catalog_json); + apply_exact!(check_for_update_on_startup); + apply_exact!(allow_login_shell); + + if let Some(enabled) = self.feedback.as_ref().and_then(|feedback| feedback.enabled) { + config.feedback.get_or_insert_default().enabled = Some(enabled); + } + if let Some(sandbox_private_desktop) = self + .windows + .as_ref() + .and_then(|windows| windows.sandbox_private_desktop) + { + config + .windows + .get_or_insert_default() + .sandbox_private_desktop = Some(sandbox_private_desktop); + } + } + + /// Returns the exact managed field affected by editing `segments`. + pub fn exact_requirement_for_config_path(&self, segments: &[String]) -> Option<&'static str> { + let managed_fields: [(bool, &[&str], &'static str); 7] = [ + (self.sqlite_home.is_some(), &["sqlite_home"], "sqlite_home"), + (self.log_dir.is_some(), &["log_dir"], "log_dir"), + ( + self.model_catalog_json.is_some(), + &["model_catalog_json"], + "model_catalog_json", + ), + ( + self.check_for_update_on_startup.is_some(), + &["check_for_update_on_startup"], + "check_for_update_on_startup", + ), + ( + self.allow_login_shell.is_some(), + &["allow_login_shell"], + "allow_login_shell", + ), + ( + self.feedback + .as_ref() + .and_then(|feedback| feedback.enabled) + .is_some(), + &["feedback", "enabled"], + "feedback.enabled", + ), + ( + self.windows + .as_ref() + .and_then(|windows| windows.sandbox_private_desktop) + .is_some(), + &["windows", "sandbox_private_desktop"], + "windows.sandbox_private_desktop", + ), + ]; + + managed_fields + .into_iter() + .find_map(|(is_managed, managed_path, field)| { + (is_managed && config_paths_overlap(segments, managed_path)).then_some(field) + }) + } +} + +fn config_paths_overlap(segments: &[String], managed_path: &[&str]) -> bool { + segments + .iter() + .zip(managed_path) + .all(|(segment, managed_segment)| segment == managed_segment) } impl TryFrom for ConfigRequirements { diff --git a/codex-rs/core/src/session/config_lock.rs b/codex-rs/core/src/session/config_lock.rs index ec2056581c..ecc60e6943 100644 --- a/codex-rs/core/src/session/config_lock.rs +++ b/codex-rs/core/src/session/config_lock.rs @@ -88,6 +88,10 @@ fn session_configuration_to_lock_config_toml( .effective_config() .try_into() .context("failed to deserialize effective config for config lock")?; + config + .config_layer_stack + .requirements_toml() + .apply_exact_to_config(&mut lock_config); if config.config_lock_save_fields_resolved_from_model_catalog { save_session_resolved_fields(sc, &mut lock_config); @@ -203,6 +207,7 @@ where #[cfg(test)] mod tests { use super::*; + use codex_config::test_support::CloudConfigBundleFixture; use pretty_assertions::assert_eq; use std::sync::Arc; @@ -302,6 +307,58 @@ mod tests { assert_eq!(lock.approvals_reviewer, None); } + #[tokio::test] + async fn lock_contains_exact_managed_requirements() { + let codex_home = tempfile::tempdir().expect("create temp dir"); + let sqlite_home = codex_home.path().join("managed-state"); + let log_dir = codex_home.path().join("managed-logs"); + let requirements = format!( + r#" +sqlite_home = {:?} +log_dir = {:?} +check_for_update_on_startup = false +allow_login_shell = false + +[feedback] +enabled = false + +[windows] +sandbox_private_desktop = false +"#, + sqlite_home.display(), + log_dir.display(), + ); + let config = crate::config::ConfigBuilder::without_managed_config_for_tests() + .codex_home(codex_home.path().to_path_buf()) + .fallback_cwd(Some(codex_home.path().to_path_buf())) + .cloud_config_bundle( + CloudConfigBundleFixture::loader_with_enterprise_requirement(requirements), + ) + .build() + .await + .expect("config should load"); + let mut sc = crate::session::tests::make_session_configuration_for_tests().await; + sc.original_config_do_not_use = Arc::new(config); + + let lockfile = sc.to_config_lockfile_toml().expect("lock should serialize"); + let lock = &lockfile.config; + + assert_eq!(lock.sqlite_home.as_deref(), Some(sqlite_home.as_path())); + assert_eq!(lock.log_dir.as_deref(), Some(log_dir.as_path())); + assert_eq!(lock.check_for_update_on_startup, Some(false)); + assert_eq!(lock.allow_login_shell, Some(false)); + assert_eq!( + lock.feedback.as_ref().and_then(|feedback| feedback.enabled), + Some(false) + ); + assert_eq!( + lock.windows + .as_ref() + .and_then(|windows| windows.sandbox_private_desktop), + Some(false) + ); + } + #[tokio::test] async fn lock_validation_reports_config_diff() { let sc = crate::session::tests::make_session_configuration_for_tests().await;