Add credential brokering to network proxy feature config (#40466)

## What changed

- Add `features.network_proxy.credential_broker` and preserve structured network proxy settings when toggling the feature through config APIs.
- Protect broker enablement and provider context variables from project config, while carrying trusted context into filtered shell environments.
- Propagate brokered credentials through shell snapshots and restore real credentials for unsandboxed escalated commands.
- Normalize broker context environment keys case-insensitively on Windows and avoid conflicting remote managed-network enforcement when no proxy launch configuration is available.

## Testing

- Cover config layering, editing, project sanitization, Windows environment handling, shell snapshots, escalated execution, and end-to-end GitHub credential brokering in the zsh-fork runtime.

GitOrigin-RevId: 500e51e804e1988022052ccfe00b8fac5e495f4f
This commit is contained in:
Winston Howes
2026-08-24 19:52:27 +00:00
committed by copyberry
parent c2904b9c5a
commit c3d5e4418f
27 changed files with 1000 additions and 92 deletions
@@ -19,6 +19,7 @@ use codex_config::ConfigLayerStack;
use codex_config::ConfigRequirementsToml;
use codex_config::ShellEnvironmentPolicyFilterRepresentation;
use codex_config::config_toml::ConfigToml;
use codex_config::is_structured_feature_path;
use codex_config::merge_toml_values;
use codex_config::shell_environment_filter_entry;
use codex_config::validate_shell_environment_policy_filter_config;
@@ -312,6 +313,22 @@ impl ConfigManager {
{
segments[2] = pattern;
}
if cfg!(windows)
&& let [policy, field, key] = segments.as_slice()
&& policy == "shell_environment_policy"
&& field == "set"
&& let Some(existing) = user_config
.get(policy)
.and_then(|policy| policy.get(field))
.and_then(TomlValue::as_table)
.and_then(|overrides| {
overrides
.keys()
.find(|candidate| candidate.eq_ignore_ascii_case(key))
})
{
segments[2].clone_from(existing);
}
if !value.is_null() {
match segments.as_slice() {
[segment] if segment == "profile" => {
@@ -329,9 +346,28 @@ impl ConfigManager {
_ => {}
}
}
let parsed_value = parse_value(value).map_err(|message| {
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message)
})?;
let preserves_network_proxy_settings = value.is_null()
&& is_structured_feature_path(&segments)
&& segments
.last()
.is_some_and(|feature| feature == "network_proxy")
&& {
let has_broker_settings = |config: &TomlValue| {
value_at_path(config, &segments)
.and_then(TomlValue::as_table)
.is_some_and(|feature| feature.contains_key("credential_broker"))
};
has_broker_settings(&user_config)
|| !has_broker_settings(&user_layer.config)
&& has_broker_settings(&layers.effective_config())
};
let parsed_value = if preserves_network_proxy_settings {
Some(TomlValue::Boolean(false))
} else {
parse_value(value).map_err(|message| {
ConfigManagerError::write(ConfigWriteErrorCode::ConfigValidationError, message)
})?
};
if matches!(strategy, MergeStrategy::Upsert)
&& let Some(value) = parsed_value.as_ref()
&& matches!(segments.as_slice(), [policy, ..] if policy == "shell_environment_policy")
@@ -354,6 +390,15 @@ impl ConfigManager {
segments.clone()
};
let original_value = value_at_path(&user_config, &persist_segments).cloned();
let structured_feature_toggle = preserves_network_proxy_settings
|| is_structured_feature_path(&segments)
&& parsed_value.as_ref().is_some_and(|value| {
value.is_bool()
|| matches!(strategy, MergeStrategy::Upsert)
&& value.as_table().is_some_and(|table| {
table.len() == 1 && table.contains_key("enabled")
})
});
apply_merge(&mut user_config, &segments, parsed_value.as_ref(), strategy).map_err(
|err| match err {
@@ -379,6 +424,9 @@ impl ConfigManager {
});
}
if structured_feature_toggle {
segments.push("enabled".to_string());
}
parsed_segments.push(segments);
}
@@ -569,6 +617,16 @@ enum MergeError {
Validation(String),
}
fn structured_feature_depth(segments: &[String]) -> Option<usize> {
let depth = match segments {
[profiles, _, _, _, ..] if profiles == "profiles" => 4,
[_, _, ..] => 2,
_ => return None,
};
is_structured_feature_path(&segments[..depth]).then_some(depth)
}
fn apply_merge(
root: &mut TomlValue,
segments: &[String],
@@ -585,17 +643,8 @@ fn apply_merge(
));
};
let multi_agent_v2_feature_depth = match segments {
[features, feature, ..] if features == "features" && feature == "multi_agent_v2" => Some(2),
[profiles, _, features, feature, ..]
if profiles == "profiles" && features == "features" && feature == "multi_agent_v2" =>
{
Some(4)
}
_ => None,
};
let preserves_multi_agent_v2_feature_config =
multi_agent_v2_feature_depth.is_some_and(|feature_depth| {
let preserves_structured_feature_config =
structured_feature_depth(segments).is_some_and(|feature_depth| {
match value_at_path(root, &segments[..feature_depth]) {
Some(TomlValue::Boolean(_)) => {
segments.len() > feature_depth || matches!(value, TomlValue::Table(_))
@@ -607,7 +656,7 @@ fn apply_merge(
}
});
if preserves_multi_agent_v2_feature_config
if preserves_structured_feature_config
|| matches!(strategy, MergeStrategy::Upsert)
&& (shell_environment_policy_representation_switch(root, segments, value)
|| (matches!(value_at_path(root, segments), Some(TomlValue::Table(_)))
@@ -770,20 +819,26 @@ fn value_at_path<'a>(root: &'a TomlValue, segments: &[String]) -> Option<&'a Tom
fn value_at_semantic_path<'a>(root: &'a TomlValue, segments: &[String]) -> Option<&'a TomlValue> {
shell_environment_filter_entry(root, segments)
.map(|(_, value)| value)
.or_else(|| match segments {
[policy, field, key]
if cfg!(windows) && policy == "shell_environment_policy" && field == "set" =>
{
root.get(policy)?
.get(field)?
.as_table()?
.iter()
.find(|(candidate, _)| candidate.eq_ignore_ascii_case(key))
.map(|(_, value)| value)
}
_ => None,
})
.or_else(|| value_at_path(root, segments))
.or_else(|| {
let (field, parents) = segments.split_last()?;
if field != "enabled" {
return None;
}
let is_multi_agent_v2_feature = match parents {
[features, feature] => features == "features" && feature == "multi_agent_v2",
[profiles, _, features, feature] => {
profiles == "profiles" && features == "features" && feature == "multi_agent_v2"
}
_ => false,
};
if !is_multi_agent_v2_feature {
if structured_feature_depth(parents) != Some(parents.len()) {
return None;
}
let feature = value_at_path(root, parents)?;
@@ -1198,12 +1198,16 @@ async fn multi_agent_v2_boolean_layer_owns_enabled_origin_and_overrides() {
let user_path = tmp.path().join(CONFIG_TOML_FILE);
std::fs::write(
&user_path,
"[features.multi_agent_v2]\nenabled = true\nsubagent_usage_hint_text = \"keep\"\n",
"[features.multi_agent_v2]\nenabled = true\nsubagent_usage_hint_text = \"keep\"\n\n[features.network_proxy]\nenabled = true\ncredential_broker = true\n",
)
.expect("user config");
let managed_path = tmp.path().join("managed_config.toml");
std::fs::write(&managed_path, "[features]\nmulti_agent_v2 = false\n").expect("managed config");
std::fs::write(
&managed_path,
"[features]\nmulti_agent_v2 = false\nnetwork_proxy = false\n",
)
.expect("managed config");
let managed_file = AbsolutePathBuf::try_from(managed_path.clone()).expect("managed file");
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
@@ -1219,15 +1223,18 @@ async fn multi_agent_v2_boolean_layer_owns_enabled_origin_and_overrides() {
})
.await
.expect("read config");
assert_eq!(
read.origins
.get("features.multi_agent_v2.enabled")
.expect("enabled origin")
.name,
ApiConfigLayerSource::LegacyManagedConfigTomlFromFile {
file: managed_file.clone(),
},
);
for path in [
"features.multi_agent_v2.enabled",
"features.network_proxy",
"features.network_proxy.enabled",
] {
assert_eq!(
read.origins.get(path).expect("managed feature origin").name,
ApiConfigLayerSource::LegacyManagedConfigTomlFromFile {
file: managed_file.clone(),
},
);
}
let result = service
.write_value(ConfigValueWriteParams {
@@ -1248,6 +1255,109 @@ async fn multi_agent_v2_boolean_layer_owns_enabled_origin_and_overrides() {
assert_eq!(overridden.effective_value, serde_json::json!(false));
}
#[tokio::test]
async fn structured_feature_toggle_ignores_unrelated_managed_settings() -> Result<()> {
let tmp = tempdir()?;
let user_path = tmp.path().join(CONFIG_TOML_FILE);
std::fs::write(
&user_path,
"[features.network_proxy]\nenabled = false\ncredential_broker = true\n",
)?;
let managed_path = tmp.path().join("managed_config.toml");
std::fs::write(
&managed_path,
"[features.network_proxy]\nproxy_url = 'http://127.0.0.1:4321'\n",
)?;
let service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
LoaderOverrides::with_managed_config_path_for_tests(managed_path.clone()),
CloudConfigBundleLoader::default(),
);
service
.write_value(ConfigValueWriteParams {
file_path: Some(user_path.display().to_string()),
key_path: "features.network_proxy".to_string(),
value: serde_json::Value::Null,
merge_strategy: MergeStrategy::Replace,
expected_version: None,
})
.await?;
assert_eq!(
toml::from_str::<TomlValue>(&std::fs::read_to_string(&user_path)?)?,
toml::from_str::<TomlValue>(
"[features.network_proxy]\nenabled = false\ncredential_broker = true\n"
)?
);
let result = service
.write_value(ConfigValueWriteParams {
file_path: Some(user_path.display().to_string()),
key_path: "features.network_proxy".to_string(),
value: serde_json::json!(true),
merge_strategy: MergeStrategy::Replace,
expected_version: None,
})
.await?;
assert_eq!(result.status, WriteStatus::Ok);
assert_eq!(result.overridden_metadata, None);
let selected_path = tmp.path().join("work.config.toml");
std::fs::write(&selected_path, "")?;
let mut loader_overrides = LoaderOverrides::with_managed_config_path_for_tests(managed_path);
loader_overrides.user_config_path = Some(AbsolutePathBuf::from_absolute_path(&selected_path)?);
loader_overrides.user_config_profile = Some("work".parse()?);
let profile_service = ConfigManager::new_for_tests(
tmp.path().to_path_buf(),
vec![],
loader_overrides,
CloudConfigBundleLoader::default(),
);
profile_service
.write_value(ConfigValueWriteParams {
file_path: Some(selected_path.display().to_string()),
key_path: "features.network_proxy".to_string(),
value: serde_json::Value::Null,
merge_strategy: MergeStrategy::Replace,
expected_version: None,
})
.await?;
assert_eq!(
toml::from_str::<TomlValue>(&std::fs::read_to_string(&selected_path)?)?,
toml::from_str::<TomlValue>("[features]\nnetwork_proxy = false\n")?
);
service
.batch_write(ConfigBatchWriteParams {
edits: vec![
codex_app_server_protocol::ConfigEdit {
key_path: "features.network_proxy.credential_broker".to_string(),
value: serde_json::Value::Null,
merge_strategy: MergeStrategy::Replace,
},
codex_app_server_protocol::ConfigEdit {
key_path: "features.network_proxy".to_string(),
value: serde_json::Value::Null,
merge_strategy: MergeStrategy::Replace,
},
],
file_path: Some(user_path.display().to_string()),
expected_version: None,
reload_user_config: false,
})
.await?;
assert!(
toml::from_str::<TomlValue>(&std::fs::read_to_string(&user_path)?)?
.get("features")
.and_then(|features| features.get("network_proxy"))
.is_none()
);
Ok(())
}
#[tokio::test]
async fn upsert_merges_tables_replace_overwrites() -> Result<()> {
let tmp = tempdir().expect("tempdir");
@@ -1485,6 +1595,29 @@ subagent_usage_hint_text = "Delegate carefully."
serde_json::Value::Null,
"",
),
(
r#"[features]
network_proxy = true
"#,
"features.network_proxy.credential_broker",
serde_json::json!(true),
r#"[features.network_proxy]
enabled = true
credential_broker = true
"#,
),
(
r#"[features.network_proxy]
enabled = true
credential_broker = true
"#,
"features.network_proxy",
serde_json::json!(false),
r#"[features.network_proxy]
enabled = false
credential_broker = true
"#,
),
(
r#"[desktop.features.multi_agent_v2]
custom = true
@@ -1590,7 +1723,7 @@ inherit = "all"
exclude = [
"AWS_*", # keep this comment
]
set = { KEEP = "1", OTHER = "2" } # keep this inline table
set = { KEEP = "1", OTHER = "2", GH_HOST = "github.stale.example" } # keep this inline table
"#,
)?;
@@ -1612,9 +1745,32 @@ inherit = "core"
exclude = [
"AWS_*", # keep this comment
]
set = { KEEP = "1", OTHER = "2" } # keep this inline table
set = { KEEP = "1", OTHER = "2", GH_HOST = "github.stale.example" } # keep this inline table
"#
);
#[cfg(windows)]
{
service
.write_value(ConfigValueWriteParams {
file_path: Some(path.display().to_string()),
key_path: "shell_environment_policy.set.gh_host".to_string(),
value: serde_json::json!("github.trusted.example"),
merge_strategy: MergeStrategy::Upsert,
expected_version: None,
})
.await?;
let config: TomlValue = toml::from_str(&std::fs::read_to_string(&path)?)?;
let overrides = config
.get("shell_environment_policy")
.and_then(|policy| policy.get("set"))
.and_then(TomlValue::as_table)
.expect("environment overrides");
assert_eq!(
overrides.get("GH_HOST").and_then(TomlValue::as_str),
Some("github.trusted.example")
);
assert!(!overrides.contains_key("gh_host"));
}
service
.read(ConfigReadParams {
include_layers: false,
@@ -1723,6 +1879,7 @@ exclude = ["AWS_*"]
"#,
"shell_environment_policy.filters.AWS_*",
serde_json::json!("include"),
serde_json::Value::Null,
),
(
r#"[shell_environment_policy.filters]
@@ -1730,10 +1887,18 @@ exclude = ["AWS_*"]
"#,
"shell_environment_policy.exclude",
serde_json::json!(["AWS_*"]),
serde_json::Value::Null,
),
#[cfg(windows)]
(
"[shell_environment_policy.set]\nGH_HOST = 'github.managed.example'\n",
"shell_environment_policy.set.gh_host",
serde_json::json!("github.user.example"),
serde_json::json!("github.managed.example"),
),
];
for (managed, key_path, value) in cases {
for (managed, key_path, value, expected_effective_value) in cases {
let tmp = tempdir()?;
let path = tmp.path().join(CONFIG_TOML_FILE);
std::fs::write(&path, "")?;
@@ -1765,7 +1930,7 @@ exclude = ["AWS_*"]
overridden.overriding_layer.name,
ApiConfigLayerSource::LegacyManagedConfigTomlFromFile { file: managed_file }
);
assert_eq!(overridden.effective_value, serde_json::Value::Null);
assert_eq!(overridden.effective_value, expected_effective_value);
service
.read(ConfigReadParams {
include_layers: false,