Base: codex-main originale (prima del fork aKode)
This commit is contained in:
7
codex-rs/config/BUILD.bazel
Normal file
7
codex-rs/config/BUILD.bazel
Normal file
@@ -0,0 +1,7 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "config",
|
||||
compile_data = ["defaults.toml"],
|
||||
crate_name = "codex_config",
|
||||
)
|
||||
79
codex-rs/config/Cargo.toml
Normal file
79
codex-rs/config/Cargo.toml
Normal file
@@ -0,0 +1,79 @@
|
||||
[package]
|
||||
name = "codex-config"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[example]]
|
||||
name = "generate-proto"
|
||||
path = "examples/generate-proto.rs"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
base64 = { workspace = true }
|
||||
codex-execpolicy = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
codex-file-system = { workspace = true }
|
||||
codex-git-utils = { workspace = true }
|
||||
codex-http-client = { workspace = true }
|
||||
codex-model-provider-info = { workspace = true }
|
||||
codex-network-proxy = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-path = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
codex-utils-redacted-string = { workspace = true }
|
||||
dunce = { workspace = true }
|
||||
futures = { workspace = true, features = ["alloc", "std"] }
|
||||
gethostname = { workspace = true }
|
||||
indexmap = { workspace = true, features = ["serde"] }
|
||||
multimap = { workspace = true }
|
||||
prost = "0.14.3"
|
||||
regex-lite = { workspace = true }
|
||||
schemars = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_ignored = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
serde_path_to_error = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
tokio = { workspace = true, features = ["fs"] }
|
||||
tokio-util = { workspace = true, features = ["rt"] }
|
||||
toml = { workspace = true, features = ["preserve_order"] }
|
||||
toml_edit = { workspace = true }
|
||||
tonic = { workspace = true, features = ["tls-native-roots", "tls-ring"] }
|
||||
tonic-prost = { workspace = true }
|
||||
tracing = { workspace = true }
|
||||
wildmatch = { workspace = true }
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
dns-lookup = { workspace = true }
|
||||
libc = { workspace = true }
|
||||
|
||||
[target.'cfg(target_os = "macos")'.dependencies]
|
||||
core-foundation = "0.9"
|
||||
|
||||
[target.'cfg(target_os = "windows")'.dependencies]
|
||||
codex-windows-sandbox = { workspace = true }
|
||||
winapi-util = { workspace = true }
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_System_Com",
|
||||
"Win32_UI_Shell",
|
||||
] }
|
||||
winreg = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
test-case = "3.3.1"
|
||||
tokio = { workspace = true, features = ["full"] }
|
||||
tokio-stream = { workspace = true, features = ["net"] }
|
||||
tonic = { workspace = true, features = ["router", "transport"] }
|
||||
tonic-prost-build = { version = "=0.14.3", default-features = false, features = ["transport"] }
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
18
codex-rs/config/defaults.toml
Normal file
18
codex-rs/config/defaults.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
# Fixed defaults for packaged Codex clients.
|
||||
include_permissions_instructions = true
|
||||
include_apps_instructions = true
|
||||
include_collaboration_mode_instructions = true
|
||||
include_environment_context = true
|
||||
include_environment_context_time = true
|
||||
cli_auth_credentials_store = "file"
|
||||
mcp_oauth_credentials_store = "auto"
|
||||
project_doc_max_bytes = 32768
|
||||
project_doc_fallback_filenames = []
|
||||
background_terminal_max_timeout = 300000
|
||||
file_opener = "vscode"
|
||||
hide_agent_reasoning = false
|
||||
chatgpt_base_url = "https://chatgpt.com/backend-api/"
|
||||
project_root_markers = [".git"]
|
||||
|
||||
[history]
|
||||
persistence = "save-all"
|
||||
19
codex-rs/config/examples/generate-proto.rs
Normal file
19
codex-rs/config/examples/generate-proto.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let Some(proto_dir_arg) = std::env::args().nth(1) else {
|
||||
eprintln!("Usage: generate-proto <proto-dir>");
|
||||
std::process::exit(1);
|
||||
};
|
||||
|
||||
let proto_dir = PathBuf::from(proto_dir_arg);
|
||||
let proto_file = proto_dir.join("codex.thread_config.v1.proto");
|
||||
|
||||
tonic_prost_build::configure()
|
||||
.build_client(true)
|
||||
.build_server(true)
|
||||
.out_dir(&proto_dir)
|
||||
.compile_protos(&[proto_file], &[proto_dir])?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
38
codex-rs/config/scripts/generate-proto.sh
Executable file
38
codex-rs/config/scripts/generate-proto.sh
Executable file
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
repo_root="$(cd "$script_dir/../../.." && pwd)"
|
||||
proto_dir="$repo_root/codex-rs/config/src/thread_config/proto"
|
||||
generated="$proto_dir/codex.thread_config.v1.rs"
|
||||
tmpdir="$(mktemp -d)"
|
||||
|
||||
cleanup() {
|
||||
rm -rf "$tmpdir"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
(
|
||||
cd "$repo_root/codex-rs"
|
||||
CARGO_TARGET_DIR="$tmpdir/target" cargo run \
|
||||
-p codex-config \
|
||||
--example generate-proto \
|
||||
-- "$proto_dir"
|
||||
)
|
||||
|
||||
if ! sed -n '2p' "$generated" | grep -q 'clippy::trivially_copy_pass_by_ref'; then
|
||||
{
|
||||
sed -n '1p' "$generated"
|
||||
printf '#![allow(clippy::trivially_copy_pass_by_ref)]\n'
|
||||
sed '1d' "$generated"
|
||||
} > "$tmpdir/generated.rs"
|
||||
mv "$tmpdir/generated.rs" "$generated"
|
||||
fi
|
||||
|
||||
rustfmt --edition 2024 "$generated"
|
||||
|
||||
awk '
|
||||
NR == 3 && previous ~ /clippy::trivially_copy_pass_by_ref/ && $0 != "" { print "" }
|
||||
{ print; previous = $0 }
|
||||
' "$generated" > "$tmpdir/formatted.rs"
|
||||
mv "$tmpdir/formatted.rs" "$generated"
|
||||
73
codex-rs/config/src/application_requirements.rs
Normal file
73
codex-rs/config/src/application_requirements.rs
Normal file
@@ -0,0 +1,73 @@
|
||||
//! Managed application destinations are independent of agent network permissions.
|
||||
//! Enabled policies deny unlisted domains and use normal managed TOML precedence.
|
||||
|
||||
use crate::NetworkDomainPermissionToml;
|
||||
use serde::Deserialize;
|
||||
use serde::de::Error;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ApplicationRequirementsToml {
|
||||
pub network: Option<ApplicationNetworkRequirementsToml>,
|
||||
// Keep optional storage paths out of config-loading futures' inline state.
|
||||
pub storage: Option<Box<crate::ApplicationStorageRequirementsToml>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ApplicationNetworkRequirementsToml {
|
||||
pub enabled: bool,
|
||||
pub domains: BTreeMap<String, NetworkDomainPermissionToml>,
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ApplicationNetworkRequirementsToml {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Network {
|
||||
enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
domains: BTreeMap<String, NetworkDomainPermissionToml>,
|
||||
}
|
||||
|
||||
let raw = Network::deserialize(deserializer)?;
|
||||
let mut domains = BTreeMap::new();
|
||||
for (domain, permission) in raw.domains {
|
||||
let normalized = domain
|
||||
.strip_suffix('.')
|
||||
.unwrap_or(&domain)
|
||||
.to_ascii_lowercase();
|
||||
if normalized.len() > 253
|
||||
|| normalized.split('.').any(|label| {
|
||||
label.is_empty()
|
||||
|| label.len() > 63
|
||||
|| !label.starts_with(|c: char| c.is_ascii_alphanumeric())
|
||||
|| !label.ends_with(|c: char| c.is_ascii_alphanumeric())
|
||||
|| !label
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || c == b'-')
|
||||
})
|
||||
{
|
||||
return Err(D::Error::custom(
|
||||
"application.network.domains requires exact ASCII domain names without URLs, ports, or wildcards",
|
||||
));
|
||||
}
|
||||
if domains.insert(normalized, permission).is_some() {
|
||||
return Err(D::Error::custom(format!(
|
||||
"duplicate application.network domain after normalization: {domain:?}"
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
enabled: raw.enabled.unwrap_or(true),
|
||||
domains,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "application_requirements_tests.rs"]
|
||||
mod tests;
|
||||
252
codex-rs/config/src/application_requirements_tests.rs
Normal file
252
codex-rs/config/src/application_requirements_tests.rs
Normal file
@@ -0,0 +1,252 @@
|
||||
//! Application requirements use managed precedence and deny unlisted destinations.
|
||||
|
||||
use super::*;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::ConfigRequirementsWithSources;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::Sourced;
|
||||
use crate::compose_requirements_for_hostname;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
const INSTALLATION: &str = r#"
|
||||
[application.network.domains]
|
||||
"shared.example.com" = "allow"
|
||||
"installed.example.com" = "allow"
|
||||
"blocked.example.com" = "deny"
|
||||
"#;
|
||||
const WORKSPACE: &str = r#"
|
||||
[application.network.domains]
|
||||
"shared.example.com" = "allow"
|
||||
"workspace.example.com" = "allow"
|
||||
"blocked.example.com" = "allow"
|
||||
"#;
|
||||
const MERGED: &str = r#"
|
||||
[application.network.domains]
|
||||
"shared.example.com" = "allow"
|
||||
"installed.example.com" = "allow"
|
||||
"workspace.example.com" = "allow"
|
||||
"blocked.example.com" = "allow"
|
||||
"#;
|
||||
|
||||
fn parse(contents: &str) -> ConfigRequirementsToml {
|
||||
toml::from_str(contents).expect("valid application requirements")
|
||||
}
|
||||
|
||||
fn cloud_source() -> RequirementSource {
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: "workspace".to_string(),
|
||||
name: "Workspace policy".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn managed_source() -> RequirementSource {
|
||||
RequirementSource::MdmManagedPreferences {
|
||||
domain: "com.openai.codex".to_string(),
|
||||
key: "requirements".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_network_defaults_to_enabled_and_denies_unlisted_domains() {
|
||||
assert!(parse("[application]").is_empty());
|
||||
let requirements = parse("[application.network]");
|
||||
assert!(!requirements.is_empty());
|
||||
assert_eq!(
|
||||
requirements.application,
|
||||
Some(ApplicationRequirementsToml {
|
||||
storage: None,
|
||||
network: Some(ApplicationNetworkRequirementsToml {
|
||||
enabled: true,
|
||||
domains: BTreeMap::new(),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
assert_eq!(
|
||||
parse("[application.network.domains]\n\"EXAMPLE.com.\" = \"deny\""),
|
||||
parse("[application.network.domains]\n\"example.com\" = \"deny\""),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_network_is_preserved_from_each_managed_source() {
|
||||
for source in [
|
||||
RequirementSource::SystemRequirementsToml {
|
||||
file: crate::AbsolutePathBuf::try_from(std::env::temp_dir().join("requirements.toml"))
|
||||
.expect("absolute requirements path"),
|
||||
},
|
||||
managed_source(),
|
||||
cloud_source(),
|
||||
] {
|
||||
let requirements = compose_requirements_for_hostname(
|
||||
[RequirementsLayerEntry::from_toml(
|
||||
source.clone(),
|
||||
INSTALLATION,
|
||||
)],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
.expect("compose application requirements")
|
||||
.expect("application requirements are not empty");
|
||||
assert_eq!(
|
||||
requirements,
|
||||
ConfigRequirementsWithSources {
|
||||
application: Some(Sourced::new(
|
||||
parse(INSTALLATION).application.expect("application"),
|
||||
source,
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let normalized: ConfigRequirements =
|
||||
requirements.clone().try_into().expect("runtime policy");
|
||||
assert_eq!(normalized.application, requirements.application);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn application_network_uses_regular_toml_precedence() {
|
||||
let installed_wins = MERGED.replace(
|
||||
"\"blocked.example.com\" = \"allow\"",
|
||||
"\"blocked.example.com\" = \"deny\"",
|
||||
);
|
||||
let disabled_installation = format!("[application.network]\nenabled = false\n{INSTALLATION}");
|
||||
for (low, high, expected) in [
|
||||
(INSTALLATION, WORKSPACE, MERGED),
|
||||
(WORKSPACE, INSTALLATION, installed_wins.as_str()),
|
||||
(
|
||||
INSTALLATION,
|
||||
"[application.network]\nenabled = false",
|
||||
disabled_installation.as_str(),
|
||||
),
|
||||
(
|
||||
disabled_installation.as_str(),
|
||||
"[application.network]\nenabled = true",
|
||||
INSTALLATION,
|
||||
),
|
||||
(
|
||||
"[application.network]\nenabled = false",
|
||||
INSTALLATION,
|
||||
disabled_installation.as_str(),
|
||||
),
|
||||
(INSTALLATION, "[application.network]", INSTALLATION),
|
||||
(INSTALLATION, "", INSTALLATION),
|
||||
("[application]", INSTALLATION, INSTALLATION),
|
||||
("[application.network]", WORKSPACE, WORKSPACE),
|
||||
(
|
||||
"[application.network.domains]\n'example.com' = 'allow'",
|
||||
"[application.network.domains]\n'EXAMPLE.COM.' = 'deny'",
|
||||
"[application.network.domains]\n'example.com' = 'deny'",
|
||||
),
|
||||
(
|
||||
"[application.network.domains]\n'EXAMPLE.COM.' = 'deny'",
|
||||
"[application.network.domains]\n'example.com' = 'allow'",
|
||||
"[application.network.domains]\n'example.com' = 'allow'",
|
||||
),
|
||||
] {
|
||||
let composed = compose_requirements_for_hostname(
|
||||
[
|
||||
RequirementsLayerEntry::from_toml(managed_source(), low),
|
||||
RequirementsLayerEntry::from_toml(cloud_source(), high),
|
||||
],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
.expect("compose application requirements")
|
||||
.expect("configured requirements");
|
||||
assert_eq!(
|
||||
composed.into_toml(),
|
||||
parse(expected),
|
||||
"low: {low}, high: {high}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_application_merge_uses_whole_table_precedence() {
|
||||
for (high, low) in [
|
||||
(INSTALLATION, WORKSPACE),
|
||||
(WORKSPACE, INSTALLATION),
|
||||
("[application.network]\nenabled = false", INSTALLATION),
|
||||
("[application]", INSTALLATION),
|
||||
] {
|
||||
let mut composed = ConfigRequirementsWithSources::default();
|
||||
composed.merge_unset_fields(managed_source(), parse(high));
|
||||
composed.merge_unset_fields(cloud_source(), parse(low));
|
||||
assert_eq!(
|
||||
composed,
|
||||
ConfigRequirementsWithSources {
|
||||
application: Some(Sourced::new(
|
||||
parse(high).application.expect("application"),
|
||||
managed_source(),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut composed = ConfigRequirementsWithSources::default();
|
||||
composed.merge_unset_fields(managed_source(), parse(""));
|
||||
composed.merge_unset_fields(cloud_source(), parse(INSTALLATION));
|
||||
assert_eq!(composed.into_toml(), parse(INSTALLATION));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_application_policy_is_rejected_before_layer_overrides() {
|
||||
for invalid in [
|
||||
"[application.network]\nenabled = 'true'",
|
||||
"[application.network]\nallowed_domains = ['example.com']",
|
||||
"[application.network.domains]\n'example.com' = 'prompt'",
|
||||
"[application.network.domains]\n'*.example.com' = 'allow'",
|
||||
"[application.network.domains]\n'https://example.com' = 'allow'",
|
||||
"[application.network.domains]\n'example.com:443' = 'allow'",
|
||||
"[application.network.domains]\n'example..com' = 'allow'",
|
||||
"[application.network.domains]\n' example.com' = 'allow'",
|
||||
"[application.network.domains]\n'EXAMPLE.com' = 'allow'\n'example.com.' = 'deny'",
|
||||
] {
|
||||
assert!(
|
||||
toml::from_str::<ConfigRequirementsToml>(invalid).is_err(),
|
||||
"{invalid}"
|
||||
);
|
||||
assert!(
|
||||
compose_requirements_for_hostname(
|
||||
[
|
||||
RequirementsLayerEntry::from_toml(cloud_source(), invalid),
|
||||
RequirementsLayerEntry::from_toml(managed_source(), INSTALLATION),
|
||||
],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
.is_err(),
|
||||
"{invalid}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_bundle_application_network_uses_managed_precedence() {
|
||||
let base_dir =
|
||||
crate::AbsolutePathBuf::try_from(std::env::temp_dir()).expect("absolute base directory");
|
||||
let bundle = crate::CloudConfigBundle {
|
||||
requirements_toml: crate::CloudRequirementsTomlBundle {
|
||||
enterprise_managed: vec![crate::CloudRequirementsFragment {
|
||||
id: "workspace".to_string(),
|
||||
name: "Workspace".to_string(),
|
||||
contents: WORKSPACE.to_string(),
|
||||
}],
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let mut layers = crate::CloudConfigBundleLayers::from_bundle(bundle, &base_dir)
|
||||
.expect("load cloud bundle")
|
||||
.enterprise_managed_requirements;
|
||||
layers.push(RequirementsLayerEntry::from_toml(
|
||||
managed_source(),
|
||||
INSTALLATION,
|
||||
));
|
||||
let composed = compose_requirements_for_hostname(layers, /*hostname*/ None)
|
||||
.expect("compose cloud and installation requirements")
|
||||
.expect("requirements");
|
||||
let expected = MERGED.replace(
|
||||
"\"blocked.example.com\" = \"allow\"",
|
||||
"\"blocked.example.com\" = \"deny\"",
|
||||
);
|
||||
assert_eq!(composed.into_toml(), parse(&expected));
|
||||
}
|
||||
74
codex-rs/config/src/application_storage_requirements.rs
Normal file
74
codex-rs/config/src/application_storage_requirements.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
//! Managed locations for newly created Desktop workspaces. These requirements
|
||||
//! fix the storage settings; they do not restrict access to other directories.
|
||||
|
||||
use crate::AbsolutePathBuf;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ApplicationStorageRequirementsToml {
|
||||
#[serde(default, deserialize_with = "deserialize_absolute_path")]
|
||||
pub default_project_parent: Option<AbsolutePathBuf>,
|
||||
#[serde(default, deserialize_with = "deserialize_absolute_path")]
|
||||
pub projectless_workspace_root: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
impl ApplicationStorageRequirementsToml {
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.default_project_parent.is_none() && self.projectless_workspace_root.is_none()
|
||||
}
|
||||
|
||||
pub(crate) fn apply_to_config(&self, config: &mut ConfigToml) {
|
||||
for (key, path) in [
|
||||
("defaultProjectParent", &self.default_project_parent),
|
||||
("projectlessWorkspaceRoot", &self.projectless_workspace_root),
|
||||
] {
|
||||
if let Some(path) = path {
|
||||
config.desktop.get_or_insert_default().insert(
|
||||
key.to_string(),
|
||||
Value::String(path.to_string_lossy().into_owned()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn exact_requirement_for_config_path(
|
||||
&self,
|
||||
segments: &[String],
|
||||
) -> Option<&'static str> {
|
||||
[
|
||||
(
|
||||
self.default_project_parent.is_some(),
|
||||
"defaultProjectParent",
|
||||
"desktop.defaultProjectParent",
|
||||
),
|
||||
(
|
||||
self.projectless_workspace_root.is_some(),
|
||||
"projectlessWorkspaceRoot",
|
||||
"desktop.projectlessWorkspaceRoot",
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.find_map(|(managed, key, name)| {
|
||||
let path = ["desktop", key];
|
||||
(managed && segments.iter().zip(path).all(|(left, right)| left == right))
|
||||
.then_some(name)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "application_storage_requirements_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
// Requirements must not resolve relative to a machine-specific config directory.
|
||||
fn deserialize_absolute_path<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<Option<AbsolutePathBuf>, D::Error> {
|
||||
let path = std::path::PathBuf::deserialize(deserializer)?;
|
||||
AbsolutePathBuf::from_absolute_path_checked(path)
|
||||
.map(Some)
|
||||
.map_err(serde::de::Error::custom)
|
||||
}
|
||||
170
codex-rs/config/src/application_storage_requirements_tests.rs
Normal file
170
codex-rs/config/src/application_storage_requirements_tests.rs
Normal file
@@ -0,0 +1,170 @@
|
||||
//! Exercises managed storage projection, validation, and cloud layer precedence.
|
||||
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
/// Managed paths override local preferences without replacing unrelated desktop settings.
|
||||
#[test]
|
||||
fn storage_requirements_project_and_protect_only_managed_settings() {
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let parent = home.path().join("projects");
|
||||
let scratch = home.path().join("scratch");
|
||||
let requirements: ConfigRequirementsToml = toml::from_str(&format!(
|
||||
"[application.storage]\ndefault_project_parent = '{}'\nprojectless_workspace_root = '{}'\n",
|
||||
parent.display(),
|
||||
scratch.display()
|
||||
))
|
||||
.unwrap();
|
||||
let mut config: ConfigToml = toml::from_str(
|
||||
"[desktop]\ndefaultProjectParent = 'local'\nprojectlessWorkspaceRoot = 'local'\nlocaleOverride = 'fr-FR'"
|
||||
).unwrap();
|
||||
requirements.apply_exact_to_config(&mut config);
|
||||
assert_eq!(
|
||||
serde_json::to_value(config.desktop).unwrap(),
|
||||
json!({
|
||||
"defaultProjectParent": parent,
|
||||
"projectlessWorkspaceRoot": scratch,
|
||||
"localeOverride": "fr-FR"
|
||||
})
|
||||
);
|
||||
for (segments, expected) in [
|
||||
(vec![], Some("desktop.defaultProjectParent")),
|
||||
(vec!["desktop"], Some("desktop.defaultProjectParent")),
|
||||
(
|
||||
vec!["desktop", "defaultProjectParent"],
|
||||
Some("desktop.defaultProjectParent"),
|
||||
),
|
||||
(
|
||||
vec!["desktop", "projectlessWorkspaceRoot"],
|
||||
Some("desktop.projectlessWorkspaceRoot"),
|
||||
),
|
||||
(vec!["desktop", "localeOverride"], None),
|
||||
(vec!["model"], None),
|
||||
] {
|
||||
let segments = segments.into_iter().map(str::to_owned).collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
requirements.exact_requirement_for_config_path(&segments),
|
||||
expected
|
||||
);
|
||||
}
|
||||
assert!(!requirements.is_empty());
|
||||
}
|
||||
|
||||
/// Invalid managed paths must fail parsing rather than silently selecting Documents.
|
||||
#[test]
|
||||
fn storage_requirements_reject_relative_paths_and_non_path_values() {
|
||||
for contents in [
|
||||
"[application.storage]\ndefault_project_parent = 'relative'",
|
||||
"[application.storage]\nprojectless_workspace_root = 'relative'",
|
||||
"[application.storage]\ndefault_project_parent = false",
|
||||
"[application.storage]\ndefault_project_parent = '${HOME}/Codex'",
|
||||
] {
|
||||
assert!(toml::from_str::<ConfigRequirementsToml>(contents).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
/// Misspelled policy keys must not silently leave storage unmanaged.
|
||||
#[test]
|
||||
fn storage_requirements_reject_unknown_keys() {
|
||||
for key in ["default_project_parrent", "projectless_workspace_rot"] {
|
||||
let contents = format!("[application.storage]\n{key} = 'ignored'");
|
||||
let error = toml::from_str::<ConfigRequirementsToml>(&contents).unwrap_err();
|
||||
assert!(error.message().contains(&format!("unknown field `{key}`")));
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloud fragments merge per setting without losing independent fields from lower-priority layers.
|
||||
#[test]
|
||||
fn cloud_storage_layers_preserve_independent_fields_and_precedence() {
|
||||
use crate::AbsolutePathBuf;
|
||||
use crate::CloudConfigBundle;
|
||||
use crate::CloudConfigBundleLayers;
|
||||
use crate::CloudRequirementsFragment;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements;
|
||||
let home = tempfile::tempdir().unwrap();
|
||||
let base = AbsolutePathBuf::from_absolute_path(home.path()).unwrap();
|
||||
let projects = home.path().join("projects");
|
||||
let chats = home.path().join("chats");
|
||||
let local = home.path().join("local");
|
||||
let mut bundle = CloudConfigBundle::default();
|
||||
bundle.requirements_toml.enterprise_managed = vec![
|
||||
CloudRequirementsFragment {
|
||||
id: "high".into(),
|
||||
name: "Projects".into(),
|
||||
contents: format!(
|
||||
"[application.network]\nenabled = false\n[application.storage]\ndefault_project_parent = '{}'",
|
||||
projects.display()
|
||||
),
|
||||
},
|
||||
CloudRequirementsFragment {
|
||||
id: "low".into(),
|
||||
name: "Storage".into(),
|
||||
contents: format!(
|
||||
"[application.storage]\ndefault_project_parent = '{}'\nprojectless_workspace_root = '{}'",
|
||||
home.path().display(),
|
||||
chats.display()
|
||||
),
|
||||
},
|
||||
];
|
||||
let mut layers = CloudConfigBundleLayers::from_bundle(bundle, &base)
|
||||
.unwrap()
|
||||
.enterprise_managed_requirements;
|
||||
let requirements = compose_requirements(layers.clone())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.into_toml();
|
||||
assert!(
|
||||
!requirements
|
||||
.application
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.network
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
assert_eq!(
|
||||
requirements
|
||||
.application
|
||||
.unwrap()
|
||||
.storage
|
||||
.map(|storage| *storage),
|
||||
Some(super::ApplicationStorageRequirementsToml {
|
||||
default_project_parent: Some(AbsolutePathBuf::from_absolute_path(&projects).unwrap()),
|
||||
projectless_workspace_root: Some(AbsolutePathBuf::from_absolute_path(&chats).unwrap()),
|
||||
})
|
||||
);
|
||||
layers.push(RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
format!(
|
||||
"[application.storage]\ndefault_project_parent = '{}'",
|
||||
local.display()
|
||||
),
|
||||
));
|
||||
let requirements = compose_requirements(layers).unwrap().unwrap().into_toml();
|
||||
assert!(
|
||||
!requirements
|
||||
.application
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.network
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.enabled
|
||||
);
|
||||
assert_eq!(
|
||||
requirements
|
||||
.application
|
||||
.unwrap()
|
||||
.storage
|
||||
.map(|storage| *storage),
|
||||
Some(super::ApplicationStorageRequirementsToml {
|
||||
default_project_parent: Some(AbsolutePathBuf::from_absolute_path(local).unwrap()),
|
||||
projectless_workspace_root: Some(AbsolutePathBuf::from_absolute_path(chats).unwrap()),
|
||||
})
|
||||
);
|
||||
}
|
||||
61
codex-rs/config/src/auth_policy.rs
Normal file
61
codex-rs/config/src/auth_policy.rs
Normal file
@@ -0,0 +1,61 @@
|
||||
use codex_protocol::config_types::ForcedLoginMethod;
|
||||
|
||||
/// Authentication restrictions supplied by locally managed requirements.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ManagedAuthPolicy {
|
||||
pub allowed_login_methods: Option<Vec<ForcedLoginMethod>>,
|
||||
pub allowed_chatgpt_workspaces: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
impl ManagedAuthPolicy {
|
||||
pub fn allows_login_method(
|
||||
&self,
|
||||
method: ForcedLoginMethod,
|
||||
forced_login_method: Option<ForcedLoginMethod>,
|
||||
forced_workspaces: Option<&[String]>,
|
||||
) -> bool {
|
||||
forced_login_method.is_none_or(|forced| forced == method)
|
||||
&& self
|
||||
.allowed_login_methods
|
||||
.as_ref()
|
||||
.is_none_or(|allowed| allowed.contains(&method))
|
||||
&& (method != ForcedLoginMethod::Chatgpt
|
||||
|| self
|
||||
.effective_chatgpt_workspaces(forced_workspaces)
|
||||
.is_none_or(|workspaces| !workspaces.is_empty()))
|
||||
}
|
||||
|
||||
pub fn allowed_login_methods(
|
||||
&self,
|
||||
forced_login_method: Option<ForcedLoginMethod>,
|
||||
forced_workspaces: Option<&[String]>,
|
||||
) -> Vec<ForcedLoginMethod> {
|
||||
[ForcedLoginMethod::Api, ForcedLoginMethod::Chatgpt]
|
||||
.into_iter()
|
||||
.filter(|method| {
|
||||
self.allows_login_method(*method, forced_login_method, forced_workspaces)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn effective_chatgpt_workspaces(
|
||||
&self,
|
||||
forced_workspaces: Option<&[String]>,
|
||||
) -> Option<Vec<String>> {
|
||||
match (
|
||||
forced_workspaces,
|
||||
self.allowed_chatgpt_workspaces.as_deref(),
|
||||
) {
|
||||
(Some(forced), Some(allowed)) => Some(
|
||||
forced
|
||||
.iter()
|
||||
.filter(|workspace| allowed.contains(workspace))
|
||||
.cloned()
|
||||
.collect(),
|
||||
),
|
||||
(Some(forced), None) => Some(forced.to_vec()),
|
||||
(None, Some(allowed)) => Some(allowed.to_vec()),
|
||||
(None, None) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
48
codex-rs/config/src/bedrock_runtime_tests.rs
Normal file
48
codex-rs/config/src/bedrock_runtime_tests.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use codex_model_provider_info::AMAZON_BEDROCK_RUNTIME_PROVIDER_ID;
|
||||
use codex_model_provider_info::ModelProviderAwsAuthInfo;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::ConfigToml;
|
||||
|
||||
#[test]
|
||||
fn runtime_provider_accepts_aws_profile_and_region_overrides() {
|
||||
let config = toml::from_str::<ConfigToml>(
|
||||
r#"
|
||||
[model_providers.amazon-bedrock-runtime.aws]
|
||||
profile = "runtime-profile"
|
||||
region = "us-west-2"
|
||||
"#,
|
||||
)
|
||||
.expect("Bedrock Runtime AWS overrides should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
config
|
||||
.model_providers
|
||||
.get(AMAZON_BEDROCK_RUNTIME_PROVIDER_ID)
|
||||
.and_then(|provider| provider.aws.clone()),
|
||||
Some(ModelProviderAwsAuthInfo {
|
||||
profile: Some("runtime-profile".to_string()),
|
||||
region: Some("us-west-2".to_string()),
|
||||
credential_export: None,
|
||||
auth_refresh: None,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_provider_still_rejects_aws_auth() {
|
||||
let error = toml::from_str::<ConfigToml>(
|
||||
r#"
|
||||
[model_providers.custom]
|
||||
name = "Custom"
|
||||
|
||||
[model_providers.custom.aws]
|
||||
region = "us-west-2"
|
||||
"#,
|
||||
)
|
||||
.expect_err("custom providers must not accept AWS auth");
|
||||
|
||||
assert!(error.to_string().contains(
|
||||
"provider aws is only supported for `amazon-bedrock` or `amazon-bedrock-runtime`"
|
||||
));
|
||||
}
|
||||
141
codex-rs/config/src/browser_computer_use_requirements.rs
Normal file
141
codex-rs/config/src/browser_computer_use_requirements.rs
Normal file
@@ -0,0 +1,141 @@
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AllowDenyRequirementToml {
|
||||
Allow,
|
||||
Deny,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct BrowserUseOriginPolicyToml {
|
||||
pub access: Option<AllowDenyRequirementToml>,
|
||||
pub downloads: Option<AllowDenyRequirementToml>,
|
||||
pub uploads: Option<AllowDenyRequirementToml>,
|
||||
pub full_cdp_access: Option<AllowDenyRequirementToml>,
|
||||
pub auto_review: Option<AllowDenyRequirementToml>,
|
||||
pub persistent_approval: Option<bool>,
|
||||
pub access_approval_lifetime: Option<BrowserUseAccessApprovalLifetimeToml>,
|
||||
}
|
||||
|
||||
impl BrowserUseOriginPolicyToml {
|
||||
fn is_empty(&self) -> bool {
|
||||
self.access.is_none()
|
||||
&& self.downloads.is_none()
|
||||
&& self.uploads.is_none()
|
||||
&& self.full_cdp_access.is_none()
|
||||
&& self.auto_review.is_none()
|
||||
&& self.persistent_approval.is_none()
|
||||
&& self.access_approval_lifetime.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum BrowserUseAccessApprovalLifetimeToml {
|
||||
Turn,
|
||||
Thread,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct BrowserUseRequirementsToml {
|
||||
pub extension: Option<BrowserUseExtensionRequirementsToml>,
|
||||
pub allow_webmcp: Option<bool>,
|
||||
pub allow_history_access: Option<bool>,
|
||||
pub disable_auto_review: Option<bool>,
|
||||
pub allow_global_persistent_approval: Option<bool>,
|
||||
pub default_origin_policy: Option<BrowserUseOriginPolicyToml>,
|
||||
pub origins: Option<BTreeMap<String, BrowserUseOriginPolicyToml>>,
|
||||
}
|
||||
|
||||
impl BrowserUseRequirementsToml {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.extension
|
||||
.as_ref()
|
||||
.is_none_or(|extension| extension.request_headers.is_none())
|
||||
&& self.allow_webmcp.is_none()
|
||||
&& self.allow_history_access.is_none()
|
||||
&& self.disable_auto_review.is_none()
|
||||
&& self.allow_global_persistent_approval.is_none()
|
||||
&& self
|
||||
.default_origin_policy
|
||||
.as_ref()
|
||||
.is_none_or(BrowserUseOriginPolicyToml::is_empty)
|
||||
&& self
|
||||
.origins
|
||||
.as_ref()
|
||||
.is_none_or(|origins| origins.values().all(BrowserUseOriginPolicyToml::is_empty))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct BrowserUseExtensionRequirementsToml {
|
||||
pub request_headers: Option<Vec<RequestHeaderToml>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, PartialEq, Eq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RequestHeaderToml {
|
||||
pub name: String,
|
||||
pub value: String,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RequestHeaderToml {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RequestHeaderToml")
|
||||
.field("name", &self.name)
|
||||
.field("value", &"[REDACTED]")
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ComputerUseMacosRequirementsToml {
|
||||
pub bundle_ids: Option<BTreeMap<String, AllowDenyRequirementToml>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ComputerUseWindowsRequirementsToml {
|
||||
pub aumids: Option<BTreeMap<String, AllowDenyRequirementToml>>,
|
||||
pub exes: Option<Vec<ComputerUseWindowsExeRequirementToml>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ComputerUseWindowsExeRequirementToml {
|
||||
pub publisher_name: String,
|
||||
pub product_name: String,
|
||||
pub binary_name: Option<String>,
|
||||
pub access: AllowDenyRequirementToml,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ComputerUseRequirementsToml {
|
||||
pub allow_locked_computer_use: Option<bool>,
|
||||
pub allow_persistent_approval: Option<bool>,
|
||||
pub default_app_access: Option<AllowDenyRequirementToml>,
|
||||
pub macos: Option<ComputerUseMacosRequirementsToml>,
|
||||
pub windows: Option<ComputerUseWindowsRequirementsToml>,
|
||||
}
|
||||
|
||||
impl ComputerUseRequirementsToml {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.allow_locked_computer_use.is_none()
|
||||
&& self.allow_persistent_approval.is_none()
|
||||
&& self.default_app_access.is_none()
|
||||
&& self
|
||||
.macos
|
||||
.as_ref()
|
||||
.is_none_or(|macos| macos.bundle_ids.as_ref().is_none_or(BTreeMap::is_empty))
|
||||
&& self.windows.as_ref().is_none_or(|windows| {
|
||||
windows.aumids.as_ref().is_none_or(BTreeMap::is_empty)
|
||||
&& windows.exes.as_ref().is_none_or(Vec::is_empty)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "browser_computer_use_requirements_tests.rs"]
|
||||
mod tests;
|
||||
136
codex-rs/config/src/browser_computer_use_requirements_tests.rs
Normal file
136
codex-rs/config/src/browser_computer_use_requirements_tests.rs
Normal file
@@ -0,0 +1,136 @@
|
||||
use crate::BrowserUseRequirementsToml;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn webmcp_requirements_preserve_explicit_values_and_omission() {
|
||||
for (contents, expected_browser_use, expected_empty) in [
|
||||
("", None, true),
|
||||
("[browser_use]", Some(None), true),
|
||||
(
|
||||
"[browser_use]\nallow_webmcp = true",
|
||||
Some(Some(true)),
|
||||
false,
|
||||
),
|
||||
(
|
||||
"[browser_use]\nallow_webmcp = false",
|
||||
Some(Some(false)),
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let requirements: ConfigRequirementsToml =
|
||||
toml::from_str(contents).expect("parse managed WebMCP policy");
|
||||
assert_eq!(
|
||||
requirements,
|
||||
ConfigRequirementsToml {
|
||||
browser_use: expected_browser_use.map(|allow_webmcp| BrowserUseRequirementsToml {
|
||||
allow_webmcp,
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(requirements.is_empty(), expected_empty, "{contents}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn webmcp_requirements_reject_non_booleans() {
|
||||
for value in ["\"true\"", "1", "[]"] {
|
||||
let contents = format!("[browser_use]\nallow_webmcp = {value}");
|
||||
let error = toml::from_str::<ConfigRequirementsToml>(&contents)
|
||||
.expect_err("WebMCP policy must be a boolean");
|
||||
assert!(error.to_string().contains("allow_webmcp"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_headers_preserve_templates_and_explicit_disablement() {
|
||||
for (value, expected) in [
|
||||
("[]", vec![]),
|
||||
(
|
||||
r#"[{name = "x-browser-agent", value = "ChatGPT/{{session_id}}"}]"#,
|
||||
vec![crate::RequestHeaderToml {
|
||||
name: "x-browser-agent".into(),
|
||||
value: "ChatGPT/{{session_id}}".into(),
|
||||
}],
|
||||
),
|
||||
] {
|
||||
let requirements: ConfigRequirementsToml = toml::from_str(&format!(
|
||||
"[browser_use.extension]\nrequest_headers = {value}"
|
||||
))
|
||||
.unwrap();
|
||||
assert!(!requirements.is_empty());
|
||||
assert_eq!(
|
||||
requirements
|
||||
.browser_use
|
||||
.unwrap()
|
||||
.extension
|
||||
.unwrap()
|
||||
.request_headers,
|
||||
Some(expected)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_headers_reject_malformed_entries() {
|
||||
for value in [
|
||||
"true",
|
||||
r#"[{name = "x-test"}]"#,
|
||||
r#"[{name = "x-test", value = 1}]"#,
|
||||
r#"[{name = "x-test", value = "ok", typo = true}]"#,
|
||||
] {
|
||||
assert!(
|
||||
toml::from_str::<ConfigRequirementsToml>(&format!(
|
||||
"[browser_use.extension]\nrequest_headers = {value}"
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extension_headers_remain_scoped_to_extension() {
|
||||
let extension = r#"[browser_use.extension]
|
||||
request_headers = [{ name = "x-extension", value = "{{session_id}}" }]"#;
|
||||
let other = r#"[browser_use.iab]
|
||||
request_headers = [{ name = "x-iab", value = "future" }]"#;
|
||||
let expected: ConfigRequirementsToml = toml::from_str(extension).unwrap();
|
||||
let combined: ConfigRequirementsToml =
|
||||
toml::from_str(&format!("{extension}\n{other}")).unwrap();
|
||||
assert_eq!(combined, expected);
|
||||
for contents in [other, "[browser_use.extension]"] {
|
||||
let requirements: ConfigRequirementsToml = toml::from_str(contents).unwrap();
|
||||
assert!(requirements.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_header_debug_redacts_values_in_parent_requirements() {
|
||||
let requirements: ConfigRequirementsToml = toml::from_str(
|
||||
r#"[browser_use.extension]
|
||||
request_headers = [{ name = "x-company-token", value = "private-header-token" }]"#,
|
||||
)
|
||||
.unwrap();
|
||||
let header = &requirements
|
||||
.browser_use
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.extension
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.request_headers
|
||||
.as_ref()
|
||||
.unwrap()[0];
|
||||
assert_eq!(header.value, "private-header-token");
|
||||
assert_eq!(
|
||||
format!("{header:?}"),
|
||||
r#"RequestHeaderToml { name: "x-company-token", value: "[REDACTED]" }"#
|
||||
);
|
||||
for debug in [format!("{requirements:?}"), format!("{requirements:#?}")] {
|
||||
assert!(!debug.contains("private-header-token"));
|
||||
assert!(debug.contains("x-company-token"));
|
||||
assert!(debug.contains("[REDACTED]"));
|
||||
}
|
||||
}
|
||||
26
codex-rs/config/src/browser_use.rs
Normal file
26
codex-rs/config/src/browser_use.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
use crate::AllowDenyRequirementToml;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct BrowserUseConfigToml {
|
||||
pub allow_history_access: Option<bool>,
|
||||
pub default_origin_policy: Option<BrowserUseOriginPolicyConfigToml>,
|
||||
pub origins: Option<BTreeMap<String, BrowserUseOriginPolicyConfigToml>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct BrowserUseOriginPolicyConfigToml {
|
||||
pub access: Option<AllowDenyRequirementToml>,
|
||||
pub downloads: Option<AllowDenyRequirementToml>,
|
||||
pub uploads: Option<AllowDenyRequirementToml>,
|
||||
pub full_cdp_access: Option<AllowDenyRequirementToml>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "browser_use_tests.rs"]
|
||||
mod tests;
|
||||
52
codex-rs/config/src/browser_use_tests.rs
Normal file
52
codex-rs/config/src/browser_use_tests.rs
Normal file
@@ -0,0 +1,52 @@
|
||||
use super::*;
|
||||
use crate::AllowDenyRequirementToml;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn browser_use_origin_policies_round_trip() {
|
||||
let config: ConfigToml = toml::from_str(
|
||||
r#"
|
||||
[browser_use]
|
||||
allow_history_access = true
|
||||
|
||||
[browser_use.default_origin_policy]
|
||||
access = "deny"
|
||||
downloads = "allow"
|
||||
uploads = "deny"
|
||||
full_cdp_access = "allow"
|
||||
|
||||
[browser_use.origins."https://example.com"]
|
||||
access = "allow"
|
||||
downloads = "deny"
|
||||
uploads = "allow"
|
||||
full_cdp_access = "deny"
|
||||
"#,
|
||||
)
|
||||
.expect("browser use config should deserialize");
|
||||
|
||||
let expected = BrowserUseConfigToml {
|
||||
allow_history_access: Some(true),
|
||||
default_origin_policy: Some(BrowserUseOriginPolicyConfigToml {
|
||||
access: Some(AllowDenyRequirementToml::Deny),
|
||||
downloads: Some(AllowDenyRequirementToml::Allow),
|
||||
uploads: Some(AllowDenyRequirementToml::Deny),
|
||||
full_cdp_access: Some(AllowDenyRequirementToml::Allow),
|
||||
}),
|
||||
origins: Some(BTreeMap::from([(
|
||||
"https://example.com".to_string(),
|
||||
BrowserUseOriginPolicyConfigToml {
|
||||
access: Some(AllowDenyRequirementToml::Allow),
|
||||
downloads: Some(AllowDenyRequirementToml::Deny),
|
||||
uploads: Some(AllowDenyRequirementToml::Allow),
|
||||
full_cdp_access: Some(AllowDenyRequirementToml::Deny),
|
||||
},
|
||||
)])),
|
||||
};
|
||||
assert_eq!(config.browser_use, Some(expected.clone()));
|
||||
|
||||
let serialized = toml::to_string(&config).expect("browser use config should serialize");
|
||||
let reparsed: ConfigToml =
|
||||
toml::from_str(&serialized).expect("serialized browser use config should deserialize");
|
||||
assert_eq!(reparsed.browser_use, Some(expected));
|
||||
}
|
||||
528
codex-rs/config/src/cloud_config_bundle.rs
Normal file
528
codex-rs/config/src/cloud_config_bundle.rs
Normal file
@@ -0,0 +1,528 @@
|
||||
//! Cloud config bundle domain model and shared in-memory loader.
|
||||
//!
|
||||
//! The backend bundle groups cloud-delivered config and requirements fragments
|
||||
//! by source bucket. `CloudConfigBundleLayers` converts those raw buckets into
|
||||
//! layer entries while preserving each bucket's insertion semantics.
|
||||
|
||||
use crate::CloudConfigFragment;
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::cloud_config_layers::CloudConfigLayerError;
|
||||
use crate::cloud_config_layers::cloud_config_layers_from_fragments_strict;
|
||||
use crate::cloud_config_layers_from_fragments;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::FutureExt;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::watch;
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct CloudConfigBundle {
|
||||
pub config_toml: CloudConfigTomlBundle,
|
||||
pub requirements_toml: CloudRequirementsTomlBundle,
|
||||
}
|
||||
|
||||
impl CloudConfigBundle {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let CloudConfigBundle {
|
||||
config_toml,
|
||||
requirements_toml,
|
||||
} = self;
|
||||
let CloudConfigTomlBundle {
|
||||
enterprise_managed: config_enterprise_managed,
|
||||
} = config_toml;
|
||||
let CloudRequirementsTomlBundle {
|
||||
enterprise_managed: requirements_enterprise_managed,
|
||||
} = requirements_toml;
|
||||
|
||||
config_enterprise_managed.is_empty() && requirements_enterprise_managed.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct CloudConfigTomlBundle {
|
||||
pub enterprise_managed: Vec<CloudConfigFragment>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct CloudRequirementsTomlBundle {
|
||||
pub enterprise_managed: Vec<CloudRequirementsFragment>,
|
||||
}
|
||||
|
||||
impl CloudRequirementsTomlBundle {
|
||||
pub(crate) fn into_layers(self) -> Vec<RequirementsLayerEntry> {
|
||||
// Bundle fragments arrive highest-priority first; requirements merge in reverse order.
|
||||
self.enterprise_managed
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|fragment| {
|
||||
// Older backends used this fragment to deny every accelerated tier.
|
||||
// Preserve that meaning through mixed deployments and rollbacks.
|
||||
if fragment.id == "rbac-fast-mode"
|
||||
&& let Ok(mut contents) = toml::from_str::<toml::Value>(&fragment.contents)
|
||||
&& let Some(features) = contents
|
||||
.get_mut("features")
|
||||
.and_then(toml::Value::as_table_mut)
|
||||
&& features.get("fast_mode").and_then(toml::Value::as_bool) == Some(false)
|
||||
{
|
||||
features.insert("ultrafast_mode".to_string(), toml::Value::Boolean(false));
|
||||
return RequirementsLayerEntry::from_toml_value(
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: fragment.id,
|
||||
name: fragment.name,
|
||||
},
|
||||
contents,
|
||||
);
|
||||
}
|
||||
RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: fragment.id,
|
||||
name: fragment.name,
|
||||
},
|
||||
fragment.contents,
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct CloudRequirementsFragment {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub contents: String,
|
||||
}
|
||||
|
||||
/// Cloud config bundle converted into semantic layer buckets.
|
||||
///
|
||||
/// This is not a final config stack. Callers still decide where each bucket is
|
||||
/// inserted relative to local/system/user layers.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CloudConfigBundleLayers {
|
||||
/// Enterprise-managed config layers in `ConfigLayerStack` order.
|
||||
pub enterprise_managed_config: Vec<ConfigLayerEntry>,
|
||||
/// Enterprise-managed requirements layers in requirements layer merge order.
|
||||
pub enterprise_managed_requirements: Vec<RequirementsLayerEntry>,
|
||||
}
|
||||
|
||||
impl CloudConfigBundleLayers {
|
||||
pub fn from_bundle(
|
||||
bundle: CloudConfigBundle,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
) -> Result<Self, CloudConfigLayerError> {
|
||||
Self::from_bundle_impl(bundle, base_dir, /*strict_config*/ false)
|
||||
}
|
||||
|
||||
pub fn from_bundle_strict_config(
|
||||
bundle: CloudConfigBundle,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
) -> Result<Self, CloudConfigLayerError> {
|
||||
Self::from_bundle_impl(bundle, base_dir, /*strict_config*/ true)
|
||||
}
|
||||
|
||||
fn from_bundle_impl(
|
||||
bundle: CloudConfigBundle,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
strict_config: bool,
|
||||
) -> Result<Self, CloudConfigLayerError> {
|
||||
// Keep this destructuring exhaustive so adding a new bundle bucket forces
|
||||
// an explicit choice about how it becomes layer data.
|
||||
let CloudConfigBundle {
|
||||
config_toml:
|
||||
CloudConfigTomlBundle {
|
||||
enterprise_managed: config_enterprise_managed,
|
||||
},
|
||||
requirements_toml,
|
||||
} = bundle;
|
||||
|
||||
let enterprise_managed_config = if strict_config {
|
||||
cloud_config_layers_from_fragments_strict(config_enterprise_managed, base_dir)?
|
||||
} else {
|
||||
cloud_config_layers_from_fragments(config_enterprise_managed, base_dir)?
|
||||
};
|
||||
|
||||
let enterprise_managed_requirements = requirements_toml
|
||||
.into_layers()
|
||||
.into_iter()
|
||||
.map(|layer| layer.with_base_dir(base_dir.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
Ok(Self {
|
||||
enterprise_managed_config,
|
||||
enterprise_managed_requirements,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CloudConfigBundleLoadErrorCode {
|
||||
Auth,
|
||||
Timeout,
|
||||
RequestFailed,
|
||||
InvalidBundle,
|
||||
Internal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Error, PartialEq)]
|
||||
#[error("{message}")]
|
||||
pub struct CloudConfigBundleLoadError {
|
||||
code: CloudConfigBundleLoadErrorCode,
|
||||
message: String,
|
||||
status_code: Option<u16>,
|
||||
}
|
||||
|
||||
impl CloudConfigBundleLoadError {
|
||||
pub fn new(
|
||||
code: CloudConfigBundleLoadErrorCode,
|
||||
status_code: Option<u16>,
|
||||
message: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
status_code,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code(&self) -> CloudConfigBundleLoadErrorCode {
|
||||
self.code
|
||||
}
|
||||
|
||||
pub fn status_code(&self) -> Option<u16> {
|
||||
self.status_code
|
||||
}
|
||||
}
|
||||
|
||||
type CloudConfigBundleGetter = dyn Fn() -> BoxFuture<'static, Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError>>
|
||||
+ Send
|
||||
+ Sync;
|
||||
|
||||
/// Tracks which delivered policy may authorize new enterprise MCP requests.
|
||||
#[derive(Clone)]
|
||||
pub struct CloudConfigBundlePolicy(watch::Sender<CloudConfigBundlePolicyState>);
|
||||
|
||||
struct CloudConfigBundlePolicyState {
|
||||
revision: u64,
|
||||
bundle: Option<CloudConfigBundle>,
|
||||
phase: CloudConfigBundlePolicyPhase,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Eq, PartialEq)]
|
||||
enum CloudConfigBundlePolicyPhase {
|
||||
Uninitialized,
|
||||
Suspended,
|
||||
Active,
|
||||
Retired,
|
||||
}
|
||||
|
||||
impl Default for CloudConfigBundlePolicy {
|
||||
fn default() -> Self {
|
||||
Self(
|
||||
watch::channel(CloudConfigBundlePolicyState {
|
||||
revision: 0,
|
||||
bundle: None,
|
||||
phase: CloudConfigBundlePolicyPhase::Uninitialized,
|
||||
})
|
||||
.0,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CloudConfigBundlePolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CloudConfigBundlePolicy").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl CloudConfigBundlePolicy {
|
||||
/// Suspends old EMA admission before a changed delivered bundle is validated or cached.
|
||||
pub fn observe_remote_bundle(
|
||||
&self,
|
||||
bundle: &CloudConfigBundle,
|
||||
) -> Option<CloudConfigBundlePolicyRevision> {
|
||||
let bundle = (!bundle.is_empty()).then(|| bundle.clone());
|
||||
let mut observed_revision = None;
|
||||
self.0.send_if_modified(|state| {
|
||||
if state.phase == CloudConfigBundlePolicyPhase::Retired {
|
||||
return false;
|
||||
}
|
||||
if state.phase != CloudConfigBundlePolicyPhase::Uninitialized && state.bundle == bundle
|
||||
{
|
||||
observed_revision = Some(state.revision);
|
||||
return false;
|
||||
}
|
||||
if state.phase != CloudConfigBundlePolicyPhase::Uninitialized {
|
||||
let Some(revision) = state.revision.checked_add(1) else {
|
||||
state.phase = CloudConfigBundlePolicyPhase::Retired;
|
||||
return true;
|
||||
};
|
||||
state.revision = revision;
|
||||
}
|
||||
state.bundle = bundle;
|
||||
state.phase = CloudConfigBundlePolicyPhase::Suspended;
|
||||
observed_revision = Some(state.revision);
|
||||
true
|
||||
});
|
||||
observed_revision.map(|revision| CloudConfigBundlePolicyRevision {
|
||||
revision,
|
||||
policy: self.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Pairs a service result with its EMA revision before the snapshot becomes visible.
|
||||
pub fn publish_snapshot(&self, snapshot: &mut CloudConfigBundleSnapshot) {
|
||||
let Ok(bundle) = &snapshot.bundle else {
|
||||
return;
|
||||
};
|
||||
self.0.send_if_modified(|state| {
|
||||
let current = state.phase != CloudConfigBundlePolicyPhase::Retired
|
||||
&& (state.phase == CloudConfigBundlePolicyPhase::Uninitialized
|
||||
|| state.bundle == *bundle);
|
||||
snapshot.binding = Some(CloudConfigBundleBinding {
|
||||
revision: current.then_some(state.revision),
|
||||
policy: self.clone(),
|
||||
});
|
||||
if current && state.phase != CloudConfigBundlePolicyPhase::Active {
|
||||
state.bundle = bundle.clone();
|
||||
state.phase = CloudConfigBundlePolicyPhase::Active;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn retire(&self) {
|
||||
self.0
|
||||
.send_modify(|state| state.phase = CloudConfigBundlePolicyPhase::Retired);
|
||||
}
|
||||
}
|
||||
|
||||
/// An observed remote policy revision permitted to commit staged persistence.
|
||||
pub struct CloudConfigBundlePolicyRevision {
|
||||
revision: u64,
|
||||
policy: CloudConfigBundlePolicy,
|
||||
}
|
||||
|
||||
impl CloudConfigBundlePolicyRevision {
|
||||
/// Executes a synchronous commit only while this observation is still current.
|
||||
/// Prepare expensive work first; the guard blocks newer observations and retirement.
|
||||
pub fn commit_if_current<E>(self, commit: impl FnOnce() -> Result<(), E>) -> Result<(), E> {
|
||||
let state = self.policy.0.borrow();
|
||||
if state.revision == self.revision
|
||||
&& matches!(
|
||||
state.phase,
|
||||
CloudConfigBundlePolicyPhase::Suspended | CloudConfigBundlePolicyPhase::Active
|
||||
)
|
||||
{
|
||||
commit()
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The policy revision used to resolve one set of enterprise MCP inputs.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct CloudConfigBundleBinding {
|
||||
revision: Option<u64>,
|
||||
policy: CloudConfigBundlePolicy,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CloudConfigBundleBindingStatus {
|
||||
Current,
|
||||
Stale,
|
||||
Suspended,
|
||||
}
|
||||
|
||||
impl CloudConfigBundleBinding {
|
||||
/// Wait until this delivered policy no longer authorizes its EMA owner.
|
||||
pub async fn invalidated(&self) {
|
||||
let mut changes = self.policy.0.subscribe();
|
||||
loop {
|
||||
if self.read().status != CloudConfigBundleBindingStatus::Current {
|
||||
return;
|
||||
}
|
||||
if changes.changed().await.is_err() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Keeps the policy observation stable until this guard is dropped.
|
||||
pub fn read(&self) -> CloudConfigBundleBindingGuard<'_> {
|
||||
let state = self.policy.0.borrow();
|
||||
let status = match (state.phase, self.revision) {
|
||||
(CloudConfigBundlePolicyPhase::Active, Some(expected))
|
||||
if state.revision == expected =>
|
||||
{
|
||||
CloudConfigBundleBindingStatus::Current
|
||||
}
|
||||
(CloudConfigBundlePolicyPhase::Active, Some(_)) => {
|
||||
CloudConfigBundleBindingStatus::Stale
|
||||
}
|
||||
_ => CloudConfigBundleBindingStatus::Suspended,
|
||||
};
|
||||
CloudConfigBundleBindingGuard {
|
||||
_state: state,
|
||||
status,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CloudConfigBundleBindingGuard<'a> {
|
||||
_state: watch::Ref<'a, CloudConfigBundlePolicyState>,
|
||||
pub status: CloudConfigBundleBindingStatus,
|
||||
}
|
||||
|
||||
pub struct CloudConfigBundlePolicyChanges(watch::Receiver<CloudConfigBundlePolicyState>);
|
||||
|
||||
impl CloudConfigBundlePolicyChanges {
|
||||
pub fn is_active(&self) -> bool {
|
||||
self.0.borrow().phase == CloudConfigBundlePolicyPhase::Active
|
||||
}
|
||||
|
||||
pub async fn changed(&mut self) -> Result<(), watch::error::RecvError> {
|
||||
self.0.changed().await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CloudConfigBundleSnapshot {
|
||||
pub bundle: Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError>,
|
||||
pub binding: Option<CloudConfigBundleBinding>,
|
||||
pub config_server: Option<crate::ConfigServer>,
|
||||
}
|
||||
|
||||
type CloudConfigBundleSnapshotGetter =
|
||||
dyn Fn() -> BoxFuture<'static, CloudConfigBundleSnapshot> + Send + Sync;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CloudConfigBundleLoader {
|
||||
getter: Arc<CloudConfigBundleGetter>,
|
||||
snapshot_getter: Option<Arc<CloudConfigBundleSnapshotGetter>>,
|
||||
ema_policy: Option<CloudConfigBundlePolicy>,
|
||||
config_server: Option<crate::ConfigServer>,
|
||||
}
|
||||
|
||||
impl CloudConfigBundleLoader {
|
||||
pub fn new<F>(fut: F) -> Self
|
||||
where
|
||||
F: Future<Output = Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
let fut = fut.boxed().shared();
|
||||
Self::from_getter(move || fut.clone())
|
||||
}
|
||||
|
||||
/// Creates a loader that requests the latest bundle on every call.
|
||||
pub fn from_getter<F, Fut>(getter: F) -> Self
|
||||
where
|
||||
F: Fn() -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError>>
|
||||
+ Send
|
||||
+ 'static,
|
||||
{
|
||||
Self {
|
||||
getter: Arc::new(move || getter().boxed()),
|
||||
snapshot_getter: None,
|
||||
ema_policy: None,
|
||||
config_server: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Freezes the delivered bundle while retaining its live policy revision binding.
|
||||
pub fn from_snapshot(snapshot: CloudConfigBundleSnapshot) -> Self {
|
||||
let bundle = snapshot.bundle.clone();
|
||||
let mut loader = Self::from_getter(move || std::future::ready(bundle.clone()));
|
||||
loader.config_server = snapshot.config_server.clone();
|
||||
loader.ema_policy = snapshot
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(|binding| binding.policy.clone());
|
||||
loader.snapshot_getter = Some(Arc::new(move || {
|
||||
std::future::ready(snapshot.clone()).boxed()
|
||||
}));
|
||||
loader
|
||||
}
|
||||
|
||||
pub fn with_ema_policy_snapshots<F, Fut>(
|
||||
mut self,
|
||||
policy: CloudConfigBundlePolicy,
|
||||
getter: F,
|
||||
) -> Self
|
||||
where
|
||||
F: Fn() -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = CloudConfigBundleSnapshot> + Send + 'static,
|
||||
{
|
||||
self.ema_policy = Some(policy);
|
||||
self.snapshot_getter = Some(Arc::new(move || getter().boxed()));
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn get_snapshot(&self) -> CloudConfigBundleSnapshot {
|
||||
let mut snapshot = match &self.snapshot_getter {
|
||||
Some(getter) => getter().await,
|
||||
None => CloudConfigBundleSnapshot {
|
||||
bundle: self.get().await,
|
||||
binding: None,
|
||||
config_server: None,
|
||||
},
|
||||
};
|
||||
if snapshot.bundle.is_ok() && self.config_server.is_some() {
|
||||
snapshot.config_server = self.config_server.clone();
|
||||
}
|
||||
snapshot
|
||||
}
|
||||
|
||||
pub fn with_config_server(mut self, service_config: crate::ConfigServer) -> Self {
|
||||
self.config_server = Some(service_config);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn config_server(&self) -> Option<&crate::ConfigServer> {
|
||||
self.config_server.as_ref()
|
||||
}
|
||||
|
||||
pub fn ema_policy_changes(&self) -> Option<CloudConfigBundlePolicyChanges> {
|
||||
self.ema_policy
|
||||
.as_ref()
|
||||
.map(|policy| CloudConfigBundlePolicyChanges(policy.0.subscribe()))
|
||||
}
|
||||
|
||||
/// Stops new EMA admission from this owner without changing generic loader behavior.
|
||||
pub fn retire_ema_policy(&self) {
|
||||
if let Some(policy) = &self.ema_policy {
|
||||
policy.retire();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the current bundle snapshot.
|
||||
pub async fn get(&self) -> Result<Option<CloudConfigBundle>, CloudConfigBundleLoadError> {
|
||||
(self.getter)().await
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for CloudConfigBundleLoader {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("CloudConfigBundleLoader").finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CloudConfigBundleLoader {
|
||||
fn default() -> Self {
|
||||
Self::new(async { Ok(None) })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cloud_config_bundle_tests.rs"]
|
||||
mod tests;
|
||||
330
codex-rs/config/src/cloud_config_bundle_tests.rs
Normal file
330
codex-rs/config/src/cloud_config_bundle_tests.rs
Normal file
@@ -0,0 +1,330 @@
|
||||
use super::*;
|
||||
use crate::AbsolutePathBufGuard;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::FilesystemDenyReadPattern;
|
||||
use crate::SandboxModeRequirement;
|
||||
use crate::compose_requirements;
|
||||
use crate::compose_requirements_for_hostname;
|
||||
use crate::config_requirements::FilesystemRequirementsToml;
|
||||
use crate::config_requirements::PermissionsRequirementsToml;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::types::SandboxWorkspaceWrite;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn legacy_speed_denial_is_normalized_without_changing_other_fragments() {
|
||||
for (id, contents, expected_ultrafast) in [
|
||||
(
|
||||
"rbac-fast-mode",
|
||||
"[features]\nfast_mode = false",
|
||||
Some(false),
|
||||
),
|
||||
("rbac-fast-mode", "[features]\nfast_mode = true", None),
|
||||
("admin-layer", "[features]\nfast_mode = false", None),
|
||||
] {
|
||||
let requirements = compose_requirements(
|
||||
CloudRequirementsTomlBundle {
|
||||
enterprise_managed: vec![CloudRequirementsFragment {
|
||||
id: id.to_string(),
|
||||
name: id.to_string(),
|
||||
contents: contents.to_string(),
|
||||
}],
|
||||
}
|
||||
.into_layers(),
|
||||
)
|
||||
.expect("valid cloud requirements")
|
||||
.expect("requirements layer")
|
||||
.into_toml();
|
||||
assert_eq!(
|
||||
requirements
|
||||
.feature_requirements
|
||||
.expect("feature requirements")
|
||||
.entries
|
||||
.get("ultrafast_mode")
|
||||
.copied(),
|
||||
expected_ultrafast,
|
||||
"fragment={id}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enterprise_speed_override_still_takes_precedence_over_legacy_baseline() {
|
||||
let requirements = compose_requirements(
|
||||
CloudRequirementsTomlBundle {
|
||||
enterprise_managed: vec![
|
||||
CloudRequirementsFragment {
|
||||
id: "admin-layer".to_string(),
|
||||
name: "Admin".to_string(),
|
||||
contents: "[features]\nultrafast_mode = true".to_string(),
|
||||
},
|
||||
CloudRequirementsFragment {
|
||||
id: "rbac-fast-mode".to_string(),
|
||||
name: "Legacy RBAC".to_string(),
|
||||
contents: "[features]\nfast_mode = false".to_string(),
|
||||
},
|
||||
],
|
||||
}
|
||||
.into_layers(),
|
||||
)
|
||||
.expect("valid cloud requirements")
|
||||
.expect("requirements layers")
|
||||
.into_toml();
|
||||
assert_eq!(
|
||||
requirements
|
||||
.feature_requirements
|
||||
.expect("feature requirements")
|
||||
.entries,
|
||||
std::collections::BTreeMap::from([
|
||||
("fast_mode".to_string(), false),
|
||||
("ultrafast_mode".to_string(), true),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn shared_future_runs_once() {
|
||||
let counter = Arc::new(AtomicUsize::new(0));
|
||||
let counter_clone = Arc::clone(&counter);
|
||||
let loader = CloudConfigBundleLoader::new(async move {
|
||||
counter_clone.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(Some(CloudConfigBundle::default()))
|
||||
});
|
||||
let cloned_loader = loader.clone();
|
||||
|
||||
let (first, second) = tokio::join!(loader.get(), cloned_loader.get());
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(loader.get().await, first);
|
||||
assert_eq!(counter.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn getter_returns_latest_result_across_clones() {
|
||||
let initial_error = CloudConfigBundleLoadError::new(
|
||||
CloudConfigBundleLoadErrorCode::RequestFailed,
|
||||
/*status_code*/ None,
|
||||
"initial load failed",
|
||||
);
|
||||
let latest = Arc::new(RwLock::new(Err(initial_error.clone())));
|
||||
let getter_latest = Arc::clone(&latest);
|
||||
let loader = CloudConfigBundleLoader::from_getter(move || {
|
||||
let latest = Arc::clone(&getter_latest);
|
||||
async move { latest.read().expect("bundle state lock").clone() }
|
||||
});
|
||||
let cloned_loader = loader.clone();
|
||||
|
||||
assert_eq!(loader.get().await, Err(initial_error));
|
||||
|
||||
let bundle = CloudConfigBundle {
|
||||
config_toml: CloudConfigTomlBundle {
|
||||
enterprise_managed: vec![CloudConfigFragment {
|
||||
id: "managed".to_string(),
|
||||
name: "Managed".to_string(),
|
||||
contents: "model = \"managed\"".to_string(),
|
||||
}],
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
*latest.write().expect("bundle state lock") = Ok(Some(bundle.clone()));
|
||||
|
||||
assert_eq!(cloned_loader.get().await, Ok(Some(bundle)));
|
||||
assert_eq!(CloudConfigBundleLoader::default().get().await, Ok(None));
|
||||
|
||||
*latest.write().expect("bundle state lock") = Ok(None);
|
||||
|
||||
assert_eq!(loader.get().await, Ok(None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_layers_preserve_enterprise_managed_bucket_order() {
|
||||
let tempdir = tempdir().expect("tempdir");
|
||||
let base_dir = AbsolutePathBuf::from_absolute_path(tempdir.path()).expect("absolute path");
|
||||
let layers = CloudConfigBundleLayers::from_bundle(
|
||||
CloudConfigBundle {
|
||||
config_toml: CloudConfigTomlBundle {
|
||||
enterprise_managed: vec![
|
||||
CloudConfigFragment {
|
||||
id: "cfg_high".to_string(),
|
||||
name: "High config".to_string(),
|
||||
contents: "model = \"high\"".to_string(),
|
||||
},
|
||||
CloudConfigFragment {
|
||||
id: "cfg_low".to_string(),
|
||||
name: "Low config".to_string(),
|
||||
contents: "model = \"low\"".to_string(),
|
||||
},
|
||||
],
|
||||
},
|
||||
requirements_toml: CloudRequirementsTomlBundle {
|
||||
enterprise_managed: vec![
|
||||
CloudRequirementsFragment {
|
||||
id: "req_high".to_string(),
|
||||
name: "High requirements".to_string(),
|
||||
contents: "allowed_approval_policies = [\"on-request\"]".to_string(),
|
||||
},
|
||||
CloudRequirementsFragment {
|
||||
id: "req_low".to_string(),
|
||||
name: "Low requirements".to_string(),
|
||||
contents: "allowed_approval_policies = [\"never\"]".to_string(),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
&base_dir,
|
||||
)
|
||||
.expect("bundle should be converted into layers");
|
||||
|
||||
assert_eq!(
|
||||
layers
|
||||
.enterprise_managed_config
|
||||
.iter()
|
||||
.map(|layer| layer.name.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "cfg_low".to_string(),
|
||||
name: "Low config".to_string(),
|
||||
},
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "cfg_high".to_string(),
|
||||
name: "High config".to_string(),
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
compose_requirements(layers.enterprise_managed_requirements)
|
||||
.expect("requirements should compose")
|
||||
.expect("requirements should be present")
|
||||
.into_toml(),
|
||||
ConfigRequirementsToml {
|
||||
allowed_approval_policies: Some(vec![AskForApproval::OnRequest]),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_layers_can_strict_validate_enterprise_managed_config() {
|
||||
let tempdir = tempdir().expect("tempdir");
|
||||
let base_dir = AbsolutePathBuf::from_absolute_path(tempdir.path()).expect("absolute path");
|
||||
let err = CloudConfigBundleLayers::from_bundle_strict_config(
|
||||
CloudConfigBundle {
|
||||
config_toml: CloudConfigTomlBundle {
|
||||
enterprise_managed: vec![CloudConfigFragment {
|
||||
id: "cfg".to_string(),
|
||||
name: "Cloud config".to_string(),
|
||||
contents: "unknown_key = true".to_string(),
|
||||
}],
|
||||
},
|
||||
requirements_toml: CloudRequirementsTomlBundle {
|
||||
enterprise_managed: Vec::new(),
|
||||
},
|
||||
},
|
||||
&base_dir,
|
||||
)
|
||||
.expect_err("strict config should reject unknown fields");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
CloudConfigLayerError::Invalid {
|
||||
fragment: crate::CloudConfigFragmentSource {
|
||||
id: "cfg".to_string(),
|
||||
name: "Cloud config".to_string(),
|
||||
},
|
||||
message: "unknown configuration field `unknown_key`".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundle_layers_resolve_paths_and_requirements_for_the_execution_host() {
|
||||
let temp_dir = tempdir().expect("temporary directories");
|
||||
let executor_home = temp_dir.path().join("executor-home");
|
||||
let executor_codex_home = AbsolutePathBuf::from_absolute_path(executor_home.join(".codex"))
|
||||
.expect("absolute executor Codex home");
|
||||
let bundle = CloudConfigBundle {
|
||||
config_toml: CloudConfigTomlBundle {
|
||||
enterprise_managed: vec![CloudConfigFragment {
|
||||
id: "config".to_string(),
|
||||
name: "Executor config".to_string(),
|
||||
contents: r#"
|
||||
[sandbox_workspace_write]
|
||||
writable_roots = ["~/cloud-root", "./relative-root"]
|
||||
"#
|
||||
.to_string(),
|
||||
}],
|
||||
},
|
||||
requirements_toml: CloudRequirementsTomlBundle {
|
||||
enterprise_managed: vec![CloudRequirementsFragment {
|
||||
id: "requirements".to_string(),
|
||||
name: "Executor requirements".to_string(),
|
||||
contents: r#"
|
||||
[permissions.filesystem]
|
||||
deny_read = ["~/private"]
|
||||
|
||||
[[remote_sandbox_config]]
|
||||
hostname_patterns = ["executor-*"]
|
||||
allowed_sandbox_modes = ["read-only"]
|
||||
"#
|
||||
.to_string(),
|
||||
}],
|
||||
},
|
||||
};
|
||||
|
||||
let (config, requirements) = AbsolutePathBufGuard::with_home_directory(&executor_home, || {
|
||||
let layers =
|
||||
CloudConfigBundleLayers::from_bundle_strict_config(bundle, &executor_codex_home)
|
||||
.expect("executor bundle should convert into layers");
|
||||
let config: ConfigToml = layers.enterprise_managed_config[0]
|
||||
.config
|
||||
.clone()
|
||||
.try_into()
|
||||
.expect("deserialize executor config");
|
||||
let requirements = compose_requirements_for_hostname(
|
||||
layers.enterprise_managed_requirements,
|
||||
Some("executor-01"),
|
||||
)
|
||||
.expect("compose executor requirements")
|
||||
.expect("executor requirements should be present")
|
||||
.into_toml();
|
||||
(config, requirements)
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
config.sandbox_workspace_write,
|
||||
Some(SandboxWorkspaceWrite {
|
||||
writable_roots: vec![
|
||||
AbsolutePathBuf::from_absolute_path(executor_home.join("cloud-root"))
|
||||
.expect("absolute cloud root"),
|
||||
AbsolutePathBuf::from_absolute_path(
|
||||
executor_codex_home.as_path().join("relative-root"),
|
||||
)
|
||||
.expect("absolute relative root"),
|
||||
],
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
requirements,
|
||||
ConfigRequirementsToml {
|
||||
allowed_sandbox_modes: Some(vec![SandboxModeRequirement::ReadOnly]),
|
||||
permissions: Some(PermissionsRequirementsToml {
|
||||
filesystem: Some(FilesystemRequirementsToml {
|
||||
deny_read: Some(vec![FilesystemDenyReadPattern::from(
|
||||
AbsolutePathBuf::from_absolute_path(executor_home.join("private"))
|
||||
.expect("absolute private root"),
|
||||
)]),
|
||||
}),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
151
codex-rs/config/src/cloud_config_layers.rs
Normal file
151
codex-rs/config/src/cloud_config_layers.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
//! Conversion from cloud-delivered config TOML fragments into config stack layers.
|
||||
//!
|
||||
//! Backend fragments arrive in backend priority order. This module parses each
|
||||
//! fragment, resolves relative path fields against the cloud config base
|
||||
//! directory, and returns layers in `ConfigLayerStack` order.
|
||||
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::TomlValue;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::loader::resolve_relative_paths_in_config_toml;
|
||||
use crate::strict_config::config_error_from_ignored_toml_value_fields_for_source_name;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
use std::io;
|
||||
use thiserror::Error;
|
||||
|
||||
/// Config fragment delivered by the cloud config bundle.
|
||||
///
|
||||
/// The bundle orders fragments from highest precedence to lowest precedence.
|
||||
/// This module returns config layers in stack order, so callers can append the
|
||||
/// result between system and user config without re-sorting.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct CloudConfigFragment {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub contents: String,
|
||||
}
|
||||
|
||||
impl CloudConfigFragment {
|
||||
fn source_ref(&self) -> CloudConfigFragmentSource {
|
||||
CloudConfigFragmentSource {
|
||||
id: self.id.clone(),
|
||||
name: self.name.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct CloudConfigFragmentSource {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl fmt::Display for CloudConfigFragmentSource {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "{} ({})", self.name, self.id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum CloudConfigLayerError {
|
||||
#[error("failed to parse cloud config fragment {fragment}: {message}")]
|
||||
Parse {
|
||||
fragment: CloudConfigFragmentSource,
|
||||
message: String,
|
||||
},
|
||||
#[error("invalid cloud config fragment {fragment}: {message}")]
|
||||
Invalid {
|
||||
fragment: CloudConfigFragmentSource,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn cloud_config_layers_from_fragments(
|
||||
fragments: impl IntoIterator<Item = CloudConfigFragment>,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
) -> Result<Vec<ConfigLayerEntry>, CloudConfigLayerError> {
|
||||
cloud_config_layers_from_fragments_impl(fragments, base_dir, /*strict_config*/ false)
|
||||
}
|
||||
|
||||
pub(crate) fn cloud_config_layers_from_fragments_strict(
|
||||
fragments: impl IntoIterator<Item = CloudConfigFragment>,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
) -> Result<Vec<ConfigLayerEntry>, CloudConfigLayerError> {
|
||||
cloud_config_layers_from_fragments_impl(fragments, base_dir, /*strict_config*/ true)
|
||||
}
|
||||
|
||||
fn cloud_config_layers_from_fragments_impl(
|
||||
fragments: impl IntoIterator<Item = CloudConfigFragment>,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
strict_config: bool,
|
||||
) -> Result<Vec<ConfigLayerEntry>, CloudConfigLayerError> {
|
||||
let mut layers = Vec::new();
|
||||
for fragment in fragments {
|
||||
let source_ref = fragment.source_ref();
|
||||
let raw_toml = fragment.contents;
|
||||
let value: TomlValue =
|
||||
toml::from_str(&raw_toml).map_err(|err| CloudConfigLayerError::Parse {
|
||||
fragment: source_ref.clone(),
|
||||
message: err.to_string(),
|
||||
})?;
|
||||
if strict_config {
|
||||
validate_fragment_strictly(&source_ref, &raw_toml, &value, base_dir)?;
|
||||
}
|
||||
let resolved =
|
||||
resolve_relative_paths_in_config_toml(value, base_dir.as_path()).map_err(|err| {
|
||||
CloudConfigLayerError::Invalid {
|
||||
fragment: source_ref.clone(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})?;
|
||||
layers.push(ConfigLayerEntry::new_with_raw_toml(
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: fragment.id,
|
||||
name: fragment.name,
|
||||
},
|
||||
resolved,
|
||||
raw_toml,
|
||||
base_dir.clone(),
|
||||
));
|
||||
}
|
||||
|
||||
// Bundle fragments arrive highest-priority first, while ConfigLayerStack
|
||||
// folds lowest-priority to highest-priority.
|
||||
layers.reverse();
|
||||
Ok(layers)
|
||||
}
|
||||
|
||||
fn validate_fragment_strictly(
|
||||
source_ref: &CloudConfigFragmentSource,
|
||||
raw_toml: &str,
|
||||
value: &TomlValue,
|
||||
base_dir: &AbsolutePathBuf,
|
||||
) -> Result<(), CloudConfigLayerError> {
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir.as_path());
|
||||
if let Some(config_error) = config_error_from_ignored_toml_value_fields_for_source_name::<
|
||||
ConfigToml,
|
||||
>(&source_ref.to_string(), raw_toml, value.clone())
|
||||
{
|
||||
return Err(CloudConfigLayerError::Invalid {
|
||||
fragment: source_ref.clone(),
|
||||
message: config_error.message,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl From<CloudConfigLayerError> for io::Error {
|
||||
fn from(error: CloudConfigLayerError) -> Self {
|
||||
io::Error::new(io::ErrorKind::InvalidData, error)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "cloud_config_layers_tests.rs"]
|
||||
mod tests;
|
||||
226
codex-rs/config/src/cloud_config_layers_tests.rs
Normal file
226
codex-rs/config/src/cloud_config_layers_tests.rs
Normal file
@@ -0,0 +1,226 @@
|
||||
use super::*;
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::first_layer_config_error_from_entries;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
|
||||
fn fragment(id: &str, name: &str, contents: &str) -> CloudConfigFragment {
|
||||
CloudConfigFragment {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
contents: contents.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn toml(contents: &str) -> TomlValue {
|
||||
toml::from_str(contents).expect("test TOML should parse")
|
||||
}
|
||||
|
||||
fn base_dir() -> AbsolutePathBuf {
|
||||
test_path_buf("/var/lib/codex").abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_are_returned_in_stack_order() {
|
||||
let base_dir = base_dir();
|
||||
let layers = cloud_config_layers_from_fragments(
|
||||
vec![
|
||||
fragment("high", "High priority", "model = \"cloud-high\""),
|
||||
fragment("low", "Low priority", "model_provider = \"cloud-low\""),
|
||||
],
|
||||
&base_dir,
|
||||
)
|
||||
.expect("cloud config layers should compose");
|
||||
|
||||
assert_eq!(
|
||||
layers
|
||||
.iter()
|
||||
.map(|layer| layer.name.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "low".to_string(),
|
||||
name: "Low priority".to_string(),
|
||||
},
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "high".to_string(),
|
||||
name: "High priority".to_string(),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_layers_reject_unknown_config_fields() {
|
||||
let base_dir = base_dir();
|
||||
let err = cloud_config_layers_from_fragments_strict(
|
||||
vec![fragment("strict", "Strict layer", "unknown_key = true")],
|
||||
&base_dir,
|
||||
)
|
||||
.expect_err("strict config should reject unknown fields");
|
||||
|
||||
assert_eq!(
|
||||
err,
|
||||
CloudConfigLayerError::Invalid {
|
||||
fragment: CloudConfigFragmentSource {
|
||||
id: "strict".to_string(),
|
||||
name: "Strict layer".to_string(),
|
||||
},
|
||||
message: "unknown configuration field `unknown_key`".to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enterprise_layers_precede_user_and_override_system() {
|
||||
let base_dir = base_dir();
|
||||
let mut layers = vec![ConfigLayerEntry::new(
|
||||
ConfigLayerSource::System {
|
||||
file: test_path_buf("/etc/codex/config.toml").abs(),
|
||||
},
|
||||
toml(
|
||||
r#"
|
||||
model = "system"
|
||||
model_provider = "system"
|
||||
review_model = "system-review"
|
||||
"#,
|
||||
),
|
||||
)];
|
||||
layers.extend(
|
||||
cloud_config_layers_from_fragments(
|
||||
vec![
|
||||
fragment("high", "High priority", "model_provider = \"cloud-high\""),
|
||||
fragment("low", "Low priority", "review_model = \"cloud-low-review\""),
|
||||
],
|
||||
&base_dir,
|
||||
)
|
||||
.expect("cloud config layers should compose"),
|
||||
);
|
||||
layers.push(ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: test_path_buf("/home/alice/.codex/config.toml").abs(),
|
||||
profile: None,
|
||||
},
|
||||
toml("model = \"user\""),
|
||||
));
|
||||
|
||||
let stack = ConfigLayerStack::new(
|
||||
layers,
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("stack should be ordered");
|
||||
|
||||
assert_eq!(
|
||||
stack
|
||||
.layers_low_to_high()
|
||||
.map(|layer| layer.name.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
ConfigLayerSource::System {
|
||||
file: test_path_buf("/etc/codex/config.toml").abs(),
|
||||
},
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "low".to_string(),
|
||||
name: "Low priority".to_string(),
|
||||
},
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "high".to_string(),
|
||||
name: "High priority".to_string(),
|
||||
},
|
||||
ConfigLayerSource::User {
|
||||
file: test_path_buf("/home/alice/.codex/config.toml").abs(),
|
||||
profile: None,
|
||||
},
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
stack.effective_config(),
|
||||
toml(
|
||||
r#"
|
||||
model = "user"
|
||||
model_provider = "cloud-high"
|
||||
review_model = "cloud-low-review"
|
||||
"#,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_absolute_path_fields_resolve_against_base_dir() {
|
||||
let base_dir = base_dir();
|
||||
let layers = cloud_config_layers_from_fragments(
|
||||
vec![fragment(
|
||||
"cfg_123",
|
||||
"Base policy",
|
||||
"model_instructions_file = \"instructions.md\"",
|
||||
)],
|
||||
&base_dir,
|
||||
)
|
||||
.expect("relative paths should match existing MDM semantics");
|
||||
|
||||
let path = layers[0]
|
||||
.config
|
||||
.get("model_instructions_file")
|
||||
.and_then(TomlValue::as_str)
|
||||
.expect("path should be present");
|
||||
let expected =
|
||||
AbsolutePathBuf::resolve_path_against_base("instructions.md", base_dir.as_path());
|
||||
assert_eq!(path, expected.to_string_lossy());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn home_relative_path_fields_are_allowed_and_resolved() {
|
||||
let base_dir = base_dir();
|
||||
let layers = cloud_config_layers_from_fragments(
|
||||
vec![fragment(
|
||||
"cfg_123",
|
||||
"Base policy",
|
||||
"model_instructions_file = \"~/instructions.md\"",
|
||||
)],
|
||||
&base_dir,
|
||||
)
|
||||
.expect("home-relative paths should be accepted");
|
||||
|
||||
let path = layers[0]
|
||||
.config
|
||||
.get("model_instructions_file")
|
||||
.and_then(TomlValue::as_str)
|
||||
.expect("path should be present");
|
||||
let expected =
|
||||
AbsolutePathBuf::resolve_path_against_base("~/instructions.md", base_dir.as_path());
|
||||
assert_eq!(path, expected.to_string_lossy());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raw_toml_diagnostics_use_enterprise_layer_name() {
|
||||
let base_dir = base_dir();
|
||||
let layers = cloud_config_layers_from_fragments(
|
||||
vec![fragment(
|
||||
"cfg_123",
|
||||
"Base policy",
|
||||
"model_instructions_file = \"instructions.md\"\nmodel = 1",
|
||||
)],
|
||||
&base_dir,
|
||||
)
|
||||
.expect("cloud config layers should parse");
|
||||
|
||||
let error = first_layer_config_error_from_entries::<ConfigToml>(&layers, CONFIG_TOML_FILE)
|
||||
.await
|
||||
.expect("invalid raw TOML should produce a layer diagnostic");
|
||||
|
||||
assert_eq!(
|
||||
error.path,
|
||||
Path::new("enterprise-managed (Base policy, cfg_123)").to_path_buf()
|
||||
);
|
||||
assert_eq!(error.range.start.line, 2);
|
||||
assert_eq!(error.range.start.column, 9);
|
||||
assert!(error.message.contains("invalid type: integer `1`"));
|
||||
}
|
||||
28
codex-rs/config/src/codex_home_symlink.rs
Normal file
28
codex-rs/config/src/codex_home_symlink.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! Resolves the host's symlink opt-out from its already-loaded user config.
|
||||
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
/// Returns the opted-in home without consulting project config or rereading config files.
|
||||
pub fn allowed_symlinked_codex_home(
|
||||
config_layer_stack: &ConfigLayerStack,
|
||||
codex_home: &AbsolutePathBuf,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
let enabled = config_layer_stack
|
||||
.layers_low_to_high()
|
||||
.find(|layer| matches!(layer.name, ConfigLayerSource::User { profile: None, .. }))?
|
||||
.config
|
||||
.get("allow_symlinked_codex_home")?
|
||||
.as_bool()?;
|
||||
if !enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Preserve a configured alias only when lexical normalization did not change its target.
|
||||
let alias = std::env::var_os("CODEX_HOME")
|
||||
.filter(|path| !path.is_empty())
|
||||
.and_then(|path| AbsolutePathBuf::from_absolute_path(path).ok())
|
||||
.filter(|path| path.canonicalize().ok().as_ref() == Some(codex_home));
|
||||
Some(alias.unwrap_or_else(|| codex_home.clone()))
|
||||
}
|
||||
39
codex-rs/config/src/computer_use.rs
Normal file
39
codex-rs/config/src/computer_use.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use crate::AllowDenyRequirementToml;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ComputerUseConfigToml {
|
||||
pub default_app_access: Option<AllowDenyRequirementToml>,
|
||||
pub macos: Option<ComputerUseMacosConfigToml>,
|
||||
pub windows: Option<ComputerUseWindowsConfigToml>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ComputerUseMacosConfigToml {
|
||||
pub bundle_ids: Option<BTreeMap<String, AllowDenyRequirementToml>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ComputerUseWindowsConfigToml {
|
||||
pub aumids: Option<BTreeMap<String, AllowDenyRequirementToml>>,
|
||||
pub exes: Option<Vec<ComputerUseWindowsExeConfigToml>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ComputerUseWindowsExeConfigToml {
|
||||
pub publisher_name: String,
|
||||
pub product_name: String,
|
||||
pub binary_name: Option<String>,
|
||||
pub access: AllowDenyRequirementToml,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "computer_use_tests.rs"]
|
||||
mod tests;
|
||||
54
codex-rs/config/src/computer_use_tests.rs
Normal file
54
codex-rs/config/src/computer_use_tests.rs
Normal file
@@ -0,0 +1,54 @@
|
||||
use super::*;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn computer_use_config_round_trips() {
|
||||
let config: ConfigToml = toml::from_str(
|
||||
r#"
|
||||
[computer_use]
|
||||
default_app_access = "deny"
|
||||
|
||||
[computer_use.macos.bundle_ids]
|
||||
"com.apple.Safari" = "allow"
|
||||
|
||||
[computer_use.windows.aumids]
|
||||
"Microsoft.Paint_8wekyb3d8bbwe!App" = "deny"
|
||||
|
||||
[[computer_use.windows.exes]]
|
||||
publisher_name = "CN=Google LLC"
|
||||
product_name = "Google Chrome"
|
||||
binary_name = "chrome.exe"
|
||||
access = "allow"
|
||||
"#,
|
||||
)
|
||||
.expect("computer use config should deserialize");
|
||||
|
||||
let expected = ComputerUseConfigToml {
|
||||
default_app_access: Some(AllowDenyRequirementToml::Deny),
|
||||
macos: Some(ComputerUseMacosConfigToml {
|
||||
bundle_ids: Some(BTreeMap::from([(
|
||||
"com.apple.Safari".to_string(),
|
||||
AllowDenyRequirementToml::Allow,
|
||||
)])),
|
||||
}),
|
||||
windows: Some(ComputerUseWindowsConfigToml {
|
||||
aumids: Some(BTreeMap::from([(
|
||||
"Microsoft.Paint_8wekyb3d8bbwe!App".to_string(),
|
||||
AllowDenyRequirementToml::Deny,
|
||||
)])),
|
||||
exes: Some(vec![ComputerUseWindowsExeConfigToml {
|
||||
publisher_name: "CN=Google LLC".to_string(),
|
||||
product_name: "Google Chrome".to_string(),
|
||||
binary_name: Some("chrome.exe".to_string()),
|
||||
access: AllowDenyRequirementToml::Allow,
|
||||
}]),
|
||||
}),
|
||||
};
|
||||
assert_eq!(config.computer_use, Some(expected.clone()));
|
||||
|
||||
let serialized = toml::to_string(&config).expect("computer use config should serialize");
|
||||
let reparsed: ConfigToml =
|
||||
toml::from_str(&serialized).expect("serialized computer use config should deserialize");
|
||||
assert_eq!(reparsed.computer_use, Some(expected));
|
||||
}
|
||||
109
codex-rs/config/src/config_layer_source.rs
Normal file
109
codex-rs/config/src/config_layer_source.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde_json::Value as JsonValue;
|
||||
|
||||
/// Provenance for one layer in the effective Codex configuration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ConfigLayerSource {
|
||||
/// Default configuration supplied with the installed Codex package.
|
||||
PackagedDefaults { file: AbsolutePathBuf },
|
||||
/// Managed preferences delivered by MDM.
|
||||
Mdm { domain: String, key: String },
|
||||
/// Host-wide configuration loaded from a file.
|
||||
System { file: AbsolutePathBuf },
|
||||
/// Configuration delivered by an enterprise cloud bundle.
|
||||
EnterpriseManaged { id: String, name: String },
|
||||
/// User configuration, optionally augmented by a selected profile.
|
||||
User {
|
||||
file: AbsolutePathBuf,
|
||||
profile: Option<String>,
|
||||
},
|
||||
/// Configuration loaded from a project's `.codex` directory.
|
||||
Project { dot_codex_folder: AbsolutePathBuf },
|
||||
/// Overrides supplied for the current session.
|
||||
SessionFlags,
|
||||
/// Legacy managed configuration loaded from a file.
|
||||
LegacyManagedConfigTomlFromFile { file: AbsolutePathBuf },
|
||||
/// Legacy managed configuration delivered by MDM.
|
||||
LegacyManagedConfigTomlFromMdm,
|
||||
}
|
||||
|
||||
impl ConfigLayerSource {
|
||||
/// A setting from a layer with a higher precedence overrides a setting
|
||||
/// from a layer with a lower precedence.
|
||||
pub fn precedence(&self) -> i16 {
|
||||
match self {
|
||||
ConfigLayerSource::PackagedDefaults { .. } => -10,
|
||||
ConfigLayerSource::Mdm { .. } => 0,
|
||||
ConfigLayerSource::System { .. } => 10,
|
||||
ConfigLayerSource::EnterpriseManaged { .. } => 15,
|
||||
ConfigLayerSource::User { profile, .. } => {
|
||||
if profile.is_some() {
|
||||
21
|
||||
} else {
|
||||
20
|
||||
}
|
||||
}
|
||||
ConfigLayerSource::Project { .. } => 25,
|
||||
ConfigLayerSource::SessionFlags => 30,
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => 40,
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromMdm => 50,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compares [`ConfigLayerSource`] by precedence, so `A < B` means settings
|
||||
/// from layer `A` will be overridden by settings from layer `B`.
|
||||
impl PartialOrd for ConfigLayerSource {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
|
||||
Some(self.precedence().cmp(&other.precedence()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Identity and version information for a configuration layer.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ConfigLayerMetadata {
|
||||
pub name: ConfigLayerSource,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
/// A materialized configuration layer and its provenance.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ConfigLayer {
|
||||
pub name: ConfigLayerSource,
|
||||
pub version: String,
|
||||
pub config: JsonValue,
|
||||
pub disabled_reason: Option<String>,
|
||||
}
|
||||
|
||||
pub fn format_config_layer_source(source: &ConfigLayerSource, config_toml_file: &str) -> String {
|
||||
match source {
|
||||
ConfigLayerSource::PackagedDefaults { file } => {
|
||||
format!("packaged defaults ({})", file.as_path().display())
|
||||
}
|
||||
ConfigLayerSource::Mdm { domain, key } => {
|
||||
format!("MDM ({domain}:{key})")
|
||||
}
|
||||
ConfigLayerSource::System { file } => {
|
||||
format!("system ({})", file.as_path().display())
|
||||
}
|
||||
ConfigLayerSource::EnterpriseManaged { id, name } => {
|
||||
format!("enterprise-managed ({name}, {id})")
|
||||
}
|
||||
ConfigLayerSource::User { file, .. } => {
|
||||
format!("user ({})", file.as_path().display())
|
||||
}
|
||||
ConfigLayerSource::Project { dot_codex_folder } => {
|
||||
format!(
|
||||
"project ({}/{config_toml_file})",
|
||||
dot_codex_folder.as_path().display()
|
||||
)
|
||||
}
|
||||
ConfigLayerSource::SessionFlags => "session-flags".to_string(),
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => {
|
||||
format!("legacy managed_config.toml ({})", file.as_path().display())
|
||||
}
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromMdm => {
|
||||
"legacy managed_config.toml (MDM)".to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
5561
codex-rs/config/src/config_requirements.rs
Normal file
5561
codex-rs/config/src/config_requirements.rs
Normal file
File diff suppressed because it is too large
Load Diff
69
codex-rs/config/src/config_server.rs
Normal file
69
codex-rs/config/src/config_server.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! Trusted enrollment settings for a customer-hosted configuration server.
|
||||
//!
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::fmt;
|
||||
|
||||
pub use codex_model_provider_info::OAuthSessionConfig as ConfigServerOAuth;
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(try_from = "ConfigServerInput")]
|
||||
pub struct ConfigServer {
|
||||
pub base_url: String,
|
||||
// Boxing keeps config-loader futures small.
|
||||
pub oauth: Option<Box<ConfigServerOAuth>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ConfigServerInput {
|
||||
base_url: String,
|
||||
oauth: Option<Box<ConfigServerOAuth>>,
|
||||
}
|
||||
|
||||
impl TryFrom<ConfigServerInput> for ConfigServer {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(input: ConfigServerInput) -> Result<Self, Self::Error> {
|
||||
let service = Self {
|
||||
base_url: input.base_url,
|
||||
oauth: input.oauth,
|
||||
};
|
||||
service.validated_base_url()?;
|
||||
Ok(service)
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigServer {
|
||||
/// Validates the trusted settings and returns the normalized base URL.
|
||||
pub fn validated_base_url(&self) -> Result<String, String> {
|
||||
let validate_https_url = |value: &str| {
|
||||
codex_http_client::validate_endpoint_url(value, "config_server")
|
||||
.ok()
|
||||
.filter(|url| url.scheme() == "https")
|
||||
.ok_or("config_server URLs must use HTTPS without userinfo or fragments")
|
||||
};
|
||||
let endpoint = validate_https_url(&self.base_url)?;
|
||||
if endpoint.query().is_some() {
|
||||
return Err("config_server.base_url must not contain a query".into());
|
||||
}
|
||||
if let Some(oauth) = &self.oauth {
|
||||
validate_https_url(&oauth.authorization_url)?;
|
||||
validate_https_url(&oauth.token_url)?;
|
||||
if let Some(url) = &oauth.device_authorization_url {
|
||||
validate_https_url(url)?;
|
||||
}
|
||||
if oauth.client_id.trim().is_empty() || oauth.redirect_port == Some(0) {
|
||||
return Err("config_server OAuth requires a client ID and a nonzero redirect port when specified".into());
|
||||
}
|
||||
}
|
||||
Ok(endpoint.into())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for ConfigServer {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("ConfigServer").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
1205
codex-rs/config/src/config_toml.rs
Normal file
1205
codex-rs/config/src/config_toml.rs
Normal file
File diff suppressed because it is too large
Load Diff
344
codex-rs/config/src/constraint.rs
Normal file
344
codex-rs/config/src/constraint.rs
Normal file
@@ -0,0 +1,344 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::config_requirements::RequirementSource;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum ConstraintError {
|
||||
#[error(
|
||||
"invalid value for `{field_name}`: `{candidate}` is not in the allowed set {allowed} (set by {requirement_source})"
|
||||
)]
|
||||
InvalidValue {
|
||||
field_name: &'static str,
|
||||
candidate: String,
|
||||
allowed: String,
|
||||
requirement_source: RequirementSource,
|
||||
},
|
||||
|
||||
#[error("To use model `{model}`, you need to use auto review.")]
|
||||
AutoReviewRequired { model: String },
|
||||
|
||||
#[error("field `{field_name}` cannot be empty")]
|
||||
EmptyField { field_name: String },
|
||||
|
||||
#[error("invalid rules in requirements (set by {requirement_source}): {reason}")]
|
||||
ExecPolicyParse {
|
||||
requirement_source: RequirementSource,
|
||||
reason: String,
|
||||
},
|
||||
|
||||
#[error(
|
||||
"invalid requirement for MCP server `{server_name}` (set by {requirement_source}): {reason}"
|
||||
)]
|
||||
McpServerRequirementParse {
|
||||
server_name: String,
|
||||
requirement_source: RequirementSource,
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl ConstraintError {
|
||||
pub fn empty_field(field_name: impl Into<String>) -> Self {
|
||||
Self::EmptyField {
|
||||
field_name: field_name.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type ConstraintResult<T> = Result<T, ConstraintError>;
|
||||
|
||||
impl From<ConstraintError> for std::io::Error {
|
||||
fn from(err: ConstraintError) -> Self {
|
||||
std::io::Error::new(std::io::ErrorKind::InvalidInput, err)
|
||||
}
|
||||
}
|
||||
|
||||
type ConstraintValidator<T> = dyn Fn(&T) -> ConstraintResult<()> + Send + Sync;
|
||||
/// A ConstraintNormalizer is a function which transforms a value into another of the same type.
|
||||
/// `Constrained` uses normalizers to transform values to satisfy constraints or enforce values.
|
||||
type ConstraintNormalizer<T> = dyn Fn(T) -> T + Send + Sync;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Constrained<T> {
|
||||
value: T,
|
||||
validator: Arc<ConstraintValidator<T>>,
|
||||
normalizer: Option<Arc<ConstraintNormalizer<T>>>,
|
||||
}
|
||||
|
||||
impl<T: Send + Sync> Constrained<T> {
|
||||
pub fn new(
|
||||
initial_value: T,
|
||||
validator: impl Fn(&T) -> ConstraintResult<()> + Send + Sync + 'static,
|
||||
) -> ConstraintResult<Self> {
|
||||
let validator: Arc<ConstraintValidator<T>> = Arc::new(validator);
|
||||
validator(&initial_value)?;
|
||||
Ok(Self {
|
||||
value: initial_value,
|
||||
validator,
|
||||
normalizer: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// normalized creates a `Constrained` value with a normalizer function and a validator that allows any value.
|
||||
pub fn normalized(
|
||||
initial_value: T,
|
||||
normalizer: impl Fn(T) -> T + Send + Sync + 'static,
|
||||
) -> ConstraintResult<Self> {
|
||||
let validator: Arc<ConstraintValidator<T>> = Arc::new(|_| Ok(()));
|
||||
let normalizer: Arc<ConstraintNormalizer<T>> = Arc::new(normalizer);
|
||||
let normalized = normalizer(initial_value);
|
||||
validator(&normalized)?;
|
||||
Ok(Self {
|
||||
value: normalized,
|
||||
validator,
|
||||
normalizer: Some(normalizer),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn allow_any(initial_value: T) -> Self {
|
||||
Self {
|
||||
value: initial_value,
|
||||
validator: Arc::new(|_| Ok(())),
|
||||
normalizer: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn allow_only(only_value: T) -> Self
|
||||
where
|
||||
T: Clone + fmt::Debug + PartialEq + 'static,
|
||||
{
|
||||
let allowed_value = only_value.clone();
|
||||
Self {
|
||||
value: only_value,
|
||||
validator: Arc::new(move |candidate| {
|
||||
if candidate == &allowed_value {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ConstraintError::InvalidValue {
|
||||
field_name: "<unknown>",
|
||||
candidate: format!("{candidate:?}"),
|
||||
allowed: format!("[{allowed_value:?}]"),
|
||||
requirement_source: RequirementSource::Unknown,
|
||||
})
|
||||
}
|
||||
}),
|
||||
normalizer: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Allow any value of T, using T's Default as the initial value.
|
||||
pub fn allow_any_from_default() -> Self
|
||||
where
|
||||
T: Default,
|
||||
{
|
||||
Self::allow_any(T::default())
|
||||
}
|
||||
|
||||
pub fn get(&self) -> &T {
|
||||
&self.value
|
||||
}
|
||||
|
||||
pub fn value(&self) -> T
|
||||
where
|
||||
T: Copy,
|
||||
{
|
||||
self.value
|
||||
}
|
||||
|
||||
pub fn can_set(&self, candidate: &T) -> ConstraintResult<()> {
|
||||
(self.validator)(candidate)
|
||||
}
|
||||
|
||||
/// Composes an additional validator onto the current constraint.
|
||||
///
|
||||
/// The existing value must satisfy the combined validator before it is installed.
|
||||
pub fn add_validator(
|
||||
&mut self,
|
||||
validator: impl Fn(&T) -> ConstraintResult<()> + Send + Sync + 'static,
|
||||
) -> ConstraintResult<()>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let existing_validator = self.validator.clone();
|
||||
let combined_validator: Arc<ConstraintValidator<T>> = Arc::new(move |candidate| {
|
||||
existing_validator(candidate)?;
|
||||
validator(candidate)
|
||||
});
|
||||
|
||||
combined_validator(&self.value)?;
|
||||
self.validator = combined_validator;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set(&mut self, value: T) -> ConstraintResult<()> {
|
||||
let value = if let Some(normalizer) = &self.normalizer {
|
||||
normalizer(value)
|
||||
} else {
|
||||
value
|
||||
};
|
||||
(self.validator)(&value)?;
|
||||
self.value = value;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::ops::Deref for Constrained<T> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.value
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: fmt::Debug> fmt::Debug for Constrained<T> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("Constrained")
|
||||
.field("value", &self.value)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: PartialEq> PartialEq for Constrained<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.value == other.value
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn invalid_value(candidate: impl Into<String>, allowed: impl Into<String>) -> ConstraintError {
|
||||
ConstraintError::InvalidValue {
|
||||
field_name: "<unknown>",
|
||||
candidate: candidate.into(),
|
||||
allowed: allowed.into(),
|
||||
requirement_source: RequirementSource::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_allow_any_accepts_any_value() {
|
||||
let mut constrained = Constrained::allow_any(/*initial_value*/ 5);
|
||||
constrained
|
||||
.set(/*value*/ -10)
|
||||
.expect("allow any accepts all values");
|
||||
assert_eq!(constrained.value(), -10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_allow_any_default_uses_default_value() {
|
||||
let constrained = Constrained::<i32>::allow_any_from_default();
|
||||
assert_eq!(constrained.value(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_allow_only_rejects_different_values() {
|
||||
let mut constrained = Constrained::allow_only(/*only_value*/ 5);
|
||||
constrained
|
||||
.set(/*value*/ 5)
|
||||
.expect("allowed value should be accepted");
|
||||
|
||||
let err = constrained
|
||||
.set(/*value*/ 6)
|
||||
.expect_err("different value should be rejected");
|
||||
assert_eq!(err, invalid_value("6", "[5]"));
|
||||
assert_eq!(constrained.value(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_normalizer_applies_on_init_and_set() -> anyhow::Result<()> {
|
||||
let mut constrained =
|
||||
Constrained::normalized(/*initial_value*/ -1, |value| value.max(0))?;
|
||||
assert_eq!(constrained.value(), 0);
|
||||
constrained.set(/*value*/ -5)?;
|
||||
assert_eq!(constrained.value(), 0);
|
||||
constrained.set(/*value*/ 10)?;
|
||||
assert_eq!(constrained.value(), 10);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_add_validator_composes_with_existing_validator() -> anyhow::Result<()> {
|
||||
let mut constrained = Constrained::new(/*initial_value*/ 5, |value: &i32| {
|
||||
if *value >= 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ConstraintError::empty_field("value"))
|
||||
}
|
||||
})?;
|
||||
constrained.add_validator(|value| {
|
||||
if *value <= 10 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ConstraintError::empty_field("value"))
|
||||
}
|
||||
})?;
|
||||
|
||||
assert_eq!(constrained.can_set(&7), Ok(()));
|
||||
assert_eq!(
|
||||
constrained.can_set(&11),
|
||||
Err(ConstraintError::empty_field("value"))
|
||||
);
|
||||
assert_eq!(
|
||||
constrained.can_set(&-1),
|
||||
Err(ConstraintError::empty_field("value"))
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_new_rejects_invalid_initial_value() {
|
||||
let result = Constrained::new(/*initial_value*/ 0, |value| {
|
||||
if *value > 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(value.to_string(), "positive values"))
|
||||
}
|
||||
});
|
||||
|
||||
assert_eq!(result, Err(invalid_value("0", "positive values")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_set_rejects_invalid_value_and_leaves_previous() {
|
||||
let mut constrained = Constrained::new(/*initial_value*/ 1, |value| {
|
||||
if *value > 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(value.to_string(), "positive values"))
|
||||
}
|
||||
})
|
||||
.expect("initial value should be accepted");
|
||||
|
||||
let err = constrained
|
||||
.set(/*value*/ -5)
|
||||
.expect_err("negative values should be rejected");
|
||||
assert_eq!(err, invalid_value("-5", "positive values"));
|
||||
assert_eq!(constrained.value(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constrained_can_set_allows_probe_without_setting() {
|
||||
let constrained = Constrained::new(/*initial_value*/ 1, |value| {
|
||||
if *value > 0 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(invalid_value(value.to_string(), "positive values"))
|
||||
}
|
||||
})
|
||||
.expect("initial value should be accepted");
|
||||
|
||||
constrained
|
||||
.can_set(&2)
|
||||
.expect("can_set should accept positive value");
|
||||
let err = constrained
|
||||
.can_set(&-1)
|
||||
.expect_err("can_set should reject negative value");
|
||||
assert_eq!(err, invalid_value("-1", "positive values"));
|
||||
assert_eq!(constrained.value(), 1);
|
||||
}
|
||||
}
|
||||
495
codex-rs/config/src/diagnostics.rs
Normal file
495
codex-rs/config/src/diagnostics.rs
Normal file
@@ -0,0 +1,495 @@
|
||||
//! Helpers for mapping config parse/validation failures to file locations and
|
||||
//! rendering them in a user-friendly way.
|
||||
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::format_config_layer_source;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde_path_to_error::Path as SerdePath;
|
||||
use serde_path_to_error::Segment as SerdeSegment;
|
||||
use std::fmt;
|
||||
use std::fmt::Write;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use toml_edit::Document;
|
||||
use toml_edit::Item;
|
||||
use toml_edit::Table;
|
||||
use toml_edit::Value;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TextPosition {
|
||||
pub line: usize,
|
||||
pub column: usize,
|
||||
}
|
||||
|
||||
/// Text range in 1-based line/column coordinates.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TextRange {
|
||||
pub start: TextPosition,
|
||||
pub end: TextPosition,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ConfigError {
|
||||
pub path: PathBuf,
|
||||
pub range: TextRange,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ConfigError {
|
||||
pub fn new(path: PathBuf, range: TextRange, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
path,
|
||||
range,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ConfigLoadError {
|
||||
error: ConfigError,
|
||||
source: Option<toml::de::Error>,
|
||||
}
|
||||
|
||||
impl ConfigLoadError {
|
||||
pub fn new(error: ConfigError, source: Option<toml::de::Error>) -> Self {
|
||||
Self { error, source }
|
||||
}
|
||||
|
||||
pub fn config_error(&self) -> &ConfigError {
|
||||
&self.error
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for ConfigLoadError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{}:{}:{}: {}",
|
||||
self.error.path.display(),
|
||||
self.error.range.start.line,
|
||||
self.error.range.start.column,
|
||||
self.error.message
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConfigLoadError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
self.source
|
||||
.as_ref()
|
||||
.map(|err| err as &dyn std::error::Error)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum ConfigDiagnosticSource<'a> {
|
||||
Path(&'a Path),
|
||||
DisplayName(&'a str),
|
||||
}
|
||||
|
||||
impl ConfigDiagnosticSource<'_> {
|
||||
pub(crate) fn to_path_buf(self) -> PathBuf {
|
||||
match self {
|
||||
ConfigDiagnosticSource::Path(path) => path.to_path_buf(),
|
||||
ConfigDiagnosticSource::DisplayName(name) => PathBuf::from(name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn io_error_from_config_error(
|
||||
kind: io::ErrorKind,
|
||||
error: ConfigError,
|
||||
source: Option<toml::de::Error>,
|
||||
) -> io::Error {
|
||||
io::Error::new(kind, ConfigLoadError::new(error, source))
|
||||
}
|
||||
|
||||
pub fn config_error_from_toml(
|
||||
path: impl AsRef<Path>,
|
||||
contents: &str,
|
||||
err: toml::de::Error,
|
||||
) -> ConfigError {
|
||||
config_error_from_toml_for_source(ConfigDiagnosticSource::Path(path.as_ref()), contents, err)
|
||||
}
|
||||
|
||||
pub(crate) fn config_error_from_toml_for_source(
|
||||
source: ConfigDiagnosticSource<'_>,
|
||||
contents: &str,
|
||||
err: toml::de::Error,
|
||||
) -> ConfigError {
|
||||
let range = err
|
||||
.span()
|
||||
.map(|span| text_range_from_span(contents, span))
|
||||
.unwrap_or_else(default_range);
|
||||
ConfigError::new(source.to_path_buf(), range, err.message())
|
||||
}
|
||||
|
||||
pub fn config_error_from_typed_toml<T: DeserializeOwned>(
|
||||
path: impl AsRef<Path>,
|
||||
contents: &str,
|
||||
) -> Option<ConfigError> {
|
||||
config_error_from_typed_toml_for_source::<T>(
|
||||
ConfigDiagnosticSource::Path(path.as_ref()),
|
||||
contents,
|
||||
)
|
||||
}
|
||||
|
||||
fn config_error_from_typed_toml_for_source<T: DeserializeOwned>(
|
||||
source: ConfigDiagnosticSource<'_>,
|
||||
contents: &str,
|
||||
) -> Option<ConfigError> {
|
||||
let deserializer = match toml::de::Deserializer::parse(contents) {
|
||||
Ok(deserializer) => deserializer,
|
||||
Err(err) => return Some(config_error_from_toml_for_source(source, contents, err)),
|
||||
};
|
||||
|
||||
let result: Result<T, _> = serde_path_to_error::deserialize(deserializer);
|
||||
match result {
|
||||
Ok(_) => None,
|
||||
Err(err) => {
|
||||
let path_hint = err.path().clone();
|
||||
let toml_err: toml::de::Error = err.into_inner();
|
||||
let range = span_for_config_path(contents, &path_hint)
|
||||
.or_else(|| toml_err.span())
|
||||
.map(|span| text_range_from_span(contents, span))
|
||||
.unwrap_or_else(default_range);
|
||||
Some(ConfigError::new(
|
||||
source.to_path_buf(),
|
||||
range,
|
||||
toml_err.message(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn first_layer_config_error<T: DeserializeOwned>(
|
||||
layers: &ConfigLayerStack,
|
||||
config_toml_file: &str,
|
||||
) -> Option<ConfigError> {
|
||||
// When the merged config fails schema validation, we surface the first concrete
|
||||
// per-file error to point users at a specific file and range rather than an
|
||||
// opaque merged-layer failure.
|
||||
first_layer_config_error_for_entries::<T, _>(layers.layers_low_to_high(), config_toml_file)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn first_layer_config_error_from_entries<T: DeserializeOwned>(
|
||||
layers: &[ConfigLayerEntry],
|
||||
config_toml_file: &str,
|
||||
) -> Option<ConfigError> {
|
||||
first_layer_config_error_for_entries::<T, _>(layers.iter(), config_toml_file).await
|
||||
}
|
||||
|
||||
async fn first_layer_config_error_for_entries<'a, T: DeserializeOwned, I>(
|
||||
layers: I,
|
||||
config_toml_file: &str,
|
||||
) -> Option<ConfigError>
|
||||
where
|
||||
I: IntoIterator<Item = &'a ConfigLayerEntry>,
|
||||
{
|
||||
for layer in layers {
|
||||
if layer.is_disabled() {
|
||||
continue;
|
||||
}
|
||||
if let Some(contents) = layer.raw_toml() {
|
||||
let source_name = format_config_layer_source(&layer.name, config_toml_file);
|
||||
let Some(base_dir) = layer.raw_toml_base_dir() else {
|
||||
tracing::debug!(
|
||||
"Skipping raw TOML diagnostics for {source_name} because it has no base directory"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
// Match the base directory used when the raw non-file layer was
|
||||
// parsed into the runtime layer so diagnostics resolve relative
|
||||
// path fields with the same semantics.
|
||||
let _absolute_path_base = AbsolutePathBufGuard::new(base_dir.as_path());
|
||||
if let Some(error) = config_error_from_typed_toml_for_source::<T>(
|
||||
ConfigDiagnosticSource::DisplayName(&source_name),
|
||||
contents,
|
||||
) {
|
||||
return Some(error);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(path) = config_path_for_layer(layer, config_toml_file) else {
|
||||
continue;
|
||||
};
|
||||
let contents = match tokio::fs::read_to_string(&path).await {
|
||||
Ok(contents) => contents,
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => continue,
|
||||
Err(err) => {
|
||||
tracing::debug!("Failed to read config file {}: {err}", path.display());
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(parent) = path.parent() else {
|
||||
tracing::debug!("Config file {} has no parent directory", path.display());
|
||||
continue;
|
||||
};
|
||||
let _guard = AbsolutePathBufGuard::new(parent);
|
||||
if let Some(error) = config_error_from_typed_toml::<T>(&path, &contents) {
|
||||
return Some(error);
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn config_path_for_layer(layer: &ConfigLayerEntry, config_toml_file: &str) -> Option<PathBuf> {
|
||||
match &layer.name {
|
||||
ConfigLayerSource::PackagedDefaults { file } => Some(file.to_path_buf()),
|
||||
ConfigLayerSource::System { file } => Some(file.to_path_buf()),
|
||||
ConfigLayerSource::User { file, .. } => Some(file.to_path_buf()),
|
||||
ConfigLayerSource::Project { dot_codex_folder } => {
|
||||
Some(dot_codex_folder.as_path().join(config_toml_file))
|
||||
}
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => Some(file.to_path_buf()),
|
||||
ConfigLayerSource::Mdm { .. }
|
||||
| ConfigLayerSource::EnterpriseManaged { .. }
|
||||
| ConfigLayerSource::SessionFlags
|
||||
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn text_range_from_span(contents: &str, span: std::ops::Range<usize>) -> TextRange {
|
||||
let start = position_for_offset(contents, span.start);
|
||||
let end_index = if span.end > span.start {
|
||||
span.end - 1
|
||||
} else {
|
||||
span.end
|
||||
};
|
||||
let end = position_for_offset(contents, end_index);
|
||||
TextRange { start, end }
|
||||
}
|
||||
|
||||
pub fn format_config_error(error: &ConfigError, contents: &str) -> String {
|
||||
let mut output = String::new();
|
||||
let start = error.range.start;
|
||||
let _ = writeln!(
|
||||
output,
|
||||
"{}:{}:{}: {}",
|
||||
error.path.display(),
|
||||
start.line,
|
||||
start.column,
|
||||
error.message
|
||||
);
|
||||
|
||||
let line_index = start.line.saturating_sub(1);
|
||||
let line = match contents.lines().nth(line_index) {
|
||||
Some(line) => line.trim_end_matches('\r'),
|
||||
None => return output.trim_end().to_string(),
|
||||
};
|
||||
|
||||
let line_number = start.line;
|
||||
let gutter = line_number.to_string().len();
|
||||
let _ = writeln!(output, "{:width$} |", "", width = gutter);
|
||||
let _ = writeln!(output, "{line_number:>gutter$} | {line}");
|
||||
|
||||
let highlight_len = if error.range.end.line == error.range.start.line
|
||||
&& error.range.end.column >= error.range.start.column
|
||||
{
|
||||
error.range.end.column - error.range.start.column + 1
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let spaces = " ".repeat(start.column.saturating_sub(1));
|
||||
let carets = "^".repeat(highlight_len.max(1));
|
||||
let _ = writeln!(output, "{:width$} | {spaces}{carets}", "", width = gutter);
|
||||
output.trim_end().to_string()
|
||||
}
|
||||
|
||||
pub fn format_config_error_with_source(error: &ConfigError) -> String {
|
||||
match std::fs::read_to_string(&error.path) {
|
||||
Ok(contents) => format_config_error(error, &contents),
|
||||
Err(_) => format_config_error(error, ""),
|
||||
}
|
||||
}
|
||||
|
||||
fn position_for_offset(contents: &str, index: usize) -> TextPosition {
|
||||
let bytes = contents.as_bytes();
|
||||
if bytes.is_empty() {
|
||||
return TextPosition { line: 1, column: 1 };
|
||||
}
|
||||
|
||||
let safe_index = index.min(bytes.len().saturating_sub(1));
|
||||
let column_offset = index.saturating_sub(safe_index);
|
||||
let index = safe_index;
|
||||
|
||||
let line_start = bytes[..index]
|
||||
.iter()
|
||||
.rposition(|byte| *byte == b'\n')
|
||||
.map(|pos| pos + 1)
|
||||
.unwrap_or(0);
|
||||
let line = bytes[..line_start]
|
||||
.iter()
|
||||
.filter(|byte| **byte == b'\n')
|
||||
.count();
|
||||
|
||||
let column = std::str::from_utf8(&bytes[line_start..=index])
|
||||
.map(|slice| slice.chars().count().saturating_sub(1))
|
||||
.unwrap_or_else(|_| index - line_start);
|
||||
let column = column + column_offset;
|
||||
|
||||
TextPosition {
|
||||
line: line + 1,
|
||||
column: column + 1,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn default_range() -> TextRange {
|
||||
let position = TextPosition { line: 1, column: 1 };
|
||||
TextRange {
|
||||
start: position,
|
||||
end: position,
|
||||
}
|
||||
}
|
||||
|
||||
enum TomlNode<'a> {
|
||||
Item(&'a Item),
|
||||
Table(&'a Table),
|
||||
Value(&'a Value),
|
||||
}
|
||||
|
||||
fn span_for_path(contents: &str, path: &SerdePath) -> Option<std::ops::Range<usize>> {
|
||||
let doc = contents.parse::<Document<String>>().ok()?;
|
||||
let node = node_for_path(doc.as_item(), path)?;
|
||||
match node {
|
||||
TomlNode::Item(item) => item.span(),
|
||||
TomlNode::Table(table) => table.span(),
|
||||
TomlNode::Value(value) => value.span(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn span_for_config_path(
|
||||
contents: &str,
|
||||
path: &SerdePath,
|
||||
) -> Option<std::ops::Range<usize>> {
|
||||
if is_features_table_path(path)
|
||||
&& let Some(span) = span_for_features_value(contents)
|
||||
{
|
||||
return Some(span);
|
||||
}
|
||||
span_for_path(contents, path)
|
||||
}
|
||||
|
||||
pub(crate) fn span_for_toml_key_path(
|
||||
contents: &str,
|
||||
path: &[String],
|
||||
) -> Option<std::ops::Range<usize>> {
|
||||
let doc = contents.parse::<Document<String>>().ok()?;
|
||||
let mut node = TomlNode::Item(doc.as_item());
|
||||
for (index, segment) in path.iter().enumerate() {
|
||||
if index + 1 == path.len() {
|
||||
let key_span = match &node {
|
||||
TomlNode::Item(item) => item
|
||||
.as_table_like()
|
||||
.and_then(|table| table.get_key_value(segment))
|
||||
.and_then(|(key, _)| key.span()),
|
||||
TomlNode::Table(table) => {
|
||||
table.get_key_value(segment).and_then(|(key, _)| key.span())
|
||||
}
|
||||
TomlNode::Value(Value::InlineTable(table)) => {
|
||||
table.get_key_value(segment).and_then(|(key, _)| key.span())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if key_span.is_some() {
|
||||
return key_span;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(next) = map_child(&node, segment) {
|
||||
node = next;
|
||||
continue;
|
||||
}
|
||||
|
||||
let index = segment.parse::<usize>().ok()?;
|
||||
node = seq_child(&node, index)?;
|
||||
}
|
||||
|
||||
match node {
|
||||
TomlNode::Item(item) => item.span(),
|
||||
TomlNode::Table(table) => table.span(),
|
||||
TomlNode::Value(value) => value.span(),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_features_table_path(path: &SerdePath) -> bool {
|
||||
let mut segments = path.iter();
|
||||
matches!(segments.next(), Some(SerdeSegment::Map { key }) if key == "features")
|
||||
&& segments.next().is_none()
|
||||
}
|
||||
|
||||
fn span_for_features_value(contents: &str) -> Option<std::ops::Range<usize>> {
|
||||
let doc = contents.parse::<Document<String>>().ok()?;
|
||||
let root = doc.as_item().as_table_like()?;
|
||||
let features_item = root.get("features")?;
|
||||
let features_table = features_item.as_table_like()?;
|
||||
for (_, item) in features_table.iter() {
|
||||
match item {
|
||||
Item::Value(Value::Boolean(_)) => continue,
|
||||
Item::Value(value) => return value.span(),
|
||||
Item::Table(table) => return table.span(),
|
||||
Item::ArrayOfTables(array) => return array.span(),
|
||||
Item::None => continue,
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn node_for_path<'a>(item: &'a Item, path: &SerdePath) -> Option<TomlNode<'a>> {
|
||||
let segments: Vec<_> = path.iter().cloned().collect();
|
||||
let mut node = TomlNode::Item(item);
|
||||
let mut index = 0;
|
||||
while index < segments.len() {
|
||||
match &segments[index] {
|
||||
SerdeSegment::Map { key } | SerdeSegment::Enum { variant: key } => {
|
||||
if let Some(next) = map_child(&node, key) {
|
||||
node = next;
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if index + 1 < segments.len() {
|
||||
index += 1;
|
||||
continue;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
SerdeSegment::Seq { index: seq_index } => {
|
||||
node = seq_child(&node, *seq_index)?;
|
||||
index += 1;
|
||||
}
|
||||
SerdeSegment::Unknown => return None,
|
||||
}
|
||||
}
|
||||
Some(node)
|
||||
}
|
||||
|
||||
fn map_child<'a>(node: &TomlNode<'a>, key: &str) -> Option<TomlNode<'a>> {
|
||||
match node {
|
||||
TomlNode::Item(item) => {
|
||||
let table = item.as_table_like()?;
|
||||
table.get(key).map(TomlNode::Item)
|
||||
}
|
||||
TomlNode::Table(table) => table.get(key).map(TomlNode::Item),
|
||||
TomlNode::Value(Value::InlineTable(table)) => table.get(key).map(TomlNode::Value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn seq_child<'a>(node: &TomlNode<'a>, index: usize) -> Option<TomlNode<'a>> {
|
||||
match node {
|
||||
TomlNode::Item(Item::Value(Value::Array(array))) => array.get(index).map(TomlNode::Value),
|
||||
TomlNode::Item(Item::ArrayOfTables(array)) => array.get(index).map(TomlNode::Table),
|
||||
TomlNode::Value(Value::Array(array)) => array.get(index).map(TomlNode::Value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
62
codex-rs/config/src/filesystem_constraints.rs
Normal file
62
codex-rs/config/src/filesystem_constraints.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
//! Convert resolved filesystem denials into portable policy entries.
|
||||
|
||||
use crate::FilesystemConstraints;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_path_uri::LegacyAppPathStringError;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::io;
|
||||
|
||||
impl FilesystemConstraints {
|
||||
/// Adds denials without changing existing entries or other policy settings.
|
||||
/// `convention` must match the executor facts used to resolve these requirements.
|
||||
/// Literal paths become URIs; glob spellings and entry order are preserved.
|
||||
/// Invalid denials return an error before the policy is changed.
|
||||
pub fn apply_to_policy(
|
||||
&self,
|
||||
policy: &mut FileSystemSandboxPolicy,
|
||||
convention: PathConvention,
|
||||
) -> io::Result<()> {
|
||||
let entries = self
|
||||
.deny_read
|
||||
.iter()
|
||||
.map(|deny_read| {
|
||||
PathUri::validate_config_path_text(deny_read.as_str(), convention)?;
|
||||
let path = if deny_read.contains_glob() {
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: deny_read.as_str().to_string(),
|
||||
}
|
||||
} else {
|
||||
let mut path = LegacyAppPathString::from_string(deny_read.as_str())
|
||||
.to_path_uri(convention)?;
|
||||
path.validate_config_path(convention)?;
|
||||
// Match Core's existing URI spelling for UNC share roots.
|
||||
if path.to_url().host_str().is_some() {
|
||||
path = path.join(".")?;
|
||||
}
|
||||
path.into()
|
||||
};
|
||||
Ok(FileSystemSandboxEntry::new(
|
||||
path,
|
||||
FileSystemAccessMode::Deny,
|
||||
))
|
||||
})
|
||||
.collect::<Result<Vec<_>, LegacyAppPathStringError>>()
|
||||
.map_err(|error| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("invalid permissions.filesystem.deny_read path: {error}"),
|
||||
)
|
||||
})?;
|
||||
for entry in entries {
|
||||
if !policy.entries.contains(&entry) {
|
||||
policy.entries.push(entry);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
70
codex-rs/config/src/fingerprint.rs
Normal file
70
codex-rs/config/src/fingerprint.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use crate::ConfigLayerMetadata;
|
||||
use crate::merge::is_structured_feature_path;
|
||||
use serde_json::Value as JsonValue;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
use std::collections::HashMap;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
pub(super) fn record_origins(
|
||||
value: &TomlValue,
|
||||
meta: &ConfigLayerMetadata,
|
||||
path: &mut Vec<String>,
|
||||
origins: &mut HashMap<String, ConfigLayerMetadata>,
|
||||
include: &impl Fn(&[String]) -> bool,
|
||||
) {
|
||||
match value {
|
||||
TomlValue::Table(table) => {
|
||||
for (key, val) in table {
|
||||
path.push(key.clone());
|
||||
record_origins(val, meta, path, origins, include);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
TomlValue::Array(items) => {
|
||||
for (idx, item) in (0_i32..).zip(items.iter()) {
|
||||
path.push(idx.to_string());
|
||||
record_origins(item, meta, path, origins, include);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if !path.is_empty() {
|
||||
if !include(path) {
|
||||
return;
|
||||
}
|
||||
if matches!(value, TomlValue::Boolean(_)) && is_structured_feature_path(path) {
|
||||
if path
|
||||
.last()
|
||||
.is_some_and(|feature| feature == "network_proxy")
|
||||
{
|
||||
origins.insert(path.join("."), meta.clone());
|
||||
}
|
||||
path.push("enabled".to_string());
|
||||
origins.insert(path.join("."), meta.clone());
|
||||
path.pop();
|
||||
return;
|
||||
}
|
||||
origins.insert(path.join("."), meta.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn version_for_toml(value: &TomlValue) -> String {
|
||||
let mut json = serde_json::to_value(value).unwrap_or(JsonValue::Null);
|
||||
json.sort_all_objects();
|
||||
let serialized = serde_json::to_vec(&json).unwrap_or_default();
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(serialized);
|
||||
let hash = hasher.finalize();
|
||||
let hex = hash
|
||||
.iter()
|
||||
.map(|byte| format!("{byte:02x}"))
|
||||
.collect::<String>();
|
||||
format!("sha256:{hex}")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "fingerprint_tests.rs"]
|
||||
mod tests;
|
||||
26
codex-rs/config/src/fingerprint_tests.rs
Normal file
26
codex-rs/config/src/fingerprint_tests.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
//! Protects fingerprint bytes when nested configuration keys are reordered.
|
||||
|
||||
use super::version_for_toml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn fingerprint_preserves_nested_key_order_independence_and_existing_hash() {
|
||||
for input in [
|
||||
r#"rows = [{ z = 2, a = 1 }, { z = 4, a = 3 }]
|
||||
[nested]
|
||||
z = "text"
|
||||
a = true
|
||||
"#,
|
||||
r#"rows = [{ a = 1, z = 2 }, { a = 3, z = 4 }]
|
||||
[nested]
|
||||
a = true
|
||||
z = "text"
|
||||
"#,
|
||||
] {
|
||||
let value = toml::from_str(input).expect("valid config");
|
||||
assert_eq!(
|
||||
version_for_toml(&value),
|
||||
"sha256:a5e4c8fbdbc75d185b0f2b5291bfb2de10e8c523d6c89248876fd78a97c83176"
|
||||
);
|
||||
}
|
||||
}
|
||||
109
codex-rs/config/src/guardian.rs
Normal file
109
codex-rs/config/src/guardian.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
//! Translates legacy Guardian settings and applies captured managed constraints.
|
||||
//! Catalog policies take precedence over legacy scope and feature settings.
|
||||
|
||||
use codex_features::FeatureToml;
|
||||
use codex_features::GuardianV2ConfigToml;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::GuardianModelPolicy;
|
||||
use codex_protocol::openai_models::GuardianReviewMode;
|
||||
use codex_protocol::openai_models::GuardianUnscoredAction;
|
||||
use codex_protocol::openai_models::ModelInfo;
|
||||
|
||||
use crate::ConfigRequirements;
|
||||
|
||||
/// Load-boundary adapter for configuration that predates model-owned policies.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GuardianPolicyLoader {
|
||||
default: GuardianModelPolicy,
|
||||
scoring_disabled: bool,
|
||||
}
|
||||
|
||||
impl GuardianPolicyLoader {
|
||||
pub fn new(legacy: Option<&FeatureToml<GuardianV2ConfigToml>>) -> Self {
|
||||
let scope = match legacy {
|
||||
Some(FeatureToml::Config(config)) => config.review_scope.as_ref(),
|
||||
Some(FeatureToml::Enabled(_)) | None => None,
|
||||
};
|
||||
let computer_use_only = scope
|
||||
.and_then(|scope| scope.computer_use_only)
|
||||
.unwrap_or(/*default*/ true);
|
||||
let other = if computer_use_only {
|
||||
GuardianReviewMode::Synchronous
|
||||
} else {
|
||||
GuardianReviewMode::Adaptive
|
||||
};
|
||||
let default = GuardianModelPolicy {
|
||||
computer_use: Some(GuardianReviewMode::Adaptive),
|
||||
shell: Some(other),
|
||||
file_changes: Some(other),
|
||||
mcp: Some(other),
|
||||
network: Some(other),
|
||||
permissions: Some(other),
|
||||
other_tools: other,
|
||||
unscored_action: if computer_use_only {
|
||||
GuardianUnscoredAction::Ignore
|
||||
} else {
|
||||
GuardianUnscoredAction::AgeScore
|
||||
},
|
||||
initial_cua_call: Some(computer_use_only),
|
||||
sandboxed_exec_commands: Some(
|
||||
!computer_use_only
|
||||
&& scope
|
||||
.and_then(|scope| scope.sandboxed_exec_commands)
|
||||
.unwrap_or(/*default*/ false),
|
||||
),
|
||||
};
|
||||
let enabled = legacy.and_then(FeatureToml::enabled);
|
||||
Self {
|
||||
default,
|
||||
scoring_disabled: !enabled.unwrap_or(/*default*/ false),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(
|
||||
&self,
|
||||
model: Option<&ModelInfo>,
|
||||
requirements: &ConfigRequirements,
|
||||
) -> GuardianModelPolicy {
|
||||
let catalog = model.and_then(|model| model.guardian.as_ref());
|
||||
let mut policy = catalog.cloned().unwrap_or_else(|| self.default.clone());
|
||||
if catalog.is_none()
|
||||
&& policy.allows_initial_cua_call()
|
||||
&& model.is_some_and(|model| !model.node_repl_auto_review_required)
|
||||
{
|
||||
policy.computer_use = Some(GuardianReviewMode::Synchronous);
|
||||
policy.initial_cua_call = Some(false);
|
||||
policy.unscored_action = GuardianUnscoredAction::InvalidateScore;
|
||||
}
|
||||
// Preserve the legacy feature gate: explicit catalog policies bypass it.
|
||||
if self.scoring_disabled && catalog.is_none() {
|
||||
policy.disable_scoring();
|
||||
}
|
||||
requirements.constrain_guardian_policy(&mut policy, model.map(|model| model.slug.as_str()));
|
||||
policy
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigRequirements {
|
||||
/// Applies the supplied administrator requirements to an already resolved model policy.
|
||||
/// The reviewer allowlist applies even when model metadata is unavailable.
|
||||
pub fn constrain_guardian_policy(&self, policy: &mut GuardianModelPolicy, model: Option<&str>) {
|
||||
if [ApprovalsReviewer::User, ApprovalsReviewer::AutoReview]
|
||||
.iter()
|
||||
.any(|reviewer| self.approvals_reviewer.can_set(reviewer).is_err())
|
||||
{
|
||||
policy.disable_scoring();
|
||||
} else if model.is_some_and(|model| self.auto_review_required_for_model(model)) {
|
||||
let computer_use = policy.computer_use;
|
||||
let initial_cua_call = policy.allows_initial_cua_call();
|
||||
policy.disable_scoring();
|
||||
if initial_cua_call {
|
||||
policy.computer_use = computer_use;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "guardian_tests.rs"]
|
||||
mod tests;
|
||||
151
codex-rs/config/src/guardian_tests.rs
Normal file
151
codex-rs/config/src/guardian_tests.rs
Normal file
@@ -0,0 +1,151 @@
|
||||
use super::*;
|
||||
use crate::FeatureRequirementsToml;
|
||||
use crate::RequirementSource;
|
||||
use crate::Sourced;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[test]
|
||||
fn explicit_catalog_policy_preserves_precedence_over_the_legacy_switch() {
|
||||
let catalog: GuardianModelPolicy = serde_json::from_value(json!({
|
||||
"computer_use": "adaptive", "shell": "disabled"
|
||||
}))
|
||||
.unwrap();
|
||||
for legacy in [json!(false), json!({"enabled": false})] {
|
||||
let legacy = serde_json::from_value(legacy).unwrap();
|
||||
for managed in [None, Some(false), Some(true)] {
|
||||
let requirements = ConfigRequirements {
|
||||
feature_requirements: managed.map(|enabled| {
|
||||
Sourced::new(
|
||||
FeatureRequirementsToml {
|
||||
entries: [("guardianv2".to_owned(), enabled)].into(),
|
||||
..Default::default()
|
||||
},
|
||||
RequirementSource::Unknown,
|
||||
)
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let mut model = test_model();
|
||||
model.guardian = Some(catalog.clone());
|
||||
assert_eq!(
|
||||
GuardianPolicyLoader::new(Some(&legacy)).resolve(Some(&model), &requirements),
|
||||
catalog
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_scope_applies_only_to_models_without_catalog_policy() {
|
||||
let legacy = serde_json::from_value(json!({
|
||||
"enabled": true,
|
||||
"review_scope": {"computer_use_only": false, "sandboxed_exec_commands": true}
|
||||
}))
|
||||
.unwrap();
|
||||
let loader = GuardianPolicyLoader::new(Some(&legacy));
|
||||
let expected = GuardianModelPolicy {
|
||||
computer_use: Some(GuardianReviewMode::Adaptive),
|
||||
shell: Some(GuardianReviewMode::Adaptive),
|
||||
file_changes: Some(GuardianReviewMode::Adaptive),
|
||||
mcp: Some(GuardianReviewMode::Adaptive),
|
||||
network: Some(GuardianReviewMode::Adaptive),
|
||||
permissions: Some(GuardianReviewMode::Adaptive),
|
||||
other_tools: GuardianReviewMode::Adaptive,
|
||||
unscored_action: GuardianUnscoredAction::AgeScore,
|
||||
initial_cua_call: Some(false),
|
||||
sandboxed_exec_commands: Some(true),
|
||||
};
|
||||
assert_eq!(
|
||||
loader.resolve(/*model*/ None, &ConfigRequirements::default()),
|
||||
expected
|
||||
);
|
||||
let catalog: GuardianModelPolicy =
|
||||
serde_json::from_value(json!({"computer_use": "adaptive"})).unwrap();
|
||||
let mut model = test_model();
|
||||
model.guardian = Some(catalog.clone());
|
||||
assert_eq!(
|
||||
loader.resolve(Some(&model), &ConfigRequirements::default()),
|
||||
catalog
|
||||
);
|
||||
for reviewer in [ApprovalsReviewer::AutoReview, ApprovalsReviewer::User] {
|
||||
let restricted: ConfigRequirements = crate::ConfigRequirementsWithSources {
|
||||
allowed_approvals_reviewers: Some(Sourced::new(
|
||||
vec![reviewer],
|
||||
RequirementSource::Unknown,
|
||||
)),
|
||||
..Default::default()
|
||||
}
|
||||
.try_into()
|
||||
.unwrap();
|
||||
// Reuse the same cached base across tightening and relaxation, including
|
||||
// decisions without model metadata.
|
||||
for model in [None, Some(&model)] {
|
||||
let base = loader.resolve(model, &ConfigRequirements::default());
|
||||
let mut synchronous = base.clone();
|
||||
synchronous.disable_scoring();
|
||||
assert_eq!(loader.resolve(model, &restricted), synchronous);
|
||||
assert_eq!(loader.resolve(model, &ConfigRequirements::default()), base);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_models_preserve_cua_allowance_and_disable_all_tools_scoring() {
|
||||
let requirements = ConfigRequirements {
|
||||
auto_review_required_models: Some(Sourced::new(
|
||||
BTreeSet::from(["protected-model".to_owned()]),
|
||||
RequirementSource::Unknown,
|
||||
)),
|
||||
..Default::default()
|
||||
};
|
||||
let legacy = serde_json::from_value(json!({
|
||||
"enabled": true, "review_scope": {"computer_use_only": false}
|
||||
}))
|
||||
.unwrap();
|
||||
let cua_only = FeatureToml::Enabled(true);
|
||||
for legacy in [Some(&cua_only), Some(&legacy)] {
|
||||
let loader = GuardianPolicyLoader::new(legacy);
|
||||
let ordinary = loader.resolve(/*model*/ None, &requirements);
|
||||
let mut expected = ordinary.clone();
|
||||
expected.disable_scoring();
|
||||
if ordinary.allows_initial_cua_call() {
|
||||
expected.computer_use = ordinary.computer_use;
|
||||
}
|
||||
let mut actual = ordinary;
|
||||
requirements.constrain_guardian_policy(&mut actual, Some("provider/protected-model"));
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_cua_opt_in_and_disabled_feature_preserve_scoring_behavior() {
|
||||
for legacy in [
|
||||
json!(false),
|
||||
json!({"review_scope": {"computer_use_only": true}}),
|
||||
json!(true),
|
||||
] {
|
||||
let enabled = legacy == json!(true);
|
||||
let legacy = serde_json::from_value(legacy).unwrap();
|
||||
let loader = GuardianPolicyLoader::new(Some(&legacy));
|
||||
for required in [false, true] {
|
||||
let mut model = test_model();
|
||||
model.node_repl_auto_review_required = required;
|
||||
let policy = loader.resolve(Some(&model), &ConfigRequirements::default());
|
||||
assert_eq!(policy.scoring_enabled(), enabled && required);
|
||||
assert_eq!(model.computer_use_review_required(), required);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn test_model() -> ModelInfo {
|
||||
serde_json::from_value(json!({
|
||||
"slug": "test-model", "display_name": "test-model",
|
||||
"supported_reasoning_levels": [], "shell_type": "shell_command",
|
||||
"visibility": "list", "supported_in_api": true, "priority": 0,
|
||||
"support_verbosity": false, "truncation_policy": {"mode": "bytes", "limit": 10000},
|
||||
"experimental_supported_tools": []
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
77
codex-rs/config/src/hook_config.rs
Normal file
77
codex-rs/config/src/hook_config.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
pub use codex_protocol::hooks::HookEventsToml;
|
||||
pub use codex_protocol::hooks::HookHandlerConfig;
|
||||
pub use codex_protocol::hooks::MatcherGroup;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct HooksFile {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub description: Option<String>,
|
||||
#[serde(default)]
|
||||
pub hooks: HookEventsToml,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct HooksToml {
|
||||
#[serde(flatten)]
|
||||
pub events: HookEventsToml,
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub state: BTreeMap<String, HookStateToml>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct HookStateToml {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub trusted_hash: Option<String>,
|
||||
/// Approved plugin contents; kept separate for declaration-only clients.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub trusted_content_hash: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ManagedHooksRequirementsToml {
|
||||
pub managed_dir: Option<PathBuf>,
|
||||
pub windows_managed_dir: Option<PathBuf>,
|
||||
#[serde(flatten)]
|
||||
pub hooks: Box<HookEventsToml>,
|
||||
}
|
||||
|
||||
impl ManagedHooksRequirementsToml {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
let Self {
|
||||
managed_dir,
|
||||
windows_managed_dir,
|
||||
hooks,
|
||||
} = self;
|
||||
managed_dir.is_none() && windows_managed_dir.is_none() && hooks.is_empty()
|
||||
}
|
||||
|
||||
pub fn handler_count(&self) -> usize {
|
||||
self.hooks.handler_count()
|
||||
}
|
||||
|
||||
pub fn managed_dir_for_current_platform(&self) -> Option<&Path> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
self.windows_managed_dir.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
self.managed_dir.as_deref()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "hooks_tests.rs"]
|
||||
mod tests;
|
||||
364
codex-rs/config/src/hooks_tests.rs
Normal file
364
codex-rs/config/src/hooks_tests.rs
Normal file
@@ -0,0 +1,364 @@
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use super::HookEventsToml;
|
||||
use super::HookHandlerConfig;
|
||||
use super::HooksFile;
|
||||
use super::HooksToml;
|
||||
use super::ManagedHooksRequirementsToml;
|
||||
use super::MatcherGroup;
|
||||
|
||||
#[test]
|
||||
fn hooks_file_deserializes_existing_json_shape() {
|
||||
let parsed: HooksFile = serde_json::from_str(
|
||||
r#"{
|
||||
"description": "Optional stop-time review gate for Codex Companion.",
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "^Bash$",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 /tmp/pre.py",
|
||||
"timeout": 10,
|
||||
"statusMessage": "checking",
|
||||
"additionalContextLimit": 4096
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}"#,
|
||||
)
|
||||
.expect("hooks.json should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HooksFile {
|
||||
description: Some("Optional stop-time review gate for Codex Companion.".to_string()),
|
||||
hooks: HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("^Bash$".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "python3 /tmp/pre.py".to_string(),
|
||||
command_windows: None,
|
||||
timeout_sec: Some(10),
|
||||
r#async: false,
|
||||
status_message: Some("checking".to_string()),
|
||||
additional_context_limit: Some(4096),
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooks_file_deserializes_mcp_tool_handler_with_json_inputs() {
|
||||
let parsed: HooksFile = serde_json::from_value(serde_json::json!({
|
||||
"hooks": {
|
||||
"PostToolUse": [{
|
||||
"matcher": "Write|Edit",
|
||||
"hooks": [{
|
||||
"type": "mcp_tool",
|
||||
"server": "security",
|
||||
"tool": "scan",
|
||||
"input": {
|
||||
"file_path": "${tool_input.file_path}",
|
||||
"include_ignored": false,
|
||||
},
|
||||
"timeout": 30,
|
||||
"statusMessage": "Scanning file",
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}))
|
||||
.expect("MCP tool hooks should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed.hooks.post_tool_use[0].hooks,
|
||||
vec![HookHandlerConfig::McpTool {
|
||||
server: "security".to_string(),
|
||||
tool: "scan".to_string(),
|
||||
input: serde_json::Map::from_iter([
|
||||
(
|
||||
"file_path".to_string(),
|
||||
serde_json::Value::String("${tool_input.file_path}".to_string()),
|
||||
),
|
||||
(
|
||||
"include_ignored".to_string(),
|
||||
serde_json::Value::Bool(false)
|
||||
),
|
||||
]),
|
||||
timeout_sec: Some(30),
|
||||
status_message: Some("Scanning file".to_string()),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooks_file_rejects_mcp_tool_handler_with_null_input() {
|
||||
for input in [
|
||||
serde_json::json!({ "optional": null }),
|
||||
serde_json::json!({ "metadata": { "optional": null } }),
|
||||
serde_json::json!({ "values": [null] }),
|
||||
] {
|
||||
let error = serde_json::from_value::<HooksFile>(serde_json::json!({
|
||||
"hooks": {
|
||||
"PostToolUse": [{
|
||||
"hooks": [{
|
||||
"type": "mcp_tool",
|
||||
"server": "security",
|
||||
"tool": "scan",
|
||||
"input": input,
|
||||
}],
|
||||
}],
|
||||
},
|
||||
}))
|
||||
.expect_err("literal null MCP hook arguments should be rejected");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("MCP hook input must be representable as TOML"),
|
||||
"unexpected parse error: {error}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooks_file_rejects_events_outside_hooks_object() {
|
||||
let error = serde_json::from_str::<HooksFile>(
|
||||
r#"{
|
||||
"SessionStart": [
|
||||
{
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "python3 /tmp/session_start.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}"#,
|
||||
)
|
||||
.expect_err("root-level hook events should be rejected");
|
||||
|
||||
assert!(
|
||||
error.to_string().contains("unknown field `SessionStart`"),
|
||||
"unexpected parse error: {error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_events_deserialize_from_toml_arrays_of_tables() {
|
||||
let parsed: HookEventsToml = toml::from_str(
|
||||
r#"
|
||||
[[PreToolUse]]
|
||||
matcher = "^Bash$"
|
||||
|
||||
[[PreToolUse.hooks]]
|
||||
type = "command"
|
||||
command = "python3 /tmp/pre.py"
|
||||
timeout = 10
|
||||
statusMessage = "checking"
|
||||
additionalContextLimit = 4096
|
||||
"#,
|
||||
)
|
||||
.expect("hook events TOML should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("^Bash$".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "python3 /tmp/pre.py".to_string(),
|
||||
command_windows: None,
|
||||
timeout_sec: Some(10),
|
||||
r#async: false,
|
||||
status_message: Some("checking".to_string()),
|
||||
additional_context_limit: Some(4096),
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hooks_toml_deserializes_inline_events_and_state_map() {
|
||||
let parsed: HooksToml = toml::from_str(
|
||||
r#"
|
||||
[state."/tmp/hooks.json:pre_tool_use:0:0"]
|
||||
enabled = false
|
||||
trusted_hash = "sha256:abc123"
|
||||
|
||||
[[PreToolUse]]
|
||||
matcher = "^Bash$"
|
||||
|
||||
[[PreToolUse.hooks]]
|
||||
type = "command"
|
||||
command = "python3 /tmp/pre.py"
|
||||
"#,
|
||||
)
|
||||
.expect("hooks TOML should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HooksToml {
|
||||
events: HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("^Bash$".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "python3 /tmp/pre.py".to_string(),
|
||||
command_windows: None,
|
||||
timeout_sec: None,
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
additional_context_limit: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
state: BTreeMap::from([(
|
||||
"/tmp/hooks.json:pre_tool_use:0:0".to_string(),
|
||||
super::HookStateToml {
|
||||
enabled: Some(false),
|
||||
trusted_hash: Some("sha256:abc123".to_string()),
|
||||
trusted_content_hash: None,
|
||||
},
|
||||
)]),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_hooks_requirements_flatten_hook_events() {
|
||||
let parsed: ManagedHooksRequirementsToml = toml::from_str(
|
||||
r#"
|
||||
managed_dir = "/enterprise/place"
|
||||
|
||||
[[PreToolUse]]
|
||||
matcher = "^Bash$"
|
||||
|
||||
[[PreToolUse.hooks]]
|
||||
type = "command"
|
||||
command = "python3 /enterprise/place/pre.py"
|
||||
"#,
|
||||
)
|
||||
.expect("requirements hooks TOML should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
ManagedHooksRequirementsToml {
|
||||
managed_dir: Some(std::path::PathBuf::from("/enterprise/place")),
|
||||
windows_managed_dir: None,
|
||||
hooks: Box::new(HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("^Bash$".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "python3 /enterprise/place/pre.py".to_string(),
|
||||
command_windows: None,
|
||||
timeout_sec: None,
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
additional_context_limit: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_events_deserialize_windows_override_from_toml() {
|
||||
let parsed: HookEventsToml = toml::from_str(
|
||||
r#"
|
||||
[[PreToolUse]]
|
||||
matcher = "^Bash$"
|
||||
|
||||
[[PreToolUse.hooks]]
|
||||
type = "command"
|
||||
command = "bash /enterprise/hooks/pre.sh"
|
||||
command_windows = "powershell -File C:\\enterprise\\hooks\\pre.ps1"
|
||||
"#,
|
||||
)
|
||||
.expect("hook command Windows override TOML should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("^Bash$".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "bash /enterprise/hooks/pre.sh".to_string(),
|
||||
command_windows: Some(
|
||||
r"powershell -File C:\enterprise\hooks\pre.ps1".to_string(),
|
||||
),
|
||||
timeout_sec: None,
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
additional_context_limit: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_events_deserialize_camel_case_windows_override_from_toml() {
|
||||
let parsed: HookEventsToml = toml::from_str(
|
||||
r#"
|
||||
[[PreToolUse]]
|
||||
matcher = "^Bash$"
|
||||
|
||||
[[PreToolUse.hooks]]
|
||||
type = "command"
|
||||
command = "bash /enterprise/hooks/pre.sh"
|
||||
commandWindows = "powershell -File C:\\enterprise\\hooks\\pre.ps1"
|
||||
"#,
|
||||
)
|
||||
.expect("camelCase hook command Windows override TOML should deserialize");
|
||||
|
||||
assert_eq!(
|
||||
parsed,
|
||||
HookEventsToml {
|
||||
pre_tool_use: vec![MatcherGroup {
|
||||
matcher: Some("^Bash$".to_string()),
|
||||
hooks: vec![HookHandlerConfig::Command {
|
||||
command: "bash /enterprise/hooks/pre.sh".to_string(),
|
||||
command_windows: Some(
|
||||
r"powershell -File C:\enterprise\hooks\pre.ps1".to_string(),
|
||||
),
|
||||
timeout_sec: None,
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
additional_context_limit: None,
|
||||
}],
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hook_handler_omits_unset_additional_context_limit() {
|
||||
let handler = HookHandlerConfig::Command {
|
||||
command: "python3 /tmp/pre.py".to_string(),
|
||||
command_windows: None,
|
||||
timeout_sec: None,
|
||||
r#async: false,
|
||||
status_message: None,
|
||||
additional_context_limit: None,
|
||||
};
|
||||
|
||||
let serialized = serde_json::to_value(handler).expect("hook handler should serialize");
|
||||
|
||||
assert_eq!(serialized.get("additionalContextLimit"), None);
|
||||
}
|
||||
119
codex-rs/config/src/host_name.rs
Normal file
119
codex-rs/config/src/host_name.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
#[cfg(unix)]
|
||||
use dns_lookup::AddrInfoHints;
|
||||
#[cfg(unix)]
|
||||
use dns_lookup::getaddrinfo;
|
||||
use std::sync::LazyLock;
|
||||
#[cfg(windows)]
|
||||
use winapi_util::sysinfo::ComputerNameKind;
|
||||
#[cfg(windows)]
|
||||
use winapi_util::sysinfo::get_computer_name;
|
||||
|
||||
static HOST_NAME: LazyLock<Option<String>> = LazyLock::new(compute_host_name);
|
||||
static OS_HOST_NAME: LazyLock<Option<String>> = LazyLock::new(|| {
|
||||
let kernel_hostname = gethostname::gethostname();
|
||||
normalize_host_name(&kernel_hostname.to_string_lossy())
|
||||
});
|
||||
|
||||
/// Returns a process-cached canonical hostname, falling back to the normalized
|
||||
/// kernel hostname. The first call on Unix may perform blocking DNS resolution.
|
||||
pub fn host_name() -> Option<String> {
|
||||
HOST_NAME.clone()
|
||||
}
|
||||
|
||||
/// Returns the process-cached operating-system hostname without DNS resolution.
|
||||
pub fn os_host_name() -> Option<String> {
|
||||
OS_HOST_NAME.clone()
|
||||
}
|
||||
|
||||
fn compute_host_name() -> Option<String> {
|
||||
let kernel_hostname = os_host_name()?;
|
||||
|
||||
// Remote sandbox requirements are meant to target remote hosts by DNS name,
|
||||
// so prefer the canonical FQDN when the local resolver can provide one.
|
||||
// This is best-effort host classification, not authenticated device proof.
|
||||
if let Some(fqdn) = local_fqdn_for_hostname(&kernel_hostname) {
|
||||
return Some(fqdn);
|
||||
}
|
||||
|
||||
// Some machines have only a short local hostname or resolver setup that
|
||||
// does not return AI_CANONNAME. Keep matching behavior best-effort by
|
||||
// falling back to the cleaned kernel hostname instead of returning None.
|
||||
Some(kernel_hostname)
|
||||
}
|
||||
|
||||
fn normalize_host_name(hostname: &str) -> Option<String> {
|
||||
let hostname = hostname.trim().trim_end_matches('.');
|
||||
(!hostname.is_empty()).then(|| hostname.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn local_fqdn_for_hostname(hostname: &str) -> Option<String> {
|
||||
let hints = AddrInfoHints {
|
||||
flags: libc::AI_CANONNAME,
|
||||
..AddrInfoHints::default()
|
||||
};
|
||||
|
||||
getaddrinfo(Some(hostname), /*service*/ None, Some(hints))
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.filter_map(|addr| addr.canonname)
|
||||
// getaddrinfo may return the short hostname as canonname when no FQDN
|
||||
// is available. Treat only DNS-qualified names as an FQDN result.
|
||||
.find_map(|hostname| normalize_fqdn_candidate(&hostname))
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn local_fqdn_for_hostname(_hostname: &str) -> Option<String> {
|
||||
get_computer_name(ComputerNameKind::PhysicalDnsFullyQualified)
|
||||
.ok()
|
||||
.and_then(|hostname| hostname.into_string().ok())
|
||||
.and_then(|hostname| normalize_fqdn_candidate(&hostname))
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn local_fqdn_for_hostname(_hostname: &str) -> Option<String> {
|
||||
None
|
||||
}
|
||||
|
||||
fn normalize_fqdn_candidate(hostname: &str) -> Option<String> {
|
||||
normalize_host_name(hostname).filter(|hostname| hostname.contains('.'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::normalize_fqdn_candidate;
|
||||
use super::normalize_host_name;
|
||||
use super::os_host_name;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn os_host_name_matches_normalized_kernel_hostname() {
|
||||
let kernel_hostname = gethostname::gethostname();
|
||||
|
||||
assert_eq!(
|
||||
os_host_name(),
|
||||
normalize_host_name(&kernel_hostname.to_string_lossy())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_fqdn_candidate_accepts_dns_qualified_name() {
|
||||
assert_eq!(
|
||||
normalize_fqdn_candidate("runner-01.ci.example.com"),
|
||||
Some("runner-01.ci.example.com".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_fqdn_candidate_rejects_short_name() {
|
||||
assert_eq!(normalize_fqdn_candidate("runner-01"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_fqdn_candidate_trims_trailing_dot_and_normalizes_case() {
|
||||
assert_eq!(
|
||||
normalize_fqdn_candidate("RUNNER-01.CI.EXAMPLE.COM."),
|
||||
Some("runner-01.ci.example.com".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
14
codex-rs/config/src/in_app_browser_requirements.rs
Normal file
14
codex-rs/config/src/in_app_browser_requirements.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
use serde::Deserialize;
|
||||
|
||||
/// Managed requirements for the interactive in-app browser, not agent Browser Use.
|
||||
#[derive(Deserialize, Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct InAppBrowserRequirementsToml {
|
||||
/// Whether external browser settings may be imported. Only `Some(false)`
|
||||
/// denies import; omission is effectively `true`. Keep omission unset while
|
||||
/// composing managed layers so it cannot replace an explicit requirement.
|
||||
pub allow_external_browser_settings_import: Option<bool>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "in_app_browser_requirements_tests.rs"]
|
||||
mod tests;
|
||||
144
codex-rs/config/src/in_app_browser_requirements_tests.rs
Normal file
144
codex-rs/config/src/in_app_browser_requirements_tests.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
use super::InAppBrowserRequirementsToml;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::ConfigRequirementsWithSources;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::Sourced;
|
||||
use crate::compose_requirements_for_hostname;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
const EMPTY: &str = "[in_app_browser]";
|
||||
const ALLOW: &str = "[in_app_browser]\nallow_external_browser_settings_import = true";
|
||||
const DENY: &str = "[in_app_browser]\nallow_external_browser_settings_import = false";
|
||||
|
||||
fn parse(contents: &str) -> ConfigRequirementsToml {
|
||||
toml::from_str(contents).expect("parse requirements")
|
||||
}
|
||||
|
||||
fn source(name: &str) -> RequirementSource {
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: name.to_string(),
|
||||
name: name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_requirement_preserves_unset_and_explicit_values() {
|
||||
for (contents, expected_table) in [
|
||||
("", None),
|
||||
(EMPTY, Some(None)),
|
||||
(ALLOW, Some(Some(true))),
|
||||
(DENY, Some(Some(false))),
|
||||
] {
|
||||
let requirements = parse(contents);
|
||||
assert_eq!(
|
||||
requirements,
|
||||
ConfigRequirementsToml {
|
||||
in_app_browser: expected_table.map(|value| InAppBrowserRequirementsToml {
|
||||
allow_external_browser_settings_import: value,
|
||||
}),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let configured = requirements
|
||||
.in_app_browser
|
||||
.as_ref()
|
||||
.and_then(|policy| policy.allow_external_browser_settings_import);
|
||||
assert_eq!(requirements.is_empty(), configured.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_requirement_uses_normal_managed_toml_precedence() {
|
||||
for (low, high, expected) in [
|
||||
("", EMPTY, None),
|
||||
(DENY, "", Some(DENY)),
|
||||
(DENY, EMPTY, Some(DENY)),
|
||||
(DENY, ALLOW, Some(ALLOW)),
|
||||
(ALLOW, DENY, Some(DENY)),
|
||||
] {
|
||||
let composed = compose_requirements_for_hostname(
|
||||
[
|
||||
RequirementsLayerEntry::from_toml(source("low"), low),
|
||||
RequirementsLayerEntry::from_toml(source("high"), high),
|
||||
],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
.expect("compose managed import policy")
|
||||
.map(ConfigRequirementsWithSources::into_toml);
|
||||
assert_eq!(composed, expected.map(parse));
|
||||
}
|
||||
|
||||
let composed = compose_requirements_for_hostname(
|
||||
[RequirementsLayerEntry::from_toml(source("managed"), DENY)],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
.expect("compose managed denial");
|
||||
assert_eq!(
|
||||
composed,
|
||||
Some(ConfigRequirementsWithSources {
|
||||
in_app_browser: Some(Sourced::new(
|
||||
InAppBrowserRequirementsToml {
|
||||
allow_external_browser_settings_import: Some(false),
|
||||
},
|
||||
source("managed"),
|
||||
)),
|
||||
..Default::default()
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_merge_uses_whole_table_precedence() {
|
||||
for (high, low, expected, expected_source) in [
|
||||
(EMPTY, DENY, EMPTY, "high"),
|
||||
("", ALLOW, ALLOW, "low"),
|
||||
(DENY, ALLOW, DENY, "high"),
|
||||
(ALLOW, DENY, ALLOW, "high"),
|
||||
] {
|
||||
let mut composed = ConfigRequirementsWithSources::default();
|
||||
composed.merge_unset_fields(source("high"), parse(high));
|
||||
composed.merge_unset_fields(source("low"), parse(low));
|
||||
assert_eq!(
|
||||
composed,
|
||||
ConfigRequirementsWithSources {
|
||||
in_app_browser: Some(Sourced::new(
|
||||
parse(expected).in_app_browser.expect("requirements table"),
|
||||
source(expected_source),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
assert_eq!(composed.into_toml(), parse(expected));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_import_requirement_is_rejected_even_when_overridden() {
|
||||
for invalid in ["\"false\"", "1", "[]", "{}"] {
|
||||
let contents =
|
||||
format!("[in_app_browser]\nallow_external_browser_settings_import = {invalid}");
|
||||
let error = toml::from_str::<ConfigRequirementsToml>(&contents)
|
||||
.expect_err("import requirement must be a boolean");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("allow_external_browser_settings_import"),
|
||||
"{error}",
|
||||
);
|
||||
let error = compose_requirements_for_hostname(
|
||||
[
|
||||
RequirementsLayerEntry::from_toml(source("invalid"), contents),
|
||||
RequirementsLayerEntry::from_toml(source("higher"), ALLOW),
|
||||
],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
.expect_err("invalid managed layers must not be silently ignored");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("allow_external_browser_settings_import"),
|
||||
"{error}",
|
||||
);
|
||||
}
|
||||
}
|
||||
126
codex-rs/config/src/key_aliases.rs
Normal file
126
codex-rs/config/src/key_aliases.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Normalize config aliases before merging layers and reporting origins.
|
||||
|
||||
use toml::Value as TomlValue;
|
||||
use toml::map::Map as TomlMap;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct ConfigKeyAlias {
|
||||
legacy: &'static [&'static str],
|
||||
canonical: &'static [&'static str],
|
||||
}
|
||||
|
||||
const CONFIG_KEY_ALIASES: &[ConfigKeyAlias] = &[
|
||||
ConfigKeyAlias {
|
||||
legacy: &["tui", "whimsy"],
|
||||
canonical: &["tui", "effects", "starfield"],
|
||||
},
|
||||
ConfigKeyAlias {
|
||||
legacy: &["memories", "no_memories_if_mcp_or_web_search"],
|
||||
canonical: &["memories", "disable_on_external_context"],
|
||||
},
|
||||
ConfigKeyAlias {
|
||||
legacy: &["agents", "max_threads"],
|
||||
canonical: &["agents", "max_concurrent_threads_per_session"],
|
||||
},
|
||||
];
|
||||
|
||||
fn normalize_table_key_aliases(path: &[String], table: &mut TomlMap<String, TomlValue>) {
|
||||
'aliases: for alias in CONFIG_KEY_ALIASES {
|
||||
// Destinations stay within the legacy key's containing table.
|
||||
let Some((legacy_key, table_path)) = alias.legacy.split_last() else {
|
||||
continue;
|
||||
};
|
||||
if path
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.eq(table_path.iter().copied())
|
||||
&& let Some(canonical_path) = alias.canonical.strip_prefix(table_path)
|
||||
&& let Some(value) = table.remove(*legacy_key)
|
||||
{
|
||||
// Insert at the canonical path if absent.
|
||||
let Some((key, parents)) = canonical_path.split_last() else {
|
||||
continue;
|
||||
};
|
||||
let mut destination = &mut *table;
|
||||
for parent in parents {
|
||||
let child = destination
|
||||
.entry((*parent).to_string())
|
||||
.or_insert_with(|| TomlValue::Table(TomlMap::new()));
|
||||
let Some(child) = child.as_table_mut() else {
|
||||
continue 'aliases;
|
||||
};
|
||||
destination = child;
|
||||
}
|
||||
destination.entry((*key).to_string()).or_insert(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn normalize_key_aliases(value: &TomlValue) -> TomlValue {
|
||||
normalize_key_aliases_at_path(value, &[])
|
||||
}
|
||||
|
||||
fn normalize_key_aliases_at_path(value: &TomlValue, path: &[String]) -> TomlValue {
|
||||
// Alias normalization cannot affect subtrees outside the registered legacy paths.
|
||||
if !CONFIG_KEY_ALIASES.iter().any(|alias| {
|
||||
alias
|
||||
.legacy
|
||||
.get(..path.len())
|
||||
.is_some_and(|prefix| path.iter().map(String::as_str).eq(prefix.iter().copied()))
|
||||
}) {
|
||||
return value.clone();
|
||||
}
|
||||
|
||||
match value {
|
||||
TomlValue::Table(table) => {
|
||||
let mut normalized = TomlMap::new();
|
||||
for (key, child) in table {
|
||||
let mut child_path = path.to_vec();
|
||||
child_path.push(key.clone());
|
||||
normalized.insert(
|
||||
key.clone(),
|
||||
normalize_key_aliases_at_path(child, &child_path),
|
||||
);
|
||||
}
|
||||
normalize_table_key_aliases(path, &mut normalized);
|
||||
TomlValue::Table(normalized)
|
||||
}
|
||||
TomlValue::Array(items) => TomlValue::Array(
|
||||
items
|
||||
.iter()
|
||||
.map(|item| normalize_key_aliases_at_path(item, path))
|
||||
.collect(),
|
||||
),
|
||||
_ => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalize only base tables reached by the overlay, leaving unrelated raw config intact.
|
||||
///
|
||||
/// Config-edit table Upserts start from the raw user layer, not the normalized effective config.
|
||||
/// They use a sparse overlay and persist only the edited subtree, but compute the returned
|
||||
/// version from the whole in-memory config. Normalizing unrelated base tables would make
|
||||
/// that version disagree with the file on disk.
|
||||
///
|
||||
/// For example, given `[memories] no_memories_if_mcp_or_web_search = false` and
|
||||
/// `[agents] max_depth = 1`, upserting `agents` with `{ "max_depth": 2 }` must leave
|
||||
/// the memories alias untouched. Renaming it only in memory would cause the next write
|
||||
/// using the returned version to fail with `ConfigVersionConflict`, despite no intervening edit.
|
||||
pub(crate) fn normalize_base_key_aliases(
|
||||
base: &mut TomlValue,
|
||||
overlay: &TomlValue,
|
||||
path: &mut Vec<String>,
|
||||
) {
|
||||
if let TomlValue::Table(base) = base
|
||||
&& let TomlValue::Table(overlay) = overlay
|
||||
{
|
||||
normalize_table_key_aliases(path, base);
|
||||
for (key, value) in overlay {
|
||||
if let Some(existing) = base.get_mut(key) {
|
||||
path.push(key.clone());
|
||||
normalize_base_key_aliases(existing, value, path);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
252
codex-rs/config/src/lib.rs
Normal file
252
codex-rs/config/src/lib.rs
Normal file
@@ -0,0 +1,252 @@
|
||||
mod application_requirements;
|
||||
mod application_storage_requirements;
|
||||
mod auth_policy;
|
||||
mod browser_computer_use_requirements;
|
||||
mod browser_use;
|
||||
mod cloud_config_bundle;
|
||||
mod cloud_config_layers;
|
||||
#[cfg(target_os = "macos")]
|
||||
mod codex_home_symlink;
|
||||
mod computer_use;
|
||||
mod config_layer_source;
|
||||
mod config_requirements;
|
||||
mod config_server;
|
||||
pub mod config_toml;
|
||||
mod constraint;
|
||||
mod diagnostics;
|
||||
mod filesystem_constraints;
|
||||
mod fingerprint;
|
||||
mod guardian;
|
||||
mod hook_config;
|
||||
mod host_name;
|
||||
mod in_app_browser_requirements;
|
||||
mod key_aliases;
|
||||
pub mod loader;
|
||||
mod marketplace_edit;
|
||||
mod mcp_edit;
|
||||
mod mcp_ema;
|
||||
mod mcp_ema_cancellation;
|
||||
pub use mcp_ema_cancellation::McpEmaCancellation;
|
||||
mod mcp_requirements;
|
||||
mod mcp_types;
|
||||
mod merge;
|
||||
mod model_provider_defaults;
|
||||
mod model_provider_requirements;
|
||||
mod overrides;
|
||||
mod path_context;
|
||||
pub mod permissions_toml;
|
||||
mod plugin_edit;
|
||||
pub mod profile_toml;
|
||||
mod project_root_markers;
|
||||
mod project_trust;
|
||||
mod requirements_exec_policy;
|
||||
mod requirements_layers;
|
||||
pub mod schema;
|
||||
mod shell_environment_policy;
|
||||
mod skills_config;
|
||||
mod state;
|
||||
mod strict_config;
|
||||
pub mod test_support;
|
||||
mod thread_config;
|
||||
mod tui_effects;
|
||||
mod tui_keymap;
|
||||
mod tui_mouse_scroll;
|
||||
mod tui_rendering;
|
||||
pub mod types;
|
||||
|
||||
pub const CONFIG_TOML_FILE: &str = "config.toml";
|
||||
|
||||
pub use application_requirements::ApplicationNetworkRequirementsToml;
|
||||
pub use application_requirements::ApplicationRequirementsToml;
|
||||
pub use application_storage_requirements::ApplicationStorageRequirementsToml;
|
||||
pub use auth_policy::ManagedAuthPolicy;
|
||||
pub use browser_computer_use_requirements::AllowDenyRequirementToml;
|
||||
pub use browser_computer_use_requirements::BrowserUseAccessApprovalLifetimeToml;
|
||||
pub use browser_computer_use_requirements::BrowserUseExtensionRequirementsToml;
|
||||
pub use browser_computer_use_requirements::BrowserUseOriginPolicyToml;
|
||||
pub use browser_computer_use_requirements::BrowserUseRequirementsToml;
|
||||
pub use browser_computer_use_requirements::ComputerUseMacosRequirementsToml;
|
||||
pub use browser_computer_use_requirements::ComputerUseRequirementsToml;
|
||||
pub use browser_computer_use_requirements::ComputerUseWindowsExeRequirementToml;
|
||||
pub use browser_computer_use_requirements::ComputerUseWindowsRequirementsToml;
|
||||
pub use browser_computer_use_requirements::RequestHeaderToml;
|
||||
pub use browser_use::BrowserUseConfigToml;
|
||||
pub use browser_use::BrowserUseOriginPolicyConfigToml;
|
||||
pub use cloud_config_bundle::CloudConfigBundle;
|
||||
pub use cloud_config_bundle::CloudConfigBundleBinding;
|
||||
pub use cloud_config_bundle::CloudConfigBundleBindingGuard;
|
||||
pub use cloud_config_bundle::CloudConfigBundleBindingStatus;
|
||||
pub use cloud_config_bundle::CloudConfigBundleLayers;
|
||||
pub use cloud_config_bundle::CloudConfigBundleLoadError;
|
||||
pub use cloud_config_bundle::CloudConfigBundleLoadErrorCode;
|
||||
pub use cloud_config_bundle::CloudConfigBundleLoader;
|
||||
pub use cloud_config_bundle::CloudConfigBundlePolicy;
|
||||
pub use cloud_config_bundle::CloudConfigBundlePolicyChanges;
|
||||
pub use cloud_config_bundle::CloudConfigBundlePolicyRevision;
|
||||
pub use cloud_config_bundle::CloudConfigBundleSnapshot;
|
||||
pub use cloud_config_bundle::CloudConfigTomlBundle;
|
||||
pub use cloud_config_bundle::CloudRequirementsFragment;
|
||||
pub use cloud_config_bundle::CloudRequirementsTomlBundle;
|
||||
pub use cloud_config_layers::CloudConfigFragment;
|
||||
pub use cloud_config_layers::CloudConfigFragmentSource;
|
||||
pub use cloud_config_layers::CloudConfigLayerError;
|
||||
pub use cloud_config_layers::cloud_config_layers_from_fragments;
|
||||
pub use codex_execpolicy::RequirementsExecPolicy;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub use codex_home_symlink::allowed_symlinked_codex_home;
|
||||
pub use codex_protocol::config_types::ProfileV2Name;
|
||||
pub use codex_protocol::config_types::ProfileV2NameParseError;
|
||||
pub use codex_protocol::config_types::ToolExposureSurface;
|
||||
pub use codex_protocol::mcp_policy::McpServerCommandMatcher;
|
||||
pub use codex_protocol::mcp_policy::McpServerIdentity;
|
||||
pub use codex_protocol::mcp_policy::McpServerRequirement;
|
||||
pub use codex_protocol::mcp_policy::McpServerValueMatcher;
|
||||
pub use codex_protocol::mcp_policy::PluginMcpRequirements as PluginRequirementsToml;
|
||||
pub use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
pub use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
pub use computer_use::ComputerUseConfigToml;
|
||||
pub use computer_use::ComputerUseMacosConfigToml;
|
||||
pub use computer_use::ComputerUseWindowsConfigToml;
|
||||
pub use computer_use::ComputerUseWindowsExeConfigToml;
|
||||
pub use config_layer_source::ConfigLayer;
|
||||
pub use config_layer_source::ConfigLayerMetadata;
|
||||
pub use config_layer_source::ConfigLayerSource;
|
||||
pub use config_layer_source::format_config_layer_source;
|
||||
pub use config_requirements::AppRequirementToml;
|
||||
pub use config_requirements::AppToolRequirementToml;
|
||||
pub use config_requirements::AppToolResultSourceFormat;
|
||||
pub use config_requirements::AppToolResultSourceRequirementToml;
|
||||
pub use config_requirements::AppToolsRequirementsToml;
|
||||
pub use config_requirements::AppsRequirementsToml;
|
||||
pub use config_requirements::AutoReviewRequirementsToml;
|
||||
pub use config_requirements::ConfigRequirements;
|
||||
pub use config_requirements::ConfigRequirementsToml;
|
||||
pub use config_requirements::ConfigRequirementsWithSources;
|
||||
pub use config_requirements::ConstrainedWithSource;
|
||||
pub use config_requirements::FeatureRequirementsToml;
|
||||
pub use config_requirements::FilesystemConstraints;
|
||||
pub use config_requirements::FilesystemDenyReadPattern;
|
||||
pub use config_requirements::MarketplaceAllowedSourceKind;
|
||||
pub use config_requirements::MarketplaceAllowedSourceToml;
|
||||
pub use config_requirements::MarketplaceRequirementsToml;
|
||||
pub use config_requirements::ModelsRequirementsToml;
|
||||
pub use config_requirements::NetworkConstraints;
|
||||
pub use config_requirements::NetworkDomainPermissionToml;
|
||||
pub use config_requirements::NetworkDomainPermissionsToml;
|
||||
pub use config_requirements::NetworkHeaderInjectionToml;
|
||||
pub use config_requirements::NetworkRequirementsToml;
|
||||
pub use config_requirements::NetworkUnixSocketPermissionToml;
|
||||
pub use config_requirements::NetworkUnixSocketPermissionsToml;
|
||||
pub use config_requirements::NewThreadModelDefaultsToml;
|
||||
pub use config_requirements::OtelRequirementsToml;
|
||||
pub use config_requirements::RemoteSandboxConfigToml;
|
||||
pub use config_requirements::RequirementSource;
|
||||
pub use config_requirements::ResidencyRequirement;
|
||||
pub use config_requirements::SandboxModeRequirement;
|
||||
pub use config_requirements::Sourced;
|
||||
pub use config_requirements::WebSearchModeRequirement;
|
||||
pub use config_requirements::WindowsRequirementsToml;
|
||||
pub use config_requirements::WindowsSandboxImplementationToml;
|
||||
pub use config_requirements::apply_otel_requirements;
|
||||
pub use config_requirements::sandbox_mode_requirement_for_permission_profile;
|
||||
pub use config_server::ConfigServer;
|
||||
pub use config_server::ConfigServerOAuth;
|
||||
pub use config_toml::effective_sandbox_mode;
|
||||
pub use constraint::Constrained;
|
||||
pub use constraint::ConstraintError;
|
||||
pub use constraint::ConstraintResult;
|
||||
pub use diagnostics::ConfigError;
|
||||
pub use diagnostics::ConfigLoadError;
|
||||
pub use diagnostics::TextPosition;
|
||||
pub use diagnostics::TextRange;
|
||||
pub use diagnostics::config_error_from_toml;
|
||||
pub use diagnostics::config_error_from_typed_toml;
|
||||
pub use diagnostics::first_layer_config_error;
|
||||
pub use diagnostics::first_layer_config_error_from_entries;
|
||||
pub use diagnostics::format_config_error;
|
||||
pub use diagnostics::format_config_error_with_source;
|
||||
pub use diagnostics::io_error_from_config_error;
|
||||
pub use fingerprint::version_for_toml;
|
||||
pub use guardian::GuardianPolicyLoader;
|
||||
pub use hook_config::HookEventsToml;
|
||||
pub use hook_config::HookHandlerConfig;
|
||||
pub use hook_config::HookStateToml;
|
||||
pub use hook_config::HooksFile;
|
||||
pub use hook_config::HooksToml;
|
||||
pub use hook_config::ManagedHooksRequirementsToml;
|
||||
pub use hook_config::MatcherGroup;
|
||||
pub use host_name::host_name;
|
||||
pub use host_name::os_host_name;
|
||||
pub use in_app_browser_requirements::InAppBrowserRequirementsToml;
|
||||
pub use marketplace_edit::MarketplaceConfigUpdate;
|
||||
pub use marketplace_edit::RemoveMarketplaceConfigOutcome;
|
||||
pub use marketplace_edit::record_user_marketplace;
|
||||
pub use marketplace_edit::remove_user_marketplace;
|
||||
pub use marketplace_edit::remove_user_marketplace_config;
|
||||
pub use mcp_edit::load_global_mcp_servers;
|
||||
pub use mcp_ema::McpEmaAuthScope;
|
||||
pub use mcp_ema::McpEmaRegistration;
|
||||
pub use mcp_ema::McpEmaTokenEndpointAuthMethod;
|
||||
pub use mcp_ema::McpEnterpriseManagedAuthConfig;
|
||||
pub use mcp_ema::McpServerIdpOAuthConfig;
|
||||
pub use mcp_types::AppToolApproval;
|
||||
pub use mcp_types::DEFAULT_MCP_SERVER_ENVIRONMENT_ID;
|
||||
pub use mcp_types::McpServerAuth;
|
||||
pub use mcp_types::McpServerConfig;
|
||||
pub use mcp_types::McpServerDisabledReason;
|
||||
pub use mcp_types::McpServerEnvVar;
|
||||
pub use mcp_types::McpServerOAuthConfig;
|
||||
pub use mcp_types::McpServerToolConfig;
|
||||
pub use mcp_types::McpServerTransportConfig;
|
||||
pub use mcp_types::McpStartupReadiness;
|
||||
pub use mcp_types::RawMcpServerConfig;
|
||||
pub use merge::ShellEnvironmentPolicyFilterRepresentation;
|
||||
pub use merge::is_structured_feature_path;
|
||||
pub use merge::merge_toml_values;
|
||||
pub use merge::shell_environment_filter_entry;
|
||||
pub use model_provider_defaults::apply_default_gcp_auth;
|
||||
pub use overrides::build_cli_overrides_layer;
|
||||
pub use path_context::ConfigPathContext;
|
||||
pub use plugin_edit::PluginConfigEdit;
|
||||
pub use plugin_edit::apply_user_plugin_config_edits;
|
||||
pub use plugin_edit::clear_user_plugin;
|
||||
pub use plugin_edit::set_user_plugin_enabled;
|
||||
pub use project_root_markers::default_project_root_markers;
|
||||
pub use project_root_markers::project_root_markers_from_config;
|
||||
pub use project_trust::ProjectTrustLookup;
|
||||
pub use project_trust::ProjectTrustPath;
|
||||
pub use requirements_exec_policy::RequirementsExecPolicyDecisionToml;
|
||||
pub use requirements_exec_policy::RequirementsExecPolicyParseError;
|
||||
pub use requirements_exec_policy::RequirementsExecPolicyPatternTokenToml;
|
||||
pub use requirements_exec_policy::RequirementsExecPolicyPrefixRuleToml;
|
||||
pub use requirements_exec_policy::RequirementsExecPolicyToml;
|
||||
pub use requirements_layers::RequirementsLayerEntry;
|
||||
pub use requirements_layers::compose_requirements;
|
||||
pub use requirements_layers::compose_requirements_for_hostname;
|
||||
pub use shell_environment_policy::validate_shell_environment_policy_filter_config;
|
||||
pub use skills_config::BundledSkillsConfig;
|
||||
pub use skills_config::ScopedSkillsConfig;
|
||||
pub use skills_config::SkillConfig;
|
||||
pub use skills_config::SkillConfigRule;
|
||||
pub use skills_config::SkillConfigRuleSelector;
|
||||
pub use skills_config::SkillConfigRules;
|
||||
pub use skills_config::SkillsConfig;
|
||||
pub use skills_config::bundled_skills_enabled_from_stack;
|
||||
pub use skills_config::skill_config_rules_from_stack;
|
||||
pub use state::ConfigLayerEntry;
|
||||
pub use state::ConfigLayerStack;
|
||||
pub use state::ConfigLoadOptions;
|
||||
pub use state::LoaderOverrides;
|
||||
pub use strict_config::config_error_from_ignored_toml_fields;
|
||||
pub use thread_config::NoopThreadConfigLoader;
|
||||
pub use thread_config::RemoteThreadConfigLoader;
|
||||
pub use thread_config::SessionThreadConfig;
|
||||
pub use thread_config::StaticThreadConfigLoader;
|
||||
pub use thread_config::ThreadConfigContext;
|
||||
pub use thread_config::ThreadConfigLoadError;
|
||||
pub use thread_config::ThreadConfigLoadErrorCode;
|
||||
pub use thread_config::ThreadConfigLoader;
|
||||
pub use thread_config::ThreadConfigLoaderFuture;
|
||||
pub use thread_config::ThreadConfigSource;
|
||||
pub use thread_config::UserThreadConfig;
|
||||
pub use toml::Value as TomlValue;
|
||||
90
codex-rs/config/src/loader/README.md
Normal file
90
codex-rs/config/src/loader/README.md
Normal file
@@ -0,0 +1,90 @@
|
||||
# `codex-config` loader
|
||||
|
||||
This module is the canonical place to **load and describe Codex configuration layers** (user config, CLI/session overrides, cloud-managed config, managed config, and MDM-managed preferences) and to produce:
|
||||
|
||||
- An **effective merged** TOML config.
|
||||
- **Per-key origins** metadata (which layer “wins” for a given key).
|
||||
- **Per-layer versions** (stable fingerprints) used for optimistic concurrency / conflict detection.
|
||||
|
||||
## Public surface
|
||||
|
||||
Exported from `codex_config::loader`:
|
||||
|
||||
- `load_config_layers_state(fs, codex_home, cwd_opt, cli_overrides, options, thread_config_loader) -> ConfigLayerStack`
|
||||
- `ConfigLayerStack`
|
||||
- `effective_config() -> toml::Value`
|
||||
- `origins() -> HashMap<String, ConfigLayerMetadata>`
|
||||
- `layers_high_to_low() -> impl Iterator<Item = &ConfigLayerEntry>`
|
||||
- `with_user_config(user_config) -> ConfigLayerStack`
|
||||
- `ConfigLayerEntry` (one layer’s `{name, config, version, disabled_reason}`; `name` carries source metadata)
|
||||
- `ConfigLoadOptions` (user-facing load behavior such as strict config validation)
|
||||
- `LoaderOverrides` (test/override hooks for managed config sources)
|
||||
- `merge_toml_values(base, overlay)` (public helper used elsewhere)
|
||||
|
||||
## Layering model
|
||||
|
||||
Precedence is **top overrides bottom**:
|
||||
|
||||
1. `LegacyManagedConfigTomlFromMdm` (MDM-delivered `managed_config.toml`, while it is being phased out)
|
||||
2. `LegacyManagedConfigTomlFromFile` (`managed_config.toml`, while it is being phased out)
|
||||
3. `SessionFlags` (CLI overrides, applied as dotted-path TOML writes)
|
||||
4. `Project` config (`.codex/config.toml`)
|
||||
5. `User` profile config, when present
|
||||
6. `User` config (`config.toml`)
|
||||
7. `EnterpriseManaged` cloud-managed config bundle layers
|
||||
8. `System` config (`/etc/codex/config.toml` or the Windows system config path)
|
||||
|
||||
`ConfigLayerStack` stores layers in the opposite order internally: lowest
|
||||
precedence first, highest precedence last, so later layers override earlier
|
||||
layers when folded. Thread config entries supplied by `thread_config_loader` are
|
||||
inserted according to their translated `ConfigLayerSource` precedence.
|
||||
|
||||
Project-root discovery and project trust use the applicable non-project layers,
|
||||
including legacy managed-file and MDM config at their normal precedence. The
|
||||
managed layers remain above project and session layers in the final stack.
|
||||
Executor-local reads use their own system, base-user, and legacy managed sources;
|
||||
they do not include cloud config, selected profiles, or session flags.
|
||||
|
||||
Layers with a `disabled_reason` are still surfaced for UI, but are ignored when
|
||||
computing the effective config and origins metadata. This is what
|
||||
`ConfigLayerStack::effective_config()` implements.
|
||||
|
||||
## Typical usage
|
||||
|
||||
Most callers want the effective config plus metadata:
|
||||
|
||||
```rust
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::NoopThreadConfigLoader;
|
||||
use codex_config::loader::load_config_layers_state;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
let cli_overrides: Vec<(String, TomlValue)> = Vec::new();
|
||||
let cwd = AbsolutePathBuf::current_dir()?;
|
||||
let layers = load_config_layers_state(
|
||||
LOCAL_FS.as_ref(),
|
||||
&codex_home,
|
||||
Some(cwd),
|
||||
&cli_overrides,
|
||||
LoaderOverrides::default(),
|
||||
&NoopThreadConfigLoader,
|
||||
).await?;
|
||||
|
||||
let effective = layers.effective_config();
|
||||
let origins = layers.origins();
|
||||
let layers_for_ui = layers.layers_high_to_low().collect::<Vec<_>>();
|
||||
```
|
||||
|
||||
## Internal layout
|
||||
|
||||
Implementation is split by concern:
|
||||
|
||||
- `state.rs`: public types (`ConfigLayerEntry`, `ConfigLayerStack`) + merge/origins convenience methods.
|
||||
- `layer_io.rs`: reading `config.toml`, managed config, and managed preferences inputs.
|
||||
- `project_discovery.rs`: shared managed-config composition for project-root and trust discovery.
|
||||
- `overrides.rs`: CLI dotted-path overrides → TOML “session flags” layer.
|
||||
- `merge.rs`: recursive TOML merge.
|
||||
- `fingerprint.rs`: stable per-layer hashing and per-key origins traversal.
|
||||
- `macos.rs`: managed preferences integration (macOS only).
|
||||
102
codex-rs/config/src/loader/application.rs
Normal file
102
codex-rs/config/src/loader/application.rs
Normal file
@@ -0,0 +1,102 @@
|
||||
//! Reads application requirements independently of user, project, and cloud configuration.
|
||||
//! Captured local layers retain their positions around cloud layers during composition.
|
||||
|
||||
use crate::ApplicationRequirementsToml;
|
||||
use crate::CloudRequirementsTomlBundle;
|
||||
use crate::LoaderOverrides;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements;
|
||||
use codex_file_system::ExecutorFileSystem;
|
||||
use std::io;
|
||||
use toml::Value;
|
||||
|
||||
/// Local application sources captured without waiting for a cloud request.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LocalApplicationRequirements {
|
||||
system: Option<RequirementsLayerEntry>,
|
||||
mdm: Option<RequirementsLayerEntry>,
|
||||
ignore_managed: bool,
|
||||
}
|
||||
|
||||
impl LocalApplicationRequirements {
|
||||
/// Composes system, cloud, and MDM application policy in the normal requirements order.
|
||||
pub fn compose(
|
||||
&self,
|
||||
cloud: CloudRequirementsTomlBundle,
|
||||
) -> io::Result<Option<ApplicationRequirementsToml>> {
|
||||
if self.ignore_managed {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut layers = self.system.clone().into_iter().collect::<Vec<_>>();
|
||||
for layer in cloud.into_layers() {
|
||||
layers.extend(application_layer(layer)?);
|
||||
}
|
||||
layers.extend(self.mdm.clone());
|
||||
Ok(compose_requirements(layers)?
|
||||
.and_then(|requirements| requirements.into_toml().application))
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads only the local sources that can set application requirements.
|
||||
/// macOS policy reads require a successful preference refresh before using cached values.
|
||||
pub async fn load_local_application_requirements(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
overrides: &LoaderOverrides,
|
||||
) -> io::Result<LocalApplicationRequirements> {
|
||||
if overrides.ignore_managed_requirements {
|
||||
return Ok(LocalApplicationRequirements {
|
||||
ignore_managed: true,
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
let system_path = super::system_requirements_toml_file_with_overrides(overrides)?;
|
||||
let system = super::load_requirements_toml(fs, &system_path)
|
||||
.await?
|
||||
.map(application_layer)
|
||||
.transpose()?
|
||||
.flatten();
|
||||
#[cfg(target_os = "macos")]
|
||||
let mdm = {
|
||||
if overrides.macos_managed_config_requirements_base64.is_none() {
|
||||
tokio::task::spawn_blocking(super::macos::synchronize_managed_preferences)
|
||||
.await
|
||||
.map_err(io::Error::other)??;
|
||||
}
|
||||
super::macos::load_managed_admin_requirements_layer(
|
||||
overrides
|
||||
.macos_managed_config_requirements_base64
|
||||
.as_deref(),
|
||||
)
|
||||
.await?
|
||||
.map(application_layer)
|
||||
.transpose()?
|
||||
.flatten()
|
||||
};
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let mdm = None;
|
||||
let local = LocalApplicationRequirements {
|
||||
system,
|
||||
mdm,
|
||||
ignore_managed: false,
|
||||
};
|
||||
// Validate local requirements before cloud loading.
|
||||
local.compose(CloudRequirementsTomlBundle::default())?;
|
||||
Ok(local)
|
||||
}
|
||||
|
||||
fn application_layer(layer: RequirementsLayerEntry) -> io::Result<Option<RequirementsLayerEntry>> {
|
||||
let (source, mut value, _base_dir) = layer.into_raw_parts()?;
|
||||
let Some(application) = value
|
||||
.as_table_mut()
|
||||
.and_then(|table| table.remove("application"))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(RequirementsLayerEntry::from_toml_value(
|
||||
source,
|
||||
Value::Table(toml::map::Map::from_iter([(
|
||||
"application".into(),
|
||||
application,
|
||||
)])),
|
||||
)))
|
||||
}
|
||||
233
codex-rs/config/src/loader/layer_io.rs
Normal file
233
codex-rs/config/src/loader/layer_io.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::macos::ManagedAdminConfigLayer;
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::macos::load_managed_admin_config_layer;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::diagnostics::config_error_from_toml;
|
||||
use crate::diagnostics::io_error_from_config_error;
|
||||
use crate::state::LoaderOverrides;
|
||||
use crate::strict_config::config_error_from_ignored_toml_value_fields;
|
||||
use codex_file_system::ExecutorFileSystem;
|
||||
#[cfg(windows)]
|
||||
use codex_file_system::GetMetadataOptions;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
#[cfg(unix)]
|
||||
const CODEX_MANAGED_CONFIG_SYSTEM_PATH: &str = "/etc/codex/managed_config.toml";
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct MangedConfigFromFile {
|
||||
pub managed_config: TomlValue,
|
||||
pub file: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct ManagedConfigFromMdm {
|
||||
pub managed_config: TomlValue,
|
||||
pub raw_toml: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct LoadedConfigLayers {
|
||||
/// If present, data read from a file such as `/etc/codex/managed_config.toml`.
|
||||
pub managed_config: Option<MangedConfigFromFile>,
|
||||
/// If present, data read from managed preferences (macOS only).
|
||||
pub managed_config_from_mdm: Option<ManagedConfigFromMdm>,
|
||||
/// User-facing warnings discovered while loading managed configuration.
|
||||
pub startup_warnings: Vec<String>,
|
||||
}
|
||||
|
||||
pub(super) async fn load_config_layers_internal(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
codex_home: &Path,
|
||||
overrides: LoaderOverrides,
|
||||
strict_config: bool,
|
||||
) -> io::Result<LoadedConfigLayers> {
|
||||
#[cfg(target_os = "macos")]
|
||||
let LoaderOverrides {
|
||||
managed_config_path,
|
||||
managed_preferences_base64,
|
||||
..
|
||||
} = overrides;
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let LoaderOverrides {
|
||||
managed_config_path,
|
||||
..
|
||||
} = overrides;
|
||||
|
||||
#[cfg(windows)]
|
||||
let ignore_default_managed_config = managed_config_path.is_none();
|
||||
#[cfg(not(windows))]
|
||||
let ignore_default_managed_config = false;
|
||||
|
||||
let managed_config_path = AbsolutePathBuf::from_absolute_path(
|
||||
managed_config_path.unwrap_or_else(|| managed_config_default_path(codex_home)),
|
||||
)?;
|
||||
|
||||
#[cfg(windows)]
|
||||
let startup_warnings = if ignore_default_managed_config {
|
||||
let path_uri = PathUri::from_abs_path(&managed_config_path);
|
||||
match fs
|
||||
.get_metadata(
|
||||
&path_uri,
|
||||
GetMetadataOptions::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(_) => vec![format!(
|
||||
"Ignoring deprecated managed config file at {}; CODEX_HOME/managed_config.toml is no longer supported on Windows. Use %ProgramData%\\OpenAI\\Codex\\requirements.toml for enforced settings or config.toml for defaults.",
|
||||
managed_config_path.as_path().display()
|
||||
)],
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => Vec::new(),
|
||||
Err(err) => {
|
||||
tracing::debug!(
|
||||
error = %err,
|
||||
path = %managed_config_path.as_path().display(),
|
||||
"Failed to check deprecated managed config file"
|
||||
);
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let startup_warnings = Vec::new();
|
||||
|
||||
let managed_config = if ignore_default_managed_config {
|
||||
None
|
||||
} else {
|
||||
read_config_from_path(
|
||||
fs,
|
||||
&managed_config_path,
|
||||
/*log_missing_as_info*/ false,
|
||||
strict_config,
|
||||
)
|
||||
.await?
|
||||
.map(|loaded| MangedConfigFromFile {
|
||||
managed_config: loaded,
|
||||
file: managed_config_path.clone(),
|
||||
})
|
||||
};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
let managed_preferences = load_managed_admin_config_layer(
|
||||
managed_preferences_base64.as_deref(),
|
||||
strict_config,
|
||||
codex_home,
|
||||
)
|
||||
.await?
|
||||
.map(map_managed_admin_layer);
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
let managed_preferences = None;
|
||||
|
||||
Ok(LoadedConfigLayers {
|
||||
managed_config,
|
||||
managed_config_from_mdm: managed_preferences,
|
||||
startup_warnings,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn map_managed_admin_layer(layer: ManagedAdminConfigLayer) -> ManagedConfigFromMdm {
|
||||
let ManagedAdminConfigLayer { config, raw_toml } = layer;
|
||||
ManagedConfigFromMdm {
|
||||
managed_config: config,
|
||||
raw_toml,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn read_config_from_path(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
path: &AbsolutePathBuf,
|
||||
log_missing_as_info: bool,
|
||||
strict_config: bool,
|
||||
) -> io::Result<Option<TomlValue>> {
|
||||
let path_uri = PathUri::from_abs_path(path);
|
||||
match fs
|
||||
.read_file_text(&path_uri, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(contents) => match toml::from_str::<TomlValue>(&contents) {
|
||||
Ok(value) => {
|
||||
if strict_config {
|
||||
validate_config_toml_strictly(path, &contents, &value)?;
|
||||
}
|
||||
Ok(Some(value))
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to parse {}: {err}", path.as_path().display());
|
||||
let config_error = config_error_from_toml(path.as_path(), &contents, err.clone());
|
||||
Err(io_error_from_config_error(
|
||||
io::ErrorKind::InvalidData,
|
||||
config_error,
|
||||
Some(err),
|
||||
))
|
||||
}
|
||||
},
|
||||
Err(err) if err.kind() == io::ErrorKind::NotFound => {
|
||||
if log_missing_as_info {
|
||||
tracing::info!("{} not found, using defaults", path.as_path().display());
|
||||
} else {
|
||||
tracing::debug!("{} not found", path.as_path().display());
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!("Failed to read {}: {err}", path.as_path().display());
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_config_toml_strictly(
|
||||
path: &AbsolutePathBuf,
|
||||
contents: &str,
|
||||
value: &TomlValue,
|
||||
) -> io::Result<()> {
|
||||
let Some(base_dir) = path.as_path().parent() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("Config file {} has no parent directory", path.display()),
|
||||
));
|
||||
};
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir);
|
||||
if let Some(config_error) = config_error_from_ignored_toml_value_fields::<ConfigToml>(
|
||||
path.as_path(),
|
||||
contents,
|
||||
value.clone(),
|
||||
) {
|
||||
return Err(io_error_from_config_error(
|
||||
io::ErrorKind::InvalidData,
|
||||
config_error,
|
||||
/*source*/ None,
|
||||
));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Return the legacy managed config path.
|
||||
///
|
||||
/// On Windows, the default path is only checked so callers can warn that it is ignored.
|
||||
pub(super) fn managed_config_default_path(codex_home: &Path) -> PathBuf {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
let _ = codex_home;
|
||||
PathBuf::from(CODEX_MANAGED_CONFIG_SYSTEM_PATH)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
codex_home.join("managed_config.toml")
|
||||
}
|
||||
}
|
||||
440
codex-rs/config/src/loader/local.rs
Normal file
440
codex-rs/config/src/loader/local.rs
Normal file
@@ -0,0 +1,440 @@
|
||||
use super::apply_credential_broker_requirements;
|
||||
use super::credential_broker_trusted_config;
|
||||
use super::discover_project_layers;
|
||||
use super::layer_io;
|
||||
use super::load_config_toml_for_required_layer_raw;
|
||||
use super::load_requirements_toml;
|
||||
use super::load_root_checkout_project_config;
|
||||
use super::project_discovery;
|
||||
use super::project_root_markers_from_config;
|
||||
use super::project_trust_context;
|
||||
use super::requirements_layers_from_legacy_scheme;
|
||||
use super::system_config_toml_file_with_overrides;
|
||||
use super::system_requirements_toml_file_with_overrides;
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::LoaderOverrides;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements;
|
||||
use crate::default_project_root_markers;
|
||||
use crate::merge_toml_values;
|
||||
use codex_file_system::ExecutorFileSystem;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::collections::BTreeMap;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
/// Executor-local configuration and requirements layers before schema-specific
|
||||
/// path resolution or requirements composition.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LocalConfigLayers {
|
||||
pub config: LocalTomlLayerStack<ConfigLayerSource>,
|
||||
pub requirements: LocalTomlLayerStack<RequirementSource>,
|
||||
}
|
||||
|
||||
impl LocalConfigLayers {
|
||||
/// Retains only the requested TOML paths and drops empty layers.
|
||||
///
|
||||
/// An empty path selects the entire document. RPC boundaries should reject
|
||||
/// that form if whole-document reads are not part of their contract.
|
||||
pub fn project(self, config_paths: &[Vec<String>], requirements_paths: &[Vec<String>]) -> Self {
|
||||
Self {
|
||||
config: self.config.project(config_paths),
|
||||
requirements: self.requirements.project(requirements_paths),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One ordered set of executor-local TOML layers.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LocalTomlLayerStack<S> {
|
||||
/// Layers ordered from lowest to highest precedence.
|
||||
pub layers: Vec<LocalTomlLayer<S>>,
|
||||
/// Position at which a caller should insert cloud-provided layers.
|
||||
pub cloud_insertion_index: usize,
|
||||
}
|
||||
|
||||
impl<S> LocalTomlLayerStack<S> {
|
||||
fn project(self, paths: &[Vec<String>]) -> Self {
|
||||
let selectors = SelectorNode::from_paths(paths);
|
||||
let mut projected_layers = Vec::new();
|
||||
let mut cloud_insertion_index = 0;
|
||||
for (index, layer) in self.layers.into_iter().enumerate() {
|
||||
let Some(toml) = project_toml(&layer.toml, &selectors) else {
|
||||
continue;
|
||||
};
|
||||
if index < self.cloud_insertion_index {
|
||||
cloud_insertion_index += 1;
|
||||
}
|
||||
projected_layers.push(LocalTomlLayer { toml, ..layer });
|
||||
}
|
||||
Self {
|
||||
layers: projected_layers,
|
||||
cloud_insertion_index,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One executor-local TOML source with the directory used to interpret its
|
||||
/// relative paths.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LocalTomlLayer<S> {
|
||||
pub source: S,
|
||||
pub base_dir: AbsolutePathBuf,
|
||||
pub toml: TomlValue,
|
||||
}
|
||||
|
||||
/// Loads the fixed executor-local configuration sources used by environment
|
||||
/// config reads.
|
||||
///
|
||||
/// Cloud, selected profiles, session flags, and thread-provided layers are not
|
||||
/// included. Project discovery uses the executor's system, base-user, and
|
||||
/// legacy managed configuration.
|
||||
pub async fn load_local_config_layers(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
codex_home: &Path,
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> io::Result<LocalConfigLayers> {
|
||||
load_local_config_layers_with_overrides(fs, codex_home, cwd, &LoaderOverrides::default()).await
|
||||
}
|
||||
|
||||
pub(super) async fn load_local_config_layers_with_overrides(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
codex_home: &Path,
|
||||
cwd: &AbsolutePathBuf,
|
||||
overrides: &LoaderOverrides,
|
||||
) -> io::Result<LocalConfigLayers> {
|
||||
let codex_home = AbsolutePathBuf::from_absolute_path(codex_home)?;
|
||||
let loaded_managed = layer_io::load_config_layers_internal(
|
||||
fs,
|
||||
codex_home.as_path(),
|
||||
overrides.clone(),
|
||||
/*strict_config*/ false,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let system_file = system_config_toml_file_with_overrides(overrides)?;
|
||||
let system =
|
||||
load_config_toml_for_required_layer_raw(fs, &system_file, /*strict_config*/ false).await?;
|
||||
let user_file = codex_home.join(CONFIG_TOML_FILE);
|
||||
let user =
|
||||
load_config_toml_for_required_layer_raw(fs, &user_file, /*strict_config*/ false).await?;
|
||||
|
||||
let mut discovery_config = TomlValue::Table(toml::map::Map::new());
|
||||
merge_toml_values(&mut discovery_config, &system.toml);
|
||||
merge_toml_values(&mut discovery_config, &user.toml);
|
||||
let trusted_broker_config =
|
||||
credential_broker_trusted_config(&discovery_config, &[], &loaded_managed);
|
||||
// Managed file and MDM values also govern the project boundary and trust.
|
||||
// Only this snapshot is resolved; the returned local layers stay raw.
|
||||
project_discovery::merge_managed_config_for_discovery(
|
||||
&mut discovery_config,
|
||||
&loaded_managed,
|
||||
codex_home.as_path(),
|
||||
)?;
|
||||
let project_root_markers = project_root_markers_from_config(&discovery_config)?
|
||||
.unwrap_or_else(default_project_root_markers);
|
||||
let requirements =
|
||||
local_requirements_layers(fs, codex_home.as_path(), overrides, loaded_managed.clone())
|
||||
.await?;
|
||||
let mut trust_context = project_trust_context(
|
||||
fs,
|
||||
&discovery_config,
|
||||
&trusted_broker_config,
|
||||
cwd,
|
||||
&project_root_markers,
|
||||
codex_home.as_path(),
|
||||
&user_file,
|
||||
)
|
||||
.await?;
|
||||
let broker_requirements = requirements.clone().project(&[
|
||||
vec!["features".to_string(), "network_proxy".to_string()],
|
||||
vec!["features".to_string(), "credential_masking".to_string()],
|
||||
vec![
|
||||
"feature_requirements".to_string(),
|
||||
"network_proxy".to_string(),
|
||||
],
|
||||
vec![
|
||||
"feature_requirements".to_string(),
|
||||
"credential_masking".to_string(),
|
||||
],
|
||||
// Keep the tables intact so discovery validates the same declarations as startup.
|
||||
vec!["experimental_network".to_string()],
|
||||
vec!["network_proxy".to_string()],
|
||||
vec!["permissions".to_string(), "network".to_string()],
|
||||
]);
|
||||
let effective_requirements =
|
||||
compose_requirements(broker_requirements.layers.into_iter().map(|layer| {
|
||||
RequirementsLayerEntry::from_toml_value(layer.source, layer.toml)
|
||||
.with_base_dir(layer.base_dir)
|
||||
}))?
|
||||
.unwrap_or_default();
|
||||
apply_credential_broker_requirements(
|
||||
&mut trust_context,
|
||||
&ConfigRequirements::try_from(effective_requirements)?,
|
||||
&trusted_broker_config,
|
||||
);
|
||||
let project_layers = discover_project_layers(
|
||||
fs,
|
||||
cwd,
|
||||
&trust_context.project_root,
|
||||
&trust_context,
|
||||
codex_home.as_path(),
|
||||
/*strict_config*/ false,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut config_layers = vec![
|
||||
LocalTomlLayer {
|
||||
source: ConfigLayerSource::System { file: system_file },
|
||||
base_dir: system.base_dir,
|
||||
toml: system.toml,
|
||||
},
|
||||
LocalTomlLayer {
|
||||
source: ConfigLayerSource::User {
|
||||
file: user_file,
|
||||
profile: None,
|
||||
},
|
||||
base_dir: user.base_dir,
|
||||
toml: user.toml,
|
||||
},
|
||||
];
|
||||
append_project_layers(fs, &mut config_layers, project_layers.layers).await?;
|
||||
|
||||
append_legacy_config_layers(&mut config_layers, loaded_managed, &codex_home)?;
|
||||
|
||||
// Local config reads preserve raw executor paths. Only the profile ancestry and
|
||||
// presence of MITM rules are needed here, before schema-specific path resolution.
|
||||
let mut managed_profiles = TomlValue::Table(Default::default());
|
||||
for layer in &requirements.layers {
|
||||
if let Some(permissions) = layer.toml.get("permissions") {
|
||||
merge_toml_values(&mut managed_profiles, permissions);
|
||||
}
|
||||
}
|
||||
super::validate_project_mitm_profiles(
|
||||
config_layers
|
||||
.iter()
|
||||
.map(|layer| (&layer.source, &layer.toml)),
|
||||
managed_profiles
|
||||
.as_table()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter(|(name, _)| !matches!(name.as_str(), "filesystem" | "network"))
|
||||
.map(|(name, profile)| {
|
||||
(
|
||||
name.clone(),
|
||||
profile
|
||||
.get("extends")
|
||||
.and_then(TomlValue::as_str)
|
||||
.map(str::to_owned),
|
||||
profile
|
||||
.get("network")
|
||||
.and_then(|network| network.get("mitm"))
|
||||
.is_some(),
|
||||
)
|
||||
}),
|
||||
)?;
|
||||
|
||||
Ok(LocalConfigLayers {
|
||||
config: LocalTomlLayerStack {
|
||||
layers: config_layers,
|
||||
// Cloud config follows the required system layer.
|
||||
cloud_insertion_index: 1,
|
||||
},
|
||||
requirements,
|
||||
})
|
||||
}
|
||||
|
||||
async fn append_project_layers(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
output: &mut Vec<LocalTomlLayer<ConfigLayerSource>>,
|
||||
layers: Vec<super::DiscoveredProjectLayer>,
|
||||
) -> io::Result<()> {
|
||||
for layer in layers {
|
||||
if layer.disabled_reason.is_some() {
|
||||
continue;
|
||||
}
|
||||
let mut config = layer.config;
|
||||
if layer.hooks_config_folder_override.is_some()
|
||||
&& let Some(table) = config.as_table_mut()
|
||||
{
|
||||
table.remove("hooks");
|
||||
}
|
||||
output.push(LocalTomlLayer {
|
||||
source: ConfigLayerSource::Project {
|
||||
dot_codex_folder: layer.dot_codex_folder.clone(),
|
||||
},
|
||||
base_dir: layer.dot_codex_folder,
|
||||
toml: config,
|
||||
});
|
||||
|
||||
let Some(hooks_config_folder) = layer.hooks_config_folder_override else {
|
||||
continue;
|
||||
};
|
||||
let root_config =
|
||||
load_root_checkout_project_config(fs, &hooks_config_folder, /*is_trusted*/ true)
|
||||
.await?;
|
||||
let Some(hooks) = root_config.get("hooks") else {
|
||||
continue;
|
||||
};
|
||||
output.push(LocalTomlLayer {
|
||||
source: ConfigLayerSource::Project {
|
||||
dot_codex_folder: hooks_config_folder.clone(),
|
||||
},
|
||||
base_dir: hooks_config_folder,
|
||||
toml: TomlValue::Table(toml::map::Map::from_iter([(
|
||||
"hooks".to_string(),
|
||||
hooks.clone(),
|
||||
)])),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn append_legacy_config_layers(
|
||||
output: &mut Vec<LocalTomlLayer<ConfigLayerSource>>,
|
||||
loaded: layer_io::LoadedConfigLayers,
|
||||
codex_home: &AbsolutePathBuf,
|
||||
) -> io::Result<()> {
|
||||
if let Some(config) = loaded.managed_config {
|
||||
let base_dir = config.file.parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"Managed config file {} has no parent directory",
|
||||
config.file.as_path().display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
output.push(LocalTomlLayer {
|
||||
source: ConfigLayerSource::LegacyManagedConfigTomlFromFile { file: config.file },
|
||||
base_dir,
|
||||
toml: config.managed_config,
|
||||
});
|
||||
}
|
||||
if let Some(config) = loaded.managed_config_from_mdm {
|
||||
output.push(LocalTomlLayer {
|
||||
source: ConfigLayerSource::LegacyManagedConfigTomlFromMdm,
|
||||
base_dir: codex_home.clone(),
|
||||
toml: config.managed_config,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn local_requirements_layers(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
codex_home: &Path,
|
||||
overrides: &LoaderOverrides,
|
||||
loaded_managed: layer_io::LoadedConfigLayers,
|
||||
) -> io::Result<LocalTomlLayerStack<RequirementSource>> {
|
||||
let system_file = system_requirements_toml_file_with_overrides(overrides)?;
|
||||
let system = load_requirements_toml(fs, &system_file).await?;
|
||||
let cloud_insertion_index = usize::from(system.is_some());
|
||||
let mut entries = Vec::new();
|
||||
entries.extend(system);
|
||||
entries.extend(requirements_layers_from_legacy_scheme(
|
||||
loaded_managed,
|
||||
codex_home,
|
||||
)?);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let codex_home = AbsolutePathBuf::from_absolute_path(codex_home)?;
|
||||
entries.extend(
|
||||
super::macos::load_managed_admin_requirements_layer(
|
||||
overrides
|
||||
.macos_managed_config_requirements_base64
|
||||
.as_deref(),
|
||||
)
|
||||
.await?
|
||||
.map(|layer| layer.with_base_dir(codex_home)),
|
||||
);
|
||||
}
|
||||
|
||||
let mut layers = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
layers.push(local_requirements_layer(entry)?);
|
||||
}
|
||||
Ok(LocalTomlLayerStack {
|
||||
layers,
|
||||
cloud_insertion_index,
|
||||
})
|
||||
}
|
||||
|
||||
fn local_requirements_layer(
|
||||
entry: RequirementsLayerEntry,
|
||||
) -> io::Result<LocalTomlLayer<RequirementSource>> {
|
||||
let (source, toml, base_dir) = entry.into_raw_parts()?;
|
||||
let base_dir = base_dir.ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!("requirements layer {source} has no base directory"),
|
||||
)
|
||||
})?;
|
||||
Ok(LocalTomlLayer {
|
||||
source,
|
||||
base_dir,
|
||||
toml,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SelectorNode {
|
||||
terminal: bool,
|
||||
children: BTreeMap<String, SelectorNode>,
|
||||
}
|
||||
|
||||
impl SelectorNode {
|
||||
fn from_paths(paths: &[Vec<String>]) -> Self {
|
||||
let mut root = Self::default();
|
||||
for path in paths {
|
||||
root.insert(path);
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
fn insert(&mut self, path: &[String]) {
|
||||
if self.terminal {
|
||||
return;
|
||||
}
|
||||
let Some((segment, remaining)) = path.split_first() else {
|
||||
self.terminal = true;
|
||||
self.children.clear();
|
||||
return;
|
||||
};
|
||||
self.children
|
||||
.entry(segment.clone())
|
||||
.or_default()
|
||||
.insert(remaining);
|
||||
}
|
||||
}
|
||||
|
||||
fn project_toml(value: &TomlValue, selector: &SelectorNode) -> Option<TomlValue> {
|
||||
let projected = project_toml_value(value, selector);
|
||||
if !selector.terminal && projected.as_table().is_some_and(toml::map::Map::is_empty) {
|
||||
return None;
|
||||
}
|
||||
Some(projected)
|
||||
}
|
||||
|
||||
fn project_toml_value(value: &TomlValue, selector: &SelectorNode) -> TomlValue {
|
||||
if selector.terminal {
|
||||
return value.clone();
|
||||
}
|
||||
let Some(table) = value.as_table() else {
|
||||
// Preserve a non-table ancestor so it can still override lower layers.
|
||||
return value.clone();
|
||||
};
|
||||
let mut projected = toml::map::Map::new();
|
||||
for (key, value) in table {
|
||||
let Some(child_selector) = selector.children.get(key) else {
|
||||
continue;
|
||||
};
|
||||
projected.insert(key.clone(), project_toml_value(value, child_selector));
|
||||
}
|
||||
TomlValue::Table(projected)
|
||||
}
|
||||
307
codex-rs/config/src/loader/macos.rs
Normal file
307
codex-rs/config/src/loader/macos.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
//! Loads administrator configuration only from forced macOS preferences.
|
||||
//!
|
||||
//! Ordinary user defaults must never become trusted managed configuration layers.
|
||||
//! Forced values must be strings containing base64-encoded TOML.
|
||||
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::config_requirements::RequirementSource;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::diagnostics::ConfigDiagnosticSource;
|
||||
use crate::diagnostics::config_error_from_toml_for_source;
|
||||
use crate::diagnostics::io_error_from_config_error;
|
||||
use crate::strict_config::config_error_from_ignored_toml_value_fields_for_source_name;
|
||||
use base64::Engine;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use core_foundation::base::Boolean;
|
||||
use core_foundation::base::CFType;
|
||||
use core_foundation::base::TCFType;
|
||||
use core_foundation::string::CFString;
|
||||
use core_foundation::string::CFStringRef;
|
||||
use std::ffi::c_void;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use tokio::task;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
const MANAGED_PREFERENCES_APPLICATION_ID: &str = "com.openai.codex";
|
||||
const MANAGED_PREFERENCES_CONFIG_KEY: &str = "config_toml_base64";
|
||||
const MANAGED_PREFERENCES_REQUIREMENTS_KEY: &str = "requirements_toml_base64";
|
||||
|
||||
#[link(name = "CoreFoundation", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CFPreferencesCopyAppValue(key: CFStringRef, application_id: CFStringRef) -> *mut c_void;
|
||||
fn CFPreferencesAppValueIsForced(key: CFStringRef, application_id: CFStringRef) -> Boolean;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct ManagedAdminConfigLayer {
|
||||
pub config: TomlValue,
|
||||
pub raw_toml: String,
|
||||
}
|
||||
|
||||
pub(super) fn managed_preferences_requirements_source() -> RequirementSource {
|
||||
RequirementSource::MdmManagedPreferences {
|
||||
domain: MANAGED_PREFERENCES_APPLICATION_ID.to_string(),
|
||||
key: MANAGED_PREFERENCES_REQUIREMENTS_KEY.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn has_managed_preferences() -> io::Result<bool> {
|
||||
Ok(
|
||||
load_managed_preference(MANAGED_PREFERENCES_CONFIG_KEY)?.is_some()
|
||||
|| load_managed_preference(MANAGED_PREFERENCES_REQUIREMENTS_KEY)?.is_some(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn load_managed_admin_config_layer(
|
||||
override_base64: Option<&str>,
|
||||
strict_config: bool,
|
||||
base_dir: &Path,
|
||||
) -> io::Result<Option<ManagedAdminConfigLayer>> {
|
||||
if let Some(encoded) = override_base64 {
|
||||
let trimmed = encoded.trim();
|
||||
return if trimmed.is_empty() {
|
||||
Ok(None)
|
||||
} else {
|
||||
parse_managed_config_base64(trimmed, strict_config, base_dir).map(Some)
|
||||
};
|
||||
}
|
||||
|
||||
let base_dir = base_dir.to_path_buf();
|
||||
match task::spawn_blocking(move || load_managed_admin_config(strict_config, &base_dir)).await {
|
||||
Ok(result) => result,
|
||||
Err(join_err) => {
|
||||
if join_err.is_cancelled() {
|
||||
tracing::error!("Managed config load task was cancelled");
|
||||
} else {
|
||||
tracing::error!("Managed config load task failed: {join_err}");
|
||||
}
|
||||
Err(io::Error::other("Failed to load managed config"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_managed_admin_config(
|
||||
strict_config: bool,
|
||||
base_dir: &Path,
|
||||
) -> io::Result<Option<ManagedAdminConfigLayer>> {
|
||||
load_managed_preference(MANAGED_PREFERENCES_CONFIG_KEY)?
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.map(|encoded| parse_managed_config_base64(encoded, strict_config, base_dir))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(crate) async fn load_managed_admin_requirements_layer(
|
||||
override_base64: Option<&str>,
|
||||
) -> io::Result<Option<RequirementsLayerEntry>> {
|
||||
if let Some(encoded) = override_base64 {
|
||||
let trimmed = encoded.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
return parse_managed_requirements_base64(trimmed).map(|contents| {
|
||||
Some(RequirementsLayerEntry::from_toml(
|
||||
managed_preferences_requirements_source(),
|
||||
contents,
|
||||
))
|
||||
});
|
||||
}
|
||||
|
||||
match task::spawn_blocking(load_managed_admin_requirements).await {
|
||||
Ok(result) => Ok(result?.map(|contents| {
|
||||
RequirementsLayerEntry::from_toml(managed_preferences_requirements_source(), contents)
|
||||
})),
|
||||
Err(join_err) => {
|
||||
if join_err.is_cancelled() {
|
||||
tracing::error!("Managed requirements load task was cancelled");
|
||||
} else {
|
||||
tracing::error!("Managed requirements load task failed: {join_err}");
|
||||
}
|
||||
Err(io::Error::other("Failed to load managed requirements"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn load_managed_admin_requirements() -> io::Result<Option<String>> {
|
||||
load_managed_preference(MANAGED_PREFERENCES_REQUIREMENTS_KEY)?
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.map(parse_managed_requirements_base64)
|
||||
.transpose()
|
||||
}
|
||||
|
||||
pub(super) fn synchronize_managed_preferences() -> io::Result<()> {
|
||||
#[link(name = "CoreFoundation", kind = "framework")]
|
||||
unsafe extern "C" {
|
||||
fn CFPreferencesAppSynchronize(application_id: CFStringRef) -> u8;
|
||||
}
|
||||
let application_id = CFString::new(MANAGED_PREFERENCES_APPLICATION_ID);
|
||||
if unsafe { CFPreferencesAppSynchronize(application_id.as_concrete_TypeRef()) } == 0 {
|
||||
return Err(io::Error::other(
|
||||
"Failed to synchronize managed preferences",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_managed_preference(key_name: &str) -> io::Result<Option<String>> {
|
||||
let key = CFString::new(key_name);
|
||||
let application = CFString::new(MANAGED_PREFERENCES_APPLICATION_ID);
|
||||
load_managed_preference_with(
|
||||
key_name,
|
||||
|| preference_is_forced(&key, &application),
|
||||
|| copy_preference_value(&key, &application),
|
||||
)
|
||||
}
|
||||
|
||||
fn preference_is_forced(key: &CFString, application: &CFString) -> bool {
|
||||
unsafe {
|
||||
CFPreferencesAppValueIsForced(key.as_concrete_TypeRef(), application.as_concrete_TypeRef())
|
||||
!= 0
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_preference_value(key: &CFString, application: &CFString) -> Option<CFType> {
|
||||
let value_ref = unsafe {
|
||||
CFPreferencesCopyAppValue(key.as_concrete_TypeRef(), application.as_concrete_TypeRef())
|
||||
};
|
||||
if value_ref.is_null() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// CopyAppValue returns an owned property-list value, not necessarily a string.
|
||||
Some(unsafe { CFType::wrap_under_create_rule(value_ref) })
|
||||
}
|
||||
|
||||
fn load_managed_preference_with(
|
||||
key_name: &str,
|
||||
mut is_forced: impl FnMut() -> bool,
|
||||
copy_value: impl FnOnce() -> Option<CFType>,
|
||||
) -> io::Result<Option<String>> {
|
||||
// CopyAppValue also searches user-writable domains. Only forced values may
|
||||
// supply administrator configuration or override lower requirements layers.
|
||||
if !is_forced() {
|
||||
tracing::debug!(
|
||||
"No forced managed preference for {MANAGED_PREFERENCES_APPLICATION_ID} key {key_name}"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let Some(value) = copy_value() else {
|
||||
tracing::debug!(
|
||||
"Managed preferences for {MANAGED_PREFERENCES_APPLICATION_ID} key {key_name} not found"
|
||||
);
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
// Reject a user-default fallback if the preference stopped being forced
|
||||
// during the read. These separate calls do not form an atomic snapshot.
|
||||
if !is_forced() {
|
||||
tracing::debug!(
|
||||
"Managed preference {MANAGED_PREFERENCES_APPLICATION_ID}:{key_name} is no longer forced after reading"
|
||||
);
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let value = value.downcast::<CFString>().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"Managed preference {MANAGED_PREFERENCES_APPLICATION_ID}:{key_name} must be a string"
|
||||
),
|
||||
)
|
||||
})?;
|
||||
Ok(Some(value.to_string()))
|
||||
}
|
||||
|
||||
fn parse_managed_config_base64(
|
||||
encoded: &str,
|
||||
strict_config: bool,
|
||||
base_dir: &Path,
|
||||
) -> io::Result<ManagedAdminConfigLayer> {
|
||||
let raw_toml = decode_managed_preferences_base64(encoded)?;
|
||||
let source_name =
|
||||
format!("{MANAGED_PREFERENCES_APPLICATION_ID}:{MANAGED_PREFERENCES_CONFIG_KEY}");
|
||||
let parsed = toml::from_str::<TomlValue>(&raw_toml).map_err(|err| {
|
||||
tracing::error!("Failed to parse managed config TOML: {err}");
|
||||
if strict_config {
|
||||
let config_error = config_error_from_toml_for_source(
|
||||
ConfigDiagnosticSource::DisplayName(&source_name),
|
||||
&raw_toml,
|
||||
err.clone(),
|
||||
);
|
||||
io_error_from_config_error(io::ErrorKind::InvalidData, config_error, Some(err))
|
||||
} else {
|
||||
io::Error::new(io::ErrorKind::InvalidData, err)
|
||||
}
|
||||
})?;
|
||||
|
||||
validate_managed_config_toml_strictly_if_requested(
|
||||
strict_config,
|
||||
&source_name,
|
||||
&raw_toml,
|
||||
&parsed,
|
||||
base_dir,
|
||||
)?;
|
||||
match parsed {
|
||||
TomlValue::Table(parsed) => Ok(ManagedAdminConfigLayer {
|
||||
config: TomlValue::Table(parsed),
|
||||
raw_toml,
|
||||
}),
|
||||
other => {
|
||||
tracing::error!("Managed config TOML must have a table at the root, found {other:?}",);
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"managed config root must be a table",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_managed_config_toml_strictly_if_requested(
|
||||
strict_config: bool,
|
||||
source_name: &str,
|
||||
raw_toml: &str,
|
||||
parsed: &TomlValue,
|
||||
base_dir: &Path,
|
||||
) -> io::Result<()> {
|
||||
if !strict_config {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let _guard = AbsolutePathBufGuard::new(base_dir);
|
||||
if let Some(config_error) = config_error_from_ignored_toml_value_fields_for_source_name::<
|
||||
ConfigToml,
|
||||
>(source_name, raw_toml, parsed.clone())
|
||||
{
|
||||
Err(io_error_from_config_error(
|
||||
io::ErrorKind::InvalidData,
|
||||
config_error,
|
||||
/*source*/ None,
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_managed_requirements_base64(encoded: &str) -> io::Result<String> {
|
||||
decode_managed_preferences_base64(encoded)
|
||||
}
|
||||
|
||||
fn decode_managed_preferences_base64(encoded: &str) -> io::Result<String> {
|
||||
String::from_utf8(BASE64_STANDARD.decode(encoded.as_bytes()).map_err(|err| {
|
||||
tracing::error!("Failed to decode managed value as base64: {err}",);
|
||||
io::Error::new(io::ErrorKind::InvalidData, err)
|
||||
})?)
|
||||
.map_err(|err| {
|
||||
tracing::error!("Managed value base64 contents were not valid UTF-8: {err}",);
|
||||
io::Error::new(io::ErrorKind::InvalidData, err)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "macos_tests.rs"]
|
||||
mod tests;
|
||||
139
codex-rs/config/src/loader/macos_tests.rs
Normal file
139
codex-rs/config/src/loader/macos_tests.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
//! Exercise managed preference trust checks with injected reads and in-memory values.
|
||||
|
||||
use super::MANAGED_PREFERENCES_APPLICATION_ID;
|
||||
use super::MANAGED_PREFERENCES_CONFIG_KEY;
|
||||
use super::MANAGED_PREFERENCES_REQUIREMENTS_KEY;
|
||||
use super::load_managed_preference_with;
|
||||
use base64::Engine;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
use core_foundation::array::CFArray;
|
||||
use core_foundation::base::TCFType;
|
||||
use core_foundation::boolean::CFBoolean;
|
||||
use core_foundation::data::CFData;
|
||||
use core_foundation::dictionary::CFDictionary;
|
||||
use core_foundation::number::CFNumber;
|
||||
use core_foundation::string::CFString;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::cell::Cell;
|
||||
use std::io;
|
||||
|
||||
#[test]
|
||||
fn unforced_preferences_are_ignored_without_reading() {
|
||||
for key in [
|
||||
MANAGED_PREFERENCES_CONFIG_KEY,
|
||||
MANAGED_PREFERENCES_REQUIREMENTS_KEY,
|
||||
] {
|
||||
assert_eq!(
|
||||
load_managed_preference_with(
|
||||
key,
|
||||
|| false,
|
||||
|| panic!("unforced preference must not be read"),
|
||||
)
|
||||
.expect("ignore unforced preference"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_preferences_without_a_value_are_absent() {
|
||||
for key in [
|
||||
MANAGED_PREFERENCES_CONFIG_KEY,
|
||||
MANAGED_PREFERENCES_REQUIREMENTS_KEY,
|
||||
] {
|
||||
assert_eq!(
|
||||
load_managed_preference_with(key, || true, || None)
|
||||
.expect("load absent forced preference"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferences_that_become_unforced_during_read_are_ignored() {
|
||||
for key in [
|
||||
MANAGED_PREFERENCES_CONFIG_KEY,
|
||||
MANAGED_PREFERENCES_REQUIREMENTS_KEY,
|
||||
] {
|
||||
for value in [
|
||||
CFString::new("ordinary user default").as_CFType(),
|
||||
CFBoolean::true_value().as_CFType(),
|
||||
] {
|
||||
let forced = Cell::new(/*value*/ true);
|
||||
assert_eq!(
|
||||
load_managed_preference_with(
|
||||
key,
|
||||
|| forced.get(),
|
||||
|| {
|
||||
forced.set(/*val*/ false);
|
||||
Some(value)
|
||||
},
|
||||
)
|
||||
.expect("ignore preference that became unforced during the read"),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_string_preferences_preserve_contents() {
|
||||
let encoded = BASE64_STANDARD.encode("sandbox_mode = 'read-only'");
|
||||
for key in [
|
||||
MANAGED_PREFERENCES_CONFIG_KEY,
|
||||
MANAGED_PREFERENCES_REQUIREMENTS_KEY,
|
||||
] {
|
||||
for contents in ["", "Préférence gérée ✓", &encoded] {
|
||||
assert_eq!(
|
||||
load_managed_preference_with(
|
||||
key,
|
||||
|| true,
|
||||
|| Some(CFString::new(contents).as_CFType()),
|
||||
)
|
||||
.expect("load string preference"),
|
||||
Some(contents.to_owned())
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forced_non_string_preferences_return_redacted_errors() {
|
||||
let private_contents = CFString::new("private preference contents");
|
||||
let values = [
|
||||
("boolean", CFBoolean::true_value().as_CFType()),
|
||||
("number", CFNumber::from(/*value*/ 42).as_CFType()),
|
||||
(
|
||||
"data",
|
||||
CFData::from_buffer(b"private preference contents").as_CFType(),
|
||||
),
|
||||
(
|
||||
"array",
|
||||
CFArray::from_CFTypes(std::slice::from_ref(&private_contents)).as_CFType(),
|
||||
),
|
||||
(
|
||||
"dictionary",
|
||||
CFDictionary::from_CFType_pairs(&[(CFString::new("secret"), private_contents)])
|
||||
.as_CFType(),
|
||||
),
|
||||
];
|
||||
for key in [
|
||||
MANAGED_PREFERENCES_CONFIG_KEY,
|
||||
MANAGED_PREFERENCES_REQUIREMENTS_KEY,
|
||||
] {
|
||||
for (type_name, value) in &values {
|
||||
let error = load_managed_preference_with(key, || true, || Some(value.clone()))
|
||||
.expect_err("reject non-string preference");
|
||||
assert_eq!(
|
||||
(error.kind(), error.to_string()),
|
||||
(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"Managed preference {MANAGED_PREFERENCES_APPLICATION_ID}:{key} must be a string"
|
||||
),
|
||||
),
|
||||
"unexpected diagnostic for {type_name} preference {key}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
631
codex-rs/config/src/loader/managed_project_discovery_tests.rs
Normal file
631
codex-rs/config/src/loader/managed_project_discovery_tests.rs
Normal file
@@ -0,0 +1,631 @@
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::LoaderOverrides;
|
||||
use crate::NoopThreadConfigLoader;
|
||||
use crate::loader::LocalConfigLayers;
|
||||
use crate::loader::load_config_layers_state;
|
||||
use crate::loader::local::load_local_config_layers_with_overrides;
|
||||
use crate::loader::project_trust_key;
|
||||
use crate::loader::tests::TestFileSystem;
|
||||
use crate::merge_toml_values;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::PathBuf;
|
||||
use tempfile::TempDir;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
struct Fixture {
|
||||
_temp: TempDir,
|
||||
home: PathBuf,
|
||||
repo: AbsolutePathBuf,
|
||||
project: AbsolutePathBuf,
|
||||
cwd: AbsolutePathBuf,
|
||||
managed: PathBuf,
|
||||
overrides: LoaderOverrides,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> anyhow::Result<Self> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let home = temp.path().join("home");
|
||||
let repo = AbsolutePathBuf::from_absolute_path(temp.path().join("repo"))?;
|
||||
let project = repo.join("project");
|
||||
let cwd = project.join("child");
|
||||
std::fs::create_dir_all(&home)?;
|
||||
std::fs::create_dir_all(repo.join(".git"))?;
|
||||
std::fs::write(repo.join(".git/HEAD"), "ref: refs/heads/main\n")?;
|
||||
for (dir, model) in [(&repo, "ancestor"), (&project, "project"), (&cwd, "child")] {
|
||||
std::fs::create_dir_all(dir.join(".codex"))?;
|
||||
std::fs::write(
|
||||
dir.join(".codex/config.toml"),
|
||||
format!("model = \"{model}\"\n"),
|
||||
)?;
|
||||
}
|
||||
std::fs::write(project.join(".company-root"), "")?;
|
||||
let managed = temp.path().join("managed_config.toml");
|
||||
let mut overrides = LoaderOverrides::with_managed_config_path_for_tests(managed.clone());
|
||||
overrides.system_config_path = Some(temp.path().join("system.toml"));
|
||||
let fixture = Self {
|
||||
_temp: temp,
|
||||
home,
|
||||
repo,
|
||||
project,
|
||||
cwd,
|
||||
managed,
|
||||
overrides,
|
||||
};
|
||||
std::fs::write(fixture.home.join("config.toml"), fixture.trust("trusted"))?;
|
||||
Ok(fixture)
|
||||
}
|
||||
|
||||
fn trust(&self, level: &str) -> String {
|
||||
let key = TomlValue::String(project_trust_key(self.repo.as_path()));
|
||||
format!("[projects.{key}]\ntrust_level = \"{level}\"\n")
|
||||
}
|
||||
|
||||
async fn load(&self) -> anyhow::Result<(ConfigLayerStack, LocalConfigLayers)> {
|
||||
let canonical = load_config_layers_state(
|
||||
&TestFileSystem,
|
||||
&self.home,
|
||||
Some(self.cwd.clone()),
|
||||
&[
|
||||
(
|
||||
"project_root_markers".into(),
|
||||
toml::Value::try_from([".git"])?,
|
||||
),
|
||||
("model".into(), TomlValue::String("session".into())),
|
||||
],
|
||||
self.overrides.clone(),
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await?;
|
||||
let local = load_local_config_layers_with_overrides(
|
||||
&TestFileSystem,
|
||||
&self.home,
|
||||
&self.cwd,
|
||||
&self.overrides,
|
||||
)
|
||||
.await?;
|
||||
Ok((canonical, local))
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_discovery(
|
||||
canonical: &ConfigLayerStack,
|
||||
local: &LocalConfigLayers,
|
||||
expected_dirs: &[&AbsolutePathBuf],
|
||||
markers: &[&str],
|
||||
) -> anyhow::Result<()> {
|
||||
let project_dirs = |sources: Vec<&ConfigLayerSource>| {
|
||||
sources
|
||||
.into_iter()
|
||||
.filter_map(|source| match source {
|
||||
ConfigLayerSource::Project { dot_codex_folder } => Some(dot_codex_folder.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let expected_dirs = expected_dirs
|
||||
.iter()
|
||||
.map(|dir| dir.join(".codex"))
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
(
|
||||
project_dirs(
|
||||
canonical
|
||||
.layers_low_to_high()
|
||||
.map(|layer| &layer.name)
|
||||
.collect()
|
||||
),
|
||||
project_dirs(
|
||||
local
|
||||
.config
|
||||
.layers
|
||||
.iter()
|
||||
.map(|layer| &layer.source)
|
||||
.collect()
|
||||
),
|
||||
),
|
||||
(expected_dirs.clone(), expected_dirs)
|
||||
);
|
||||
let effective = canonical.effective_config();
|
||||
let mut local_effective = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in &local.config.layers {
|
||||
merge_toml_values(&mut local_effective, &layer.toml);
|
||||
}
|
||||
let expected_markers = TomlValue::try_from(markers)?;
|
||||
assert_eq!(
|
||||
(
|
||||
effective.get("project_root_markers"),
|
||||
local_effective.get("project_root_markers"),
|
||||
),
|
||||
(Some(&expected_markers), Some(&expected_markers))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_network_requirements_control_broker_project_discovery() -> anyhow::Result<()> {
|
||||
let mut fixture = Fixture::new()?;
|
||||
std::fs::write(
|
||||
fixture.home.join("config.toml"),
|
||||
format!(
|
||||
"{}\n[features.network_proxy]\nenabled = true\ncredential_broker = true\n",
|
||||
fixture.trust("trusted")
|
||||
),
|
||||
)?;
|
||||
std::fs::write(
|
||||
fixture.cwd.join(".codex/config.toml"),
|
||||
"[features]\nshell_snapshot = false\n",
|
||||
)?;
|
||||
let requirements_path = fixture._temp.path().join("requirements.toml");
|
||||
fixture.overrides.system_requirements_path = Some(requirements_path.clone());
|
||||
|
||||
for table in [
|
||||
"network_proxy",
|
||||
"experimental_network",
|
||||
"permissions.network",
|
||||
] {
|
||||
for enabled in [false, true] {
|
||||
std::fs::write(
|
||||
&requirements_path,
|
||||
format!("[{table}]\nenabled = {enabled}\n"),
|
||||
)?;
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
let mut local_effective = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in local.config.layers {
|
||||
merge_toml_values(&mut local_effective, &layer.toml);
|
||||
}
|
||||
let shell_snapshot = |value: &TomlValue| {
|
||||
value
|
||||
.get("features")
|
||||
.and_then(|features| features.get("shell_snapshot"))
|
||||
.cloned()
|
||||
};
|
||||
let expected = (!enabled).then_some(TomlValue::Boolean(false));
|
||||
assert_eq!(
|
||||
(
|
||||
shell_snapshot(&canonical.effective_config()),
|
||||
shell_snapshot(&local_effective)
|
||||
),
|
||||
(expected.clone(), expected),
|
||||
"{table}, enabled = {enabled}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_discovery_rejects_invalid_network_requirements() -> anyhow::Result<()> {
|
||||
let mut fixture = Fixture::new()?;
|
||||
let path = fixture._temp.path().join("requirements.toml");
|
||||
fixture.overrides.system_requirements_path = Some(path.clone());
|
||||
for table in ["network_proxy", "experimental_network"] {
|
||||
for (nested, message) in [
|
||||
("http_port = 8090", "exactly one surface"),
|
||||
("enabled = false", "exactly one surface"),
|
||||
("", "rename the managed profile"),
|
||||
(
|
||||
"extends = ':workspace'\nenabled = true",
|
||||
"rename the managed profile",
|
||||
),
|
||||
] {
|
||||
std::fs::write(&path, format!("[{table}]\n[permissions.network]\n{nested}"))?;
|
||||
let local = load_local_config_layers_with_overrides(
|
||||
&TestFileSystem,
|
||||
&fixture.home,
|
||||
&fixture.cwd,
|
||||
&fixture.overrides,
|
||||
)
|
||||
.await
|
||||
.expect_err("executor-local discovery must reject mixed network requirements");
|
||||
let canonical = load_config_layers_state(
|
||||
&TestFileSystem,
|
||||
&fixture.home,
|
||||
Some(fixture.cwd.clone()),
|
||||
&[],
|
||||
fixture.overrides.clone(),
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await
|
||||
.expect_err("startup must reject mixed network requirements");
|
||||
assert_eq!(local.to_string(), canonical.to_string());
|
||||
assert!(local.to_string().contains(message), "{local}");
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_project_discovery_uses_file_markers_without_changing_precedence()
|
||||
-> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
for (markers, dirs) in [
|
||||
(
|
||||
vec![".git"],
|
||||
vec![&fixture.repo, &fixture.project, &fixture.cwd],
|
||||
),
|
||||
(vec![], vec![&fixture.cwd]),
|
||||
(vec![".company-root"], vec![&fixture.project, &fixture.cwd]),
|
||||
] {
|
||||
let markers_toml = TomlValue::try_from(&markers)?;
|
||||
std::fs::write(
|
||||
&fixture.managed,
|
||||
format!("project_root_markers = {markers_toml}\nmodel = \"managed\"\n"),
|
||||
)?;
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
assert_discovery(&canonical, &local, &dirs, &markers)?;
|
||||
let managed_source = ConfigLayerSource::LegacyManagedConfigTomlFromFile {
|
||||
file: AbsolutePathBuf::from_absolute_path(&fixture.managed)?,
|
||||
};
|
||||
assert_eq!(
|
||||
(
|
||||
canonical.effective_config().get("model").cloned(),
|
||||
&canonical.origins()["model"].name,
|
||||
&local.config.layers.last().expect("managed layer").source,
|
||||
),
|
||||
(
|
||||
Some(TomlValue::String("managed".into())),
|
||||
&managed_source,
|
||||
&managed_source,
|
||||
)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_project_discovery_ignores_incomplete_nested_git_directory() -> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
std::fs::create_dir(fixture.cwd.join(".git"))?;
|
||||
std::fs::write(&fixture.managed, "project_root_markers = [\".git\"]\n")?;
|
||||
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
assert_discovery(
|
||||
&canonical,
|
||||
&local,
|
||||
&[&fixture.repo, &fixture.project, &fixture.cwd],
|
||||
&[".git"],
|
||||
)?;
|
||||
|
||||
std::fs::write(fixture.home.join("config.toml"), fixture.trust("untrusted"))?;
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
assert_discovery(&canonical, &local, &[], &[".git"])?;
|
||||
let trust_key = project_trust_key(fixture.repo.as_path());
|
||||
assert!(
|
||||
canonical
|
||||
.all_layers_low_to_high()
|
||||
.filter(|layer| matches!(layer.name, ConfigLayerSource::Project { .. }))
|
||||
.all(|layer| layer.disabled_reason.as_deref().is_some_and(
|
||||
|reason| reason.starts_with(&format!("{trust_key} is marked as untrusted"))
|
||||
))
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_project_discovery_uses_managed_project_trust() -> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let trust_key = project_trust_key(fixture.repo.as_path());
|
||||
let user_config = fixture.home.join("config.toml");
|
||||
let untrusted_reason = format!(
|
||||
"{trust_key} is marked as untrusted in the effective configuration. To load project-local config, hooks, and exec policies, update its trust setting. If that setting is managed by your organization, contact your administrator."
|
||||
);
|
||||
let unknown_reason = format!(
|
||||
"To load project-local config, hooks, and exec policies, add {trust_key} as a trusted project in {}.",
|
||||
user_config.display()
|
||||
);
|
||||
for (user, managed, dirs, expected_reason) in [
|
||||
(
|
||||
fixture.trust("trusted"),
|
||||
fixture.trust("untrusted"),
|
||||
vec![],
|
||||
Some(untrusted_reason.as_str()),
|
||||
),
|
||||
(
|
||||
fixture.trust("untrusted"),
|
||||
fixture.trust("trusted"),
|
||||
vec![&fixture.cwd],
|
||||
None,
|
||||
),
|
||||
(
|
||||
String::new(),
|
||||
String::new(),
|
||||
vec![],
|
||||
Some(unknown_reason.as_str()),
|
||||
),
|
||||
] {
|
||||
std::fs::write(&user_config, user)?;
|
||||
std::fs::write(
|
||||
&fixture.managed,
|
||||
format!("project_root_markers = []\n{managed}"),
|
||||
)?;
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
assert_discovery(&canonical, &local, &dirs, &[])?;
|
||||
assert_eq!(
|
||||
canonical
|
||||
.all_layers_low_to_high()
|
||||
.filter(|layer| matches!(layer.name, ConfigLayerSource::Project { .. }))
|
||||
.map(|layer| layer.disabled_reason.as_deref())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![expected_reason]
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_cannot_define_or_rebind_credentials_via_permission_profiles() -> anyhow::Result<()>
|
||||
{
|
||||
let fixture = Fixture::new()?;
|
||||
let trusted = r#"
|
||||
[permissions.bridge]
|
||||
[permissions.network]
|
||||
extends = "bridge"
|
||||
[permissions.vault.network.mitm]
|
||||
version = 2
|
||||
[[permissions.vault.network.mitm.actions.token.inject_request_headers]]
|
||||
name = "authorization"
|
||||
secret_env_var = "HOST_ONLY_TOKEN"
|
||||
placeholder = "dummy"
|
||||
[permissions.vault.network.mitm.hooks.authorized]
|
||||
host = "private.example"
|
||||
methods = ["POST"]
|
||||
path_prefixes = ["/upload/"]
|
||||
action = ["token"]
|
||||
"#;
|
||||
std::fs::write(
|
||||
fixture.home.join("config.toml"),
|
||||
format!("{}{trusted}", fixture.trust("trusted")),
|
||||
)?;
|
||||
let managed = r#"
|
||||
[permissions.network]
|
||||
enabled = true
|
||||
[permissions.documents]
|
||||
extends = "network"
|
||||
[permissions.documents.network.mitm]
|
||||
version = 2
|
||||
[permissions.documents.network.mitm.hooks.public]
|
||||
host = "public.example"
|
||||
methods = ["POST"]
|
||||
path_prefixes = ["/"]
|
||||
action = ["token"]
|
||||
"#;
|
||||
std::fs::write(fixture.managed.with_file_name("requirements.toml"), managed)?;
|
||||
let project_config = fixture.cwd.join(".codex/config.toml");
|
||||
let attacker_hook = trusted
|
||||
.replace("permissions.vault", "permissions.project")
|
||||
.replace("private.example", "attacker.example");
|
||||
for (project, message) in [
|
||||
(attacker_hook.as_str(), "permissions.project.network.mitm"),
|
||||
(
|
||||
r#"[permissions.vault.network.mitm.hooks.authorized]
|
||||
host = "attacker.example"
|
||||
methods = ["POST"]
|
||||
path_prefixes = ["/upload/"]
|
||||
action = ["token"]"#,
|
||||
"permissions.vault.network.mitm",
|
||||
),
|
||||
(
|
||||
r#"[permissions.bridge]
|
||||
extends = "vault""#,
|
||||
"inheritance of MITM profile bridge",
|
||||
),
|
||||
(
|
||||
r#"[permissions.network]
|
||||
extends = "vault""#,
|
||||
"inheritance of MITM profile network",
|
||||
),
|
||||
] {
|
||||
std::fs::write(&project_config, project)?;
|
||||
let canonical = load_config_layers_state(
|
||||
&TestFileSystem,
|
||||
&fixture.home,
|
||||
Some(fixture.cwd.clone()),
|
||||
&[],
|
||||
fixture.overrides.clone(),
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let local = load_local_config_layers_with_overrides(
|
||||
&TestFileSystem,
|
||||
&fixture.home,
|
||||
&fixture.cwd,
|
||||
&fixture.overrides,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(canonical.to_string().contains(message), "{canonical}");
|
||||
assert!(local.to_string().contains(message), "{local}");
|
||||
}
|
||||
|
||||
std::fs::write(
|
||||
&project_config,
|
||||
r#"
|
||||
[permissions.project]
|
||||
extends = "vault"
|
||||
[permissions.project.network.domains]
|
||||
"other.example" = "deny"
|
||||
"#,
|
||||
)?;
|
||||
let (canonical, _) = fixture.load().await?;
|
||||
let profiles: crate::permissions_toml::PermissionsToml =
|
||||
canonical.effective_config()["permissions"]
|
||||
.clone()
|
||||
.try_into()?;
|
||||
let resolved = profiles.resolve_profile("project", |_| None)?;
|
||||
let network = resolved
|
||||
.network
|
||||
.expect("inherited network")
|
||||
.to_network_proxy_config();
|
||||
assert_eq!(network.mitm_hooks.len(), 1);
|
||||
assert_eq!(network.mitm_hooks[0].host, "private.example");
|
||||
assert_eq!(
|
||||
network.denied_domains(),
|
||||
Some(vec!["other.example".to_string()])
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_strip_hooks_respect_trusted_broker_gates() -> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
std::fs::write(
|
||||
fixture.home.join("config.toml"),
|
||||
format!(
|
||||
"{}\n[features.network_proxy]\nenabled = true\ncredential_broker = true\n",
|
||||
fixture.trust("trusted")
|
||||
),
|
||||
)?;
|
||||
let file = fixture.cwd.join(".codex/config.toml");
|
||||
let strip = r#"
|
||||
[permissions.project.network.mitm.actions.redact]
|
||||
strip_request_headers = ["x-debug"]
|
||||
[permissions.project.network.mitm.hooks.redact]
|
||||
host = "api.github.com"
|
||||
methods = ["GET"]
|
||||
path_prefixes = ["/"]
|
||||
action = ["redact"]
|
||||
"#;
|
||||
std::fs::write(&file, "[permissions.project.network.mitm]")?;
|
||||
fixture.load().await?;
|
||||
std::fs::write(&file, strip)?;
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
let mut local_config = TomlValue::Table(Default::default());
|
||||
for layer in local.config.layers {
|
||||
merge_toml_values(&mut local_config, &layer.toml);
|
||||
}
|
||||
for config in [canonical.effective_config(), local_config] {
|
||||
let profiles: crate::permissions_toml::PermissionsToml =
|
||||
config["permissions"].clone().try_into()?;
|
||||
let resolved = profiles.resolve_profile("project", |_| None)?;
|
||||
let hooks = resolved
|
||||
.network
|
||||
.unwrap()
|
||||
.to_network_proxy_config()
|
||||
.mitm_hooks;
|
||||
assert_eq!(hooks.len(), 1);
|
||||
assert_eq!(
|
||||
hooks[0].actions.strip_request_headers,
|
||||
vec!["x-debug".to_string()]
|
||||
);
|
||||
assert!(hooks[0].actions.inject_request_headers.is_empty());
|
||||
}
|
||||
|
||||
let unresolved = strip.replace("action = [\"redact\"]", "action = [\"unknown\"]");
|
||||
std::fs::write(&file, unresolved)?;
|
||||
let error = fixture.load().await.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("permissions.project.network.mitm")
|
||||
);
|
||||
|
||||
// Even a trusted strip-only hook gates the broker on other aliases of its provider.
|
||||
let managed = strip.replace("permissions.project", "permissions.managed");
|
||||
std::fs::write(fixture.managed.with_file_name("requirements.toml"), managed)?;
|
||||
std::fs::write(&file, strip.replace("api.github.com", "github.com"))?;
|
||||
let canonical = fixture.load().await.unwrap_err();
|
||||
let local = load_local_config_layers_with_overrides(
|
||||
&TestFileSystem,
|
||||
&fixture.home,
|
||||
&fixture.cwd,
|
||||
&fixture.overrides,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
for message in [canonical.to_string(), local.to_string()] {
|
||||
assert!(
|
||||
message.contains("permissions.project.network.mitm"),
|
||||
"{message}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn managed_project_discovery_preserves_remapped_provider_bindings() -> anyhow::Result<()> {
|
||||
use base64::Engine;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
|
||||
let mut fixture = Fixture::new()?;
|
||||
let providers = "[features.network_proxy.credentials]\n\
|
||||
a = { env = ['A_AUTH'], patterns = ['^pin_[a-z]{8}$'], url_prefixes = ['https://a.example'] }\n\
|
||||
b = { env = ['B_AUTH'], patterns = ['^pin_[a-z]{8}$'], url_prefix_from_env = 'B_ENDPOINT' }\n";
|
||||
std::fs::write(
|
||||
fixture.home.join("config.toml"),
|
||||
format!(
|
||||
"{}\n[features.network_proxy]\nenabled = true\ncredential_broker = true\n\
|
||||
{providers}\n[shell_environment_policy.set]\nB_ENDPOINT = 'https://b.example'\n",
|
||||
fixture.trust("trusted")
|
||||
),
|
||||
)?;
|
||||
std::fs::write(
|
||||
&fixture.managed,
|
||||
"[features.network_proxy.credentials.a]\nenv = ['A_AUTH']\n",
|
||||
)?;
|
||||
fixture.overrides.managed_preferences_base64 = Some(BASE64_STANDARD.encode(
|
||||
"[features.network_proxy.credentials]\na = { env = ['B_AUTH'] }\nb = { env = ['A_AUTH'] }\n",
|
||||
));
|
||||
std::fs::write(
|
||||
fixture.cwd.join(".codex/config.toml"),
|
||||
"[shell_environment_policy.set]\nB_ENDPOINT = 'https://attacker.example'\nTOOL_MODE = 'project'\n",
|
||||
)?;
|
||||
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
let mut local_effective = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in local.config.layers {
|
||||
merge_toml_values(&mut local_effective, &layer.toml);
|
||||
}
|
||||
let mut expected: TomlValue = toml::from_str(providers)?;
|
||||
let credentials = &mut expected["features"]["network_proxy"]["credentials"];
|
||||
credentials["a"]["env"] = TomlValue::try_from(["B_AUTH"])?;
|
||||
credentials["b"]["env"] = TomlValue::try_from(["A_AUTH"])?;
|
||||
let expected_policy: TomlValue =
|
||||
toml::from_str("[set]\nB_ENDPOINT = 'https://b.example'\nTOOL_MODE = 'project'\n")?;
|
||||
for effective in [canonical.effective_config(), local_effective] {
|
||||
assert_eq!(
|
||||
&effective["features"]["network_proxy"]["credentials"],
|
||||
&*credentials
|
||||
);
|
||||
assert_eq!(effective["shell_environment_policy"], expected_policy);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[tokio::test]
|
||||
async fn managed_project_discovery_mdm_overrides_file_markers() -> anyhow::Result<()> {
|
||||
use base64::Engine;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
|
||||
let mut fixture = Fixture::new()?;
|
||||
std::fs::write(&fixture.managed, "project_root_markers = [\".git\"]\n")?;
|
||||
for (markers, dirs) in [
|
||||
(vec![], vec![&fixture.cwd]),
|
||||
(vec![".company-root"], vec![&fixture.project, &fixture.cwd]),
|
||||
] {
|
||||
let markers_toml = TomlValue::try_from(&markers)?;
|
||||
fixture.overrides.managed_preferences_base64 =
|
||||
Some(BASE64_STANDARD.encode(format!("project_root_markers = {markers_toml}\n")));
|
||||
let (canonical, local) = fixture.load().await?;
|
||||
assert_discovery(&canonical, &local, &dirs, &markers)?;
|
||||
assert_eq!(
|
||||
(
|
||||
canonical
|
||||
.layers_high_to_low()
|
||||
.next()
|
||||
.map(|layer| &layer.name),
|
||||
local.config.layers.last().map(|layer| &layer.source),
|
||||
),
|
||||
(
|
||||
Some(&ConfigLayerSource::LegacyManagedConfigTomlFromMdm),
|
||||
Some(&ConfigLayerSource::LegacyManagedConfigTomlFromMdm),
|
||||
)
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
126
codex-rs/config/src/loader/managed_requirements.rs
Normal file
126
codex-rs/config/src/loader/managed_requirements.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Loads managed requirements independently of user and project configuration,
|
||||
//! retaining source layers for diagnostics during full configuration loads.
|
||||
|
||||
use super::layer_io;
|
||||
use super::layer_io::LoadedConfigLayers;
|
||||
use super::load_requirements_toml;
|
||||
#[cfg(target_os = "macos")]
|
||||
use super::macos;
|
||||
use super::requirements_layers_from_legacy_scheme;
|
||||
use super::system_requirements_toml_file_with_overrides;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements;
|
||||
use crate::config_requirements::ConfigRequirementsWithSources;
|
||||
use crate::state::ConfigLoadOptions;
|
||||
use crate::state::LoaderOverrides;
|
||||
use codex_file_system::ExecutorFileSystem;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
|
||||
/// Loads current managed requirements without reading system defaults, user or
|
||||
/// project settings, or thread-provided configuration. Legacy managed config
|
||||
/// remains a requirements source.
|
||||
pub async fn load_managed_requirements_state(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
codex_home: &Path,
|
||||
options: impl Into<ConfigLoadOptions>,
|
||||
) -> io::Result<ConfigRequirementsToml> {
|
||||
let ConfigLoadOptions {
|
||||
loader_overrides: overrides,
|
||||
strict_config,
|
||||
cloud_config_bundle,
|
||||
} = options.into();
|
||||
if overrides.ignore_managed_requirements {
|
||||
return Ok(ConfigRequirementsToml::default());
|
||||
}
|
||||
|
||||
let mut bundle_requirements = Vec::new();
|
||||
if let Some(bundle) = cloud_config_bundle.get().await.map_err(io::Error::other)? {
|
||||
let base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
|
||||
bundle_requirements = bundle
|
||||
.requirements_toml
|
||||
.into_layers()
|
||||
.into_iter()
|
||||
.map(|layer| layer.with_base_dir(base_dir.clone()))
|
||||
.collect();
|
||||
}
|
||||
let (requirements, _, _) = load_requirements_from_sources(
|
||||
fs,
|
||||
codex_home,
|
||||
&overrides,
|
||||
strict_config,
|
||||
bundle_requirements,
|
||||
)
|
||||
.await?;
|
||||
let _: ConfigRequirements = requirements.clone().try_into()?;
|
||||
let requirements_toml = requirements.into_toml();
|
||||
// Full config loads also validate required provider definitions when
|
||||
// constructing ConfigLayerStack, including providers not in use by this thread.
|
||||
let _ = crate::model_provider_requirements::to_config(&requirements_toml)?;
|
||||
Ok(requirements_toml)
|
||||
}
|
||||
|
||||
/// Composes the same requirements for full config loads and policy-only checks.
|
||||
/// The loaded legacy config and source layers are also returned for the full
|
||||
/// config stack and its ignored-field diagnostics.
|
||||
pub(super) async fn load_requirements_from_sources(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
codex_home: &Path,
|
||||
overrides: &LoaderOverrides,
|
||||
strict_config: bool,
|
||||
bundle_requirements: Vec<RequirementsLayerEntry>,
|
||||
) -> io::Result<(
|
||||
ConfigRequirementsWithSources,
|
||||
LoadedConfigLayers,
|
||||
Vec<RequirementsLayerEntry>,
|
||||
)> {
|
||||
let mut requirements_layers = Vec::new();
|
||||
let mut system_requirements_layer = None;
|
||||
let managed_preferences_requirements_layer;
|
||||
if !overrides.ignore_managed_requirements {
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
|
||||
managed_preferences_requirements_layer = macos::load_managed_admin_requirements_layer(
|
||||
overrides
|
||||
.macos_managed_config_requirements_base64
|
||||
.as_deref(),
|
||||
)
|
||||
.await?
|
||||
.map(|layer| layer.with_base_dir(base_dir));
|
||||
}
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
{
|
||||
managed_preferences_requirements_layer = None;
|
||||
}
|
||||
|
||||
let requirements_file = system_requirements_toml_file_with_overrides(overrides)?;
|
||||
system_requirements_layer = load_requirements_toml(fs, &requirements_file).await?;
|
||||
} else {
|
||||
managed_preferences_requirements_layer = None;
|
||||
}
|
||||
|
||||
let loaded_config_layers =
|
||||
layer_io::load_config_layers_internal(fs, codex_home, overrides.clone(), strict_config)
|
||||
.await?;
|
||||
if !overrides.ignore_managed_requirements {
|
||||
requirements_layers.extend(system_requirements_layer);
|
||||
requirements_layers.extend(bundle_requirements);
|
||||
// Legacy managed_config.toml contributes approval and sandbox requirements.
|
||||
requirements_layers.extend(requirements_layers_from_legacy_scheme(
|
||||
loaded_config_layers.clone(),
|
||||
codex_home,
|
||||
)?);
|
||||
requirements_layers.extend(managed_preferences_requirements_layer);
|
||||
}
|
||||
|
||||
let mut requirements = compose_requirements(requirements_layers.clone())?.unwrap_or_default();
|
||||
if overrides.ignore_login_requirements {
|
||||
requirements.allowed_login_methods = None;
|
||||
requirements.allowed_chatgpt_workspaces = None;
|
||||
}
|
||||
Ok((requirements, loaded_config_layers, requirements_layers))
|
||||
}
|
||||
2215
codex-rs/config/src/loader/mod.rs
Normal file
2215
codex-rs/config/src/loader/mod.rs
Normal file
File diff suppressed because it is too large
Load Diff
42
codex-rs/config/src/loader/project_discovery.rs
Normal file
42
codex-rs/config/src/loader/project_discovery.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
//! Shared configuration composition for project-root and trust discovery.
|
||||
|
||||
use super::layer_io::LoadedConfigLayers;
|
||||
use super::resolve_relative_paths_in_config_toml;
|
||||
use crate::merge_toml_values;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
/// Overlay the already-read managed sources at their normal precedence: file,
|
||||
/// then MDM. Resolve paths as the final loader does, without changing the raw
|
||||
/// layers or reading either source again.
|
||||
pub(super) fn merge_managed_config_for_discovery(
|
||||
discovery_config: &mut TomlValue,
|
||||
loaded: &LoadedConfigLayers,
|
||||
codex_home: &Path,
|
||||
) -> io::Result<()> {
|
||||
if let Some(config) = &loaded.managed_config {
|
||||
let base_dir = config.file.as_path().parent().ok_or_else(|| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"Managed config file {} has no parent directory",
|
||||
config.file.as_path().display()
|
||||
),
|
||||
)
|
||||
})?;
|
||||
let resolved =
|
||||
resolve_relative_paths_in_config_toml(config.managed_config.clone(), base_dir)?;
|
||||
merge_toml_values(discovery_config, &resolved);
|
||||
}
|
||||
if let Some(config) = &loaded.managed_config_from_mdm {
|
||||
let resolved =
|
||||
resolve_relative_paths_in_config_toml(config.managed_config.clone(), codex_home)?;
|
||||
merge_toml_values(discovery_config, &resolved);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "managed_project_discovery_tests.rs"]
|
||||
mod tests;
|
||||
175
codex-rs/config/src/loader/projectless_directory_tests.rs
Normal file
175
codex-rs/config/src/loader/projectless_directory_tests.rs
Normal file
@@ -0,0 +1,175 @@
|
||||
//! Projectless classification requires completed discovery without project inputs.
|
||||
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::LoaderOverrides;
|
||||
use crate::NoopThreadConfigLoader;
|
||||
use crate::loader::find_project_root;
|
||||
use crate::loader::load_config_layers_state;
|
||||
use crate::loader::project_trust_key;
|
||||
use crate::loader::tests::TestFileSystem;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
struct Fixture {
|
||||
_temp: TempDir,
|
||||
home: AbsolutePathBuf,
|
||||
cwd: AbsolutePathBuf,
|
||||
overrides: LoaderOverrides,
|
||||
}
|
||||
|
||||
impl Fixture {
|
||||
fn new() -> anyhow::Result<Self> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = AbsolutePathBuf::from_absolute_path(temp.path().canonicalize()?)?;
|
||||
let home = root.join("home");
|
||||
let cwd = root.join("workspace");
|
||||
std::fs::create_dir_all(&home)?;
|
||||
std::fs::create_dir_all(&cwd)?;
|
||||
Ok(Self {
|
||||
_temp: temp,
|
||||
home,
|
||||
cwd,
|
||||
overrides: LoaderOverrides::without_managed_config_for_tests(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn load(&self) -> anyhow::Result<ConfigLayerStack> {
|
||||
Ok(load_config_layers_state(
|
||||
&TestFileSystem,
|
||||
self.home.as_path(),
|
||||
Some(self.cwd.clone()),
|
||||
&[],
|
||||
self.overrides.clone(),
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await?)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_root_lookup_preserves_cwd_fallback() -> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
let markers = vec![".company-root".to_string()];
|
||||
for markers in [&[][..], markers.as_slice()] {
|
||||
assert_eq!(
|
||||
find_project_root(&TestFileSystem, &fixture.cwd, markers).await?,
|
||||
fixture.cwd,
|
||||
);
|
||||
}
|
||||
|
||||
std::fs::create_dir(fixture.cwd.join(".company-root"))?;
|
||||
let nested = fixture.cwd.join("nested");
|
||||
std::fs::create_dir(&nested)?;
|
||||
assert_eq!(
|
||||
find_project_root(&TestFileSystem, &nested, &markers).await?,
|
||||
fixture.cwd,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unmarked_directory_is_projectless_even_with_saved_trust() -> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
assert!(fixture.load().await?.is_projectless());
|
||||
let key = TomlValue::String(project_trust_key(fixture.cwd.as_path()));
|
||||
for level in ["trusted", "untrusted"] {
|
||||
std::fs::write(
|
||||
fixture.home.join("config.toml"),
|
||||
format!("[projects.{key}]\ntrust_level = \"{level}\"\n"),
|
||||
)?;
|
||||
assert!(fixture.load().await?.is_projectless(), "{level}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn skipped_discovery_does_not_claim_projectless() -> anyhow::Result<()> {
|
||||
let fixture = Fixture::new()?;
|
||||
for (cwd, ignore_project_config) in [(None, false), (Some(fixture.cwd.clone()), true)] {
|
||||
let layers = load_config_layers_state(
|
||||
&TestFileSystem,
|
||||
fixture.home.as_path(),
|
||||
cwd,
|
||||
&[],
|
||||
LoaderOverrides {
|
||||
ignore_project_config,
|
||||
..fixture.overrides.clone()
|
||||
},
|
||||
&NoopThreadConfigLoader,
|
||||
)
|
||||
.await?;
|
||||
assert!(!layers.is_projectless());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn project_markers_and_local_layers_prevent_projectless_classification() -> anyhow::Result<()>
|
||||
{
|
||||
for (marker, config, child) in [
|
||||
(".git", "", ""),
|
||||
(".git", "", "nested"),
|
||||
(".git", "project_root_markers = []", "nested"),
|
||||
(".codex", "", ""),
|
||||
(".codex", "project_root_markers = ['.codex']", "nested"),
|
||||
(
|
||||
".company-root",
|
||||
"project_root_markers = ['.company-root']",
|
||||
"",
|
||||
),
|
||||
(
|
||||
".company-root",
|
||||
"project_root_markers = ['.company-root']",
|
||||
"nested",
|
||||
),
|
||||
] {
|
||||
let mut fixture = Fixture::new()?;
|
||||
std::fs::create_dir(fixture.cwd.join(marker))?;
|
||||
if marker == ".git" {
|
||||
std::fs::write(fixture.cwd.join(".git/HEAD"), "ref: refs/heads/main\n")?;
|
||||
}
|
||||
std::fs::write(fixture.home.join("config.toml"), config)?;
|
||||
fixture.cwd = fixture.cwd.join(child);
|
||||
std::fs::create_dir_all(&fixture.cwd)?;
|
||||
assert!(
|
||||
!fixture.load().await?.is_projectless(),
|
||||
"marker={marker}, config={config}, child={child}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn user_codex_home_is_not_a_project_layer() -> anyhow::Result<()> {
|
||||
let mut fixture = Fixture::new()?;
|
||||
fixture.home = fixture.cwd.join(".codex");
|
||||
std::fs::create_dir(&fixture.home)?;
|
||||
std::fs::write(fixture.home.join("config.toml"), "model = 'user-model'\n")?;
|
||||
assert!(fixture.load().await?.is_projectless());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn managed_root_markers_control_projectless_classification() -> anyhow::Result<()> {
|
||||
let mut fixture = Fixture::new()?;
|
||||
std::fs::create_dir(fixture.cwd.join(".company-root"))?;
|
||||
fixture.cwd = fixture.cwd.join("nested");
|
||||
std::fs::create_dir(&fixture.cwd)?;
|
||||
std::fs::write(
|
||||
fixture.home.join("config.toml"),
|
||||
"project_root_markers = []",
|
||||
)?;
|
||||
let managed = fixture.home.join("managed_config.toml");
|
||||
fixture.overrides = LoaderOverrides::with_managed_config_path_for_tests(managed.to_path_buf());
|
||||
for (markers, expected) in [("['.company-root']", false), ("[]", true)] {
|
||||
std::fs::write(&managed, format!("project_root_markers = {markers}\n"))?;
|
||||
assert_eq!(
|
||||
fixture.load().await?.is_projectless(),
|
||||
expected,
|
||||
"{markers}"
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
1275
codex-rs/config/src/loader/tests.rs
Normal file
1275
codex-rs/config/src/loader/tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
68
codex-rs/config/src/loader/windows.rs
Normal file
68
codex-rs/config/src/loader/windows.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use super::windows_codex_system_dir;
|
||||
use std::path::Path;
|
||||
|
||||
/// Coarse compatibility result for the default Windows system-config namespace.
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum WindowsSystemConfigNamespaceProbe {
|
||||
Missing,
|
||||
Expected,
|
||||
UnexpectedType,
|
||||
UnexpectedOwner,
|
||||
StandardUserMutationAcl,
|
||||
CheckError,
|
||||
}
|
||||
|
||||
/// Observes the common user-preclaimed-directory shape without changing config loading.
|
||||
/// This is not a trust decision: it only checks directory owner and broad
|
||||
/// standard-user mutation ACLs.
|
||||
pub fn probe_windows_system_config_namespace() -> WindowsSystemConfigNamespaceProbe {
|
||||
let codex_dir = windows_codex_system_dir();
|
||||
let has_system_file = match (
|
||||
codex_dir.join("config.toml").try_exists(),
|
||||
codex_dir.join("requirements.toml").try_exists(),
|
||||
) {
|
||||
(Ok(true), _) | (_, Ok(true)) => true,
|
||||
(Ok(false), Ok(false)) => false,
|
||||
_ => return WindowsSystemConfigNamespaceProbe::CheckError,
|
||||
};
|
||||
if !has_system_file {
|
||||
return WindowsSystemConfigNamespaceProbe::Missing;
|
||||
}
|
||||
let Some(openai_dir) = codex_dir.parent() else {
|
||||
return WindowsSystemConfigNamespaceProbe::CheckError;
|
||||
};
|
||||
let result = probe_directory(
|
||||
openai_dir,
|
||||
codex_windows_sandbox::path_has_standard_user_mutation_allow,
|
||||
);
|
||||
if !matches!(result, WindowsSystemConfigNamespaceProbe::Expected) {
|
||||
return result;
|
||||
}
|
||||
let result = probe_directory(
|
||||
codex_dir.as_path(),
|
||||
codex_windows_sandbox::path_or_child_file_has_standard_user_mutation_allow,
|
||||
);
|
||||
if !matches!(result, WindowsSystemConfigNamespaceProbe::Expected) {
|
||||
return result;
|
||||
}
|
||||
WindowsSystemConfigNamespaceProbe::Expected
|
||||
}
|
||||
|
||||
fn probe_directory(
|
||||
path: &Path,
|
||||
mutation_allow: fn(&Path) -> anyhow::Result<bool>,
|
||||
) -> WindowsSystemConfigNamespaceProbe {
|
||||
if !path.is_dir() {
|
||||
return WindowsSystemConfigNamespaceProbe::UnexpectedType;
|
||||
}
|
||||
match codex_windows_sandbox::path_has_trusted_system_owner(path) {
|
||||
Ok(true) => {}
|
||||
Ok(false) => return WindowsSystemConfigNamespaceProbe::UnexpectedOwner,
|
||||
Err(_) => return WindowsSystemConfigNamespaceProbe::CheckError,
|
||||
}
|
||||
match mutation_allow(path) {
|
||||
Ok(false) => WindowsSystemConfigNamespaceProbe::Expected,
|
||||
Ok(true) => WindowsSystemConfigNamespaceProbe::StandardUserMutationAcl,
|
||||
Err(_) => WindowsSystemConfigNamespaceProbe::CheckError,
|
||||
}
|
||||
}
|
||||
301
codex-rs/config/src/marketplace_edit.rs
Normal file
301
codex-rs/config/src/marketplace_edit.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
|
||||
use toml_edit::DocumentMut;
|
||||
use toml_edit::Item as TomlItem;
|
||||
use toml_edit::Table as TomlTable;
|
||||
use toml_edit::Value as TomlValue;
|
||||
use toml_edit::value;
|
||||
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
|
||||
pub struct MarketplaceConfigUpdate<'a> {
|
||||
pub source_type: &'a str,
|
||||
pub source: &'a str,
|
||||
pub ref_name: Option<&'a str>,
|
||||
pub sparse_paths: &'a [String],
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum RemoveMarketplaceConfigOutcome {
|
||||
Removed,
|
||||
NotFound,
|
||||
NameCaseMismatch { configured_name: String },
|
||||
}
|
||||
|
||||
pub fn record_user_marketplace(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
update: &MarketplaceConfigUpdate<'_>,
|
||||
) -> std::io::Result<()> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let mut doc = read_or_create_document(&config_path)?;
|
||||
upsert_marketplace(&mut doc, marketplace_name, update);
|
||||
fs::create_dir_all(codex_home)?;
|
||||
fs::write(config_path, doc.to_string())
|
||||
}
|
||||
|
||||
pub fn remove_user_marketplace(codex_home: &Path, marketplace_name: &str) -> std::io::Result<bool> {
|
||||
let outcome = remove_user_marketplace_config(codex_home, marketplace_name)?;
|
||||
Ok(outcome == RemoveMarketplaceConfigOutcome::Removed)
|
||||
}
|
||||
|
||||
pub fn remove_user_marketplace_config(
|
||||
codex_home: &Path,
|
||||
marketplace_name: &str,
|
||||
) -> std::io::Result<RemoveMarketplaceConfigOutcome> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let mut doc = match fs::read_to_string(&config_path) {
|
||||
Ok(raw) => raw
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|err| std::io::Error::new(ErrorKind::InvalidData, err))?,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => {
|
||||
return Ok(RemoveMarketplaceConfigOutcome::NotFound);
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
let outcome = remove_marketplace(&mut doc, marketplace_name);
|
||||
if outcome != RemoveMarketplaceConfigOutcome::Removed {
|
||||
return Ok(outcome);
|
||||
}
|
||||
|
||||
fs::create_dir_all(codex_home)?;
|
||||
fs::write(config_path, doc.to_string())?;
|
||||
Ok(RemoveMarketplaceConfigOutcome::Removed)
|
||||
}
|
||||
|
||||
fn read_or_create_document(config_path: &Path) -> std::io::Result<DocumentMut> {
|
||||
match fs::read_to_string(config_path) {
|
||||
Ok(raw) => raw
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|err| std::io::Error::new(ErrorKind::InvalidData, err)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(DocumentMut::new()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn upsert_marketplace(
|
||||
doc: &mut DocumentMut,
|
||||
marketplace_name: &str,
|
||||
update: &MarketplaceConfigUpdate<'_>,
|
||||
) {
|
||||
let root = doc.as_table_mut();
|
||||
if !root.contains_key("marketplaces") {
|
||||
root.insert("marketplaces", TomlItem::Table(new_implicit_table()));
|
||||
}
|
||||
|
||||
let Some(marketplaces_item) = root.get_mut("marketplaces") else {
|
||||
return;
|
||||
};
|
||||
if !marketplaces_item.is_table() {
|
||||
*marketplaces_item = TomlItem::Table(new_implicit_table());
|
||||
}
|
||||
|
||||
let Some(marketplaces) = marketplaces_item.as_table_mut() else {
|
||||
return;
|
||||
};
|
||||
let mut entry = TomlTable::new();
|
||||
entry.set_implicit(false);
|
||||
entry["source_type"] = value(update.source_type.to_string());
|
||||
entry["source"] = value(update.source.to_string());
|
||||
if let Some(ref_name) = update.ref_name {
|
||||
entry["ref"] = value(ref_name.to_string());
|
||||
}
|
||||
if !update.sparse_paths.is_empty() {
|
||||
entry["sparse_paths"] = TomlItem::Value(TomlValue::Array(
|
||||
update.sparse_paths.iter().map(String::as_str).collect(),
|
||||
));
|
||||
}
|
||||
marketplaces.insert(marketplace_name, TomlItem::Table(entry));
|
||||
}
|
||||
|
||||
fn remove_marketplace(
|
||||
doc: &mut DocumentMut,
|
||||
marketplace_name: &str,
|
||||
) -> RemoveMarketplaceConfigOutcome {
|
||||
let root = doc.as_table_mut();
|
||||
let Some(marketplaces_item) = root.get_mut("marketplaces") else {
|
||||
return RemoveMarketplaceConfigOutcome::NotFound;
|
||||
};
|
||||
|
||||
let mut remove_marketplaces = false;
|
||||
let outcome = match marketplaces_item {
|
||||
TomlItem::Table(marketplaces) => {
|
||||
let outcome = if marketplaces.remove(marketplace_name).is_some() {
|
||||
RemoveMarketplaceConfigOutcome::Removed
|
||||
} else if let Some(configured_name) =
|
||||
case_mismatched_key(marketplaces.iter().map(|(key, _)| key), marketplace_name)
|
||||
{
|
||||
RemoveMarketplaceConfigOutcome::NameCaseMismatch { configured_name }
|
||||
} else {
|
||||
RemoveMarketplaceConfigOutcome::NotFound
|
||||
};
|
||||
remove_marketplaces = marketplaces.is_empty();
|
||||
outcome
|
||||
}
|
||||
TomlItem::Value(value) => {
|
||||
let Some(marketplaces) = value.as_inline_table_mut() else {
|
||||
return RemoveMarketplaceConfigOutcome::NotFound;
|
||||
};
|
||||
let outcome = if marketplaces.remove(marketplace_name).is_some() {
|
||||
RemoveMarketplaceConfigOutcome::Removed
|
||||
} else if let Some(configured_name) =
|
||||
case_mismatched_key(marketplaces.iter().map(|(key, _)| key), marketplace_name)
|
||||
{
|
||||
RemoveMarketplaceConfigOutcome::NameCaseMismatch { configured_name }
|
||||
} else {
|
||||
RemoveMarketplaceConfigOutcome::NotFound
|
||||
};
|
||||
remove_marketplaces = marketplaces.is_empty();
|
||||
outcome
|
||||
}
|
||||
_ => RemoveMarketplaceConfigOutcome::NotFound,
|
||||
};
|
||||
|
||||
if outcome == RemoveMarketplaceConfigOutcome::Removed && remove_marketplaces {
|
||||
root.remove("marketplaces");
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
fn case_mismatched_key<'a>(
|
||||
mut keys: impl Iterator<Item = &'a str>,
|
||||
requested_name: &str,
|
||||
) -> Option<String> {
|
||||
keys.find(|key| *key != requested_name && key.eq_ignore_ascii_case(requested_name))
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
fn new_implicit_table() -> TomlTable {
|
||||
let mut table = TomlTable::new();
|
||||
table.set_implicit(true);
|
||||
table
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[test]
|
||||
fn record_user_marketplace_omits_runtime_update_metadata() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let update = MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
};
|
||||
|
||||
record_user_marketplace(codex_home.path(), "debug", &update).unwrap();
|
||||
|
||||
let config: toml::Value =
|
||||
toml::from_str(&fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).unwrap())
|
||||
.unwrap();
|
||||
let marketplace = config
|
||||
.get("marketplaces")
|
||||
.and_then(|marketplaces| marketplaces.get("debug"))
|
||||
.expect("marketplace declaration");
|
||||
assert_eq!(
|
||||
marketplace.get("source_type").and_then(toml::Value::as_str),
|
||||
Some("git")
|
||||
);
|
||||
assert_eq!(
|
||||
marketplace.get("source").and_then(toml::Value::as_str),
|
||||
Some("https://github.com/owner/repo.git")
|
||||
);
|
||||
assert_eq!(
|
||||
marketplace.get("ref").and_then(toml::Value::as_str),
|
||||
Some("main")
|
||||
);
|
||||
assert!(marketplace.get("last_updated").is_none());
|
||||
assert!(marketplace.get("last_revision").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_user_marketplace_removes_requested_entry() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let update = MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
};
|
||||
record_user_marketplace(codex_home.path(), "debug", &update).unwrap();
|
||||
record_user_marketplace(codex_home.path(), "other", &update).unwrap();
|
||||
|
||||
let removed = remove_user_marketplace(codex_home.path(), "debug").unwrap();
|
||||
|
||||
assert!(removed);
|
||||
let config: toml::Value =
|
||||
toml::from_str(&fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).unwrap())
|
||||
.unwrap();
|
||||
let marketplaces = config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.unwrap();
|
||||
assert_eq!(marketplaces.len(), 1);
|
||||
assert!(marketplaces.contains_key("other"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_user_marketplace_returns_false_when_missing() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
|
||||
let removed = remove_user_marketplace(codex_home.path(), "debug").unwrap();
|
||||
|
||||
assert!(!removed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_user_marketplace_config_reports_case_mismatch() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let update = MarketplaceConfigUpdate {
|
||||
source_type: "git",
|
||||
source: "https://github.com/owner/repo.git",
|
||||
ref_name: Some("main"),
|
||||
sparse_paths: &[],
|
||||
};
|
||||
record_user_marketplace(codex_home.path(), "debug", &update).unwrap();
|
||||
|
||||
let outcome = remove_user_marketplace_config(codex_home.path(), "Debug").unwrap();
|
||||
|
||||
assert_eq!(
|
||||
outcome,
|
||||
RemoveMarketplaceConfigOutcome::NameCaseMismatch {
|
||||
configured_name: "debug".to_string()
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_user_marketplace_config_removes_inline_table_entry() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"
|
||||
marketplaces = {
|
||||
debug = { source_type = "git", source = "https://github.com/owner/repo.git" },
|
||||
other = { source_type = "local", source = "/tmp/marketplace" },
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let outcome = remove_user_marketplace_config(codex_home.path(), "debug").unwrap();
|
||||
|
||||
assert_eq!(outcome, RemoveMarketplaceConfigOutcome::Removed);
|
||||
let config: toml::Value =
|
||||
toml::from_str(&fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).unwrap())
|
||||
.unwrap();
|
||||
let marketplaces = config
|
||||
.get("marketplaces")
|
||||
.and_then(toml::Value::as_table)
|
||||
.unwrap();
|
||||
assert_eq!(marketplaces.len(), 1);
|
||||
assert!(marketplaces.contains_key("other"));
|
||||
}
|
||||
}
|
||||
50
codex-rs/config/src/mcp_edit.rs
Normal file
50
codex-rs/config/src/mcp_edit.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::McpServerConfig;
|
||||
|
||||
pub async fn load_global_mcp_servers(
|
||||
codex_home: &Path,
|
||||
) -> std::io::Result<BTreeMap<String, McpServerConfig>> {
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let raw = match tokio::fs::read_to_string(&config_path).await {
|
||||
Ok(raw) => raw,
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
let parsed = toml::from_str::<TomlValue>(&raw)
|
||||
.map_err(|err| std::io::Error::new(ErrorKind::InvalidData, err))?;
|
||||
let Some(servers_value) = parsed.get("mcp_servers") else {
|
||||
return Ok(BTreeMap::new());
|
||||
};
|
||||
|
||||
ensure_no_inline_bearer_tokens(servers_value)?;
|
||||
|
||||
servers_value
|
||||
.clone()
|
||||
.try_into()
|
||||
.map_err(|err| std::io::Error::new(ErrorKind::InvalidData, err))
|
||||
}
|
||||
|
||||
fn ensure_no_inline_bearer_tokens(value: &TomlValue) -> std::io::Result<()> {
|
||||
let Some(servers_table) = value.as_table() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for (server_name, server_value) in servers_table {
|
||||
if let Some(server_table) = server_value.as_table()
|
||||
&& server_table.contains_key("bearer_token")
|
||||
{
|
||||
let message = format!(
|
||||
"mcp_servers.{server_name} uses unsupported `bearer_token`; set `bearer_token_env_var`."
|
||||
);
|
||||
return Err(std::io::Error::new(ErrorKind::InvalidData, message));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
424
codex-rs/config/src/mcp_ema.rs
Normal file
424
codex-rs/config/src/mcp_ema.rs
Normal file
@@ -0,0 +1,424 @@
|
||||
//! Enterprise MCP configuration and account-scoped credential names.
|
||||
//!
|
||||
//! Only host, user, or managed configuration selects the IdP. Plugin declarations
|
||||
//! and project settings may not redirect the enterprise credential source.
|
||||
|
||||
use std::io;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use sha2::Digest;
|
||||
use sha2::Sha256;
|
||||
|
||||
use codex_features::Feature;
|
||||
use codex_utils_redacted_string::RedactedString;
|
||||
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::McpServerConfig;
|
||||
use crate::McpServerTransportConfig;
|
||||
|
||||
/// Token endpoint authentication selected by a confidential EMA client registration.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpEmaTokenEndpointAuthMethod {
|
||||
#[default]
|
||||
ClientSecretBasic,
|
||||
ClientSecretPost,
|
||||
}
|
||||
|
||||
impl McpEmaTokenEndpointAuthMethod {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::ClientSecretBasic => "client_secret_basic",
|
||||
Self::ClientSecretPost => "client_secret_post",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct McpServerIdpOAuthConfig {
|
||||
/// Issuer used for enterprise OAuth discovery and identity validation.
|
||||
pub issuer: String,
|
||||
/// OAuth client registered with that enterprise IdP.
|
||||
pub client_id: String,
|
||||
/// Provisioned client secret for confidential IdP login and token exchange.
|
||||
/// Omitted for a public client.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub client_secret: Option<RedactedString>,
|
||||
/// Registered EMA client authentication method. Defaults to client_secret_basic
|
||||
/// when a secret is configured; requires a client secret.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct McpEnterpriseManagedAuthConfig {
|
||||
/// Shared enterprise authorization, independent of Codex account credentials.
|
||||
pub idp: McpServerIdpOAuthConfig,
|
||||
}
|
||||
|
||||
/// Immutable authorization selected after trusted policy and catalog resolution.
|
||||
/// This cannot be deserialized from a server or plugin declaration.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct McpEmaRegistration {
|
||||
idp: McpServerIdpOAuthConfig,
|
||||
server_url: String,
|
||||
resource: Option<String>,
|
||||
client_id: Option<String>,
|
||||
client_secret: Option<RedactedString>,
|
||||
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
|
||||
authorization_server_issuer: Option<String>,
|
||||
scopes: Vec<String>,
|
||||
}
|
||||
|
||||
impl McpEmaRegistration {
|
||||
pub fn idp(&self) -> &McpServerIdpOAuthConfig {
|
||||
&self.idp
|
||||
}
|
||||
|
||||
pub fn server_url(&self) -> &str {
|
||||
&self.server_url
|
||||
}
|
||||
|
||||
pub fn resource(&self) -> Option<&str> {
|
||||
self.resource.as_deref()
|
||||
}
|
||||
|
||||
pub fn client_id(&self) -> Option<&str> {
|
||||
self.client_id.as_deref()
|
||||
}
|
||||
|
||||
pub fn client_secret(&self) -> Option<&str> {
|
||||
self.client_secret.as_ref().map(|secret| secret.as_str())
|
||||
}
|
||||
|
||||
pub fn token_endpoint_auth_method(&self) -> Option<McpEmaTokenEndpointAuthMethod> {
|
||||
self.token_endpoint_auth_method
|
||||
}
|
||||
|
||||
pub fn authorization_server_issuer(&self) -> Option<&str> {
|
||||
self.authorization_server_issuer.as_deref()
|
||||
}
|
||||
|
||||
pub fn scopes(&self) -> &[String] {
|
||||
&self.scopes
|
||||
}
|
||||
}
|
||||
|
||||
/// Account identity that owns an enterprise OAuth credential.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct McpEmaAuthScope {
|
||||
user_id: String,
|
||||
workspace_id: String,
|
||||
}
|
||||
|
||||
impl McpEmaAuthScope {
|
||||
pub fn new(user_id: String, workspace_id: String) -> Option<Self> {
|
||||
(!user_id.trim().is_empty() && !workspace_id.trim().is_empty()).then_some(Self {
|
||||
user_id,
|
||||
workspace_id,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl McpServerIdpOAuthConfig {
|
||||
/// Shared by allowed MCP resources, but never by another account or IdP client.
|
||||
pub fn credential_name(&self, scope: &McpEmaAuthScope) -> String {
|
||||
let mut digest = Sha256::new();
|
||||
digest.update(b"codex-ema-idp-credential-v1\0");
|
||||
for part in [
|
||||
&scope.user_id,
|
||||
&scope.workspace_id,
|
||||
&self.issuer,
|
||||
&self.client_id,
|
||||
] {
|
||||
digest.update((part.len() as u64).to_be_bytes());
|
||||
digest.update(part.as_bytes());
|
||||
}
|
||||
format!("ema-idp:{}", URL_SAFE_NO_PAD.encode(digest.finalize()))
|
||||
}
|
||||
}
|
||||
|
||||
impl McpEnterpriseManagedAuthConfig {
|
||||
/// Resolves the trusted profile and checks provenance at a config load boundary.
|
||||
pub fn resolve(
|
||||
stack: &ConfigLayerStack,
|
||||
fallback: Option<&Self>,
|
||||
servers: &std::collections::HashMap<String, McpServerConfig>,
|
||||
xaa_enabled: bool,
|
||||
) -> io::Result<Option<Self>> {
|
||||
validate_ema_auth_sources(stack, servers)?;
|
||||
validate_xaa_opt_in_source(stack, xaa_enabled)?;
|
||||
let profile = Self::from_config_layers(stack, fallback)?;
|
||||
if let Some(profile) = &profile {
|
||||
if profile
|
||||
.idp
|
||||
.client_secret
|
||||
.as_ref()
|
||||
.is_some_and(|secret| secret.trim().is_empty())
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"enterprise IdP client_secret must not be empty",
|
||||
));
|
||||
}
|
||||
if profile.idp.token_endpoint_auth_method.is_some()
|
||||
&& profile.idp.client_secret.is_none()
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"enterprise IdP token_endpoint_auth_method requires client_secret",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
/// Selects one complete trusted registration rather than merging issuer/client pairs.
|
||||
fn from_config_layers(
|
||||
stack: &ConfigLayerStack,
|
||||
fallback: Option<&Self>,
|
||||
) -> io::Result<Option<Self>> {
|
||||
if stack.layers_high_to_low().next().is_none() {
|
||||
return Ok(fallback.cloned());
|
||||
}
|
||||
let sections = || {
|
||||
stack.layers_high_to_low().filter_map(|layer| {
|
||||
layer
|
||||
.config
|
||||
.get("mcp_enterprise_managed_auth")
|
||||
.map(|section| (&layer.name, section))
|
||||
})
|
||||
};
|
||||
let selected = sections()
|
||||
.find(|(source, _)| {
|
||||
matches!(
|
||||
source,
|
||||
ConfigLayerSource::Mdm { .. }
|
||||
| ConfigLayerSource::System { .. }
|
||||
| ConfigLayerSource::EnterpriseManaged { .. }
|
||||
| ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. }
|
||||
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm
|
||||
)
|
||||
})
|
||||
.or_else(|| {
|
||||
sections().find(|(source, _)| !matches!(source, ConfigLayerSource::Project { .. }))
|
||||
});
|
||||
selected
|
||||
.map(|(_, section)| {
|
||||
section.clone().try_into().map_err(|error| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"enterprise IdP must be complete in one trusted config layer: {error}"
|
||||
),
|
||||
)
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
impl McpServerConfig {
|
||||
pub fn oauth_idp(&self) -> Option<&McpServerIdpOAuthConfig> {
|
||||
self.ema_registration().map(McpEmaRegistration::idp)
|
||||
}
|
||||
|
||||
pub fn ema_registration(&self) -> Option<&McpEmaRegistration> {
|
||||
self.oauth.as_ref()?.ema_registration.as_ref()
|
||||
}
|
||||
|
||||
/// Called once on a materialized catalog after configuration provenance is checked.
|
||||
pub fn resolve_ema_registration(
|
||||
&mut self,
|
||||
idp: &McpServerIdpOAuthConfig,
|
||||
) -> Result<(), &'static str> {
|
||||
if let Some(oauth) = &mut self.oauth {
|
||||
oauth.ema_registration = None;
|
||||
}
|
||||
if !matches!(self.auth, crate::McpServerAuth::EmaAuth) {
|
||||
return Err("enterprise registration requires ema_auth");
|
||||
}
|
||||
self.validate_ema_auth_transport()?;
|
||||
let McpServerTransportConfig::StreamableHttp { url, .. } = &self.transport else {
|
||||
unreachable!("EMA transport was validated");
|
||||
};
|
||||
let oauth = self.oauth.get_or_insert_default();
|
||||
oauth.ema_registration = Some(McpEmaRegistration {
|
||||
idp: idp.clone(),
|
||||
server_url: url.clone(),
|
||||
resource: self.oauth_resource.clone(),
|
||||
client_id: oauth.client_id.clone(),
|
||||
client_secret: oauth.client_secret.clone(),
|
||||
token_endpoint_auth_method: oauth.token_endpoint_auth_method,
|
||||
authorization_server_issuer: oauth.authorization_server_issuer.clone(),
|
||||
scopes: self.scopes.clone().unwrap_or_default(),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// EMA never falls back to an unrelated bearer or executor-owned credential.
|
||||
pub fn validate_ema_auth_transport(&self) -> Result<(), &'static str> {
|
||||
if !self.is_local_environment() {
|
||||
return Err("ema_auth requires a host-owned MCP connection");
|
||||
}
|
||||
if let Some(secret) = self.oauth_client_secret() {
|
||||
if secret.trim().is_empty() {
|
||||
return Err("ema_auth oauth.client_secret must not be empty");
|
||||
}
|
||||
if self.oauth.as_ref().is_none_or(|oauth| {
|
||||
oauth
|
||||
.authorization_server_issuer
|
||||
.as_ref()
|
||||
.is_none_or(|issuer| issuer.trim().is_empty())
|
||||
}) {
|
||||
return Err("confidential ema_auth requires oauth.authorization_server_issuer");
|
||||
}
|
||||
}
|
||||
let McpServerTransportConfig::StreamableHttp {
|
||||
bearer_token_env_var,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
http_headers_helper,
|
||||
..
|
||||
} = &self.transport
|
||||
else {
|
||||
return Err("ema_auth requires streamable HTTP");
|
||||
};
|
||||
if bearer_token_env_var.is_some()
|
||||
|| http_headers
|
||||
.as_ref()
|
||||
.is_some_and(|headers| !headers.is_empty())
|
||||
|| env_http_headers
|
||||
.as_ref()
|
||||
.is_some_and(|headers| !headers.is_empty())
|
||||
|| http_headers_helper.is_some()
|
||||
{
|
||||
return Err("ema_auth cannot be combined with alternate HTTP credentials");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn has_trusted_atomic_registration(
|
||||
stack: &ConfigLayerStack,
|
||||
non_project: &toml::Value,
|
||||
matches: impl Fn(&toml::Value) -> bool,
|
||||
) -> bool {
|
||||
matches(non_project)
|
||||
&& stack
|
||||
.layers_high_to_low()
|
||||
.filter(|layer| !matches!(layer.name, ConfigLayerSource::Project { .. }))
|
||||
.any(|layer| matches(&layer.config))
|
||||
}
|
||||
|
||||
fn reenabled_over_non_project_denial(
|
||||
effective_enabled: bool,
|
||||
non_project: Option<&toml::Value>,
|
||||
) -> bool {
|
||||
effective_enabled
|
||||
&& non_project
|
||||
.and_then(|server| server.get("enabled"))
|
||||
.and_then(toml::Value::as_bool)
|
||||
== Some(false)
|
||||
}
|
||||
|
||||
/// Projects cannot add, replace, or downgrade a non-project enterprise registration.
|
||||
fn validate_ema_auth_sources(
|
||||
stack: &ConfigLayerStack,
|
||||
servers: &std::collections::HashMap<String, McpServerConfig>,
|
||||
) -> io::Result<()> {
|
||||
if stack.layers_high_to_low().next().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut non_project = toml::Value::Table(Default::default());
|
||||
for layer in stack
|
||||
.layers_low_to_high()
|
||||
.filter(|layer| !matches!(layer.name, ConfigLayerSource::Project { .. }))
|
||||
{
|
||||
crate::merge_toml_values(&mut non_project, &layer.config);
|
||||
}
|
||||
|
||||
for (name, effective) in servers {
|
||||
let non_project_server = non_project
|
||||
.get("mcp_servers")
|
||||
.and_then(|servers| servers.get(name));
|
||||
let inherited_ema = non_project_server
|
||||
.and_then(|server| server.get("auth"))
|
||||
.and_then(toml::Value::as_str)
|
||||
== Some("ema_auth");
|
||||
if !matches!(effective.auth, crate::McpServerAuth::EmaAuth) && !inherited_ema {
|
||||
continue;
|
||||
}
|
||||
if reenabled_over_non_project_denial(effective.enabled, non_project_server) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!("project configuration cannot re-enable enterprise MCP server `{name}`"),
|
||||
));
|
||||
}
|
||||
let matches_effective_authorization = |server: &McpServerConfig| {
|
||||
matches!(server.auth, crate::McpServerAuth::EmaAuth)
|
||||
&& server.auth == effective.auth
|
||||
&& server.transport == effective.transport
|
||||
&& server.scopes == effective.scopes
|
||||
&& server.oauth == effective.oauth
|
||||
&& server.oauth_resource == effective.oauth_resource
|
||||
};
|
||||
if !has_trusted_atomic_registration(stack, &non_project, |config| {
|
||||
config
|
||||
.get("mcp_servers")
|
||||
.and_then(|servers| servers.get(name))
|
||||
.and_then(|server| server.clone().try_into::<McpServerConfig>().ok())
|
||||
.is_some_and(|server| matches_effective_authorization(&server))
|
||||
}) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
format!(
|
||||
"enterprise MCP server `{name}` must define its transport, authorization, scopes, and resource in one non-project config layer"
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Enabling XAA requires an explicit non-project setting or managed requirement.
|
||||
fn validate_xaa_opt_in_source(stack: &ConfigLayerStack, xaa_enabled: bool) -> io::Result<()> {
|
||||
if !xaa_enabled || stack.layers_high_to_low().next().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let required = stack
|
||||
.requirements()
|
||||
.feature_requirements
|
||||
.as_ref()
|
||||
.and_then(|requirements| requirements.value.entries.get(Feature::UseXaa.key()))
|
||||
.copied();
|
||||
let configured = stack
|
||||
.layers_high_to_low()
|
||||
.filter(|layer| !matches!(layer.name, ConfigLayerSource::Project { .. }))
|
||||
.find_map(|layer| {
|
||||
layer
|
||||
.config
|
||||
.get("features")?
|
||||
.get(Feature::UseXaa.key())?
|
||||
.as_bool()
|
||||
});
|
||||
if required.or(configured) == Some(true) {
|
||||
return Ok(());
|
||||
}
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"`[features].use_xaa = true` must be selected in a non-project config layer",
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_ema_tests.rs"]
|
||||
mod tests;
|
||||
84
codex-rs/config/src/mcp_ema_cancellation.rs
Normal file
84
codex-rs/config/src/mcp_ema_cancellation.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
//! Carries EMA startup cancellation across configuration loading and thread publication.
|
||||
//! Once published, a thread's existing config refresh gate owns selective revocation.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct McpEmaCancellation(Arc<State>);
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
startup: CancellationToken,
|
||||
owner: CancellationToken,
|
||||
lifetime: CancellationToken,
|
||||
published: AtomicBool,
|
||||
}
|
||||
|
||||
impl McpEmaCancellation {
|
||||
/// Capture before loading configuration so reload can fence a delayed startup.
|
||||
pub fn pending(startup: CancellationToken, owner: CancellationToken) -> Self {
|
||||
let lifetime = owner.child_token();
|
||||
Self(Arc::new(State {
|
||||
startup,
|
||||
owner,
|
||||
lifetime,
|
||||
published: AtomicBool::new(false),
|
||||
}))
|
||||
}
|
||||
|
||||
/// A fork gets its own publication state, even when it inherits loaded config.
|
||||
pub fn for_startup(&self) -> Self {
|
||||
let pending = Self::pending(self.0.startup.clone(), self.0.owner.clone());
|
||||
if self.is_cancelled() {
|
||||
pending.cancel();
|
||||
}
|
||||
pending
|
||||
}
|
||||
|
||||
/// A validated session keeps its authority and records the current startup fence
|
||||
/// for later forks. The session publication gate must protect this replacement.
|
||||
pub fn refreshed(&self, incoming: &Self) -> Self {
|
||||
Self(Arc::new(State {
|
||||
startup: incoming.0.startup.clone(),
|
||||
owner: self.0.owner.clone(),
|
||||
lifetime: self.0.lifetime.clone(),
|
||||
published: AtomicBool::new(true),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Call while holding the thread registry's publication lock. A reload either
|
||||
/// cancels this pending snapshot or discovers the published thread for validation.
|
||||
pub fn publish(&self) {
|
||||
if !self.0.published.swap(true, Ordering::AcqRel) && self.0.startup.is_cancelled() {
|
||||
self.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cancel(&self) {
|
||||
self.0.lifetime.cancel();
|
||||
}
|
||||
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.0.lifetime.is_cancelled()
|
||||
|| (!self.0.published.load(Ordering::Acquire) && self.0.startup.is_cancelled())
|
||||
}
|
||||
|
||||
pub fn token(&self) -> CancellationToken {
|
||||
self.0.lifetime.clone()
|
||||
}
|
||||
|
||||
pub async fn cancelled(&self) {
|
||||
tokio::select! {
|
||||
biased;
|
||||
() = self.0.lifetime.cancelled() => return,
|
||||
() = self.0.startup.cancelled() => {}
|
||||
}
|
||||
if self.0.published.load(Ordering::Acquire) {
|
||||
self.0.lifetime.cancelled().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
327
codex-rs/config/src/mcp_ema_tests.rs
Normal file
327
codex-rs/config/src/mcp_ema_tests.rs
Normal file
@@ -0,0 +1,327 @@
|
||||
//! Enterprise registration provenance and credential-boundary checks.
|
||||
|
||||
use super::*;
|
||||
use crate::AbsolutePathBuf;
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn stack(layers: Vec<(ConfigLayerSource, &str)>) -> ConfigLayerStack {
|
||||
ConfigLayerStack::new(
|
||||
layers
|
||||
.into_iter()
|
||||
.map(|(source, value)| ConfigLayerEntry::new(source, toml::from_str(value).unwrap()))
|
||||
.collect(),
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn local_sources(name: &str) -> (ConfigLayerSource, ConfigLayerSource, ConfigLayerSource) {
|
||||
let path = AbsolutePathBuf::from_absolute_path(std::env::temp_dir().join(name)).unwrap();
|
||||
(
|
||||
ConfigLayerSource::System { file: path.clone() },
|
||||
ConfigLayerSource::User {
|
||||
file: path.clone(),
|
||||
profile: None,
|
||||
},
|
||||
ConfigLayerSource::Project {
|
||||
dot_codex_folder: path,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn validate_effective_ema(stack: &ConfigLayerStack) -> std::io::Result<()> {
|
||||
let servers = stack
|
||||
.effective_config()
|
||||
.get("mcp_servers")
|
||||
.cloned()
|
||||
.unwrap_or_else(|| toml::Value::Table(Default::default()))
|
||||
.try_into::<std::collections::HashMap<String, McpServerConfig>>()
|
||||
.map_err(|error| std::io::Error::new(std::io::ErrorKind::InvalidInput, error))?;
|
||||
validate_ema_auth_sources(stack, &servers)
|
||||
}
|
||||
|
||||
fn valid_ema_layers(layers: Vec<(ConfigLayerSource, &str)>) -> bool {
|
||||
validate_effective_ema(&stack(layers)).is_ok()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ema_profiles_and_auth_modes_preserve_non_project_authority() {
|
||||
let (system, user, project) = local_sources("ema-config");
|
||||
let trusted = "[mcp_enterprise_managed_auth.idp]\nissuer = 'https://idp.example'\nclient_id = 'enterprise'";
|
||||
let replacement =
|
||||
"[mcp_enterprise_managed_auth.idp]\nissuer = 'https://other.example'\nclient_id = 'other'";
|
||||
let expected = McpEnterpriseManagedAuthConfig {
|
||||
idp: McpServerIdpOAuthConfig {
|
||||
issuer: "https://idp.example".into(),
|
||||
client_secret: None,
|
||||
token_endpoint_auth_method: None,
|
||||
client_id: "enterprise".into(),
|
||||
},
|
||||
};
|
||||
for (layers, selected) in [
|
||||
(
|
||||
vec![
|
||||
(system.clone(), trusted),
|
||||
(user.clone(), replacement),
|
||||
(project.clone(), replacement),
|
||||
],
|
||||
Some(expected.clone()),
|
||||
),
|
||||
(
|
||||
vec![(user.clone(), trusted), (project.clone(), replacement)],
|
||||
Some(expected.clone()),
|
||||
),
|
||||
(vec![(project, trusted)], None),
|
||||
(
|
||||
vec![
|
||||
(system, trusted),
|
||||
(
|
||||
user,
|
||||
"[mcp_enterprise_managed_auth.idp]\nclient_id = 'partial'",
|
||||
),
|
||||
],
|
||||
Some(expected),
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
McpEnterpriseManagedAuthConfig::from_config_layers(
|
||||
&stack(layers),
|
||||
/*fallback*/ None
|
||||
)
|
||||
.unwrap(),
|
||||
selected
|
||||
);
|
||||
}
|
||||
let incomplete = stack(vec![(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
"[mcp_enterprise_managed_auth.idp]\nclient_id = 'partial'",
|
||||
)]);
|
||||
assert!(
|
||||
McpEnterpriseManagedAuthConfig::from_config_layers(&incomplete, /*fallback*/ None).is_err()
|
||||
);
|
||||
|
||||
let server: McpServerConfig = toml::from_str("url='https://resource.example'\nauth='ema_auth'\n[oauth.idp]\nissuer='https://other.example'\nclient_id='other'").unwrap();
|
||||
assert_eq!(server.oauth_idp(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ema_registrations_require_one_atomic_non_project_source() {
|
||||
let (system, user, project) = local_sources("ema-registration-sources");
|
||||
let registration = r#"[mcp_servers.enterprise]
|
||||
url='https://resource.example/mcp'
|
||||
auth='ema_auth'
|
||||
scopes=['tools']
|
||||
oauth_resource='https://resource.example'
|
||||
oauth.client_id='resource-client'
|
||||
oauth.authorization_server_issuer='https://as.example'"#;
|
||||
for (source, allowed) in [
|
||||
(system.clone(), true),
|
||||
(user.clone(), true),
|
||||
(project.clone(), false),
|
||||
] {
|
||||
assert_eq!(valid_ema_layers(vec![(source, registration)]), allowed);
|
||||
}
|
||||
for change in [
|
||||
"oauth_resource='https://other.example'",
|
||||
"oauth.client_id='other-client'",
|
||||
"oauth.authorization_server_issuer='https://other-as.example'",
|
||||
"url='https://other.example/mcp'",
|
||||
"url='https://resource.example/mcp/other'",
|
||||
"scopes=['admin']",
|
||||
] {
|
||||
let overlay = format!("[mcp_servers.enterprise]\n{change}");
|
||||
assert!(!valid_ema_layers(vec![
|
||||
(system.clone(), registration),
|
||||
(project.clone(), &overlay),
|
||||
]));
|
||||
}
|
||||
let higher = registration.replace("tools", "managed-tools");
|
||||
assert!(!valid_ema_layers(vec![
|
||||
(system.clone(), registration),
|
||||
(user, &higher),
|
||||
(project.clone(), registration),
|
||||
]));
|
||||
assert!(valid_ema_layers(vec![
|
||||
(system.clone(), registration),
|
||||
(
|
||||
project.clone(),
|
||||
"[mcp_servers.enterprise]\nenabled=false\n[mcp_servers.enterprise.tools.read]\napproval_mode='prompt'"
|
||||
),
|
||||
]));
|
||||
assert!(valid_ema_layers(vec![
|
||||
(system, registration),
|
||||
(project, "[mcp_servers.enterprise]\nauth='ema_auth'"),
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_cannot_reenable_trusted_disabled_ema_registration() {
|
||||
let (system, user, project) = local_sources("ema-disabled-source");
|
||||
let trusted = "[mcp_servers.enterprise]\nurl='https://resource.example/mcp'\nauth='ema_auth'\nenabled=false";
|
||||
let project_enable = "[mcp_servers.enterprise]\nenabled=true";
|
||||
assert!(!valid_ema_layers(vec![
|
||||
(system.clone(), trusted),
|
||||
(project.clone(), project_enable)
|
||||
]));
|
||||
assert!(valid_ema_layers(vec![
|
||||
(system.clone(), trusted),
|
||||
(user, project_enable)
|
||||
]));
|
||||
let enabled = trusted.replace("enabled=false", "enabled=true");
|
||||
assert!(valid_ema_layers(vec![
|
||||
(system, &enabled),
|
||||
(project, "[mcp_servers.enterprise]\nenabled=false")
|
||||
]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_project_auth_changes_and_ordinary_oauth_remain_allowed() {
|
||||
let (system, user, project) = local_sources("ema-auth-downgrade");
|
||||
for (base_auth, source) in [("ema_auth", user), ("oauth", project)] {
|
||||
let base = format!(
|
||||
"[mcp_servers.enterprise]\nurl='https://resource.example/mcp'\nauth='{base_auth}'"
|
||||
);
|
||||
assert!(
|
||||
validate_effective_ema(&stack(vec![
|
||||
(system.clone(), &base),
|
||||
(
|
||||
source,
|
||||
"[mcp_servers.enterprise]\nauth='oauth'\nenabled=false"
|
||||
),
|
||||
]))
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xaa_opt_in_requires_a_non_project_source() {
|
||||
let (_, user, project) = local_sources("xaa-sources");
|
||||
let session = ConfigLayerSource::SessionFlags;
|
||||
let enabled = "[features]\nuse_xaa=true";
|
||||
|
||||
for (source, allowed) in [(user, true), (session, true), (project.clone(), false)] {
|
||||
assert_eq!(
|
||||
validate_xaa_opt_in_source(&stack(vec![(source, enabled)]), /*xaa_enabled*/ true,)
|
||||
.is_ok(),
|
||||
allowed
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
validate_xaa_opt_in_source(&stack(vec![(project, enabled)]), /*xaa_enabled*/ false,)
|
||||
.is_ok()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ema_credential_names_bind_user_workspace_issuer_and_client() {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for user in ["a", "b"] {
|
||||
for workspace in ["a", "b"] {
|
||||
for issuer in ["https://one.example", "https://two.example"] {
|
||||
for client in ["a", "b"] {
|
||||
let scope = McpEmaAuthScope::new(user.into(), workspace.into()).unwrap();
|
||||
let idp = McpServerIdpOAuthConfig {
|
||||
issuer: issuer.into(),
|
||||
client_secret: None,
|
||||
token_endpoint_auth_method: None,
|
||||
client_id: client.into(),
|
||||
};
|
||||
assert!(names.insert(idp.credential_name(&scope)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(McpEmaAuthScope::new(" ".into(), "workspace".into()), None);
|
||||
|
||||
let identifiers = [
|
||||
"sensitive-user@example.com",
|
||||
"sensitive-workspace-id",
|
||||
"https://sensitive-idp.example",
|
||||
"sensitive-oauth-client",
|
||||
];
|
||||
let scope = McpEmaAuthScope::new(identifiers[0].into(), identifiers[1].into()).unwrap();
|
||||
let name = McpServerIdpOAuthConfig {
|
||||
issuer: identifiers[2].into(),
|
||||
client_secret: None,
|
||||
token_endpoint_auth_method: None,
|
||||
client_id: identifiers[3].into(),
|
||||
}
|
||||
.credential_name(&scope);
|
||||
assert!(name.starts_with("ema-idp:"));
|
||||
for identifier in identifiers {
|
||||
assert!(!name.contains(identifier));
|
||||
assert!(!name.contains(&URL_SAFE_NO_PAD.encode(identifier)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ema_rejects_alternate_credentials_and_executor_custody() {
|
||||
for extra in [
|
||||
"bearer_token_env_var='TOKEN'",
|
||||
"http_headers.Authorization='secret'",
|
||||
"http_headers.Accept='application/json'",
|
||||
"env_http_headers.X-Key='TOKEN'",
|
||||
"http_headers_helper='get-headers'",
|
||||
"oauth={client_id='client', client_secret='secret'}",
|
||||
"environment_id='remote'",
|
||||
] {
|
||||
let server: McpServerConfig = toml::from_str(&format!(
|
||||
"url='https://resource.example'\nauth='ema_auth'\n{extra}"
|
||||
))
|
||||
.unwrap();
|
||||
assert!(server.validate_ema_auth_transport().is_err(), "{extra}");
|
||||
}
|
||||
let server: McpServerConfig =
|
||||
toml::from_str("url='https://resource.example'\nauth='ema_auth'\nhttp_headers={}").unwrap();
|
||||
assert_eq!(server.validate_ema_auth_transport(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn confidential_ema_registration_binds_secrets_to_trusted_issuers() {
|
||||
let (system, _, project) = local_sources("ema-confidential");
|
||||
let trusted = "[mcp_enterprise_managed_auth.idp]\nissuer='https://idp.example'\nclient_id='idp'\nclient_secret='idp-secret'\ntoken_endpoint_auth_method='client_secret_post'\n[mcp_servers.enterprise]\nurl='https://resource.example'\nauth='ema_auth'\noauth={client_id='client', client_secret='resource-secret', token_endpoint_auth_method='client_secret_basic', authorization_server_issuer='https://as.example'}";
|
||||
assert!(valid_ema_layers(vec![(system.clone(), trusted)]));
|
||||
let layers = stack(vec![
|
||||
(system.clone(), trusted),
|
||||
(
|
||||
project.clone(),
|
||||
"[mcp_enterprise_managed_auth.idp]\nclient_secret='project-secret'",
|
||||
),
|
||||
]);
|
||||
let profile =
|
||||
McpEnterpriseManagedAuthConfig::from_config_layers(&layers, /*fallback*/ None)
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(profile.idp.client_secret, Some("idp-secret".into()));
|
||||
|
||||
for invalid in [
|
||||
trusted.replace("idp-secret", " "),
|
||||
trusted.replace("client_secret='idp-secret'\n", ""),
|
||||
] {
|
||||
assert!(
|
||||
McpEnterpriseManagedAuthConfig::resolve(
|
||||
&stack(vec![(system.clone(), &invalid)]),
|
||||
/*fallback*/ None,
|
||||
&Default::default(),
|
||||
/*xaa_enabled*/ false,
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
for override_config in [
|
||||
"[mcp_servers.enterprise.oauth]\nauthorization_server_issuer='https://attacker.example'",
|
||||
"[mcp_servers.enterprise.oauth]\nclient_secret='project-secret'",
|
||||
"[mcp_servers.enterprise.oauth]\ntoken_endpoint_auth_method='client_secret_post'",
|
||||
] {
|
||||
assert!(!valid_ema_layers(vec![
|
||||
(system.clone(), trusted),
|
||||
(project.clone(), override_config)
|
||||
]));
|
||||
}
|
||||
}
|
||||
94
codex-rs/config/src/mcp_requirements.rs
Normal file
94
codex-rs/config/src/mcp_requirements.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
use crate::McpServerIdentity;
|
||||
use crate::McpServerRequirement;
|
||||
use crate::McpServerValueMatcher;
|
||||
use crate::mcp_types::McpServerConfig;
|
||||
use crate::mcp_types::McpServerTransportConfig;
|
||||
use regex_lite::Regex;
|
||||
|
||||
fn compile_full_regex(expression: &str) -> Result<Regex, String> {
|
||||
Regex::new(&format!(r"\A(?:{expression})\z")).map_err(|err| {
|
||||
format!("regex `{expression}` cannot be used for full-value matching: {err}")
|
||||
})
|
||||
}
|
||||
|
||||
fn validate_value_matcher(matcher: &McpServerValueMatcher) -> Result<(), String> {
|
||||
let McpServerValueMatcher::Regex { expression } = matcher else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
Regex::new(expression).map_err(|err| format!("invalid regex `{expression}`: {err}"))?;
|
||||
compile_full_regex(expression).map(|_| ())
|
||||
}
|
||||
|
||||
fn matches_value(matcher: &McpServerValueMatcher, candidate: &str) -> bool {
|
||||
match matcher {
|
||||
McpServerValueMatcher::Exact { value } => candidate == value,
|
||||
McpServerValueMatcher::Prefix { value } => candidate.starts_with(value),
|
||||
McpServerValueMatcher::Regex { expression } => compile_full_regex(expression)
|
||||
.ok()
|
||||
.is_some_and(|regex| regex.is_match(candidate)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn validate_mcp_server_requirement(
|
||||
requirement: &McpServerRequirement,
|
||||
) -> Result<(), String> {
|
||||
match requirement {
|
||||
McpServerRequirement::Identity { .. } => Ok(()),
|
||||
McpServerRequirement::Command(matcher) => {
|
||||
for (index, arg) in matcher.args.iter().enumerate() {
|
||||
validate_value_matcher(arg)
|
||||
.map_err(|err| format!("invalid argument matcher at index {index}: {err}"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
McpServerRequirement::Url(matcher) => validate_value_matcher(matcher),
|
||||
}
|
||||
}
|
||||
|
||||
impl McpServerConfig {
|
||||
pub fn matches_requirement(&self, requirement: &McpServerRequirement) -> bool {
|
||||
// HTTP requirements intentionally authorize the complete server configuration by URL.
|
||||
match (requirement, &self.transport) {
|
||||
(
|
||||
McpServerRequirement::Identity {
|
||||
identity:
|
||||
McpServerIdentity::Command {
|
||||
command: want_command,
|
||||
},
|
||||
},
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: got_command,
|
||||
..
|
||||
},
|
||||
) => got_command == want_command,
|
||||
(
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Url { url: want_url },
|
||||
},
|
||||
McpServerTransportConfig::StreamableHttp { url: got_url, .. },
|
||||
) => got_url == want_url,
|
||||
(
|
||||
McpServerRequirement::Command(matcher),
|
||||
McpServerTransportConfig::Stdio { command, args, .. },
|
||||
) => {
|
||||
matcher.executable == *command
|
||||
&& matcher.args.len() == args.len()
|
||||
&& matcher
|
||||
.args
|
||||
.iter()
|
||||
.zip(args)
|
||||
.all(|(matcher, arg)| matches_value(matcher, arg))
|
||||
}
|
||||
(
|
||||
McpServerRequirement::Url(matcher),
|
||||
McpServerTransportConfig::StreamableHttp { url, .. },
|
||||
) => matches_value(matcher, url),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_requirements_tests.rs"]
|
||||
mod tests;
|
||||
227
codex-rs/config/src/mcp_requirements_tests.rs
Normal file
227
codex-rs/config/src/mcp_requirements_tests.rs
Normal file
@@ -0,0 +1,227 @@
|
||||
use super::*;
|
||||
use crate::McpServerCommandMatcher;
|
||||
use crate::mcp_types::McpServerConfig;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn stdio_server(command: &str, args: &[&str]) -> McpServerConfig {
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::Stdio {
|
||||
command: command.to_string(),
|
||||
args: args.iter().map(ToString::to_string).collect(),
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
},
|
||||
environment_id: crate::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
enabled: true,
|
||||
required: false,
|
||||
startup_readiness: Default::default(),
|
||||
supports_parallel_tool_calls: false,
|
||||
tool_input_schema_max_bytes: None,
|
||||
omit_tools_from: None,
|
||||
disabled_reason: None,
|
||||
startup_timeout_sec: None,
|
||||
tool_timeout_sec: None,
|
||||
default_tools_approval_mode: None,
|
||||
enabled_tools: None,
|
||||
disabled_tools: None,
|
||||
scopes: None,
|
||||
oauth: None,
|
||||
oauth_resource: None,
|
||||
tools: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_matcher_matches_exact_positional_arguments() {
|
||||
let requirement = McpServerRequirement::Command(McpServerCommandMatcher {
|
||||
executable: "company-cli".to_string(),
|
||||
args: vec![
|
||||
McpServerValueMatcher::Exact {
|
||||
value: "mcp".to_string(),
|
||||
},
|
||||
McpServerValueMatcher::Regex {
|
||||
expression: r"https://[a-z]+\.example\.com".to_string(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert!(
|
||||
stdio_server("company-cli", &["mcp", "https://pricing.example.com"])
|
||||
.matches_requirement(&requirement)
|
||||
);
|
||||
assert!(
|
||||
!stdio_server("company-cli", &["https://pricing.example.com", "mcp"])
|
||||
.matches_requirement(&requirement)
|
||||
);
|
||||
assert!(
|
||||
!stdio_server(
|
||||
"company-cli",
|
||||
&["mcp", "https://pricing.example.com", "--verbose"]
|
||||
)
|
||||
.matches_requirement(&requirement)
|
||||
);
|
||||
assert!(
|
||||
!stdio_server(
|
||||
"/usr/local/bin/company-cli",
|
||||
&["mcp", "https://pricing.example.com"]
|
||||
)
|
||||
.matches_requirement(&requirement)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_matcher_requires_a_full_value_match() {
|
||||
let matcher = McpServerValueMatcher::Regex {
|
||||
expression: "mcp".to_string(),
|
||||
};
|
||||
|
||||
assert!(matches_value(&matcher, "mcp"));
|
||||
assert!(!matches_value(&matcher, "mcp-proxy"));
|
||||
assert!(!matches_value(&matcher, "prefix-mcp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_matcher_allows_a_later_alternative_to_match_the_full_value() {
|
||||
let matcher = McpServerValueMatcher::Regex {
|
||||
expression: r"https://api\.example\.com|https://api\.example\.com/mcp".to_string(),
|
||||
};
|
||||
|
||||
assert!(matches_value(&matcher, "https://api.example.com/mcp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn regex_matcher_validation_rejects_expression_that_cannot_be_wrapped() {
|
||||
let matcher = McpServerValueMatcher::Regex {
|
||||
expression: "(?x)mcp # trailing comment".to_string(),
|
||||
};
|
||||
|
||||
let err = validate_value_matcher(&matcher)
|
||||
.expect_err("expression should not be valid for full-value matching");
|
||||
assert!(
|
||||
err.contains("cannot be used for full-value matching"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_command_identity_keeps_ignoring_arguments() {
|
||||
let requirement: McpServerRequirement = toml::from_str(
|
||||
r#"
|
||||
[identity]
|
||||
command = "company-cli"
|
||||
"#,
|
||||
)
|
||||
.expect("legacy command identity");
|
||||
|
||||
assert!(
|
||||
stdio_server("company-cli", &["any", "arguments", "remain", "allowed"])
|
||||
.matches_requirement(&requirement)
|
||||
);
|
||||
assert!(!stdio_server("different-cli", &[]).matches_requirement(&requirement));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requirement_deserializes_command_and_url_matcher_shapes() {
|
||||
let command: McpServerRequirement = toml::from_str(
|
||||
r#"
|
||||
[identity]
|
||||
command = { executable = "company-cli", args = [
|
||||
{ match = "exact", value = "mcp" },
|
||||
{ match = "regex", expression = '^https://[a-z]+\.example\.com$' },
|
||||
] }
|
||||
"#,
|
||||
)
|
||||
.expect("command matcher");
|
||||
let url: McpServerRequirement = toml::from_str(
|
||||
r#"
|
||||
[identity]
|
||||
url = { match = "prefix", value = "https://mcp.example.com/" }
|
||||
"#,
|
||||
)
|
||||
.expect("URL matcher");
|
||||
|
||||
assert_eq!(
|
||||
command,
|
||||
McpServerRequirement::Command(McpServerCommandMatcher {
|
||||
executable: "company-cli".to_string(),
|
||||
args: vec![
|
||||
McpServerValueMatcher::Exact {
|
||||
value: "mcp".to_string(),
|
||||
},
|
||||
McpServerValueMatcher::Regex {
|
||||
expression: r"^https://[a-z]+\.example\.com$".to_string(),
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
url,
|
||||
McpServerRequirement::Url(McpServerValueMatcher::Prefix {
|
||||
value: "https://mcp.example.com/".to_string(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requirement_rejects_matchers_outside_identity() {
|
||||
for contents in [
|
||||
r#"
|
||||
command = "company-cli"
|
||||
"#,
|
||||
r#"
|
||||
command = { executable = "company-cli", args = [] }
|
||||
"#,
|
||||
r#"
|
||||
url = { match = "prefix", value = "https://mcp.example.com/" }
|
||||
"#,
|
||||
] {
|
||||
let err = toml::from_str::<McpServerRequirement>(contents)
|
||||
.expect_err("MCP server requirements should use the identity key");
|
||||
assert!(
|
||||
err.to_string().contains("missing field `identity`"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matcher_identity_rejects_unknown_fields() {
|
||||
for contents in [
|
||||
r#"
|
||||
[identity]
|
||||
unknown = "value"
|
||||
command = { executable = "company-cli", args = [] }
|
||||
"#,
|
||||
r#"
|
||||
[identity]
|
||||
command = { executable = "company-cli", args = [], unknown = "value" }
|
||||
"#,
|
||||
] {
|
||||
toml::from_str::<McpServerRequirement>(contents)
|
||||
.expect_err("matcher identities should reject unknown fields");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_requirement_keeps_ignoring_unrelated_sibling_fields() {
|
||||
let requirement: McpServerRequirement = toml::from_str(
|
||||
r#"
|
||||
unrelated = "ignored"
|
||||
[identity]
|
||||
command = "company-cli"
|
||||
"#,
|
||||
)
|
||||
.expect("legacy identity with unrelated sibling field");
|
||||
|
||||
assert_eq!(
|
||||
requirement,
|
||||
McpServerRequirement::Identity {
|
||||
identity: McpServerIdentity::Command {
|
||||
command: "company-cli".to_string(),
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
720
codex-rs/config/src/mcp_types.rs
Normal file
720
codex-rs/config/src/mcp_types.rs
Normal file
@@ -0,0 +1,720 @@
|
||||
//! MCP server configuration types.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::num::NonZeroUsize;
|
||||
use std::time::Duration;
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use codex_protocol::config_types::ToolExposureSurface;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use codex_utils_redacted_string::RedactedString;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serialize;
|
||||
use serde::de::Error as SerdeError;
|
||||
|
||||
use crate::McpEmaRegistration;
|
||||
use crate::McpEmaTokenEndpointAuthMethod;
|
||||
use crate::RequirementSource;
|
||||
|
||||
/// Effective MCP environment id when config omits `environment_id`.
|
||||
pub const DEFAULT_MCP_SERVER_ENVIRONMENT_ID: &str = "local";
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum AppToolApproval {
|
||||
#[default]
|
||||
Auto,
|
||||
Prompt,
|
||||
Writes,
|
||||
Approve,
|
||||
}
|
||||
|
||||
impl AppToolApproval {
|
||||
/// Requires approval whenever either policy could require it.
|
||||
///
|
||||
/// `Auto` and `Writes` are incomparable: each can require approval for a
|
||||
/// tool the other would approve. Their conservative intersection is `Prompt`.
|
||||
pub fn restrict_to(self, requested: Self) -> Self {
|
||||
match (self, requested) {
|
||||
(Self::Prompt, _) | (_, Self::Prompt) => Self::Prompt,
|
||||
(Self::Approve, mode) | (mode, Self::Approve) => mode,
|
||||
(Self::Auto, Self::Auto) => Self::Auto,
|
||||
(Self::Writes, Self::Writes) => Self::Writes,
|
||||
(Self::Auto, Self::Writes) | (Self::Writes, Self::Auto) => Self::Prompt,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Human-readable reason a configured MCP server was disabled after requirements
|
||||
/// were applied.
|
||||
///
|
||||
/// `Display` is intentionally implemented for CLI/TUI status output; avoid
|
||||
/// relying on `Debug` because enum variant syntax is not part of the user-facing
|
||||
/// message contract.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum McpServerDisabledReason {
|
||||
/// The server is disabled, but there is no more specific user-facing reason.
|
||||
Unknown,
|
||||
/// The server was disabled by config requirements from the given source.
|
||||
Requirements { source: RequirementSource },
|
||||
/// An explicit disable is also denied by requirements.
|
||||
ExplicitAndRequirements { source: RequirementSource },
|
||||
}
|
||||
|
||||
impl fmt::Display for McpServerDisabledReason {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
McpServerDisabledReason::Unknown => write!(f, "unknown"),
|
||||
McpServerDisabledReason::Requirements { source }
|
||||
| McpServerDisabledReason::ExplicitAndRequirements { source } => {
|
||||
write!(f, "requirements ({source})")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-tool settings for a single MCP server tool.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct McpServerToolConfig {
|
||||
/// Approval mode for this tool.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub approval_mode: Option<AppToolApproval>,
|
||||
|
||||
/// Token budget for this tool's output, before the standard 20% serialization allowance.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub output_token_limit: Option<NonZeroUsize>,
|
||||
}
|
||||
|
||||
impl McpServerToolConfig {
|
||||
/// Applies the stricter explicit output budget without changing approval policy.
|
||||
pub fn restrict_output_token_limit(&mut self, limit: Option<NonZeroUsize>) {
|
||||
self.output_token_limit = self.output_token_limit.into_iter().chain(limit).min();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(untagged, deny_unknown_fields)]
|
||||
pub enum McpServerEnvVar {
|
||||
Name(String),
|
||||
Config {
|
||||
name: String,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
source: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl McpServerEnvVar {
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
McpServerEnvVar::Name(name) => name,
|
||||
McpServerEnvVar::Config { name, .. } => name,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn source(&self) -> Option<&str> {
|
||||
match self {
|
||||
McpServerEnvVar::Name(_) => None,
|
||||
McpServerEnvVar::Config { source, .. } => source.as_deref(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_remote_source(&self) -> bool {
|
||||
self.source() == Some("remote")
|
||||
}
|
||||
|
||||
pub fn validate_source(&self) -> Result<(), String> {
|
||||
match self.source() {
|
||||
None | Some("local") | Some("remote") => Ok(()),
|
||||
Some(source) => Err(format!(
|
||||
"unsupported env_vars source `{source}`; expected `local` or `remote`"
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for McpServerEnvVar {
|
||||
fn from(value: String) -> Self {
|
||||
Self::Name(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for McpServerEnvVar {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::Name(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl AsRef<str> for McpServerEnvVar {
|
||||
fn as_ref(&self) -> &str {
|
||||
self.name()
|
||||
}
|
||||
}
|
||||
|
||||
/// Client settings for MCP OAuth login or enterprise token exchange.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct McpServerOAuthConfig {
|
||||
/// Explicit OAuth client identifier to present during authorization and token exchange.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub client_id: Option<String>,
|
||||
|
||||
/// OAuth client secret used for token exchange with a pre-registered client.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub client_secret: Option<RedactedString>,
|
||||
|
||||
/// Registered EMA client authentication method. Defaults to client_secret_basic
|
||||
/// when a secret is configured; requires a client secret.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
|
||||
|
||||
/// Registered callback URL associated with this OAuth client.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub callback_url: Option<String>,
|
||||
|
||||
/// Fixed callback port that takes precedence over Codex's global OAuth callback port.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub callback_port: Option<u16>,
|
||||
|
||||
/// Expected resource authorization server issuer for EMA token exchange.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub authorization_server_issuer: Option<String>,
|
||||
|
||||
/// Host-resolved authorization; never accepted from a server or plugin declaration.
|
||||
#[serde(skip)]
|
||||
#[schemars(skip)]
|
||||
pub ema_registration: Option<McpEmaRegistration>,
|
||||
}
|
||||
|
||||
/// Authentication flow for an HTTP MCP server. Explicit credentials take
|
||||
/// precedence for OAuth and ChatGPT; EMA rejects alternate credentials and fallback.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpServerAuth {
|
||||
/// Use stored MCP OAuth credentials when available. Starting an OAuth login
|
||||
/// is a separate operation.
|
||||
#[default]
|
||||
#[serde(rename = "oauth")]
|
||||
OAuth,
|
||||
/// Use the current ChatGPT session for servers on the trusted first-party
|
||||
/// ChatGPT origin. If no ChatGPT session provider is available, startup can
|
||||
/// still fall back to stored OAuth credentials.
|
||||
#[serde(rename = "chatgpt")]
|
||||
ChatGpt,
|
||||
/// Exchange an enterprise IdP refresh token for resource-specific authorization.
|
||||
/// Alternate credentials and ordinary OAuth fallback are not permitted.
|
||||
#[serde(rename = "ema_auth")]
|
||||
EmaAuth,
|
||||
}
|
||||
|
||||
/// Readiness needed before startup can expose this server's tools to the model.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpStartupReadiness {
|
||||
/// Use the live connection to determine startup readiness.
|
||||
#[default]
|
||||
Connection,
|
||||
/// Allow a valid cached tool catalog while the live connection starts.
|
||||
/// Tool execution still requires the current connection.
|
||||
Catalog,
|
||||
}
|
||||
|
||||
fn is_default<T: Default + PartialEq>(value: &T) -> bool {
|
||||
value == &T::default()
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone, PartialEq)]
|
||||
pub struct McpServerConfig {
|
||||
#[serde(flatten)]
|
||||
pub transport: McpServerTransportConfig,
|
||||
|
||||
/// Authentication flow, including an explicit no-fallback EMA mode.
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
pub auth: McpServerAuth,
|
||||
|
||||
/// Effective environment id for where Codex should start this MCP server.
|
||||
pub environment_id: String,
|
||||
|
||||
/// When `false`, Codex skips initializing this MCP server.
|
||||
#[serde(default = "default_enabled")]
|
||||
pub enabled: bool,
|
||||
|
||||
/// When `true`, `codex exec` exits with an error if this MCP server fails to initialize.
|
||||
/// With `startup_readiness = "catalog"`, a valid cached catalog can satisfy startup;
|
||||
/// connection failures are then reported when a tool is invoked.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub required: bool,
|
||||
|
||||
/// Whether startup requires a live connection or can use a valid cached tool catalog.
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
pub startup_readiness: McpStartupReadiness,
|
||||
|
||||
/// When `true`, every tool from this server is advertised as safe for parallel tool calls.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub supports_parallel_tool_calls: bool,
|
||||
|
||||
/// UTF-8 byte threshold for compacting each ordinary MCP tool input schema. Defaults to 5,000 bytes.
|
||||
/// Code Mode also uses an explicitly configured limit when rendering each tool's input type.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub tool_input_schema_max_bytes: Option<NonZeroUsize>,
|
||||
|
||||
/// Model-facing surfaces from which this server's tools must be omitted.
|
||||
/// `None` leaves lower-priority configuration unchanged; an empty list clears it.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub omit_tools_from: Option<Vec<ToolExposureSurface>>,
|
||||
|
||||
/// Reason this server was disabled after applying requirements.
|
||||
#[serde(skip)]
|
||||
pub disabled_reason: Option<McpServerDisabledReason>,
|
||||
|
||||
/// Startup timeout in seconds for initializing MCP server & initially listing tools.
|
||||
#[serde(
|
||||
default,
|
||||
with = "option_duration_secs",
|
||||
skip_serializing_if = "Option::is_none"
|
||||
)]
|
||||
pub startup_timeout_sec: Option<Duration>,
|
||||
|
||||
/// Default timeout for MCP tool calls initiated via this server.
|
||||
#[serde(default, with = "option_duration_secs")]
|
||||
pub tool_timeout_sec: Option<Duration>,
|
||||
|
||||
/// Approval mode for tools in this server unless a tool override exists.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub default_tools_approval_mode: Option<AppToolApproval>,
|
||||
|
||||
/// Explicit allow-list of tools exposed from this server. When set, only these tools will be registered.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub enabled_tools: Option<Vec<String>>,
|
||||
|
||||
/// Explicit deny-list of tools. These tools will be removed after applying `enabled_tools`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub disabled_tools: Option<Vec<String>>,
|
||||
|
||||
/// Optional scopes requested during MCP login or EMA token exchange.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub scopes: Option<Vec<String>>,
|
||||
|
||||
/// Optional client settings for MCP login or EMA token exchange.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub oauth: Option<McpServerOAuthConfig>,
|
||||
|
||||
/// Optional resource parameter for MCP login or EMA token exchange (RFC 8707).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub oauth_resource: Option<String>,
|
||||
|
||||
/// Per-tool settings keyed by tool name.
|
||||
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
|
||||
pub tools: HashMap<String, McpServerToolConfig>,
|
||||
}
|
||||
|
||||
impl McpServerConfig {
|
||||
/// Disables this registration without losing an existing explicit disable.
|
||||
pub fn disable_by_requirements(&mut self, source: RequirementSource) {
|
||||
let explicitly_disabled = match self.disabled_reason {
|
||||
Some(McpServerDisabledReason::Requirements { .. }) => false,
|
||||
Some(McpServerDisabledReason::ExplicitAndRequirements { .. }) => true,
|
||||
Some(McpServerDisabledReason::Unknown) | None => !self.enabled,
|
||||
};
|
||||
self.enabled = false;
|
||||
self.disabled_reason = Some(if explicitly_disabled {
|
||||
McpServerDisabledReason::ExplicitAndRequirements { source }
|
||||
} else {
|
||||
McpServerDisabledReason::Requirements { source }
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether a regular chat may defer this server when its tool catalog is cached.
|
||||
pub fn can_defer_stdio_startup(&self) -> bool {
|
||||
matches!(&self.transport, McpServerTransportConfig::Stdio { .. })
|
||||
&& (!self.required || self.startup_readiness == McpStartupReadiness::Catalog)
|
||||
}
|
||||
|
||||
pub fn is_local_environment(&self) -> bool {
|
||||
self.environment_id == DEFAULT_MCP_SERVER_ENVIRONMENT_ID
|
||||
}
|
||||
|
||||
/// Keeps local OAuth credentials compatible while reserving managed credential namespaces.
|
||||
pub fn oauth_credential_name<'a>(&self, server_name: &'a str) -> Cow<'a, str> {
|
||||
if self.is_local_environment() {
|
||||
if server_name.starts_with("executor:")
|
||||
|| server_name.starts_with("local:")
|
||||
|| server_name.starts_with("ema-idp:")
|
||||
{
|
||||
Cow::Owned(format!("local:{server_name}"))
|
||||
} else {
|
||||
Cow::Borrowed(server_name)
|
||||
}
|
||||
} else {
|
||||
let environment = URL_SAFE_NO_PAD.encode(self.environment_id.as_bytes());
|
||||
let server = URL_SAFE_NO_PAD.encode(server_name.as_bytes());
|
||||
Cow::Owned(format!("executor:{environment}:{server}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn oauth_client_id(&self) -> Option<&str> {
|
||||
self.oauth
|
||||
.as_ref()
|
||||
.and_then(|oauth| oauth.client_id.as_deref())
|
||||
}
|
||||
|
||||
pub fn oauth_client_secret(&self) -> Option<&str> {
|
||||
self.oauth
|
||||
.as_ref()
|
||||
.and_then(|oauth| oauth.client_secret.as_ref())
|
||||
.map(|secret| secret.as_str())
|
||||
}
|
||||
|
||||
pub fn oauth_callback_port(&self, global_callback_port: Option<u16>) -> Option<u16> {
|
||||
let callback_port = self.oauth.as_ref().and_then(|oauth| oauth.callback_port);
|
||||
if let Some(callback_port) = callback_port {
|
||||
tracing::info!(
|
||||
callback_port,
|
||||
?global_callback_port,
|
||||
"using plugin-specific MCP OAuth callback port instead of the global callback port"
|
||||
);
|
||||
}
|
||||
callback_port.or(global_callback_port)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw MCP config shape used for deserialization and supported-field JSON
|
||||
/// Schema generation.
|
||||
///
|
||||
/// Fields that are accepted only to produce targeted validation errors should
|
||||
/// be skipped in the generated schema.
|
||||
///
|
||||
/// Keep `TryFrom<RawMcpServerConfig> for McpServerConfig` exhaustively
|
||||
/// destructuring this struct so new TOML fields cannot be added here without
|
||||
/// updating the validation/mapping logic that produces [`McpServerConfig`].
|
||||
#[derive(Deserialize, Clone, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct RawMcpServerConfig {
|
||||
// stdio
|
||||
pub command: Option<String>,
|
||||
#[serde(default)]
|
||||
pub args: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub env: Option<HashMap<String, String>>,
|
||||
#[serde(default)]
|
||||
pub env_vars: Option<Vec<McpServerEnvVar>>,
|
||||
#[serde(default)]
|
||||
pub cwd: Option<LegacyAppPathString>,
|
||||
pub http_headers: Option<HashMap<String, String>>,
|
||||
#[serde(default)]
|
||||
pub env_http_headers: Option<HashMap<String, String>>,
|
||||
|
||||
// streamable_http
|
||||
pub url: Option<String>,
|
||||
#[schemars(skip)]
|
||||
pub bearer_token: Option<String>,
|
||||
pub bearer_token_env_var: Option<String>,
|
||||
pub http_headers_helper: Option<String>,
|
||||
|
||||
// shared
|
||||
#[serde(default)]
|
||||
pub environment_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub auth: Option<McpServerAuth>,
|
||||
#[serde(default)]
|
||||
pub startup_timeout_sec: Option<f64>,
|
||||
#[serde(default)]
|
||||
pub startup_timeout_ms: Option<u64>,
|
||||
#[serde(default, with = "option_duration_secs")]
|
||||
#[schemars(with = "Option<f64>")]
|
||||
pub tool_timeout_sec: Option<Duration>,
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub required: Option<bool>,
|
||||
/// Whether startup requires a live connection or can use a valid cached tool catalog.
|
||||
#[serde(default)]
|
||||
pub startup_readiness: Option<McpStartupReadiness>,
|
||||
#[serde(default)]
|
||||
pub supports_parallel_tool_calls: Option<bool>,
|
||||
/// UTF-8 byte threshold for compacting each ordinary MCP tool input schema. Defaults to 5,000 bytes.
|
||||
/// Code Mode also uses an explicitly configured limit when rendering each tool's input type.
|
||||
/// Larger limits preserve more parameter descriptions.
|
||||
#[serde(default)]
|
||||
#[schemars(range(min = 1))]
|
||||
pub tool_input_schema_max_bytes: Option<NonZeroUsize>,
|
||||
#[serde(default)]
|
||||
pub omit_tools_from: Option<Vec<ToolExposureSurface>>,
|
||||
#[serde(default)]
|
||||
pub default_tools_approval_mode: Option<AppToolApproval>,
|
||||
#[serde(default)]
|
||||
pub enabled_tools: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub disabled_tools: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub scopes: Option<Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub oauth: Option<McpServerOAuthConfig>,
|
||||
#[serde(default)]
|
||||
pub oauth_resource: Option<String>,
|
||||
/// Legacy display-name field accepted for backward compatibility.
|
||||
#[serde(default, rename = "name")]
|
||||
pub _name: Option<String>,
|
||||
#[serde(default)]
|
||||
pub tools: Option<HashMap<String, McpServerToolConfig>>,
|
||||
}
|
||||
|
||||
impl TryFrom<RawMcpServerConfig> for McpServerConfig {
|
||||
type Error = String;
|
||||
|
||||
fn try_from(raw: RawMcpServerConfig) -> Result<Self, Self::Error> {
|
||||
let RawMcpServerConfig {
|
||||
command,
|
||||
args,
|
||||
env,
|
||||
env_vars,
|
||||
cwd,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
url,
|
||||
bearer_token,
|
||||
bearer_token_env_var,
|
||||
http_headers_helper,
|
||||
environment_id,
|
||||
auth,
|
||||
startup_timeout_sec,
|
||||
startup_timeout_ms,
|
||||
tool_timeout_sec,
|
||||
enabled,
|
||||
required,
|
||||
startup_readiness,
|
||||
supports_parallel_tool_calls,
|
||||
tool_input_schema_max_bytes,
|
||||
omit_tools_from,
|
||||
default_tools_approval_mode,
|
||||
enabled_tools,
|
||||
disabled_tools,
|
||||
scopes,
|
||||
oauth,
|
||||
oauth_resource,
|
||||
_name: _,
|
||||
tools,
|
||||
} = raw;
|
||||
|
||||
let startup_timeout_sec = match (startup_timeout_sec, startup_timeout_ms) {
|
||||
(Some(sec), _) => {
|
||||
Some(Duration::try_from_secs_f64(sec).map_err(|err| err.to_string())?)
|
||||
}
|
||||
(None, Some(ms)) => Some(Duration::from_millis(ms)),
|
||||
(None, None) => None,
|
||||
};
|
||||
|
||||
fn throw_if_set<T>(transport: &str, field: &str, value: Option<&T>) -> Result<(), String> {
|
||||
if value.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!("{field} is not supported for {transport}"))
|
||||
}
|
||||
|
||||
let transport = if let Some(command) = command {
|
||||
throw_if_set("stdio", "url", url.as_ref())?;
|
||||
throw_if_set(
|
||||
"stdio",
|
||||
"bearer_token_env_var",
|
||||
bearer_token_env_var.as_ref(),
|
||||
)?;
|
||||
throw_if_set("stdio", "bearer_token", bearer_token.as_ref())?;
|
||||
throw_if_set("stdio", "http_headers_helper", http_headers_helper.as_ref())?;
|
||||
throw_if_set("stdio", "http_headers", http_headers.as_ref())?;
|
||||
throw_if_set("stdio", "env_http_headers", env_http_headers.as_ref())?;
|
||||
throw_if_set("stdio", "oauth", oauth.as_ref())?;
|
||||
throw_if_set("stdio", "oauth_resource", oauth_resource.as_ref())?;
|
||||
throw_if_set("stdio", "auth", auth.as_ref())?;
|
||||
let env_vars = env_vars.unwrap_or_default();
|
||||
for env_var in &env_vars {
|
||||
env_var.validate_source()?;
|
||||
}
|
||||
McpServerTransportConfig::Stdio {
|
||||
command,
|
||||
args: args.unwrap_or_default(),
|
||||
env,
|
||||
env_vars,
|
||||
cwd,
|
||||
}
|
||||
} else if let Some(url) = url {
|
||||
throw_if_set("streamable_http", "args", args.as_ref())?;
|
||||
throw_if_set("streamable_http", "env", env.as_ref())?;
|
||||
throw_if_set("streamable_http", "env_vars", env_vars.as_ref())?;
|
||||
throw_if_set("streamable_http", "cwd", cwd.as_ref())?;
|
||||
throw_if_set("streamable_http", "bearer_token", bearer_token.as_ref())?;
|
||||
if http_headers_helper
|
||||
.as_deref()
|
||||
.is_some_and(|command| command.trim().is_empty())
|
||||
{
|
||||
return Err("http_headers_helper must not be empty".to_string());
|
||||
}
|
||||
if environment_id
|
||||
.as_deref()
|
||||
.is_some_and(|environment_id| environment_id != DEFAULT_MCP_SERVER_ENVIRONMENT_ID)
|
||||
&& http_headers_helper.is_some()
|
||||
{
|
||||
return Err(
|
||||
"http_headers_helper is only supported for local MCP servers".to_string(),
|
||||
);
|
||||
}
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url,
|
||||
bearer_token_env_var,
|
||||
http_headers,
|
||||
env_http_headers,
|
||||
http_headers_helper,
|
||||
}
|
||||
} else {
|
||||
return Err("invalid transport".to_string());
|
||||
};
|
||||
|
||||
let environment_id =
|
||||
environment_id.unwrap_or_else(|| DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string());
|
||||
let auth = auth.unwrap_or_default();
|
||||
if let Some(oauth) = &oauth
|
||||
&& let Some(client_secret) = &oauth.client_secret
|
||||
{
|
||||
if client_secret.trim().is_empty() {
|
||||
return Err("oauth.client_secret must not be empty".to_string());
|
||||
}
|
||||
if oauth
|
||||
.client_id
|
||||
.as_deref()
|
||||
.is_none_or(|client_id| client_id.trim().is_empty())
|
||||
{
|
||||
return Err("oauth.client_secret requires oauth.client_id".to_string());
|
||||
}
|
||||
}
|
||||
if let Some(oauth) = &oauth
|
||||
&& oauth.token_endpoint_auth_method.is_some()
|
||||
{
|
||||
if !matches!(auth, McpServerAuth::EmaAuth) {
|
||||
return Err(
|
||||
"oauth.token_endpoint_auth_method requires auth = \"ema_auth\"".to_string(),
|
||||
);
|
||||
}
|
||||
if oauth.client_secret.is_none() {
|
||||
return Err(
|
||||
"oauth.token_endpoint_auth_method requires oauth.client_secret".to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
if !matches!(auth, McpServerAuth::EmaAuth)
|
||||
&& oauth
|
||||
.as_ref()
|
||||
.is_some_and(|oauth| oauth.authorization_server_issuer.is_some())
|
||||
{
|
||||
return Err(
|
||||
"oauth.authorization_server_issuer requires auth = \"ema_auth\"".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
transport,
|
||||
auth,
|
||||
environment_id,
|
||||
startup_timeout_sec,
|
||||
tool_timeout_sec,
|
||||
enabled: enabled.unwrap_or_else(default_enabled),
|
||||
required: required.unwrap_or_default(),
|
||||
startup_readiness: startup_readiness.unwrap_or_default(),
|
||||
supports_parallel_tool_calls: supports_parallel_tool_calls.unwrap_or_default(),
|
||||
tool_input_schema_max_bytes,
|
||||
omit_tools_from,
|
||||
disabled_reason: None,
|
||||
default_tools_approval_mode,
|
||||
enabled_tools,
|
||||
disabled_tools,
|
||||
scopes,
|
||||
oauth,
|
||||
oauth_resource,
|
||||
tools: tools.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for McpServerConfig {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
RawMcpServerConfig::deserialize(deserializer)?
|
||||
.try_into()
|
||||
.map_err(SerdeError::custom)
|
||||
}
|
||||
}
|
||||
|
||||
const fn default_enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, JsonSchema)]
|
||||
#[serde(untagged, deny_unknown_fields, rename_all = "snake_case")]
|
||||
pub enum McpServerTransportConfig {
|
||||
/// https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#stdio
|
||||
Stdio {
|
||||
command: String,
|
||||
#[serde(default)]
|
||||
args: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
env: Option<HashMap<String, String>>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
env_vars: Vec<McpServerEnvVar>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cwd: Option<LegacyAppPathString>,
|
||||
},
|
||||
/// https://modelcontextprotocol.io/specification/2025-06-18/basic/transports#streamable-http
|
||||
StreamableHttp {
|
||||
url: String,
|
||||
/// Name of the environment variable to read for an HTTP bearer token.
|
||||
/// When set, requests will include the token via `Authorization: Bearer <token>`.
|
||||
/// The actual secret value must be provided via the environment.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
bearer_token_env_var: Option<String>,
|
||||
/// Additional HTTP headers to include in requests to this server.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
http_headers: Option<HashMap<String, String>>,
|
||||
/// HTTP headers where the value is sourced from an environment variable.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
env_http_headers: Option<HashMap<String, String>>,
|
||||
/// Local-only shell command that prints a JSON object of dynamic HTTP headers.
|
||||
/// The command may be visible to local process inspection; do not embed credentials.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
http_headers_helper: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
mod option_duration_secs {
|
||||
use serde::Deserialize;
|
||||
use serde::Deserializer;
|
||||
use serde::Serializer;
|
||||
use std::time::Duration;
|
||||
|
||||
pub fn serialize<S>(value: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match value {
|
||||
Some(duration) => serializer.serialize_some(&duration.as_secs_f64()),
|
||||
None => serializer.serialize_none(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let secs = Option::<f64>::deserialize(deserializer)?;
|
||||
secs.map(|secs| Duration::try_from_secs_f64(secs).map_err(serde::de::Error::custom))
|
||||
.transpose()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mcp_types_tests.rs"]
|
||||
mod tests;
|
||||
743
codex-rs/config/src/mcp_types_tests.rs
Normal file
743
codex-rs/config/src/mcp_types_tests.rs
Normal file
@@ -0,0 +1,743 @@
|
||||
use super::*;
|
||||
use codex_utils_path_uri::LegacyAppPathString;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
|
||||
#[test]
|
||||
fn app_tool_approval_restrictions_never_weaken_either_policy() {
|
||||
use AppToolApproval::Approve;
|
||||
use AppToolApproval::Auto;
|
||||
use AppToolApproval::Prompt;
|
||||
use AppToolApproval::Writes;
|
||||
|
||||
let modes = [Approve, Auto, Writes, Prompt];
|
||||
let expected = [
|
||||
[Approve, Auto, Writes, Prompt],
|
||||
[Auto, Auto, Prompt, Prompt],
|
||||
[Writes, Prompt, Writes, Prompt],
|
||||
[Prompt, Prompt, Prompt, Prompt],
|
||||
];
|
||||
|
||||
for (parent_index, parent) in modes.into_iter().enumerate() {
|
||||
for (requested_index, requested) in modes.into_iter().enumerate() {
|
||||
assert_eq!(
|
||||
parent.restrict_to(requested),
|
||||
expected[parent_index][requested_index],
|
||||
"parent: {parent:?}, requested: {requested:?}",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize command config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec![],
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
}
|
||||
);
|
||||
assert!(cfg.enabled);
|
||||
assert!(!cfg.required);
|
||||
assert_eq!(cfg.omit_tools_from, None);
|
||||
assert!(cfg.enabled_tools.is_none());
|
||||
assert!(cfg.disabled_tools.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config_with_args() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
args = ["hello", "world"]
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize command config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec!["hello".to_string(), "world".to_string()],
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
}
|
||||
);
|
||||
assert!(cfg.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_remote_stdio_server_accepts_foreign_absolute_cwd() {
|
||||
#[cfg(not(windows))]
|
||||
let cwd = r"C:\Users\openai\share";
|
||||
#[cfg(windows)]
|
||||
let cwd = "/home/openai/share";
|
||||
let expected_cwd = LegacyAppPathString::from_path(Path::new(cwd));
|
||||
let cfg: McpServerConfig = match toml::from_str(&format!(
|
||||
r#"
|
||||
command = "echo"
|
||||
environment_id = "remote"
|
||||
cwd = {cwd:?}
|
||||
"#
|
||||
)) {
|
||||
Ok(cfg) => cfg,
|
||||
Err(error) => panic!("remote stdio MCP should accept absolute cwd: {error}"),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec![],
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: Some(expected_cwd),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config_with_arg_with_args_and_env() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
args = ["hello", "world"]
|
||||
env = { "FOO" = "BAR" }
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize command config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec!["hello".to_string(), "world".to_string()],
|
||||
env: Some(HashMap::from([("FOO".to_string(), "BAR".to_string())])),
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
}
|
||||
);
|
||||
assert!(cfg.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config_with_env_vars() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
env_vars = ["FOO", "BAR"]
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize command config with env_vars");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec![],
|
||||
env: None,
|
||||
env_vars: vec!["FOO".into(), "BAR".into()],
|
||||
cwd: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config_with_env_var_sources() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
env_vars = [
|
||||
"LEGACY_TOKEN",
|
||||
{ name = "LOCAL_TOKEN", source = "local" },
|
||||
{ name = "REMOTE_TOKEN", source = "remote" },
|
||||
]
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize command config with sourced env_vars");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec![],
|
||||
env: None,
|
||||
env_vars: vec![
|
||||
McpServerEnvVar::Name("LEGACY_TOKEN".to_string()),
|
||||
McpServerEnvVar::Config {
|
||||
name: "LOCAL_TOKEN".to_string(),
|
||||
source: Some("local".to_string()),
|
||||
},
|
||||
McpServerEnvVar::Config {
|
||||
name: "REMOTE_TOKEN".to_string(),
|
||||
source: Some("remote".to_string()),
|
||||
},
|
||||
],
|
||||
cwd: None,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config_rejects_unknown_env_var_source() {
|
||||
let err = toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
command = "echo"
|
||||
env_vars = [{ name = "TOKEN", source = "elsewhere" }]
|
||||
"#,
|
||||
)
|
||||
.expect_err("unsupported env var source should be rejected");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("unsupported env_vars source `elsewhere`"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_stdio_command_server_config_with_cwd() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
cwd = "/tmp"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize command config with cwd");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec![],
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: Some(LegacyAppPathString::from_path(Path::new("/tmp"))),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_disabled_server_config() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
enabled = false
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize disabled server config");
|
||||
|
||||
assert!(!cfg.enabled);
|
||||
assert!(!cfg.required);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_required_server_config() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
required = true
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize required server config");
|
||||
|
||||
assert!(cfg.required);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_streamable_http_server_config() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url: "https://example.com/mcp".to_string(),
|
||||
bearer_token_env_var: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
http_headers_helper: None,
|
||||
}
|
||||
);
|
||||
assert!(cfg.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_streamable_http_server_config_with_env_var() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
bearer_token_env_var = "GITHUB_TOKEN"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url: "https://example.com/mcp".to_string(),
|
||||
bearer_token_env_var: Some("GITHUB_TOKEN".to_string()),
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
http_headers_helper: None,
|
||||
}
|
||||
);
|
||||
assert!(cfg.enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_streamable_http_server_config_with_headers() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
http_headers = { "X-Foo" = "bar" }
|
||||
env_http_headers = { "X-Token" = "TOKEN_ENV" }
|
||||
http_headers_helper = "auth-cli headers"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config with headers");
|
||||
|
||||
assert_eq!(
|
||||
cfg.transport,
|
||||
McpServerTransportConfig::StreamableHttp {
|
||||
url: "https://example.com/mcp".to_string(),
|
||||
bearer_token_env_var: None,
|
||||
http_headers: Some(HashMap::from([("X-Foo".to_string(), "bar".to_string())])),
|
||||
env_http_headers: Some(HashMap::from([(
|
||||
"X-Token".to_string(),
|
||||
"TOKEN_ENV".to_string()
|
||||
)])),
|
||||
http_headers_helper: Some("auth-cli headers".to_string()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_http_headers_helper_outside_local_http_servers() {
|
||||
for contents in [
|
||||
"command = \"server\"\nhttp_headers_helper = \"auth-cli headers\"",
|
||||
"url = \"https://example.com/mcp\"\nhttp_headers_helper = \" \"",
|
||||
"url = \"https://example.com/mcp\"\nenvironment_id = \"remote\"\nhttp_headers_helper = \"auth-cli headers\"",
|
||||
] {
|
||||
toml::from_str::<McpServerConfig>(contents).expect_err("invalid helper placement");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_streamable_http_server_config_with_oauth_resource() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
oauth_resource = "https://api.example.com"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config with oauth_resource");
|
||||
|
||||
assert_eq!(
|
||||
cfg.oauth_resource,
|
||||
Some("https://api.example.com".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_streamable_http_server_config_with_oauth_client_id() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
|
||||
[oauth]
|
||||
client_id = "eci-prd-pub-codex-123"
|
||||
callback_url = "http://127.0.0.1/callback/registered"
|
||||
callback_port = 9876
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config with oauth client id");
|
||||
|
||||
assert_eq!(
|
||||
cfg.oauth,
|
||||
Some(McpServerOAuthConfig {
|
||||
client_id: Some("eci-prd-pub-codex-123".to_string()),
|
||||
callback_url: Some("http://127.0.0.1/callback/registered".to_string()),
|
||||
callback_port: Some(9876),
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_client_secret_round_trips_without_debug_disclosure() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
|
||||
[oauth]
|
||||
client_id = "confidential-client"
|
||||
client_secret = "test-client-secret"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize an OAuth client secret");
|
||||
assert_eq!(
|
||||
cfg.oauth,
|
||||
Some(McpServerOAuthConfig {
|
||||
client_id: Some("confidential-client".to_string()),
|
||||
client_secret: Some("test-client-secret".into()),
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
assert_eq!(cfg.oauth_client_secret(), Some("test-client-secret"));
|
||||
|
||||
let serialized = serde_json::to_value(&cfg).expect("serialize server as JSON");
|
||||
assert_eq!(
|
||||
serialized["oauth"],
|
||||
serde_json::json!({
|
||||
"client_id": "confidential-client",
|
||||
"client_secret": "test-client-secret"
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<McpServerConfig>(serialized).expect("deserialize JSON"),
|
||||
cfg
|
||||
);
|
||||
assert_eq!(
|
||||
toml::from_str::<McpServerConfig>(&toml::to_string(&cfg).expect("serialize TOML"))
|
||||
.expect("deserialize TOML"),
|
||||
cfg
|
||||
);
|
||||
|
||||
let debug = format!("{cfg:?}");
|
||||
assert!(!debug.contains("test-client-secret"));
|
||||
assert!(debug.contains("client_secret: Some(<redacted>)"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_client_secret_requires_nonempty_secret_and_client_id() {
|
||||
for (oauth, expected) in [
|
||||
(
|
||||
serde_json::json!({"client_id": "client", "client_secret": ""}),
|
||||
"oauth.client_secret must not be empty",
|
||||
),
|
||||
(
|
||||
serde_json::json!({"client_id": "client", "client_secret": " \t"}),
|
||||
"oauth.client_secret must not be empty",
|
||||
),
|
||||
(
|
||||
serde_json::json!({"client_secret": "test-client-secret"}),
|
||||
"oauth.client_secret requires oauth.client_id",
|
||||
),
|
||||
(
|
||||
serde_json::json!({"client_id": "", "client_secret": "test-client-secret"}),
|
||||
"oauth.client_secret requires oauth.client_id",
|
||||
),
|
||||
(
|
||||
serde_json::json!({"client_id": " \t", "client_secret": "test-client-secret"}),
|
||||
"oauth.client_secret requires oauth.client_id",
|
||||
),
|
||||
] {
|
||||
let err = serde_json::from_value::<McpServerConfig>(serde_json::json!({
|
||||
"url": "https://example.com/mcp",
|
||||
"oauth": oauth
|
||||
}))
|
||||
.expect_err("should reject invalid OAuth client credentials");
|
||||
assert_eq!(err.to_string(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_callback_port_prefers_server_port_over_global_port() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
|
||||
[oauth]
|
||||
callback_port = 9876
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config with oauth callback port");
|
||||
|
||||
assert_eq!(cfg.oauth_callback_port(Some(4321)), Some(9876));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oauth_callback_port_falls_back_to_global_port() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
url = "https://example.com/mcp"
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize http config without oauth callback port");
|
||||
|
||||
assert_eq!(cfg.oauth_callback_port(Some(4321)), Some(4321));
|
||||
assert_eq!(cfg.oauth_callback_port(/*global_callback_port*/ None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_server_config_with_tool_filters() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
enabled_tools = ["allowed"]
|
||||
disabled_tools = ["blocked"]
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize tool filters");
|
||||
|
||||
assert_eq!(cfg.enabled_tools, Some(vec!["allowed".to_string()]));
|
||||
assert_eq!(cfg.disabled_tools, Some(vec!["blocked".to_string()]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_server_config_with_parallel_tool_calls() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
supports_parallel_tool_calls = true
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize supports_parallel_tool_calls");
|
||||
|
||||
assert!(cfg.supports_parallel_tool_calls);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialize_round_trips_server_config_with_omitted_tool_exposure_surfaces() {
|
||||
for omitted_surfaces in [
|
||||
vec![],
|
||||
vec![ToolExposureSurface::CodeMode],
|
||||
vec![ToolExposureSurface::Deferred],
|
||||
vec![ToolExposureSurface::Direct],
|
||||
vec![ToolExposureSurface::CodeMode, ToolExposureSurface::Deferred],
|
||||
vec![ToolExposureSurface::CodeMode, ToolExposureSurface::Direct],
|
||||
vec![ToolExposureSurface::Deferred, ToolExposureSurface::Direct],
|
||||
vec![
|
||||
ToolExposureSurface::CodeMode,
|
||||
ToolExposureSurface::Deferred,
|
||||
ToolExposureSurface::Direct,
|
||||
],
|
||||
] {
|
||||
let serialized_surfaces = omitted_surfaces
|
||||
.iter()
|
||||
.map(|surface| format!("\"{surface}\""))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let config = format!("command = \"echo\"\nomit_tools_from = [{serialized_surfaces}]\n");
|
||||
let cfg: McpServerConfig =
|
||||
toml::from_str(&config).expect("should deserialize omitted MCP exposure surfaces");
|
||||
assert_eq!(cfg.omit_tools_from, Some(omitted_surfaces.clone()));
|
||||
|
||||
let serialized = toml::to_string(&cfg).expect("should serialize MCP config");
|
||||
assert!(serialized.contains(&format!("omit_tools_from = [{serialized_surfaces}]")));
|
||||
|
||||
let round_tripped: McpServerConfig =
|
||||
toml::from_str(&serialized).expect("should deserialize serialized MCP config");
|
||||
assert_eq!(round_tripped, cfg);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_server_config_with_default_tool_approval_mode() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
default_tools_approval_mode = "approve"
|
||||
|
||||
[tools.search]
|
||||
approval_mode = "prompt"
|
||||
output_token_limit = 30000
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize default tool approval mode");
|
||||
|
||||
assert_eq!(
|
||||
cfg.default_tools_approval_mode,
|
||||
Some(AppToolApproval::Approve)
|
||||
);
|
||||
assert_eq!(
|
||||
cfg.tools.get("search"),
|
||||
Some(&McpServerToolConfig {
|
||||
approval_mode: Some(AppToolApproval::Prompt),
|
||||
output_token_limit: std::num::NonZeroUsize::new(30_000),
|
||||
})
|
||||
);
|
||||
|
||||
let serialized = toml::to_string(&cfg).expect("should serialize MCP config");
|
||||
assert!(serialized.contains("default_tools_approval_mode = \"approve\""));
|
||||
assert!(serialized.contains("output_token_limit = 30000"));
|
||||
|
||||
let round_tripped: McpServerConfig =
|
||||
toml::from_str(&serialized).expect("should deserialize serialized MCP config");
|
||||
assert_eq!(round_tripped, cfg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_rejects_nonpositive_mcp_tool_output_limits() {
|
||||
for output_token_limit in [0, -1] {
|
||||
let config = format!(
|
||||
"command = \"echo\"\n[tools.search]\noutput_token_limit = {output_token_limit}\n"
|
||||
);
|
||||
let error = toml::from_str::<McpServerConfig>(&config)
|
||||
.expect_err("MCP tool output limit must be positive");
|
||||
assert!(error.to_string().contains("output_token_limit"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialize_round_trips_server_config_with_parallel_tool_calls() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
supports_parallel_tool_calls = true
|
||||
tool_timeout_sec = 2.0
|
||||
"#,
|
||||
)
|
||||
.expect("should deserialize supports_parallel_tool_calls");
|
||||
|
||||
let serialized = toml::to_string(&cfg).expect("should serialize MCP config");
|
||||
assert!(serialized.contains("supports_parallel_tool_calls = true"));
|
||||
|
||||
let round_tripped: McpServerConfig =
|
||||
toml::from_str(&serialized).expect("should deserialize serialized MCP config");
|
||||
assert_eq!(round_tripped, cfg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_ignores_unknown_server_fields() {
|
||||
let cfg: McpServerConfig = toml::from_str(
|
||||
r#"
|
||||
command = "echo"
|
||||
trust_level = "trusted"
|
||||
"#,
|
||||
)
|
||||
.expect("should ignore unknown server fields");
|
||||
|
||||
assert_eq!(
|
||||
cfg,
|
||||
McpServerConfig {
|
||||
auth: Default::default(),
|
||||
transport: McpServerTransportConfig::Stdio {
|
||||
command: "echo".to_string(),
|
||||
args: vec![],
|
||||
env: None,
|
||||
env_vars: Vec::new(),
|
||||
cwd: None,
|
||||
},
|
||||
environment_id: crate::DEFAULT_MCP_SERVER_ENVIRONMENT_ID.to_string(),
|
||||
enabled: true,
|
||||
required: false,
|
||||
startup_readiness: Default::default(),
|
||||
supports_parallel_tool_calls: false,
|
||||
tool_input_schema_max_bytes: None,
|
||||
omit_tools_from: None,
|
||||
disabled_reason: None,
|
||||
startup_timeout_sec: None,
|
||||
tool_timeout_sec: None,
|
||||
default_tools_approval_mode: None,
|
||||
enabled_tools: None,
|
||||
disabled_tools: None,
|
||||
scopes: None,
|
||||
oauth: None,
|
||||
oauth_resource: None,
|
||||
tools: HashMap::new(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_rejects_command_and_url() {
|
||||
toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
command = "echo"
|
||||
url = "https://example.com"
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject command+url");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_rejects_env_for_http_transport() {
|
||||
toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
url = "https://example.com"
|
||||
env = { "FOO" = "BAR" }
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject env for http transport");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_rejects_headers_for_stdio() {
|
||||
toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
command = "echo"
|
||||
http_headers = { "X-Foo" = "bar" }
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject http_headers for stdio transport");
|
||||
|
||||
toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
command = "echo"
|
||||
env_http_headers = { "X-Foo" = "BAR_ENV" }
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject env_http_headers for stdio transport");
|
||||
|
||||
let err = toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
command = "echo"
|
||||
oauth = { client_id = "eci-prd-pub-codex-123" }
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject oauth for stdio transport");
|
||||
|
||||
assert!(
|
||||
err.to_string().contains("oauth is not supported for stdio"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
|
||||
let err = toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
command = "echo"
|
||||
oauth_resource = "https://api.example.com"
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject oauth_resource for stdio transport");
|
||||
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("oauth_resource is not supported for stdio"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_rejects_inline_bearer_token_field() {
|
||||
let err = toml::from_str::<McpServerConfig>(
|
||||
r#"
|
||||
url = "https://example.com"
|
||||
bearer_token = "secret"
|
||||
"#,
|
||||
)
|
||||
.expect_err("should reject bearer_token field");
|
||||
|
||||
assert!(
|
||||
err.to_string().contains("bearer_token is not supported"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
239
codex-rs/config/src/merge.rs
Normal file
239
codex-rs/config/src/merge.rs
Normal file
@@ -0,0 +1,239 @@
|
||||
use crate::key_aliases::normalize_base_key_aliases;
|
||||
use crate::key_aliases::normalize_key_aliases;
|
||||
use codex_network_proxy::normalize_host;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
/// The mutually exclusive shell-environment filter representations.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ShellEnvironmentPolicyFilterRepresentation {
|
||||
Filters,
|
||||
Legacy,
|
||||
}
|
||||
|
||||
impl ShellEnvironmentPolicyFilterRepresentation {
|
||||
/// Returns the representation selected by a policy table, including empty fields.
|
||||
pub fn from_policy(policy: &TomlValue) -> Option<Self> {
|
||||
let policy = policy.as_table()?;
|
||||
if policy.contains_key("filters") {
|
||||
Some(Self::Filters)
|
||||
} else if policy.contains_key("exclude") || policy.contains_key("include_only") {
|
||||
Some(Self::Legacy)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the representation addressed by a dotted config path.
|
||||
pub fn from_path(path: &[String]) -> Option<Self> {
|
||||
match path {
|
||||
[policy, field, ..] if policy == "shell_environment_policy" => match field.as_str() {
|
||||
"filters" => Some(Self::Filters),
|
||||
"exclude" | "include_only" => Some(Self::Legacy),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the representation selected by an edit at `path`.
|
||||
pub fn from_edit(path: &[String], value: &TomlValue) -> Option<Self> {
|
||||
if matches!(path, [policy] if policy == "shell_environment_policy") {
|
||||
Self::from_policy(value)
|
||||
} else {
|
||||
Self::from_path(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the policy fields that must be removed when this representation is selected.
|
||||
pub fn displaced_fields(self) -> &'static [&'static str] {
|
||||
match self {
|
||||
Self::Filters => &["exclude", "include_only"],
|
||||
Self::Legacy => &["filters"],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Merge config `overlay` into `base`, giving `overlay` precedence.
|
||||
pub fn merge_toml_values(base: &mut TomlValue, overlay: &TomlValue) {
|
||||
let overlay = normalize_key_aliases(overlay);
|
||||
normalize_base_key_aliases(base, &overlay, &mut Vec::new());
|
||||
merge_toml_values_at_path(base, overlay, &mut Vec::new());
|
||||
}
|
||||
|
||||
pub fn is_structured_feature_path<S: AsRef<str>>(path: &[S]) -> bool {
|
||||
let (features, feature) = match path {
|
||||
[profiles, _, features, feature] if profiles.as_ref() == "profiles" => (features, feature),
|
||||
[features, feature] => (features, feature),
|
||||
_ => return false,
|
||||
};
|
||||
|
||||
features.as_ref() == "features"
|
||||
&& matches!(
|
||||
feature.as_ref(),
|
||||
"code_mode"
|
||||
| "multi_agent_v2"
|
||||
| "network_proxy"
|
||||
| "sleep_tool"
|
||||
| "runtime_agent_instances"
|
||||
)
|
||||
}
|
||||
|
||||
fn merge_toml_values_at_path(base: &mut TomlValue, overlay: TomlValue, path: &mut Vec<String>) {
|
||||
replace_shell_environment_policy_filter_representation(base, &overlay, path);
|
||||
|
||||
if is_structured_feature_path(path) {
|
||||
if let TomlValue::Boolean(enabled) = base
|
||||
&& overlay.is_table()
|
||||
{
|
||||
*base = TomlValue::Table(toml::map::Map::from_iter([(
|
||||
"enabled".to_string(),
|
||||
TomlValue::Boolean(*enabled),
|
||||
)]));
|
||||
} else if let TomlValue::Table(table) = base
|
||||
&& let TomlValue::Boolean(enabled) = overlay
|
||||
{
|
||||
table.insert("enabled".to_string(), TomlValue::Boolean(enabled));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if let TomlValue::Table(base_table) = &mut *base
|
||||
&& let TomlValue::Table(mut overlay_table) = overlay
|
||||
{
|
||||
if is_network_domains_path(path) {
|
||||
normalize_network_domain_keys(base_table);
|
||||
normalize_network_domain_keys(&mut overlay_table);
|
||||
}
|
||||
if is_shell_environment_filters_path(path) {
|
||||
normalize_case_insensitive_keys(base_table);
|
||||
normalize_case_insensitive_keys(&mut overlay_table);
|
||||
}
|
||||
if path.split_last().is_some_and(|(field, feature_path)| {
|
||||
field == "credentials" && is_structured_feature_path(feature_path)
|
||||
}) {
|
||||
for (provider_id, provider) in &overlay_table {
|
||||
let Some(overlay_sources) = provider.get("env").and_then(TomlValue::as_array)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
base_table.retain(|existing_id, existing| {
|
||||
existing_id == provider_id
|
||||
|| !overlay_table
|
||||
.get(existing_id)
|
||||
.and_then(|provider| provider.get("env"))
|
||||
.or_else(|| existing.get("env"))
|
||||
.and_then(TomlValue::as_array)
|
||||
.is_some_and(|existing_sources| {
|
||||
existing_sources.iter().filter_map(TomlValue::as_str).any(
|
||||
|existing_source| {
|
||||
overlay_sources.iter().filter_map(TomlValue::as_str).any(
|
||||
|overlay_source| {
|
||||
existing_source == overlay_source
|
||||
|| cfg!(windows)
|
||||
&& existing_source
|
||||
.eq_ignore_ascii_case(overlay_source)
|
||||
},
|
||||
)
|
||||
},
|
||||
)
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
for (key, value) in overlay_table {
|
||||
path.push(key.clone());
|
||||
if let Some(existing) = base_table.get_mut(&key) {
|
||||
merge_toml_values_at_path(existing, value, path);
|
||||
} else {
|
||||
base_table.insert(key, value);
|
||||
}
|
||||
path.pop();
|
||||
}
|
||||
} else {
|
||||
*base = overlay;
|
||||
}
|
||||
}
|
||||
|
||||
fn is_shell_environment_filters_path(path: &[String]) -> bool {
|
||||
matches!(
|
||||
path,
|
||||
[policy, filters]
|
||||
if policy == "shell_environment_policy" && filters == "filters"
|
||||
)
|
||||
}
|
||||
|
||||
/// Switching between legacy arrays and keyed filters replaces lower filter
|
||||
/// fields instead of attempting to reconcile the two representations. Legacy
|
||||
/// arrays already replace wholesale, so reconciling them would add merge
|
||||
/// semantics that the legacy representation never supported.
|
||||
fn replace_shell_environment_policy_filter_representation(
|
||||
base: &mut TomlValue,
|
||||
overlay: &TomlValue,
|
||||
path: &[String],
|
||||
) {
|
||||
if !matches!(path, [policy] if policy == "shell_environment_policy") {
|
||||
return;
|
||||
}
|
||||
let Some(overlay_representation) =
|
||||
ShellEnvironmentPolicyFilterRepresentation::from_policy(overlay)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let TomlValue::Table(base) = base else {
|
||||
return;
|
||||
};
|
||||
|
||||
for field in overlay_representation.displaced_fields() {
|
||||
base.remove(*field);
|
||||
}
|
||||
}
|
||||
|
||||
/// Looks up a shell-environment filter pattern while ignoring case.
|
||||
pub fn shell_environment_filter_entry<'a>(
|
||||
root: &'a TomlValue,
|
||||
path: &[String],
|
||||
) -> Option<(&'a String, &'a TomlValue)> {
|
||||
let [policy, filters, pattern] = path else {
|
||||
return None;
|
||||
};
|
||||
if policy != "shell_environment_policy" || filters != "filters" {
|
||||
return None;
|
||||
}
|
||||
|
||||
let pattern = pattern.to_lowercase();
|
||||
root.get(policy)?
|
||||
.get(filters)?
|
||||
.as_table()?
|
||||
.iter()
|
||||
.find(|(candidate, _)| candidate.to_lowercase() == pattern)
|
||||
}
|
||||
|
||||
fn is_network_domains_path(path: &[String]) -> bool {
|
||||
matches!(
|
||||
path,
|
||||
[permissions, _, network, domains]
|
||||
if permissions == "permissions" && network == "network" && domains == "domains"
|
||||
) || matches!(
|
||||
path,
|
||||
[application, network, domains]
|
||||
if application == "application" && network == "network" && domains == "domains"
|
||||
)
|
||||
}
|
||||
|
||||
fn normalize_network_domain_keys(table: &mut toml::map::Map<String, TomlValue>) {
|
||||
let entries = std::mem::take(table);
|
||||
for (pattern, value) in entries {
|
||||
table.insert(normalize_host(&pattern), value);
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_case_insensitive_keys(table: &mut toml::map::Map<String, TomlValue>) {
|
||||
let entries = std::mem::take(table);
|
||||
for (key, value) in entries {
|
||||
table.insert(key.to_lowercase(), value);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "merge_tests.rs"]
|
||||
mod tests;
|
||||
753
codex-rs/config/src/merge_tests.rs
Normal file
753
codex-rs/config/src/merge_tests.rs
Normal file
@@ -0,0 +1,753 @@
|
||||
use super::*;
|
||||
use crate::config_toml::AgentsToml;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::types::MemoriesToml;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn parse_toml(value: &str) -> TomlValue {
|
||||
toml::from_str(value).expect("TOML should parse")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_toml_values_normalizes_legacy_key_from_base_layer() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
no_memories_if_mcp_or_web_search = false
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
disable_on_external_context = true
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let expected = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
disable_on_external_context = true
|
||||
"#,
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
|
||||
let config: ConfigToml = base.try_into().expect("merged config should deserialize");
|
||||
assert_eq!(
|
||||
config.memories,
|
||||
Some(MemoriesToml {
|
||||
disable_on_external_context: Some(true),
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_toml_values_normalizes_legacy_key_from_overlay_layer() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
disable_on_external_context = false
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
no_memories_if_mcp_or_web_search = true
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let expected = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
disable_on_external_context = true
|
||||
"#,
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
|
||||
let config: ConfigToml = base.try_into().expect("merged config should deserialize");
|
||||
assert_eq!(
|
||||
config.memories,
|
||||
Some(MemoriesToml {
|
||||
disable_on_external_context: Some(true),
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_toml_values_prefers_canonical_key_when_one_layer_has_both_names() {
|
||||
let mut base = TomlValue::Table(toml::map::Map::new());
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
disable_on_external_context = true
|
||||
no_memories_if_mcp_or_web_search = false
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let expected = parse_toml(
|
||||
r#"
|
||||
[memories]
|
||||
disable_on_external_context = true
|
||||
"#,
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_toml_values_normalizes_legacy_agents_key_across_layers() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[agents]
|
||||
max_threads = 4
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[agents]
|
||||
max_concurrent_threads_per_session = 7
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let expected = parse_toml(
|
||||
r#"
|
||||
[agents]
|
||||
max_concurrent_threads_per_session = 7
|
||||
"#,
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
|
||||
let config: ConfigToml = base.try_into().expect("merged config should deserialize");
|
||||
assert_eq!(
|
||||
config.agents,
|
||||
Some(AgentsToml {
|
||||
max_concurrent_threads_per_session: Some(7),
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_toml_values_normalizes_legacy_agents_key_from_overlay() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[agents]
|
||||
max_concurrent_threads_per_session = 4
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[agents]
|
||||
max_threads = 7
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let expected = parse_toml(
|
||||
r#"
|
||||
[agents]
|
||||
max_concurrent_threads_per_session = 7
|
||||
"#,
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
}
|
||||
|
||||
/// Feature tables added above legacy toggles retain the lower layer's enabled state.
|
||||
#[test]
|
||||
fn merge_multi_agent_v2_table_preserves_legacy_boolean_toggle() {
|
||||
for feature_path in ["features", "profiles.work.features"] {
|
||||
let mut base = parse_toml(&format!("[{feature_path}]\nmulti_agent_v2 = true\n"));
|
||||
let overlay = parse_toml(&format!(
|
||||
"[{feature_path}.multi_agent_v2]\nsubagent_usage_hint_text = \"Delegate carefully.\"\n",
|
||||
));
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(
|
||||
base,
|
||||
parse_toml(&format!(
|
||||
"[{feature_path}.multi_agent_v2]\nenabled = true\nsubagent_usage_hint_text = \"Delegate carefully.\"\n",
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Legacy feature toggles update enabled state without discarding nested configuration.
|
||||
#[test]
|
||||
fn merge_multi_agent_v2_boolean_preserves_existing_feature_table() {
|
||||
for feature_path in ["features", "profiles.work.features"] {
|
||||
let mut base = parse_toml(&format!(
|
||||
"[{feature_path}.multi_agent_v2]\nenabled = true\nsubagent_usage_hint_text = \"Delegate carefully.\"\n",
|
||||
));
|
||||
let overlay = parse_toml(&format!("[{feature_path}]\nmulti_agent_v2 = false\n"));
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(
|
||||
base,
|
||||
parse_toml(&format!(
|
||||
"[{feature_path}.multi_agent_v2]\nenabled = false\nsubagent_usage_hint_text = \"Delegate carefully.\"\n",
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Opaque desktop settings retain ordinary scalar/table replacement semantics.
|
||||
#[test]
|
||||
fn merge_multi_agent_v2_compatibility_excludes_opaque_desktop_paths() {
|
||||
let cases = [
|
||||
(
|
||||
"[desktop.features.multi_agent_v2]\nenabled = true\n",
|
||||
"[desktop.features]\nmulti_agent_v2 = false\n",
|
||||
"[desktop.features]\nmulti_agent_v2 = false\n",
|
||||
),
|
||||
(
|
||||
"[desktop.features]\nmulti_agent_v2 = true\n",
|
||||
"[desktop.features.multi_agent_v2]\ncustom = true\n",
|
||||
"[desktop.features.multi_agent_v2]\ncustom = true\n",
|
||||
),
|
||||
];
|
||||
|
||||
for (base, overlay, expected) in cases {
|
||||
let mut base = parse_toml(base);
|
||||
merge_toml_values(&mut base, &parse_toml(overlay));
|
||||
assert_eq!(base, parse_toml(expected));
|
||||
}
|
||||
}
|
||||
|
||||
/// CLI overrides preserve the multi-agent toggle and nested options in either ordering.
|
||||
#[test]
|
||||
fn multi_agent_v2_cli_overrides_preserve_boolean_and_nested_configuration() {
|
||||
for feature_path in ["features", "profiles.work.features"] {
|
||||
let instructions = (
|
||||
format!("{feature_path}.multi_agent_v2.subagent_usage_hint_text"),
|
||||
TomlValue::String("Delegate carefully.".to_string()),
|
||||
);
|
||||
let enabled = (
|
||||
format!("{feature_path}.multi_agent_v2"),
|
||||
TomlValue::Boolean(true),
|
||||
);
|
||||
let feature_table = (
|
||||
format!("{feature_path}.multi_agent_v2"),
|
||||
parse_toml("subagent_usage_hint_text = \"Delegate carefully.\"\n"),
|
||||
);
|
||||
let expected = parse_toml(&format!(
|
||||
"[{feature_path}.multi_agent_v2]\nenabled = true\nsubagent_usage_hint_text = \"Delegate carefully.\"\n",
|
||||
));
|
||||
|
||||
for overrides in [
|
||||
vec![enabled.clone(), instructions.clone()],
|
||||
vec![instructions, enabled.clone()],
|
||||
vec![enabled.clone(), feature_table.clone()],
|
||||
vec![feature_table, enabled],
|
||||
] {
|
||||
assert_eq!(crate::build_cli_overrides_layer(&overrides), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn code_mode_overrides_preserve_enabled_state_and_cell_overhead() {
|
||||
for feature_path in ["features", "profiles.work.features"] {
|
||||
for enabled in [true, false] {
|
||||
let toggle = (
|
||||
format!("{feature_path}.code_mode"),
|
||||
TomlValue::Boolean(enabled),
|
||||
);
|
||||
let overhead = (
|
||||
format!("{feature_path}.code_mode.experimental_show_cell_overhead"),
|
||||
TomlValue::Boolean(true),
|
||||
);
|
||||
let expected = parse_toml(&format!(
|
||||
"[{feature_path}.code_mode]\nenabled = {enabled}\nexperimental_show_cell_overhead = true\n",
|
||||
));
|
||||
|
||||
// Adding a display option must preserve the toggle in either override order.
|
||||
for overrides in [
|
||||
vec![toggle.clone(), overhead.clone()],
|
||||
vec![overhead, toggle],
|
||||
] {
|
||||
assert_eq!(crate::build_cli_overrides_layer(&overrides), expected);
|
||||
}
|
||||
|
||||
let boolean_layer = parse_toml(&format!("[{feature_path}]\ncode_mode = {enabled}\n"));
|
||||
let table_layer = parse_toml(&format!(
|
||||
"[{feature_path}.code_mode]\nexperimental_show_cell_overhead = true\n",
|
||||
));
|
||||
for (mut base, overlay) in [
|
||||
(boolean_layer.clone(), table_layer.clone()),
|
||||
(table_layer, boolean_layer),
|
||||
] {
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
assert_eq!(base, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structured_mode_overrides_preserve_disabled_state_and_mode() {
|
||||
for (feature, selected_mode) in [
|
||||
("sleep_tool", "always_on"),
|
||||
("runtime_agent_instances", "assertion_only"),
|
||||
] {
|
||||
for feature_path in ["features", "profiles.work.features"] {
|
||||
let disabled = (
|
||||
format!("{feature_path}.{feature}"),
|
||||
TomlValue::Boolean(false),
|
||||
);
|
||||
let mode = (
|
||||
format!("{feature_path}.{feature}.mode"),
|
||||
TomlValue::String(selected_mode.to_string()),
|
||||
);
|
||||
let expected = parse_toml(&format!(
|
||||
"[{feature_path}.{feature}]\nenabled = false\nmode = \"{selected_mode}\"\n",
|
||||
));
|
||||
for overrides in [vec![disabled.clone(), mode.clone()], vec![mode, disabled]] {
|
||||
assert_eq!(crate::build_cli_overrides_layer(&overrides), expected);
|
||||
}
|
||||
|
||||
let boolean_layer = parse_toml(&format!("[{feature_path}]\n{feature} = false\n"));
|
||||
let table_layer = parse_toml(&format!(
|
||||
"[{feature_path}.{feature}]\nmode = \"{selected_mode}\"\n",
|
||||
));
|
||||
for (mut base, overlay) in [
|
||||
(boolean_layer.clone(), table_layer.clone()),
|
||||
(table_layer, boolean_layer),
|
||||
] {
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
assert_eq!(base, expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_proxy_feature_overrides_preserve_credential_broker_configuration() {
|
||||
let enabled = (
|
||||
"features.network_proxy".to_string(),
|
||||
TomlValue::Boolean(true),
|
||||
);
|
||||
let broker = (
|
||||
"features.network_proxy.credential_broker".to_string(),
|
||||
TomlValue::Boolean(true),
|
||||
);
|
||||
let expected =
|
||||
parse_toml("[features.network_proxy]\nenabled = true\ncredential_broker = true\n");
|
||||
|
||||
for overrides in [vec![enabled.clone(), broker.clone()], vec![broker, enabled]] {
|
||||
assert_eq!(crate::build_cli_overrides_layer(&overrides), expected);
|
||||
}
|
||||
|
||||
let mut base = parse_toml("[features]\nnetwork_proxy = true\n");
|
||||
merge_toml_values(
|
||||
&mut base,
|
||||
&parse_toml("[features.network_proxy]\ncredential_broker = true\n"),
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn higher_priority_credential_provider_replaces_overlapping_sources() {
|
||||
for (feature_path, base_source, overlay_source, keep_default) in [
|
||||
("features", "VENDOR_TOKEN", "VENDOR_TOKEN", false),
|
||||
(
|
||||
"profiles.work.features",
|
||||
"VENDOR_TOKEN",
|
||||
"VENDOR_TOKEN",
|
||||
false,
|
||||
),
|
||||
("features", "vendor_token", "VENDOR_TOKEN", !cfg!(windows)),
|
||||
] {
|
||||
let default_provider = format!(
|
||||
"[{feature_path}.network_proxy.credentials.default]\n\
|
||||
env = ['{base_source}']\n\
|
||||
url_prefixes = ['https://default.example']\n"
|
||||
);
|
||||
let shared_provider = format!(
|
||||
"[{feature_path}.network_proxy.credentials.shared]\n\
|
||||
env = ['SHARED_TOKEN']\n\
|
||||
patterns = ['shared_[a-z]+']\n"
|
||||
);
|
||||
let mut base = parse_toml(&format!("{default_provider}\n{shared_provider}"));
|
||||
let overlay = parse_toml(&format!(
|
||||
"[{feature_path}.network_proxy.credentials.override]\n\
|
||||
env = ['{overlay_source}']\n\
|
||||
url_prefixes = ['https://override.example']\n\
|
||||
[{feature_path}.network_proxy.credentials.shared]\n\
|
||||
url_prefixes = ['https://shared.example']\n"
|
||||
));
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let retained_default = if keep_default { &default_provider } else { "" };
|
||||
let expected = parse_toml(&format!(
|
||||
"{retained_default}\n\
|
||||
[{feature_path}.network_proxy.credentials.override]\n\
|
||||
env = ['{overlay_source}']\n\
|
||||
url_prefixes = ['https://override.example']\n\
|
||||
[{feature_path}.network_proxy.credentials.shared]\n\
|
||||
env = ['SHARED_TOKEN']\n\
|
||||
patterns = ['shared_[a-z]+']\n\
|
||||
url_prefixes = ['https://shared.example']\n"
|
||||
));
|
||||
assert_eq!(base, expected, "feature path: {feature_path}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_provider_remapping_preserves_inherited_settings() {
|
||||
let base = parse_toml(
|
||||
r#"
|
||||
[features.network_proxy.credentials.a]
|
||||
env = ["OLD_AUTH"]
|
||||
patterns = ["acme_[a-z]{24}"]
|
||||
url_prefixes = ["https://a.example"]
|
||||
auth = ["token"]
|
||||
[features.network_proxy.credentials.b]
|
||||
env = ["OTHER_AUTH"]
|
||||
patterns = ["other_[a-z]{24}"]
|
||||
url_prefixes = ["https://b.example"]
|
||||
auth = ["bearer"]
|
||||
"#,
|
||||
);
|
||||
|
||||
for new_a in ["NEW_AUTH", "OTHER_AUTH"] {
|
||||
let mut merged = base.clone();
|
||||
let mut expected = base.clone();
|
||||
let providers = &mut expected["features"]["network_proxy"]["credentials"];
|
||||
providers["a"]["env"] = TomlValue::Array(vec![new_a.into()]);
|
||||
providers["b"]["env"] = TomlValue::Array(vec!["OLD_AUTH".into()]);
|
||||
let overlay = parse_toml(&format!(
|
||||
"[features.network_proxy.credentials.a]\n\
|
||||
env = ['{new_a}']\n\
|
||||
[features.network_proxy.credentials.b]\n\
|
||||
env = ['OLD_AUTH']\n"
|
||||
));
|
||||
|
||||
merge_toml_values(&mut merged, &overlay);
|
||||
|
||||
assert_eq!(merged, expected);
|
||||
}
|
||||
}
|
||||
|
||||
/// Repeated opaque desktop overrides continue to replace their previous value.
|
||||
#[test]
|
||||
fn multi_agent_v2_cli_compatibility_excludes_opaque_desktop_paths() {
|
||||
let path = "desktop.features.multi_agent_v2".to_string();
|
||||
let enabled = (path.clone(), TomlValue::Boolean(true));
|
||||
let feature_table = (path, parse_toml("custom = true\n"));
|
||||
|
||||
assert_eq!(
|
||||
crate::build_cli_overrides_layer(&[enabled.clone(), feature_table.clone()]),
|
||||
parse_toml("[desktop.features.multi_agent_v2]\ncustom = true\n")
|
||||
);
|
||||
assert_eq!(
|
||||
crate::build_cli_overrides_layer(&[feature_table, enabled]),
|
||||
parse_toml("[desktop.features]\nmulti_agent_v2 = true\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_toml_values_normalizes_permission_network_domains_before_overlaying() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[permissions.dev.network.domains]
|
||||
"example.com" = "deny"
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[permissions.dev.network.domains]
|
||||
"EXAMPLE.COM" = "allow"
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let expected = parse_toml(
|
||||
r#"
|
||||
[permissions.dev.network.domains]
|
||||
"example.com" = "allow"
|
||||
"#,
|
||||
);
|
||||
assert_eq!(base, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_legacy_array_overlay_replaces_legacy_array() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["LOW_*", "SHARED_*"]
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["HIGH_*"]
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(base, overlay);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_set_overlay_preserves_case_distinct_keys() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[features.network_proxy.credentials.stripe]
|
||||
env = ["STRIPE_API_KEY"]
|
||||
patterns = ["stripe_[a-z]+"]
|
||||
url_prefix_from_env = "STRIPE_HOST"
|
||||
|
||||
[shell_environment_policy.set]
|
||||
stripe_api_key = "stale"
|
||||
stripe_host = "stale.example"
|
||||
foo = "lowercase"
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.set]
|
||||
STRIPE_API_KEY = "trusted"
|
||||
STRIPE_HOST = "trusted.example"
|
||||
FOO = "uppercase"
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
let values = base["shell_environment_policy"]["set"]
|
||||
.as_table()
|
||||
.expect("shell environment overrides");
|
||||
assert_eq!(
|
||||
values.get("foo").and_then(TomlValue::as_str),
|
||||
Some("lowercase")
|
||||
);
|
||||
assert_eq!(
|
||||
values.get("FOO").and_then(TomlValue::as_str),
|
||||
Some("uppercase")
|
||||
);
|
||||
assert_eq!(values.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_credential_provider_preserves_case_distinct_environment_overrides() {
|
||||
let mut base = parse_toml(
|
||||
"[shell_environment_policy.set]\n\
|
||||
stripe_api_key = 'stale'\n\
|
||||
stripe_host = 'stale.example'",
|
||||
);
|
||||
let override_layer = parse_toml(
|
||||
"[shell_environment_policy.set]\n\
|
||||
STRIPE_API_KEY = 'previous'\n\
|
||||
STRIPE_HOST = 'previous.example'",
|
||||
);
|
||||
let final_override_layer = parse_toml(
|
||||
"[shell_environment_policy.set]\n\
|
||||
stripe_api_key = 'trusted'\n\
|
||||
stripe_host = 'current.example'",
|
||||
);
|
||||
let provider_layer = parse_toml(
|
||||
"[features.network_proxy.credentials.stripe]\n\
|
||||
env = ['STRIPE_API_KEY']\n\
|
||||
url_prefix_from_env = 'STRIPE_HOST'",
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &override_layer);
|
||||
merge_toml_values(&mut base, &final_override_layer);
|
||||
merge_toml_values(&mut base, &provider_layer);
|
||||
|
||||
assert_eq!(
|
||||
base["shell_environment_policy"]["set"],
|
||||
parse_toml(
|
||||
"stripe_api_key = 'trusted'\n\
|
||||
stripe_host = 'current.example'\n\
|
||||
STRIPE_API_KEY = 'previous'\n\
|
||||
STRIPE_HOST = 'previous.example'",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_filters_overlay_merges_by_key_case_insensitively() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"FLIP_*" = "exclude"
|
||||
"KEEP_*" = "include"
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"ADD_*" = "exclude"
|
||||
"flip_*" = "include"
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(
|
||||
base,
|
||||
parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"add_*" = "exclude"
|
||||
"flip_*" = "include"
|
||||
"keep_*" = "include"
|
||||
"#,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_filters_overlay_merges_unicode_keys_case_insensitively() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"СЕКРЕТ_*" = "exclude"
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"секрет_*" = "include"
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(base, overlay);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_filters_replace_lower_legacy_filter_fields() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
inherit = "core"
|
||||
exclude = ["FLIP_TO_INCLUDE", "KEEP_EXCLUDED"]
|
||||
include_only = ["FLIP_TO_EXCLUDE", "KEEP_INCLUDED"]
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"ADD_INCLUDED" = "include"
|
||||
"FLIP_TO_EXCLUDE" = "exclude"
|
||||
"FLIP_TO_INCLUDE" = "include"
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(
|
||||
base,
|
||||
parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
inherit = "core"
|
||||
|
||||
[shell_environment_policy.filters]
|
||||
"ADD_INCLUDED" = "include"
|
||||
"FLIP_TO_EXCLUDE" = "exclude"
|
||||
"FLIP_TO_INCLUDE" = "include"
|
||||
"#,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_legacy_arrays_replace_lower_filters() {
|
||||
let mut base = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
inherit = "core"
|
||||
|
||||
[shell_environment_policy.filters]
|
||||
"FLIP_TO_EXCLUDE" = "include"
|
||||
"LOW_EXCLUDED" = "exclude"
|
||||
"KEEP_INCLUDED" = "include"
|
||||
"#,
|
||||
);
|
||||
let overlay = parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["FLIP_TO_EXCLUDE", "HIGH_EXCLUDED"]
|
||||
"#,
|
||||
);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(
|
||||
base,
|
||||
parse_toml(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
inherit = "core"
|
||||
exclude = ["FLIP_TO_EXCLUDE", "HIGH_EXCLUDED"]
|
||||
"#,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_shell_environment_filter_representations_replace_the_other_form() {
|
||||
let cases = [
|
||||
(
|
||||
r#"[shell_environment_policy]
|
||||
exclude = ["AWS_*"]
|
||||
include_only = ["PATH"]
|
||||
"#,
|
||||
r#"[shell_environment_policy.filters]
|
||||
"#,
|
||||
),
|
||||
(
|
||||
r#"[shell_environment_policy.filters]
|
||||
"AWS_*" = "include"
|
||||
"#,
|
||||
r#"[shell_environment_policy]
|
||||
exclude = []
|
||||
"#,
|
||||
),
|
||||
];
|
||||
|
||||
for (base, overlay) in cases {
|
||||
let mut base = parse_toml(base);
|
||||
let overlay = parse_toml(overlay);
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(base, overlay);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_overlay_preserves_unvisited_base_aliases() {
|
||||
let mut base = parse_toml(
|
||||
"[memories]\nno_memories_if_mcp_or_web_search = false\n[agents]\nmax_threads = 2",
|
||||
);
|
||||
let overlay = parse_toml("[agents]\nmax_depth = 3");
|
||||
|
||||
merge_toml_values(&mut base, &overlay);
|
||||
|
||||
assert_eq!(
|
||||
base,
|
||||
parse_toml(
|
||||
"[memories]\nno_memories_if_mcp_or_web_search = false\n[agents]\nmax_concurrent_threads_per_session = 2\nmax_depth = 3",
|
||||
),
|
||||
);
|
||||
}
|
||||
27
codex-rs/config/src/model_provider_defaults.rs
Normal file
27
codex-rs/config/src/model_provider_defaults.rs
Normal file
@@ -0,0 +1,27 @@
|
||||
//! Applies runtime provider defaults using the resolved session working directory.
|
||||
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_protocol::config_types::ModelProviderAuthInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use std::num::NonZeroU64;
|
||||
|
||||
/// Supplies GCP command auth when no explicit auth override is configured.
|
||||
pub fn apply_default_gcp_auth(provider: &mut ModelProviderInfo, cwd: &AbsolutePathBuf) {
|
||||
provider.auth.get_or_insert_with(|| ModelProviderAuthInfo {
|
||||
command: if cfg!(windows) {
|
||||
"gcloud.cmd"
|
||||
} else {
|
||||
"gcloud"
|
||||
}
|
||||
.to_string(),
|
||||
args: vec![
|
||||
"auth".into(),
|
||||
"application-default".into(),
|
||||
"print-access-token".into(),
|
||||
],
|
||||
timeout_ms: NonZeroU64::new(30_000).unwrap_or(NonZeroU64::MIN),
|
||||
refresh_interval_ms: 3_000_000,
|
||||
// Registry construction must not depend on the process cwd, which may be deleted.
|
||||
cwd: cwd.clone(),
|
||||
});
|
||||
}
|
||||
45
codex-rs/config/src/model_provider_requirements.rs
Normal file
45
codex-rs/config/src/model_provider_requirements.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
//! Projects complete required provider definitions before config parsing.
|
||||
//! Selection is applied with the other exact requirements after config parsing.
|
||||
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::config_toml::validate_model_providers;
|
||||
use std::io;
|
||||
use toml::Value;
|
||||
|
||||
pub(crate) fn to_config(requirements: &ConfigRequirementsToml) -> io::Result<Value> {
|
||||
let mut config = toml::Table::new();
|
||||
if let Some(providers) = &requirements.model_providers {
|
||||
validate_model_providers(providers)
|
||||
.map_err(|message| io::Error::new(io::ErrorKind::InvalidData, message))?;
|
||||
config.insert(
|
||||
"model_providers".to_string(),
|
||||
Value::try_from(providers)
|
||||
.map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?,
|
||||
);
|
||||
}
|
||||
Ok(Value::Table(config))
|
||||
}
|
||||
|
||||
pub(crate) fn apply(config: &mut Value, requirements: &Value) {
|
||||
let Some(config) = config.as_table_mut() else {
|
||||
return;
|
||||
};
|
||||
if let Some(required) = requirements
|
||||
.get("model_providers")
|
||||
.and_then(Value::as_table)
|
||||
{
|
||||
let providers = config
|
||||
.entry("model_providers")
|
||||
.or_insert_with(|| Value::Table(Default::default()));
|
||||
if !providers.is_table() {
|
||||
*providers = Value::Table(Default::default());
|
||||
}
|
||||
if let Some(providers) = providers.as_table_mut() {
|
||||
providers.extend(required.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "model_provider_requirements_tests.rs"]
|
||||
mod tests;
|
||||
99
codex-rs/config/src/model_provider_requirements_tests.rs
Normal file
99
codex-rs/config/src/model_provider_requirements_tests.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Tests exact provider requirements across layers and config projections.
|
||||
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
const REQUIRED: &str = r#"
|
||||
model_provider = "gateway"
|
||||
[model_providers.gateway]
|
||||
name = "Managed gateway"
|
||||
base_url = "https://gateway.example.test/v1"
|
||||
requires_openai_auth = true
|
||||
[model_providers.gateway.http_headers]
|
||||
X-Managed = "yes"
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn higher_requirements_merge_provider_fields_and_nested_tables() -> anyhow::Result<()> {
|
||||
let cloud_source = RequirementSource::EnterpriseManaged {
|
||||
id: "req_1".into(),
|
||||
name: "Gateway".into(),
|
||||
};
|
||||
let requirements = compose_requirements([
|
||||
RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
r#"
|
||||
model_provider = "other"
|
||||
[model_providers.gateway]
|
||||
name = "System gateway"
|
||||
base_url = "https://old.example.test"
|
||||
env_key = "OLD_KEY"
|
||||
supports_websockets = true
|
||||
[model_providers.gateway.http_headers]
|
||||
X-Old = "no"
|
||||
X-Managed = "old"
|
||||
[model_providers.other]
|
||||
name = "Other provider"
|
||||
"#,
|
||||
),
|
||||
RequirementsLayerEntry::from_toml(cloud_source.clone(), REQUIRED),
|
||||
])?
|
||||
.expect("provider requirements must not be discarded");
|
||||
let normalized = ConfigRequirements::try_from(requirements.clone())?;
|
||||
assert_eq!(
|
||||
normalized
|
||||
.model_provider
|
||||
.as_ref()
|
||||
.map(|requirement| &requirement.source),
|
||||
Some(&cloud_source)
|
||||
);
|
||||
let requirements = requirements.into_toml();
|
||||
let expected: ConfigRequirementsToml = toml::from_str(
|
||||
r#"
|
||||
model_provider = "gateway"
|
||||
[model_providers.gateway]
|
||||
name = "Managed gateway"
|
||||
base_url = "https://gateway.example.test/v1"
|
||||
requires_openai_auth = true
|
||||
env_key = "OLD_KEY"
|
||||
supports_websockets = true
|
||||
[model_providers.gateway.http_headers]
|
||||
X-Managed = "yes"
|
||||
X-Old = "no"
|
||||
[model_providers.other]
|
||||
name = "Other provider"
|
||||
"#,
|
||||
)?;
|
||||
assert_eq!(requirements, expected);
|
||||
assert_eq!(
|
||||
normalized
|
||||
.model_providers
|
||||
.map(|requirement| requirement.value),
|
||||
requirements.model_providers
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_provider_definitions_are_validated_without_local_defaults() -> anyhow::Result<()> {
|
||||
for invalid in [
|
||||
"[model_providers.gateway]\nbase_url = 'https://example.test'",
|
||||
"[model_providers.openai]\nname = 'Reserved'",
|
||||
"[model_providers.gateway]\nname = 'Gateway'\n[model_providers.gateway.aws]\nregion = 'us-east-1'",
|
||||
] {
|
||||
let requirements = toml::from_str(invalid)?;
|
||||
let local =
|
||||
ConfigLayerEntry::new(ConfigLayerSource::SessionFlags, toml::from_str(REQUIRED)?);
|
||||
let error = ConfigLayerStack::new(vec![local], ConfigRequirements::default(), requirements)
|
||||
.expect_err("local config cannot repair an invalid required provider");
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
99
codex-rs/config/src/overrides.rs
Normal file
99
codex-rs/config/src/overrides.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use crate::merge::is_structured_feature_path;
|
||||
use crate::merge::merge_toml_values;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
pub(crate) fn default_empty_table() -> TomlValue {
|
||||
TomlValue::Table(Default::default())
|
||||
}
|
||||
|
||||
pub fn build_cli_overrides_layer(cli_overrides: &[(String, TomlValue)]) -> TomlValue {
|
||||
let mut root = default_empty_table();
|
||||
for (path, value) in cli_overrides {
|
||||
apply_toml_override(&mut root, path, value.clone());
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
/// Apply a single dotted-path override onto a TOML value.
|
||||
fn apply_toml_override(root: &mut TomlValue, path: &str, value: TomlValue) {
|
||||
use toml::value::Table;
|
||||
|
||||
let mut current = root;
|
||||
let mut segments_iter = path.split('.').peekable();
|
||||
let mut traversed_segments = Vec::new();
|
||||
|
||||
while let Some(segment) = segments_iter.next() {
|
||||
traversed_segments.push(segment);
|
||||
let is_last = segments_iter.peek().is_none();
|
||||
|
||||
if is_last {
|
||||
match current {
|
||||
TomlValue::Table(table) => {
|
||||
if is_structured_feature_path(&traversed_segments)
|
||||
&& let Some(existing) = table.get_mut(segment)
|
||||
{
|
||||
match (&mut *existing, &value) {
|
||||
(TomlValue::Table(feature), TomlValue::Boolean(enabled)) => {
|
||||
feature.insert("enabled".to_string(), TomlValue::Boolean(*enabled));
|
||||
return;
|
||||
}
|
||||
(TomlValue::Boolean(enabled), TomlValue::Table(_)) => {
|
||||
*existing = TomlValue::Table(Table::from_iter([(
|
||||
"enabled".to_string(),
|
||||
TomlValue::Boolean(*enabled),
|
||||
)]));
|
||||
merge_toml_values(existing, &value);
|
||||
return;
|
||||
}
|
||||
(TomlValue::Table(_), TomlValue::Table(_)) => {
|
||||
merge_toml_values(existing, &value);
|
||||
return;
|
||||
}
|
||||
(
|
||||
TomlValue::String(_)
|
||||
| TomlValue::Integer(_)
|
||||
| TomlValue::Float(_)
|
||||
| TomlValue::Boolean(_)
|
||||
| TomlValue::Datetime(_)
|
||||
| TomlValue::Array(_)
|
||||
| TomlValue::Table(_),
|
||||
_,
|
||||
) => {}
|
||||
}
|
||||
}
|
||||
table.insert(segment.to_string(), value);
|
||||
}
|
||||
_ => {
|
||||
let mut table = Table::new();
|
||||
table.insert(segment.to_string(), value);
|
||||
*current = TomlValue::Table(table);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
match current {
|
||||
TomlValue::Table(table) => {
|
||||
current = table
|
||||
.entry(segment.to_string())
|
||||
.or_insert_with(|| TomlValue::Table(Table::new()));
|
||||
if is_structured_feature_path(&traversed_segments)
|
||||
&& let TomlValue::Boolean(enabled) = current
|
||||
{
|
||||
*current = TomlValue::Table(Table::from_iter([(
|
||||
"enabled".to_string(),
|
||||
TomlValue::Boolean(*enabled),
|
||||
)]));
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
*current = TomlValue::Table(Table::new());
|
||||
if let TomlValue::Table(tbl) = current {
|
||||
current = tbl
|
||||
.entry(segment.to_string())
|
||||
.or_insert_with(|| TomlValue::Table(Table::new()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
115
codex-rs/config/src/path_context.rs
Normal file
115
codex-rs/config/src/path_context.rs
Normal file
@@ -0,0 +1,115 @@
|
||||
//! Path facts for configuration parsing. Native callers and callers resolving
|
||||
//! another platform use the same resolver after fact capture.
|
||||
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use codex_utils_path_uri::LegacyAppPathStringError;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use std::cell::RefCell;
|
||||
|
||||
/// The owning environment's path convention, base directory, and home for configuration.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ConfigPathContext {
|
||||
convention: PathConvention,
|
||||
base_dir: Option<PathUri>,
|
||||
user_home_dir: Option<PathUri>,
|
||||
}
|
||||
|
||||
impl ConfigPathContext {
|
||||
/// Supplies the grammar and directories of the environment owning the layer.
|
||||
/// Relative paths require a base; home-relative paths require a home directory.
|
||||
pub fn new(
|
||||
convention: PathConvention,
|
||||
base_dir: Option<PathUri>,
|
||||
user_home_dir: Option<PathUri>,
|
||||
) -> Self {
|
||||
Self {
|
||||
convention,
|
||||
base_dir,
|
||||
user_home_dir,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the path grammar supplied by the owning environment.
|
||||
pub fn convention(&self) -> PathConvention {
|
||||
self.convention
|
||||
}
|
||||
|
||||
/// Resolves configuration text to a URI using the supplied directory and home facts.
|
||||
pub fn resolve_path(&self, input: &str) -> Result<PathUri, LegacyAppPathStringError> {
|
||||
PathUri::resolve_config_path_uri(
|
||||
input,
|
||||
self.convention,
|
||||
self.base_dir.as_ref(),
|
||||
self.user_home_dir.as_ref(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Resolves against a supplied base using this context's grammar and home.
|
||||
pub fn resolve_against(
|
||||
&self,
|
||||
input: &str,
|
||||
base: &PathUri,
|
||||
) -> Result<PathUri, LegacyAppPathStringError> {
|
||||
PathUri::resolve_config_path_uri(
|
||||
input,
|
||||
self.convention,
|
||||
Some(base),
|
||||
self.user_home_dir.as_ref(),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn enter(&self) -> PathContextGuard {
|
||||
PathContextGuard(PATH_CONTEXT.with(|current| current.replace(Some(self.clone()))))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static PATH_CONTEXT: RefCell<Option<ConfigPathContext>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub(crate) struct PathContextGuard(Option<ConfigPathContext>);
|
||||
|
||||
impl Drop for PathContextGuard {
|
||||
fn drop(&mut self) {
|
||||
PATH_CONTEXT.with(|current| *current.borrow_mut() = self.0.take());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn convention() -> PathConvention {
|
||||
PATH_CONTEXT.with(|current| {
|
||||
current
|
||||
.borrow()
|
||||
.as_ref()
|
||||
.map_or_else(PathConvention::native, |context| context.convention)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(input: &str) -> Result<String, String> {
|
||||
let context = match PATH_CONTEXT.with(|current| current.borrow().clone()) {
|
||||
Some(context) => context,
|
||||
None => {
|
||||
let convention = PathConvention::native();
|
||||
let base = AbsolutePathBufGuard::deserialization_base(std::path::Path::new(input))
|
||||
.map_err(str::to_owned)?
|
||||
.map(PathUri::from_host_native_path)
|
||||
.transpose()
|
||||
.map_err(|error| error.to_string())?;
|
||||
let home = convention
|
||||
.home_relative_suffix(input)
|
||||
.and_then(|_| AbsolutePathBufGuard::home_directory())
|
||||
.map(PathUri::from_host_native_path)
|
||||
.transpose()
|
||||
.map_err(|error| error.to_string())?;
|
||||
ConfigPathContext::new(convention, base, home)
|
||||
}
|
||||
};
|
||||
context
|
||||
.resolve_path(input)
|
||||
.and_then(|path| path.to_config_path_string(context.convention()))
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "path_context_tests.rs"]
|
||||
mod tests;
|
||||
255
codex-rs/config/src/path_context_tests.rs
Normal file
255
codex-rs/config/src/path_context_tests.rs
Normal file
@@ -0,0 +1,255 @@
|
||||
//! Contracts for layer-owned denial facts, parser scoping, and policy conversion.
|
||||
|
||||
use super::ConfigPathContext;
|
||||
use crate::FilesystemConstraints;
|
||||
use crate::FilesystemDenyReadPattern;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements_for_hostname;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use codex_protocol::permissions::FileSystemPath;
|
||||
use codex_protocol::permissions::FileSystemSandboxEntry;
|
||||
use codex_protocol::permissions::FileSystemSandboxKind;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn composition_applies_each_layers_base_and_home_to_policy() {
|
||||
let native_home = tempdir().expect("native home");
|
||||
let first = RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
"[permissions.filesystem]\ndeny_read = ['private', '~/secret', 'private', 'C:\\', '\\\\server\\share\\', 'private/*.key']",
|
||||
)
|
||||
.with_path_context(ConfigPathContext::new(
|
||||
PathConvention::Windows,
|
||||
Some(PathUri::parse("file:///C:/first").expect("first base")),
|
||||
Some(PathUri::parse("file:///C:/Users/first").expect("first home")),
|
||||
));
|
||||
let second = RequirementsLayerEntry::from_toml_value(
|
||||
RequirementSource::Unknown,
|
||||
toml::toml! { [permissions.filesystem] deny_read = ["private", "~/secret"] }.into(),
|
||||
)
|
||||
.with_path_context(ConfigPathContext::new(
|
||||
PathConvention::Windows,
|
||||
Some(PathUri::parse("file:///D:/second").expect("second base")),
|
||||
Some(PathUri::parse("file:///D:/Users/second").expect("second home")),
|
||||
));
|
||||
let composed = AbsolutePathBufGuard::with_home_directory(native_home.path(), || {
|
||||
compose_requirements_for_hostname([first, second], /*hostname*/ None)
|
||||
.expect("compose layers")
|
||||
.expect("requirements present")
|
||||
});
|
||||
let constraints = FilesystemConstraints::from(composed.permissions.expect("permissions").value);
|
||||
let mut expected = FileSystemSandboxPolicy {
|
||||
kind: FileSystemSandboxKind::Restricted,
|
||||
glob_scan_max_depth: Some(7),
|
||||
entries: vec![FileSystemSandboxEntry::new(
|
||||
PathUri::parse("file:///C:/allowed")
|
||||
.expect("existing path")
|
||||
.into(),
|
||||
FileSystemAccessMode::Write,
|
||||
)],
|
||||
};
|
||||
let mut policy = expected.clone();
|
||||
expected.entries.extend(
|
||||
[
|
||||
"file:///D:/second/private",
|
||||
"file:///D:/Users/second/secret",
|
||||
"file:///C:/first/private",
|
||||
"file:///C:/Users/first/secret",
|
||||
"file:///C:/",
|
||||
"file://server/share",
|
||||
]
|
||||
.map(|path| {
|
||||
FileSystemSandboxEntry::new(
|
||||
PathUri::parse(path).expect("expected denial").into(),
|
||||
FileSystemAccessMode::Deny,
|
||||
)
|
||||
}),
|
||||
);
|
||||
expected.entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: r"C:\first\private/*.key".to_string(),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
));
|
||||
constraints
|
||||
.apply_to_policy(&mut policy, PathConvention::Windows)
|
||||
.expect("apply denials");
|
||||
constraints
|
||||
.apply_to_policy(&mut policy, PathConvention::Windows)
|
||||
.expect("deduplicate existing denials");
|
||||
assert_eq!(policy, expected);
|
||||
assert!(
|
||||
constraints
|
||||
.apply_to_policy(&mut policy, PathConvention::Posix)
|
||||
.is_err(),
|
||||
"a foreign denial cannot be reinterpreted using the host convention",
|
||||
);
|
||||
assert_eq!(policy, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn common_parser_uses_supplied_windows_drive_and_glob_separators() {
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::Windows,
|
||||
Some(PathUri::parse("file:///C:/base/cwd").expect("base")),
|
||||
/*user_home_dir*/ None,
|
||||
);
|
||||
let _guard = context.enter();
|
||||
for (input, expected) in [
|
||||
(r"C:private\*.key", r"C:\base\cwd\private/*.key"),
|
||||
(r"D:\*.key", r"D:\/*.key"),
|
||||
(r"\private\*.key", r"C:\private/*.key"),
|
||||
] {
|
||||
assert_eq!(
|
||||
FilesystemDenyReadPattern::from_input(input)
|
||||
.expect("resolve pattern")
|
||||
.as_str(),
|
||||
expected,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_denial_globs_reject_ambiguous_roots_and_streams() {
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::Windows,
|
||||
Some(PathUri::parse("file://server/share/base").expect("UNC base")),
|
||||
/*user_home_dir*/ None,
|
||||
);
|
||||
let _guard = context.enter();
|
||||
for input in [
|
||||
r"\\?\C:\private",
|
||||
r"\\*\share\private",
|
||||
r"D:*.key",
|
||||
r"private\*\file:stream",
|
||||
] {
|
||||
assert!(
|
||||
FilesystemDenyReadPattern::from_input(input).is_err(),
|
||||
"{input}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_nested_composition_restores_outer_context_and_then_native_resolution() {
|
||||
let base = tempdir().expect("native base");
|
||||
let _native_guard = AbsolutePathBufGuard::new(base.path());
|
||||
let native = FilesystemDenyReadPattern::from_input("private");
|
||||
{
|
||||
let outer = ConfigPathContext::new(
|
||||
PathConvention::Posix,
|
||||
Some(PathUri::parse("file:///outer").expect("outer base")),
|
||||
/*user_home_dir*/ None,
|
||||
);
|
||||
let _outer_guard = outer.enter();
|
||||
let inner = RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
"[permissions.filesystem]\ndeny_read = ['relative']",
|
||||
)
|
||||
.with_path_context(ConfigPathContext::new(
|
||||
PathConvention::Windows,
|
||||
/*base_dir*/ None,
|
||||
/*user_home_dir*/ None,
|
||||
));
|
||||
assert!(compose_requirements_for_hostname([inner], /*hostname*/ None).is_err());
|
||||
assert_eq!(
|
||||
FilesystemDenyReadPattern::from_input("private")
|
||||
.expect("outer context restored")
|
||||
.as_str(),
|
||||
"/outer/private",
|
||||
);
|
||||
}
|
||||
assert_eq!(FilesystemDenyReadPattern::from_input("private"), native);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_guard_and_supplied_native_facts_use_the_same_parser() {
|
||||
let base = tempdir().expect("base");
|
||||
let home = tempdir().expect("home");
|
||||
let _base_guard = AbsolutePathBufGuard::new(base.path());
|
||||
AbsolutePathBufGuard::with_home_directory(home.path(), || {
|
||||
let inputs = ["./private", "~/secret/*.txt"];
|
||||
let native = inputs.map(FilesystemDenyReadPattern::from_input);
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::native(),
|
||||
Some(PathUri::from_host_native_path(base.path()).expect("native base URI")),
|
||||
Some(PathUri::from_host_native_path(home.path()).expect("native home URI")),
|
||||
);
|
||||
let _context_guard = context.enter();
|
||||
assert_eq!(inputs.map(FilesystemDenyReadPattern::from_input), native);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_supplied_home_does_not_fall_back_to_native_home() {
|
||||
let home = tempdir().expect("native home");
|
||||
let layer = RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
"[permissions.filesystem]\ndeny_read = ['~/secret']",
|
||||
)
|
||||
.with_path_context(ConfigPathContext::new(
|
||||
PathConvention::Windows,
|
||||
Some(PathUri::parse("file:///C:/base").expect("base")),
|
||||
/*user_home_dir*/ None,
|
||||
));
|
||||
AbsolutePathBufGuard::with_home_directory(home.path(), || {
|
||||
assert!(compose_requirements_for_hostname([layer], /*hostname*/ None).is_err());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn denial_resolution_rejects_glob_syntax_in_supplied_facts() {
|
||||
for directory in ["file:///home/sam[1]", "file:///C:/Users/sam[1]"] {
|
||||
let directory = PathUri::parse(directory).unwrap();
|
||||
let context = ConfigPathContext::new(
|
||||
directory.infer_path_convention().unwrap(),
|
||||
Some(directory.clone()),
|
||||
Some(directory),
|
||||
);
|
||||
// Literal denials also reject metacharacters introduced by path facts.
|
||||
for input in [
|
||||
"private/*.key",
|
||||
"~/private/*.key",
|
||||
"private/key",
|
||||
"~/private/key",
|
||||
] {
|
||||
let layer = RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
format!("[permissions.filesystem]\ndeny_read = ['{input}']"),
|
||||
)
|
||||
.with_path_context(context.clone());
|
||||
assert!(compose_requirements_for_hostname([layer], /*hostname*/ None).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_and_supplied_denials_reject_the_same_unsafe_facts() {
|
||||
let parent = tempdir().unwrap();
|
||||
let directory = parent.path().join("sam[1]");
|
||||
let _base_guard = AbsolutePathBufGuard::new(&directory);
|
||||
AbsolutePathBufGuard::with_home_directory(&directory, || {
|
||||
let inputs = [
|
||||
"private/*.key",
|
||||
"~/private/*.key",
|
||||
"private/key",
|
||||
"~/private/key",
|
||||
];
|
||||
let native = inputs.map(FilesystemDenyReadPattern::from_input);
|
||||
assert!(native.iter().all(Result::is_err));
|
||||
let directory = PathUri::from_host_native_path(&directory).unwrap();
|
||||
let context = ConfigPathContext::new(
|
||||
PathConvention::native(),
|
||||
Some(directory.clone()),
|
||||
Some(directory),
|
||||
);
|
||||
let _context_guard = context.enter();
|
||||
assert_eq!(inputs.map(FilesystemDenyReadPattern::from_input), native);
|
||||
});
|
||||
}
|
||||
680
codex-rs/config/src/permissions_toml.rs
Normal file
680
codex-rs/config/src/permissions_toml.rs
Normal file
@@ -0,0 +1,680 @@
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use crate::merge::merge_toml_values;
|
||||
use codex_network_proxy::InjectedHeaderConfig;
|
||||
use codex_network_proxy::MitmHookActionsConfig;
|
||||
use codex_network_proxy::MitmHookBodyConfig;
|
||||
use codex_network_proxy::MitmHookConfig;
|
||||
use codex_network_proxy::MitmHookMatchConfig;
|
||||
use codex_network_proxy::NetworkDomainPermission as ProxyNetworkDomainPermission;
|
||||
use codex_network_proxy::NetworkMode;
|
||||
use codex_network_proxy::NetworkProxyConfig;
|
||||
use codex_network_proxy::NetworkUnixSocketPermission as ProxyNetworkUnixSocketPermission;
|
||||
use codex_network_proxy::normalize_host;
|
||||
use codex_protocol::permissions::FileSystemAccessMode;
|
||||
use indexmap::IndexMap;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use thiserror::Error;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
pub struct PermissionsToml {
|
||||
#[serde(flatten)]
|
||||
pub entries: BTreeMap<String, PermissionProfileToml>,
|
||||
}
|
||||
|
||||
impl PermissionsToml {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
/// Resolve `profile_name` and all of its `extends` ancestors into one TOML
|
||||
/// profile.
|
||||
///
|
||||
/// Parent profiles are merged before their children, so child keys override
|
||||
/// matching parent keys before callers compile the profile into runtime
|
||||
/// permissions. The returned profile keeps the selected profile's
|
||||
/// declaration metadata, such as `description` and `extends`.
|
||||
pub fn resolve_profile<F>(
|
||||
&self,
|
||||
profile_name: &str,
|
||||
mut parent_profile: F,
|
||||
) -> Result<PermissionProfileToml, PermissionProfileResolutionError>
|
||||
where
|
||||
F: FnMut(&str) -> Option<PermissionProfileToml>,
|
||||
{
|
||||
let mut profile_names = Vec::new();
|
||||
let mut profiles = Vec::new();
|
||||
let mut next_profile_name = profile_name.to_string();
|
||||
let mut referenced_by: Option<String> = None;
|
||||
|
||||
loop {
|
||||
if let Some(cycle_start) = profile_names
|
||||
.iter()
|
||||
.position(|name| name == &next_profile_name)
|
||||
{
|
||||
let cycle = profile_names[cycle_start..]
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(std::iter::once(next_profile_name))
|
||||
.collect::<Vec<_>>();
|
||||
return Err(PermissionProfileResolutionError::Cycle { cycle });
|
||||
}
|
||||
|
||||
let profile = self
|
||||
.entries
|
||||
.get(&next_profile_name)
|
||||
.cloned()
|
||||
.or_else(|| parent_profile(&next_profile_name))
|
||||
.ok_or_else(|| {
|
||||
referenced_by.as_deref().map_or_else(
|
||||
|| PermissionProfileResolutionError::UndefinedProfile {
|
||||
profile_name: next_profile_name.clone(),
|
||||
},
|
||||
|referenced_by| {
|
||||
if next_profile_name.starts_with(':') {
|
||||
PermissionProfileResolutionError::UnsupportedBuiltInParent {
|
||||
profile_name: referenced_by.to_string(),
|
||||
parent_profile_name: next_profile_name.clone(),
|
||||
}
|
||||
} else {
|
||||
PermissionProfileResolutionError::UndefinedParent {
|
||||
profile_name: referenced_by.to_string(),
|
||||
parent_profile_name: next_profile_name.clone(),
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
})?;
|
||||
let parent_profile_name = profile.extends.clone();
|
||||
|
||||
profile_names.push(next_profile_name.clone());
|
||||
|
||||
if let Some(parent_profile_name) = parent_profile_name {
|
||||
profiles.push(profile);
|
||||
referenced_by = Some(next_profile_name);
|
||||
next_profile_name = parent_profile_name;
|
||||
continue;
|
||||
}
|
||||
|
||||
let profile = profiles
|
||||
.into_iter()
|
||||
.rev()
|
||||
.try_fold(profile, merge_permission_profiles)?;
|
||||
return Ok(profile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct PermissionProfileToml {
|
||||
pub description: Option<String>,
|
||||
pub extends: Option<String>,
|
||||
pub workspace_roots: Option<WorkspaceRootsToml>,
|
||||
pub filesystem: Option<FilesystemPermissionsToml>,
|
||||
pub network: Option<NetworkToml>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum PermissionProfileResolutionError {
|
||||
#[error("default_permissions refers to undefined profile `{profile_name}`")]
|
||||
UndefinedProfile { profile_name: String },
|
||||
#[error(
|
||||
"permissions profile `{profile_name}` extends undefined profile `{parent_profile_name}`"
|
||||
)]
|
||||
UndefinedParent {
|
||||
profile_name: String,
|
||||
parent_profile_name: String,
|
||||
},
|
||||
#[error(
|
||||
"permissions profile `{profile_name}` cannot extend unsupported built-in profile `{parent_profile_name}`"
|
||||
)]
|
||||
UnsupportedBuiltInParent {
|
||||
profile_name: String,
|
||||
parent_profile_name: String,
|
||||
},
|
||||
#[error(
|
||||
"permissions profile inheritance cycle detected: {}",
|
||||
cycle.join(" -> ")
|
||||
)]
|
||||
Cycle { cycle: Vec<String> },
|
||||
#[error("failed to serialize permissions profile while resolving inheritance: {source}")]
|
||||
SerializeProfileToml {
|
||||
#[source]
|
||||
source: toml::ser::Error,
|
||||
},
|
||||
#[error(
|
||||
"failed to deserialize merged permissions profile while resolving inheritance: {source}"
|
||||
)]
|
||||
DeserializeProfileToml {
|
||||
#[source]
|
||||
source: toml::de::Error,
|
||||
},
|
||||
}
|
||||
|
||||
fn merge_permission_profiles(
|
||||
mut parent: PermissionProfileToml,
|
||||
mut child: PermissionProfileToml,
|
||||
) -> Result<PermissionProfileToml, PermissionProfileResolutionError> {
|
||||
let merges_network_domains = parent
|
||||
.network
|
||||
.as_ref()
|
||||
.and_then(|network| network.domains.as_ref())
|
||||
.is_some()
|
||||
&& child
|
||||
.network
|
||||
.as_ref()
|
||||
.and_then(|network| network.domains.as_ref())
|
||||
.is_some();
|
||||
|
||||
// Description and inheritance metadata belong to the selected profile
|
||||
// declaration, so an inherited profile must not fill those gaps.
|
||||
parent.description = None;
|
||||
parent.extends = None;
|
||||
|
||||
if merges_network_domains {
|
||||
normalize_profile_network_domains(&mut parent);
|
||||
normalize_profile_network_domains(&mut child);
|
||||
}
|
||||
|
||||
let mut merged = TomlValue::try_from(parent)
|
||||
.map_err(|source| PermissionProfileResolutionError::SerializeProfileToml { source })?;
|
||||
let child = TomlValue::try_from(child)
|
||||
.map_err(|source| PermissionProfileResolutionError::SerializeProfileToml { source })?;
|
||||
merge_toml_values(&mut merged, &child);
|
||||
merged
|
||||
.try_into()
|
||||
.map_err(|source| PermissionProfileResolutionError::DeserializeProfileToml { source })
|
||||
}
|
||||
|
||||
fn normalize_profile_network_domains(profile: &mut PermissionProfileToml) {
|
||||
let Some(domains) = profile
|
||||
.network
|
||||
.as_mut()
|
||||
.and_then(|network| network.domains.as_mut())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
let entries = std::mem::take(&mut domains.entries);
|
||||
domains.entries = entries
|
||||
.into_iter()
|
||||
.map(|(pattern, permission)| (normalize_host(&pattern), permission))
|
||||
.collect();
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
pub struct WorkspaceRootsToml {
|
||||
#[serde(flatten)]
|
||||
pub entries: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
impl WorkspaceRootsToml {
|
||||
pub fn enabled_roots(&self) -> impl Iterator<Item = &String> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter_map(|(path, enabled)| (*enabled).then_some(path))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
pub struct FilesystemPermissionsToml {
|
||||
/// Optional maximum depth for expanding unreadable glob patterns on
|
||||
/// platforms that snapshot glob matches before sandbox startup.
|
||||
#[schemars(range(min = 1))]
|
||||
pub glob_scan_max_depth: Option<usize>,
|
||||
#[serde(flatten)]
|
||||
pub entries: BTreeMap<String, FilesystemPermissionToml>,
|
||||
}
|
||||
|
||||
impl FilesystemPermissionsToml {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(untagged)]
|
||||
pub enum FilesystemPermissionToml {
|
||||
Access(FileSystemAccessMode),
|
||||
Scoped(BTreeMap<String, FileSystemAccessMode>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
pub struct NetworkDomainPermissionsToml {
|
||||
#[serde(flatten)]
|
||||
pub entries: BTreeMap<String, NetworkDomainPermissionToml>,
|
||||
}
|
||||
|
||||
impl NetworkDomainPermissionsToml {
|
||||
pub fn allowed_domains(&self) -> Option<Vec<String>> {
|
||||
let allowed_domains: Vec<String> = self
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|(_, permission)| matches!(permission, NetworkDomainPermissionToml::Allow))
|
||||
.map(|(pattern, _)| pattern.clone())
|
||||
.collect();
|
||||
(!allowed_domains.is_empty()).then_some(allowed_domains)
|
||||
}
|
||||
|
||||
pub fn denied_domains(&self) -> Option<Vec<String>> {
|
||||
let denied_domains: Vec<String> = self
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|(_, permission)| matches!(permission, NetworkDomainPermissionToml::Deny))
|
||||
.map(|(pattern, _)| pattern.clone())
|
||||
.collect();
|
||||
(!denied_domains.is_empty()).then_some(denied_domains)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum NetworkDomainPermissionToml {
|
||||
Allow,
|
||||
Deny,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NetworkDomainPermissionToml {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let permission = match self {
|
||||
Self::Allow => "allow",
|
||||
Self::Deny => "deny",
|
||||
};
|
||||
f.write_str(permission)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
pub struct NetworkUnixSocketPermissionsToml {
|
||||
#[serde(flatten)]
|
||||
pub entries: BTreeMap<String, NetworkUnixSocketPermissionToml>,
|
||||
}
|
||||
|
||||
impl NetworkUnixSocketPermissionsToml {
|
||||
pub fn allow_unix_sockets(&self) -> Vec<String> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|(_, permission)| matches!(permission, NetworkUnixSocketPermissionToml::Allow))
|
||||
.map(|(path, _)| path.clone())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(
|
||||
Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, JsonSchema,
|
||||
)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum NetworkUnixSocketPermissionToml {
|
||||
Allow,
|
||||
Deny,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for NetworkUnixSocketPermissionToml {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let permission = match self {
|
||||
Self::Allow => "allow",
|
||||
Self::Deny => "deny",
|
||||
};
|
||||
f.write_str(permission)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct NetworkToml {
|
||||
pub enabled: Option<bool>,
|
||||
pub proxy_url: Option<String>,
|
||||
pub enable_socks5: Option<bool>,
|
||||
pub socks_url: Option<String>,
|
||||
pub enable_socks5_udp: Option<bool>,
|
||||
pub allow_upstream_proxy: Option<bool>,
|
||||
pub dangerously_allow_non_loopback_proxy: Option<bool>,
|
||||
pub dangerously_allow_all_unix_sockets: Option<bool>,
|
||||
#[schemars(with = "Option<NetworkModeSchema>")]
|
||||
pub mode: Option<NetworkMode>,
|
||||
pub domains: Option<NetworkDomainPermissionsToml>,
|
||||
pub unix_sockets: Option<NetworkUnixSocketPermissionsToml>,
|
||||
/// Permits local servers and direct host-loopback connections and skips the proxy's
|
||||
/// additional private-network destination checks. Proxy domain rules still apply.
|
||||
/// Defaults to true for MXC, which cannot enforce false; otherwise defaults to false.
|
||||
pub allow_local_binding: Option<bool>,
|
||||
pub mitm: Option<NetworkMitmToml>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct NetworkMitmToml {
|
||||
/// Set to 2 when using origin-scoped hooks or credential substitution.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[schemars(range(min = 2, max = 2))]
|
||||
pub version: Option<u8>,
|
||||
#[schemars(with = "Option<BTreeMap<String, NetworkMitmHookToml>>")]
|
||||
pub hooks: Option<IndexMap<String, NetworkMitmHookToml>>,
|
||||
#[schemars(with = "Option<BTreeMap<String, NetworkMitmActionToml>>")]
|
||||
pub actions: Option<IndexMap<String, NetworkMitmActionToml>>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct NetworkMitmTomlUnchecked {
|
||||
version: Option<u8>,
|
||||
pub hooks: Option<IndexMap<String, NetworkMitmHookToml>>,
|
||||
pub actions: Option<IndexMap<String, NetworkMitmActionToml>>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct NetworkMitmHookToml {
|
||||
#[serde(default)]
|
||||
pub schemes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub ports: Vec<u16>,
|
||||
pub host: String,
|
||||
pub methods: Vec<String>,
|
||||
pub path_prefixes: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub query: BTreeMap<String, Vec<String>>,
|
||||
#[serde(default)]
|
||||
pub headers: BTreeMap<String, Vec<String>>,
|
||||
#[schemars(with = "Option<MitmHookBodyConfigSchema>")]
|
||||
pub body: Option<MitmHookBodyConfig>,
|
||||
pub action: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum NetworkModeSchema {
|
||||
Limited,
|
||||
Full,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct NetworkMitmActionToml {
|
||||
pub body_secret_substitution: Option<codex_network_proxy::BodySecretSubstitutionConfig>,
|
||||
pub aws_sigv4: Option<codex_network_proxy::AwsSigV4Config>,
|
||||
pub strip_request_headers: Vec<String>,
|
||||
pub inject_request_headers: Vec<NetworkMitmInjectedHeaderToml>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct NetworkMitmInjectedHeaderToml {
|
||||
pub placeholder: Option<String>,
|
||||
pub name: String,
|
||||
pub secret_env_var: Option<String>,
|
||||
pub secret_file: Option<String>,
|
||||
pub prefix: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(transparent)]
|
||||
struct MitmHookBodyConfigSchema(pub serde_json::Value);
|
||||
|
||||
impl<'de> Deserialize<'de> for NetworkMitmToml {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let unchecked = NetworkMitmTomlUnchecked::deserialize(deserializer)?;
|
||||
let mitm = Self {
|
||||
version: unchecked.version,
|
||||
hooks: unchecked.hooks,
|
||||
actions: unchecked.actions,
|
||||
};
|
||||
mitm.validate_action_definitions()
|
||||
.map_err(serde::de::Error::custom)?;
|
||||
Ok(mitm)
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkMitmToml {
|
||||
pub fn validate_action_definitions(&self) -> Result<(), String> {
|
||||
if let Some(version) = self.version
|
||||
&& version != 2
|
||||
{
|
||||
return Err(format!("unsupported network.mitm.version {version}"));
|
||||
}
|
||||
if let Some(actions) = self.actions.as_ref() {
|
||||
for (action_name, action) in actions {
|
||||
let uses_placeholder = action
|
||||
.inject_request_headers
|
||||
.iter()
|
||||
.any(|header| header.placeholder.is_some());
|
||||
if self.version.is_none()
|
||||
&& (uses_placeholder
|
||||
|| action.aws_sigv4.is_some()
|
||||
|| action.body_secret_substitution.is_some())
|
||||
{
|
||||
return Err("scoped MITM actions require network.mitm.version = 2".to_string());
|
||||
}
|
||||
if action.is_empty() {
|
||||
return Err(format!(
|
||||
"network.mitm.actions.{action_name} must define at least one operation"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let Some(hooks) = self.hooks.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for (hook_name, hook) in hooks {
|
||||
let signing_count = hook
|
||||
.action
|
||||
.iter()
|
||||
.filter(|name| {
|
||||
self.actions
|
||||
.as_ref()
|
||||
.and_then(|actions| actions.get(*name))
|
||||
.is_some_and(|action| action.aws_sigv4.is_some())
|
||||
})
|
||||
.count();
|
||||
if signing_count > 1 {
|
||||
return Err(format!(
|
||||
"network.mitm.hooks.{hook_name} must select at most one AWS signing action"
|
||||
));
|
||||
}
|
||||
let substitution_count = hook
|
||||
.action
|
||||
.iter()
|
||||
.filter(|name| {
|
||||
self.actions
|
||||
.as_ref()
|
||||
.and_then(|actions| actions.get(*name))
|
||||
.is_some_and(|action| action.body_secret_substitution.is_some())
|
||||
})
|
||||
.count();
|
||||
if substitution_count > 1 {
|
||||
return Err(format!(
|
||||
"network.mitm.hooks.{hook_name} must select at most one body substitution action"
|
||||
));
|
||||
}
|
||||
if self.version.is_none() && (!hook.schemes.is_empty() || !hook.ports.is_empty()) {
|
||||
return Err("scoped MITM hooks require network.mitm.version = 2".to_string());
|
||||
}
|
||||
if hook.action.is_empty() {
|
||||
return Err(format!(
|
||||
"network.mitm.hooks.{hook_name}.action must not be empty"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn to_runtime_hooks(
|
||||
&self,
|
||||
actions_by_name: Option<&IndexMap<String, NetworkMitmActionToml>>,
|
||||
) -> Vec<MitmHookConfig> {
|
||||
self.hooks
|
||||
.as_ref()
|
||||
.map(|hooks| {
|
||||
hooks
|
||||
.values()
|
||||
.map(|hook| hook.to_runtime(actions_by_name))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkMitmActionToml {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.body_secret_substitution.is_none()
|
||||
&& self.aws_sigv4.is_none()
|
||||
&& self.strip_request_headers.is_empty()
|
||||
&& self.inject_request_headers.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkToml {
|
||||
pub fn apply_to_network_proxy_config(&self, config: &mut NetworkProxyConfig) {
|
||||
if let Some(enabled) = self.enabled {
|
||||
config.enabled = enabled;
|
||||
}
|
||||
if let Some(proxy_url) = self.proxy_url.as_ref() {
|
||||
config.proxy_url = proxy_url.clone();
|
||||
}
|
||||
if let Some(enable_socks5) = self.enable_socks5 {
|
||||
config.enable_socks5 = enable_socks5;
|
||||
}
|
||||
if let Some(socks_url) = self.socks_url.as_ref() {
|
||||
config.socks_url = socks_url.clone();
|
||||
}
|
||||
if let Some(enable_socks5_udp) = self.enable_socks5_udp {
|
||||
config.enable_socks5_udp = enable_socks5_udp;
|
||||
}
|
||||
if let Some(allow_upstream_proxy) = self.allow_upstream_proxy {
|
||||
config.allow_upstream_proxy = allow_upstream_proxy;
|
||||
}
|
||||
if let Some(dangerously_allow_non_loopback_proxy) =
|
||||
self.dangerously_allow_non_loopback_proxy
|
||||
{
|
||||
config.dangerously_allow_non_loopback_proxy = dangerously_allow_non_loopback_proxy;
|
||||
}
|
||||
if let Some(dangerously_allow_all_unix_sockets) = self.dangerously_allow_all_unix_sockets {
|
||||
config.dangerously_allow_all_unix_sockets = Some(dangerously_allow_all_unix_sockets);
|
||||
}
|
||||
if let Some(mode) = self.mode {
|
||||
config.mode = mode;
|
||||
}
|
||||
if let Some(domains) = self.domains.as_ref() {
|
||||
overlay_network_domain_permissions(config, domains);
|
||||
}
|
||||
if let Some(unix_sockets) = self.unix_sockets.as_ref() {
|
||||
let mut proxy_unix_sockets = config.unix_sockets.take().unwrap_or_default();
|
||||
for (path, permission) in &unix_sockets.entries {
|
||||
let permission = match permission {
|
||||
NetworkUnixSocketPermissionToml::Allow => {
|
||||
ProxyNetworkUnixSocketPermission::Allow
|
||||
}
|
||||
NetworkUnixSocketPermissionToml::Deny => ProxyNetworkUnixSocketPermission::Deny,
|
||||
};
|
||||
proxy_unix_sockets.entries.insert(path.clone(), permission);
|
||||
}
|
||||
config.unix_sockets = Some(proxy_unix_sockets);
|
||||
}
|
||||
if let Some(allow_local_binding) = self.allow_local_binding {
|
||||
config.allow_local_binding = Some(allow_local_binding);
|
||||
}
|
||||
if let Some(mitm) = self.mitm.as_ref() {
|
||||
config.mitm_hooks = mitm.to_runtime_hooks(mitm.actions.as_ref());
|
||||
}
|
||||
config.mitm = config.mode == NetworkMode::Limited || !config.mitm_hooks.is_empty();
|
||||
}
|
||||
|
||||
pub fn to_network_proxy_config(&self) -> NetworkProxyConfig {
|
||||
let mut config = NetworkProxyConfig::default();
|
||||
self.apply_to_network_proxy_config(&mut config);
|
||||
config
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkMitmHookToml {
|
||||
fn to_runtime(
|
||||
&self,
|
||||
actions_by_name: Option<&IndexMap<String, NetworkMitmActionToml>>,
|
||||
) -> MitmHookConfig {
|
||||
MitmHookConfig {
|
||||
host: self.host.clone(),
|
||||
matcher: MitmHookMatchConfig {
|
||||
schemes: self.schemes.clone(),
|
||||
ports: self.ports.clone(),
|
||||
methods: self.methods.clone(),
|
||||
path_prefixes: self.path_prefixes.clone(),
|
||||
query: self.query.clone(),
|
||||
headers: self.headers.clone(),
|
||||
body: self.body.clone(),
|
||||
},
|
||||
actions: self.selected_actions(actions_by_name),
|
||||
}
|
||||
}
|
||||
|
||||
fn selected_actions(
|
||||
&self,
|
||||
actions_by_name: Option<&IndexMap<String, NetworkMitmActionToml>>,
|
||||
) -> MitmHookActionsConfig {
|
||||
let Some(actions_by_name) = actions_by_name else {
|
||||
return MitmHookActionsConfig::default();
|
||||
};
|
||||
|
||||
let mut selected = MitmHookActionsConfig::default();
|
||||
for action_name in &self.action {
|
||||
if let Some(action) = actions_by_name.get(action_name) {
|
||||
if action.body_secret_substitution.is_some() {
|
||||
selected.body_secret_substitution = action.body_secret_substitution.clone();
|
||||
}
|
||||
if action.aws_sigv4.is_some() {
|
||||
selected.aws_sigv4 = action.aws_sigv4.clone();
|
||||
}
|
||||
selected
|
||||
.strip_request_headers
|
||||
.extend(action.strip_request_headers.clone());
|
||||
selected.inject_request_headers.extend(
|
||||
action
|
||||
.inject_request_headers
|
||||
.iter()
|
||||
.map(NetworkMitmInjectedHeaderToml::to_runtime),
|
||||
);
|
||||
}
|
||||
}
|
||||
selected
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkMitmInjectedHeaderToml {
|
||||
fn to_runtime(&self) -> InjectedHeaderConfig {
|
||||
InjectedHeaderConfig {
|
||||
placeholder: self.placeholder.clone(),
|
||||
name: self.name.clone(),
|
||||
secret_env_var: self.secret_env_var.clone(),
|
||||
secret_file: self.secret_file.clone(),
|
||||
prefix: self.prefix.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn overlay_network_domain_permissions(
|
||||
config: &mut NetworkProxyConfig,
|
||||
domains: &NetworkDomainPermissionsToml,
|
||||
) {
|
||||
for (pattern, permission) in &domains.entries {
|
||||
let permission = match permission {
|
||||
NetworkDomainPermissionToml::Allow => ProxyNetworkDomainPermission::Allow,
|
||||
NetworkDomainPermissionToml::Deny => ProxyNetworkDomainPermission::Deny,
|
||||
};
|
||||
config.upsert_domain_permission(pattern.clone(), permission, normalize_host);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "permissions_toml_tests.rs"]
|
||||
mod tests;
|
||||
140
codex-rs/config/src/permissions_toml_tests.rs
Normal file
140
codex-rs/config/src/permissions_toml_tests.rs
Normal file
@@ -0,0 +1,140 @@
|
||||
//! Trusted network extensions survive TOML resolution without ambiguous signing authority.
|
||||
|
||||
use super::*;
|
||||
use codex_network_proxy::ProxySecretSource;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
const SIGNING: &str = r#"
|
||||
version = 2
|
||||
[actions.aws.aws_sigv4]
|
||||
placeholder_access_key_id = "MASKEDACCESSKEY"
|
||||
region = "us-east-1"
|
||||
service = "s3"
|
||||
access_key_id = { env_var = "PROXY_ACCESS_KEY" }
|
||||
secret_access_key = { file = "/trusted/aws-secret" }
|
||||
session_token = { env_var = "PROXY_SESSION_TOKEN" }
|
||||
|
||||
[[actions.substitute.inject_request_headers]]
|
||||
name = "x-api-key"
|
||||
secret_env_var = "PROXY_API_KEY"
|
||||
placeholder = "dummy-key"
|
||||
|
||||
[actions.body.body_secret_substitution]
|
||||
port = 443
|
||||
max_body_bytes = 1024
|
||||
replacements = [{ placeholder = "codex-secret-0123456789abcdef", secret = { env_var = "BODY_SECRET" } }]
|
||||
|
||||
[hooks.bucket]
|
||||
host = "bucket.s3.amazonaws.com"
|
||||
schemes = ["https"]
|
||||
ports = [443]
|
||||
methods = ["PUT"]
|
||||
path_prefixes = ["/workspace/"]
|
||||
action = ["substitute", "body", "aws"]
|
||||
"#;
|
||||
|
||||
#[test]
|
||||
fn resolves_native_signing_and_substitution_actions_from_toml() {
|
||||
let config: NetworkMitmToml = toml::from_str(SIGNING).unwrap();
|
||||
let hooks = config.to_runtime_hooks(config.actions.as_ref());
|
||||
assert_eq!(hooks[0].matcher.schemes, vec!["https"]);
|
||||
assert_eq!(hooks[0].matcher.ports, vec![443]);
|
||||
let signer = hooks[0].actions.aws_sigv4.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
hooks[0]
|
||||
.actions
|
||||
.body_secret_substitution
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.replacements[0]
|
||||
.secret,
|
||||
ProxySecretSource::EnvVar("BODY_SECRET".into())
|
||||
);
|
||||
assert_eq!(
|
||||
signer.access_key_id,
|
||||
ProxySecretSource::EnvVar("PROXY_ACCESS_KEY".into())
|
||||
);
|
||||
assert_eq!(signer.port, 443);
|
||||
assert_eq!(
|
||||
hooks[0].actions.inject_request_headers[0]
|
||||
.placeholder
|
||||
.as_deref(),
|
||||
Some("dummy-key")
|
||||
);
|
||||
let wire = serde_json::to_value(&hooks).unwrap();
|
||||
let decoded: Vec<MitmHookConfig> = serde_json::from_value(wire).unwrap();
|
||||
assert_eq!(decoded, hooks);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scoped_rules_reject_rollback_to_the_legacy_format() {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct LegacyMitm {
|
||||
#[serde(rename = "hooks")]
|
||||
_hooks: toml::Value,
|
||||
#[serde(rename = "actions")]
|
||||
_actions: toml::Value,
|
||||
}
|
||||
|
||||
let unversioned = SIGNING.replacen("version = 2\n", "", 1);
|
||||
assert!(toml::from_str::<NetworkMitmToml>(&unversioned).is_err());
|
||||
assert!(toml::from_str::<LegacyMitm>(&unversioned).is_ok());
|
||||
assert!(toml::from_str::<LegacyMitm>(SIGNING).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_and_managed_requirements_reject_misspelled_mitm_matchers() {
|
||||
let profile = SIGNING
|
||||
.replace("[actions.", "[permissions.test.network.mitm.actions.")
|
||||
.replace("[hooks.", "[permissions.test.network.mitm.hooks.");
|
||||
let profile = format!("[permissions.test.network.mitm]\n{profile}");
|
||||
toml::from_str::<crate::config_toml::ConfigToml>(&profile).unwrap();
|
||||
toml::from_str::<crate::ConfigRequirementsToml>(&profile).unwrap();
|
||||
for (key, value) in [
|
||||
("header", r#"{ x-tenant = ["allowed"] }"#),
|
||||
("port", "[443]"),
|
||||
("scheme", r#"["https"]"#),
|
||||
] {
|
||||
let input = format!("{profile}\n{key} = {value}");
|
||||
for error in [
|
||||
toml::from_str::<crate::config_toml::ConfigToml>(&input)
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
toml::from_str::<crate::ConfigRequirementsToml>(&input)
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
] {
|
||||
assert!(error.contains(&format!("unknown field `{key}`")), "{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_misspelled_header_placeholder() {
|
||||
let input = SIGNING.replacen("placeholder =", "unknown_placeholder =", 1);
|
||||
let error = toml::from_str::<NetworkMitmToml>(&input).unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("unknown field `unknown_placeholder`")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_multiple_signing_actions_and_unknown_signing_parameters() {
|
||||
assert!(
|
||||
toml::from_str::<NetworkMitmToml>(&SIGNING.replace(
|
||||
"action = [\"substitute\", \"body\", \"aws\"]",
|
||||
"action = [\"aws\", \"aws\"]"
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
toml::from_str::<NetworkMitmToml>(&SIGNING.replace(
|
||||
"region = \"us-east-1\"",
|
||||
"region = \"us-east-1\"\nallow_unsigned_payload = true"
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
307
codex-rs/config/src/plugin_edit.rs
Normal file
307
codex-rs/config/src/plugin_edit.rs
Normal file
@@ -0,0 +1,307 @@
|
||||
use std::fs;
|
||||
use std::io::ErrorKind;
|
||||
use std::path::Path;
|
||||
|
||||
use codex_utils_path::resolve_symlink_write_paths;
|
||||
use codex_utils_path::write_atomically;
|
||||
use tokio::task;
|
||||
use toml_edit::DocumentMut;
|
||||
use toml_edit::Item as TomlItem;
|
||||
use toml_edit::Table as TomlTable;
|
||||
use toml_edit::value;
|
||||
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PluginConfigEdit {
|
||||
SetEnabled { plugin_key: String, enabled: bool },
|
||||
Clear { plugin_key: String },
|
||||
}
|
||||
|
||||
pub async fn set_user_plugin_enabled(
|
||||
codex_home: &Path,
|
||||
plugin_key: String,
|
||||
enabled: bool,
|
||||
) -> std::io::Result<()> {
|
||||
apply_user_plugin_config_edits(
|
||||
codex_home,
|
||||
vec![PluginConfigEdit::SetEnabled {
|
||||
plugin_key,
|
||||
enabled,
|
||||
}],
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn clear_user_plugin(codex_home: &Path, plugin_key: String) -> std::io::Result<()> {
|
||||
apply_user_plugin_config_edits(codex_home, vec![PluginConfigEdit::Clear { plugin_key }]).await
|
||||
}
|
||||
|
||||
pub async fn apply_user_plugin_config_edits(
|
||||
codex_home: &Path,
|
||||
edits: Vec<PluginConfigEdit>,
|
||||
) -> std::io::Result<()> {
|
||||
let codex_home = codex_home.to_path_buf();
|
||||
task::spawn_blocking(move || apply_user_plugin_config_edits_blocking(&codex_home, edits))
|
||||
.await
|
||||
.map_err(|err| std::io::Error::other(format!("config persistence task panicked: {err}")))?
|
||||
}
|
||||
|
||||
fn apply_user_plugin_config_edits_blocking(
|
||||
codex_home: &Path,
|
||||
edits: Vec<PluginConfigEdit>,
|
||||
) -> std::io::Result<()> {
|
||||
if edits.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let config_path = codex_home.join(CONFIG_TOML_FILE);
|
||||
let write_paths = resolve_symlink_write_paths(&config_path)?;
|
||||
let mut doc = read_or_create_document(write_paths.read_path.as_deref())?;
|
||||
let mut mutated = false;
|
||||
for edit in edits {
|
||||
mutated |= match edit {
|
||||
PluginConfigEdit::SetEnabled {
|
||||
plugin_key,
|
||||
enabled,
|
||||
} => set_plugin_enabled(&mut doc, &plugin_key, enabled),
|
||||
PluginConfigEdit::Clear { plugin_key } => clear_plugin(&mut doc, &plugin_key),
|
||||
};
|
||||
}
|
||||
if !mutated {
|
||||
return Ok(());
|
||||
}
|
||||
write_atomically(&write_paths.write_path, &doc.to_string())
|
||||
}
|
||||
|
||||
fn read_or_create_document(config_path: Option<&Path>) -> std::io::Result<DocumentMut> {
|
||||
let Some(config_path) = config_path else {
|
||||
return Ok(DocumentMut::new());
|
||||
};
|
||||
match fs::read_to_string(config_path) {
|
||||
Ok(raw) => raw
|
||||
.parse::<DocumentMut>()
|
||||
.map_err(|err| std::io::Error::new(ErrorKind::InvalidData, err)),
|
||||
Err(err) if err.kind() == ErrorKind::NotFound => Ok(DocumentMut::new()),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_plugin_enabled(doc: &mut DocumentMut, plugin_key: &str, enabled: bool) -> bool {
|
||||
let Some(plugins) = ensure_plugins_table(doc) else {
|
||||
return false;
|
||||
};
|
||||
let Some(plugin) = ensure_table_for_write(&mut plugins[plugin_key]) else {
|
||||
return false;
|
||||
};
|
||||
let mut replacement = value(enabled);
|
||||
if let Some(existing) = plugin.get("enabled") {
|
||||
preserve_decor(existing, &mut replacement);
|
||||
}
|
||||
plugin["enabled"] = replacement;
|
||||
true
|
||||
}
|
||||
|
||||
fn clear_plugin(doc: &mut DocumentMut, plugin_key: &str) -> bool {
|
||||
let root = doc.as_table_mut();
|
||||
let Some(plugins_item) = root.get_mut("plugins") else {
|
||||
return false;
|
||||
};
|
||||
let Some(plugins) = ensure_table_for_read(plugins_item) else {
|
||||
return false;
|
||||
};
|
||||
plugins.remove(plugin_key).is_some()
|
||||
}
|
||||
|
||||
fn ensure_plugins_table(doc: &mut DocumentMut) -> Option<&mut TomlTable> {
|
||||
let root = doc.as_table_mut();
|
||||
if !root.contains_key("plugins") {
|
||||
root.insert("plugins", TomlItem::Table(new_implicit_table()));
|
||||
}
|
||||
ensure_table_for_write(root.get_mut("plugins")?)
|
||||
}
|
||||
|
||||
fn ensure_table_for_write(item: &mut TomlItem) -> Option<&mut TomlTable> {
|
||||
match item {
|
||||
TomlItem::Table(table) => Some(table),
|
||||
TomlItem::Value(value) => {
|
||||
let table = value
|
||||
.as_inline_table()
|
||||
.map_or_else(new_implicit_table, table_from_inline);
|
||||
*item = TomlItem::Table(table);
|
||||
item.as_table_mut()
|
||||
}
|
||||
TomlItem::None => {
|
||||
*item = TomlItem::Table(new_implicit_table());
|
||||
item.as_table_mut()
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_table_for_read(item: &mut TomlItem) -> Option<&mut TomlTable> {
|
||||
match item {
|
||||
TomlItem::Table(_) => {}
|
||||
TomlItem::Value(value) => {
|
||||
let inline = value.as_inline_table()?.clone();
|
||||
*item = TomlItem::Table(table_from_inline(&inline));
|
||||
}
|
||||
_ => return None,
|
||||
}
|
||||
item.as_table_mut()
|
||||
}
|
||||
|
||||
fn table_from_inline(inline: &toml_edit::InlineTable) -> TomlTable {
|
||||
let mut table = new_implicit_table();
|
||||
for (key, value) in inline.iter() {
|
||||
let mut value = value.clone();
|
||||
value.decor_mut().set_suffix("");
|
||||
table.insert(key, TomlItem::Value(value));
|
||||
}
|
||||
table
|
||||
}
|
||||
|
||||
fn new_implicit_table() -> TomlTable {
|
||||
let mut table = TomlTable::new();
|
||||
table.set_implicit(true);
|
||||
table
|
||||
}
|
||||
|
||||
fn preserve_decor(existing: &TomlItem, replacement: &mut TomlItem) {
|
||||
if let (TomlItem::Value(existing_value), TomlItem::Value(replacement_value)) =
|
||||
(existing, replacement)
|
||||
{
|
||||
replacement_value
|
||||
.decor_mut()
|
||||
.clone_from(existing_value.decor());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_user_plugin_enabled_writes_plugin_entry() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
|
||||
set_user_plugin_enabled(
|
||||
codex_home.path(),
|
||||
"demo@market".to_string(),
|
||||
/*enabled*/ true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let config = read_config(codex_home.path());
|
||||
let expected: toml::Value = toml::from_str(
|
||||
r#"
|
||||
[plugins."demo@market"]
|
||||
enabled = true
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn set_user_plugin_enabled_preserves_existing_plugin_fields() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"
|
||||
[plugins."demo@market"]
|
||||
enabled = false
|
||||
source = "/tmp/plugin"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
set_user_plugin_enabled(
|
||||
codex_home.path(),
|
||||
"demo@market".to_string(),
|
||||
/*enabled*/ true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let config = read_config(codex_home.path());
|
||||
let expected: toml::Value = toml::from_str(
|
||||
r#"
|
||||
[plugins."demo@market"]
|
||||
enabled = true
|
||||
source = "/tmp/plugin"
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config, expected);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clear_user_plugin_removes_empty_plugins_table() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
fs::write(
|
||||
codex_home.path().join(CONFIG_TOML_FILE),
|
||||
r#"
|
||||
[plugins."demo@market"]
|
||||
enabled = true
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
clear_user_plugin(codex_home.path(), "demo@market".to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
fs::read_to_string(codex_home.path().join(CONFIG_TOML_FILE)).unwrap(),
|
||||
""
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clear_user_plugin_missing_entry_does_not_create_config() {
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
|
||||
clear_user_plugin(codex_home.path(), "demo@market".to_string())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(!codex_home.path().join(CONFIG_TOML_FILE).exists());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[cfg(unix)]
|
||||
async fn set_user_plugin_enabled_follows_config_symlink() {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
let codex_home = TempDir::new().unwrap();
|
||||
let target_path = codex_home.path().join("target_config.toml");
|
||||
symlink(&target_path, codex_home.path().join(CONFIG_TOML_FILE)).unwrap();
|
||||
|
||||
set_user_plugin_enabled(
|
||||
codex_home.path(),
|
||||
"demo@market".to_string(),
|
||||
/*enabled*/ true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let config =
|
||||
toml::from_str::<toml::Value>(&fs::read_to_string(target_path).unwrap()).unwrap();
|
||||
let expected: toml::Value = toml::from_str(
|
||||
r#"
|
||||
[plugins."demo@market"]
|
||||
enabled = true
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(config, expected);
|
||||
}
|
||||
|
||||
fn read_config(codex_home: &Path) -> toml::Value {
|
||||
toml::from_str(&fs::read_to_string(codex_home.join(CONFIG_TOML_FILE)).unwrap()).unwrap()
|
||||
}
|
||||
}
|
||||
83
codex-rs/config/src/profile_toml.rs
Normal file
83
codex-rs/config/src/profile_toml.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::config_toml::ToolsToml;
|
||||
use crate::types::AnalyticsConfigToml;
|
||||
use crate::types::ApprovalsReviewer;
|
||||
use crate::types::Personality;
|
||||
use crate::types::SessionPickerViewMode;
|
||||
use crate::types::WindowsToml;
|
||||
use codex_features::FeaturesToml;
|
||||
use codex_protocol::config_types::ReasoningSummary;
|
||||
use codex_protocol::config_types::SandboxMode;
|
||||
use codex_protocol::config_types::Verbosity;
|
||||
use codex_protocol::config_types::WebSearchMode;
|
||||
use codex_protocol::openai_models::ReasoningEffort;
|
||||
use codex_protocol::protocol::AskForApproval;
|
||||
|
||||
/// Collection of common configuration options that a user can define as a unit
|
||||
/// in `config.toml`.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ConfigProfile {
|
||||
pub model: Option<String>,
|
||||
/// Optional explicit service tier request id for new turns (for example
|
||||
/// `default`, `priority`, or `flex`; legacy `fast` also works).
|
||||
pub service_tier: Option<String>,
|
||||
/// The key in the `model_providers` map identifying the
|
||||
/// [`ModelProviderInfo`] to use.
|
||||
pub model_provider: Option<String>,
|
||||
#[schemars(with = "Option<crate::schema::ConfigAskForApproval>")]
|
||||
pub approval_policy: Option<AskForApproval>,
|
||||
pub approvals_reviewer: Option<ApprovalsReviewer>,
|
||||
pub sandbox_mode: Option<SandboxMode>,
|
||||
pub model_reasoning_effort: Option<ReasoningEffort>,
|
||||
pub plan_mode_reasoning_effort: Option<ReasoningEffort>,
|
||||
pub model_reasoning_summary: Option<ReasoningSummary>,
|
||||
pub model_verbosity: Option<Verbosity>,
|
||||
/// Optional path to a JSON model catalog (applied on startup only).
|
||||
pub model_catalog_json: Option<AbsolutePathBuf>,
|
||||
/// Deprecated: `friendly` and `pragmatic` no longer select a style.
|
||||
pub personality: Option<Personality>,
|
||||
pub chatgpt_base_url: Option<String>,
|
||||
/// Optional path to a file containing model instructions.
|
||||
pub model_instructions_file: Option<AbsolutePathBuf>,
|
||||
/// Deprecated: ignored.
|
||||
#[schemars(skip)]
|
||||
pub js_repl_node_path: Option<AbsolutePathBuf>,
|
||||
/// Deprecated: ignored.
|
||||
#[schemars(skip)]
|
||||
pub js_repl_node_module_dirs: Option<Vec<AbsolutePathBuf>>,
|
||||
pub experimental_compact_prompt_file: Option<AbsolutePathBuf>,
|
||||
pub include_permissions_instructions: Option<bool>,
|
||||
pub include_apps_instructions: Option<bool>,
|
||||
pub include_collaboration_mode_instructions: Option<bool>,
|
||||
pub include_environment_context: Option<bool>,
|
||||
pub include_environment_context_time: Option<bool>,
|
||||
pub experimental_use_unified_exec_tool: Option<bool>,
|
||||
pub tools: Option<ToolsToml>,
|
||||
pub web_search: Option<WebSearchMode>,
|
||||
pub analytics: Option<AnalyticsConfigToml>,
|
||||
/// TUI settings scoped to this profile.
|
||||
#[serde(default)]
|
||||
pub tui: Option<ProfileTui>,
|
||||
#[serde(default)]
|
||||
pub windows: Option<WindowsToml>,
|
||||
/// Optional feature toggles scoped to this profile.
|
||||
#[serde(default)]
|
||||
// Injects known feature keys into the schema and forbids unknown keys.
|
||||
#[schemars(schema_with = "crate::schema::features_schema")]
|
||||
pub features: Option<FeaturesToml>,
|
||||
pub oss_provider: Option<String>,
|
||||
}
|
||||
|
||||
/// TUI settings supported inside a named profile.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ProfileTui {
|
||||
/// Preferred layout for resume/fork session picker results.
|
||||
#[serde(default)]
|
||||
pub session_picker_view: Option<SessionPickerViewMode>,
|
||||
}
|
||||
50
codex-rs/config/src/project_root_markers.rs
Normal file
50
codex-rs/config/src/project_root_markers.rs
Normal file
@@ -0,0 +1,50 @@
|
||||
use std::io;
|
||||
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
const DEFAULT_PROJECT_ROOT_MARKERS: &[&str] = &[".git"];
|
||||
|
||||
/// Reads `project_root_markers` from a merged `config.toml` [toml::Value].
|
||||
///
|
||||
/// Invariants:
|
||||
/// - If `project_root_markers` is not specified, returns `Ok(None)`.
|
||||
/// - If `project_root_markers` is specified, returns `Ok(Some(markers))` where
|
||||
/// `markers` is a `Vec<String>` (including `Ok(Some(Vec::new()))` for an
|
||||
/// empty array, which indicates that root detection should be disabled).
|
||||
/// - Returns an error if `project_root_markers` is specified but is not an
|
||||
/// array of strings.
|
||||
pub fn project_root_markers_from_config(config: &TomlValue) -> io::Result<Option<Vec<String>>> {
|
||||
let Some(table) = config.as_table() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(markers_value) = table.get("project_root_markers") else {
|
||||
return Ok(None);
|
||||
};
|
||||
let TomlValue::Array(entries) = markers_value else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"project_root_markers must be an array of strings",
|
||||
));
|
||||
};
|
||||
if entries.is_empty() {
|
||||
return Ok(Some(Vec::new()));
|
||||
}
|
||||
let mut markers = Vec::new();
|
||||
for entry in entries {
|
||||
let Some(marker) = entry.as_str() else {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidData,
|
||||
"project_root_markers must be an array of strings",
|
||||
));
|
||||
};
|
||||
markers.push(marker.to_string());
|
||||
}
|
||||
Ok(Some(markers))
|
||||
}
|
||||
|
||||
pub fn default_project_root_markers() -> Vec<String> {
|
||||
DEFAULT_PROJECT_ROOT_MARKERS
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect()
|
||||
}
|
||||
108
codex-rs/config/src/project_trust.rs
Normal file
108
codex-rs/config/src/project_trust.rs
Normal file
@@ -0,0 +1,108 @@
|
||||
//! Match merged project settings against ordered native path spellings.
|
||||
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::config_toml::ProjectConfig;
|
||||
use codex_utils_path::normalize_for_path_comparison;
|
||||
use codex_utils_path_uri::PathConvention;
|
||||
use std::path::Path;
|
||||
|
||||
/// Original and executor-normalized canonical spellings of one native path.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ProjectTrustPath {
|
||||
pub original: String,
|
||||
pub canonical: Option<String>,
|
||||
}
|
||||
|
||||
/// Ordered project lookup keys for one executor working directory.
|
||||
///
|
||||
/// Resolve this independently of configuration layers, then apply it after all
|
||||
/// local and cloud projects maps have been merged. Cwd entries, including an
|
||||
/// entry without a trust level, take precedence over repository-root entries.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ProjectTrustLookup {
|
||||
convention: PathConvention,
|
||||
keys: Vec<String>,
|
||||
}
|
||||
|
||||
impl ProjectTrustLookup {
|
||||
pub(crate) fn from_native_path(path: &Path) -> Self {
|
||||
Self::from_paths(
|
||||
PathConvention::native(),
|
||||
ProjectTrustPath {
|
||||
original: path.to_string_lossy().into_owned(),
|
||||
canonical: normalize_for_path_comparison(path)
|
||||
.ok()
|
||||
.map(|path| path.to_string_lossy().into_owned()),
|
||||
},
|
||||
/*repo_root*/ None,
|
||||
)
|
||||
}
|
||||
|
||||
/// Build lookup keys for a cwd and optional repository root.
|
||||
///
|
||||
/// Cwd keys always take precedence over repository-root keys. Each
|
||||
/// canonical spelling is tried before its original spelling; `None` uses
|
||||
/// only the original. This method performs no filesystem access or path
|
||||
/// resolution. Callers must supply executor-normalized canonical spellings,
|
||||
/// including Windows extended-length prefixes and WSL mounted-drive folding
|
||||
/// where applicable. Original spellings remain literal. Windows keys are
|
||||
/// matched without ASCII case distinctions; POSIX keys remain case-sensitive.
|
||||
pub fn from_paths(
|
||||
convention: PathConvention,
|
||||
cwd: ProjectTrustPath,
|
||||
repo_root: Option<ProjectTrustPath>,
|
||||
) -> Self {
|
||||
let mut keys = Vec::new();
|
||||
for ProjectTrustPath {
|
||||
original,
|
||||
canonical,
|
||||
} in std::iter::once(cwd).chain(repo_root)
|
||||
{
|
||||
let original = normalize_lookup_key(&original, convention);
|
||||
let canonical = canonical
|
||||
.map(|key| normalize_lookup_key(&key, convention))
|
||||
.unwrap_or_else(|| original.clone());
|
||||
if canonical != original {
|
||||
keys.push(canonical);
|
||||
}
|
||||
keys.push(original);
|
||||
}
|
||||
Self { convention, keys }
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigToml {
|
||||
/// Select the active project from the final merged projects map.
|
||||
pub fn get_active_project_for_lookup(
|
||||
&self,
|
||||
lookup: &ProjectTrustLookup,
|
||||
) -> Option<ProjectConfig> {
|
||||
let projects = self.projects.as_ref()?;
|
||||
for key in &lookup.keys {
|
||||
if let Some(project) = projects.get(key) {
|
||||
return Some(project.clone());
|
||||
}
|
||||
// Preserve native exact-key preference and deterministic selection
|
||||
// when multiple Windows keys differ only in ASCII case.
|
||||
if let Some((_, project)) = projects
|
||||
.iter()
|
||||
.filter(|(candidate, _)| normalize_lookup_key(candidate, lookup.convention) == *key)
|
||||
.min_by_key(|(candidate, _)| *candidate)
|
||||
{
|
||||
return Some(project.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_lookup_key(key: &str, convention: PathConvention) -> String {
|
||||
match convention {
|
||||
PathConvention::Windows => key.to_ascii_lowercase(),
|
||||
PathConvention::Posix => key.to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "project_trust_tests.rs"]
|
||||
mod tests;
|
||||
91
codex-rs/config/src/project_trust_tests.rs
Normal file
91
codex-rs/config/src/project_trust_tests.rs
Normal file
@@ -0,0 +1,91 @@
|
||||
//! Exercises project-key precedence and map matching across path conventions.
|
||||
|
||||
use super::*;
|
||||
use codex_protocol::config_types::TrustLevel;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn config_with_projects(entries: &[(&str, Option<TrustLevel>)]) -> ConfigToml {
|
||||
ConfigToml {
|
||||
projects: Some(
|
||||
entries
|
||||
.iter()
|
||||
.map(|(key, trust_level)| {
|
||||
(
|
||||
key.to_string(),
|
||||
ProjectConfig {
|
||||
trust_level: *trust_level,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_lookup_order(lookup: &ProjectTrustLookup, entries: &[(&str, Option<TrustLevel>)]) {
|
||||
let mut config = config_with_projects(entries);
|
||||
for (key, trust_level) in entries {
|
||||
assert_eq!(
|
||||
config.get_active_project_for_lookup(lookup),
|
||||
Some(ProjectConfig {
|
||||
trust_level: *trust_level
|
||||
}),
|
||||
);
|
||||
config.projects.as_mut().unwrap().remove(*key);
|
||||
}
|
||||
assert_eq!(config.get_active_project_for_lookup(lookup), None);
|
||||
assert_eq!(
|
||||
ConfigToml::default().get_active_project_for_lookup(lookup),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn posix_lookup_preserves_cwd_root_alias_order_and_case() {
|
||||
let lookup = ProjectTrustLookup::from_paths(
|
||||
PathConvention::Posix,
|
||||
ProjectTrustPath {
|
||||
original: "/alias/src".into(),
|
||||
canonical: Some("/repo/src".into()),
|
||||
},
|
||||
Some(ProjectTrustPath {
|
||||
original: "/alias".into(),
|
||||
canonical: Some("/repo".into()),
|
||||
}),
|
||||
);
|
||||
assert_lookup_order(
|
||||
&lookup,
|
||||
&[
|
||||
("/repo/src", None),
|
||||
("/alias/src", Some(TrustLevel::Trusted)),
|
||||
("/repo", Some(TrustLevel::Untrusted)),
|
||||
("/alias", Some(TrustLevel::Trusted)),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
config_with_projects(&[("/Repo/src", Some(TrustLevel::Trusted))])
|
||||
.get_active_project_for_lookup(&lookup),
|
||||
None,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_prefers_exact_normalized_key_then_sorted_aliases() {
|
||||
let lookup = ProjectTrustLookup::from_paths(
|
||||
PathConvention::Windows,
|
||||
ProjectTrustPath {
|
||||
original: r"C:\Repo".into(),
|
||||
canonical: None,
|
||||
},
|
||||
/*repo_root*/ None,
|
||||
);
|
||||
assert_lookup_order(
|
||||
&lookup,
|
||||
&[
|
||||
(r"c:\repo", Some(TrustLevel::Trusted)),
|
||||
(r"C:\REPO", Some(TrustLevel::Untrusted)),
|
||||
(r"C:\Repo", Some(TrustLevel::Trusted)),
|
||||
],
|
||||
);
|
||||
}
|
||||
206
codex-rs/config/src/requirements_exec_policy.rs
Normal file
206
codex-rs/config/src/requirements_exec_policy.rs
Normal file
@@ -0,0 +1,206 @@
|
||||
use codex_execpolicy::Decision;
|
||||
use codex_execpolicy::Policy;
|
||||
use codex_execpolicy::RequirementsExecPolicy;
|
||||
use codex_execpolicy::RuleRef;
|
||||
use codex_execpolicy::rule::PatternToken;
|
||||
use codex_execpolicy::rule::PrefixPattern;
|
||||
use codex_execpolicy::rule::PrefixRule;
|
||||
use multimap::MultiMap;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
|
||||
/// TOML representation of `[rules]` within `requirements.toml`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct RequirementsExecPolicyToml {
|
||||
pub prefix_rules: Vec<RequirementsExecPolicyPrefixRuleToml>,
|
||||
}
|
||||
|
||||
/// A TOML representation of the `prefix_rule(...)` Starlark builtin.
|
||||
///
|
||||
/// This shares the builtin's matching semantics and additionally supports managed `prompt-user` decisions.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct RequirementsExecPolicyPrefixRuleToml {
|
||||
#[serde(default)]
|
||||
pub canonical_matching: bool,
|
||||
pub pattern: Vec<RequirementsExecPolicyPatternTokenToml>,
|
||||
pub decision: Option<RequirementsExecPolicyDecisionToml>,
|
||||
pub justification: Option<String>,
|
||||
}
|
||||
|
||||
/// TOML-friendly representation of a pattern token.
|
||||
///
|
||||
/// Starlark supports either a string token or a list of alternative tokens at
|
||||
/// each position, but TOML arrays cannot mix strings and arrays. Using an
|
||||
/// array of tables sidesteps that restriction.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||
pub struct RequirementsExecPolicyPatternTokenToml {
|
||||
pub token: Option<String>,
|
||||
pub any_of: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum RequirementsExecPolicyDecisionToml {
|
||||
Allow,
|
||||
Prompt,
|
||||
PromptUser,
|
||||
Forbidden,
|
||||
}
|
||||
|
||||
impl RequirementsExecPolicyDecisionToml {
|
||||
fn as_decision(self) -> Decision {
|
||||
match self {
|
||||
Self::Allow => Decision::Allow,
|
||||
Self::Prompt => Decision::Prompt,
|
||||
Self::PromptUser => Decision::PromptUser,
|
||||
Self::Forbidden => Decision::Forbidden,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum RequirementsExecPolicyParseError {
|
||||
#[error("rules prefix_rules cannot be empty")]
|
||||
EmptyPrefixRules,
|
||||
|
||||
#[error("rules prefix_rule at index {rule_index} has an empty pattern")]
|
||||
EmptyPattern { rule_index: usize },
|
||||
|
||||
#[error(
|
||||
"rules prefix_rule at index {rule_index} has an invalid pattern token at index {token_index}: {reason}"
|
||||
)]
|
||||
InvalidPatternToken {
|
||||
rule_index: usize,
|
||||
token_index: usize,
|
||||
reason: String,
|
||||
},
|
||||
|
||||
#[error("rules prefix_rule at index {rule_index} has an empty justification")]
|
||||
EmptyJustification { rule_index: usize },
|
||||
|
||||
#[error("rules prefix_rule at index {rule_index} is missing a decision")]
|
||||
MissingDecision { rule_index: usize },
|
||||
|
||||
#[error(
|
||||
"rules prefix_rule at index {rule_index} has decision 'allow', which is not permitted in requirements.toml: Codex merges these rules with other config and uses the most restrictive result (use 'prompt', 'prompt-user', or 'forbidden')"
|
||||
)]
|
||||
AllowDecisionNotAllowed { rule_index: usize },
|
||||
}
|
||||
|
||||
impl RequirementsExecPolicyToml {
|
||||
/// Convert requirements TOML rules into the internal `.rules`
|
||||
/// representation used by `codex-execpolicy`.
|
||||
pub fn to_policy(&self) -> Result<Policy, RequirementsExecPolicyParseError> {
|
||||
if self.prefix_rules.is_empty() {
|
||||
return Err(RequirementsExecPolicyParseError::EmptyPrefixRules);
|
||||
}
|
||||
|
||||
let mut rules_by_program: MultiMap<String, RuleRef> = MultiMap::new();
|
||||
|
||||
for (rule_index, rule) in self.prefix_rules.iter().enumerate() {
|
||||
if let Some(justification) = &rule.justification
|
||||
&& justification.trim().is_empty()
|
||||
{
|
||||
return Err(RequirementsExecPolicyParseError::EmptyJustification { rule_index });
|
||||
}
|
||||
|
||||
if rule.pattern.is_empty() {
|
||||
return Err(RequirementsExecPolicyParseError::EmptyPattern { rule_index });
|
||||
}
|
||||
|
||||
let pattern_tokens = rule
|
||||
.pattern
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(token_index, token)| parse_pattern_token(token, rule_index, token_index))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
|
||||
let decision = match rule.decision {
|
||||
Some(RequirementsExecPolicyDecisionToml::Allow) => {
|
||||
return Err(RequirementsExecPolicyParseError::AllowDecisionNotAllowed {
|
||||
rule_index,
|
||||
});
|
||||
}
|
||||
Some(decision) => decision.as_decision(),
|
||||
None => {
|
||||
return Err(RequirementsExecPolicyParseError::MissingDecision { rule_index });
|
||||
}
|
||||
};
|
||||
let justification = rule.justification.clone();
|
||||
|
||||
let (first_token, remaining_tokens) = pattern_tokens
|
||||
.split_first()
|
||||
.ok_or(RequirementsExecPolicyParseError::EmptyPattern { rule_index })?;
|
||||
|
||||
let rest: Arc<[PatternToken]> = remaining_tokens.to_vec().into();
|
||||
|
||||
for head in first_token.alternatives() {
|
||||
let rule: RuleRef = Arc::new(PrefixRule {
|
||||
pattern: PrefixPattern {
|
||||
canonical_matching: rule.canonical_matching,
|
||||
first: Arc::from(head.as_str()),
|
||||
rest: rest.clone(),
|
||||
},
|
||||
decision,
|
||||
justification: justification.clone(),
|
||||
});
|
||||
rules_by_program.insert(head.clone(), rule);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(Policy::new(rules_by_program))
|
||||
}
|
||||
|
||||
pub(crate) fn to_requirements_policy(
|
||||
&self,
|
||||
) -> Result<RequirementsExecPolicy, RequirementsExecPolicyParseError> {
|
||||
self.to_policy().map(RequirementsExecPolicy::new)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_pattern_token(
|
||||
token: &RequirementsExecPolicyPatternTokenToml,
|
||||
rule_index: usize,
|
||||
token_index: usize,
|
||||
) -> Result<PatternToken, RequirementsExecPolicyParseError> {
|
||||
match (&token.token, &token.any_of) {
|
||||
(Some(single), None) => {
|
||||
if single.trim().is_empty() {
|
||||
return Err(RequirementsExecPolicyParseError::InvalidPatternToken {
|
||||
rule_index,
|
||||
token_index,
|
||||
reason: "token cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(PatternToken::Single(single.clone()))
|
||||
}
|
||||
(None, Some(alternatives)) => {
|
||||
if alternatives.is_empty() {
|
||||
return Err(RequirementsExecPolicyParseError::InvalidPatternToken {
|
||||
rule_index,
|
||||
token_index,
|
||||
reason: "any_of cannot be empty".to_string(),
|
||||
});
|
||||
}
|
||||
if alternatives.iter().any(|alt| alt.trim().is_empty()) {
|
||||
return Err(RequirementsExecPolicyParseError::InvalidPatternToken {
|
||||
rule_index,
|
||||
token_index,
|
||||
reason: "any_of cannot include empty tokens".to_string(),
|
||||
});
|
||||
}
|
||||
Ok(PatternToken::Alts(alternatives.clone()))
|
||||
}
|
||||
(Some(_), Some(_)) => Err(RequirementsExecPolicyParseError::InvalidPatternToken {
|
||||
rule_index,
|
||||
token_index,
|
||||
reason: "set either token or any_of, not both".to_string(),
|
||||
}),
|
||||
(None, None) => Err(RequirementsExecPolicyParseError::InvalidPatternToken {
|
||||
rule_index,
|
||||
token_index,
|
||||
reason: "set either token or any_of".to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
245
codex-rs/config/src/requirements_layers/hooks.rs
Normal file
245
codex-rs/config/src/requirements_layers/hooks.rs
Normal file
@@ -0,0 +1,245 @@
|
||||
//! Hook events are append-only across requirements layers. The managed hook
|
||||
//! directory is different: only one directory is usable on a given platform, so
|
||||
//! conflicting values for the active platform fail closed. The inactive platform
|
||||
//! field is first-filled to allow the same layer stack to carry OS-specific
|
||||
//! directories.
|
||||
|
||||
use crate::HookEventsToml;
|
||||
use crate::ManagedHooksRequirementsToml;
|
||||
use crate::RequirementSource;
|
||||
use crate::Sourced;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::stack::composition_conflict;
|
||||
use super::stack::merge_output_source;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum HookDirectoryField {
|
||||
#[default]
|
||||
ManagedDir,
|
||||
WindowsManagedDir,
|
||||
}
|
||||
|
||||
impl HookDirectoryField {
|
||||
pub(super) fn current_platform() -> Self {
|
||||
if cfg!(windows) {
|
||||
Self::WindowsManagedDir
|
||||
} else {
|
||||
Self::ManagedDir
|
||||
}
|
||||
}
|
||||
|
||||
fn field_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::ManagedDir => "hooks.managed_dir",
|
||||
Self::WindowsManagedDir => "hooks.windows_managed_dir",
|
||||
}
|
||||
}
|
||||
|
||||
fn inactive(self) -> Self {
|
||||
match self {
|
||||
Self::ManagedDir => Self::WindowsManagedDir,
|
||||
Self::WindowsManagedDir => Self::ManagedDir,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct HookMergeState {
|
||||
directory_field: HookDirectoryField,
|
||||
dir_sources: BTreeMap<HookDirectoryField, RequirementSource>,
|
||||
}
|
||||
|
||||
impl HookMergeState {
|
||||
pub(super) fn new(directory_field: HookDirectoryField) -> Self {
|
||||
Self {
|
||||
directory_field,
|
||||
dir_sources: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn merge(
|
||||
&mut self,
|
||||
target: &mut Option<Sourced<ManagedHooksRequirementsToml>>,
|
||||
incoming: Option<ManagedHooksRequirementsToml>,
|
||||
source: &RequirementSource,
|
||||
) -> Result<(), super::stack::RequirementsCompositionError> {
|
||||
let Some(mut incoming) = incoming.filter(|value| !value.is_empty()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(existing) = target.as_mut() else {
|
||||
self.track_singleton_source(
|
||||
HookDirectoryField::ManagedDir,
|
||||
&incoming.managed_dir,
|
||||
source,
|
||||
);
|
||||
self.track_singleton_source(
|
||||
HookDirectoryField::WindowsManagedDir,
|
||||
&incoming.windows_managed_dir,
|
||||
source,
|
||||
);
|
||||
*target = Some(Sourced::new(incoming, source.clone()));
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
let active_field = self.directory_field;
|
||||
let inactive_field = active_field.inactive();
|
||||
let incoming_active_dir = take_hook_dir(&mut incoming, active_field);
|
||||
let incoming_inactive_dir = take_hook_dir(&mut incoming, inactive_field);
|
||||
let mut changed = false;
|
||||
changed |= self.merge_active_singleton(
|
||||
active_field,
|
||||
hook_dir_mut(&mut existing.value, active_field),
|
||||
incoming_active_dir,
|
||||
source,
|
||||
)?;
|
||||
changed |= self.fill_singleton(
|
||||
inactive_field,
|
||||
hook_dir_mut(&mut existing.value, inactive_field),
|
||||
incoming_inactive_dir,
|
||||
source,
|
||||
);
|
||||
changed |= append_hook_events(&mut existing.value.hooks, *incoming.hooks);
|
||||
if changed {
|
||||
merge_output_source(&mut existing.source, source);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn track_singleton_source(
|
||||
&mut self,
|
||||
field: HookDirectoryField,
|
||||
value: &Option<PathBuf>,
|
||||
source: &RequirementSource,
|
||||
) {
|
||||
if value.is_some() {
|
||||
self.dir_sources
|
||||
.entry(field)
|
||||
.or_insert_with(|| source.clone());
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_active_singleton(
|
||||
&mut self,
|
||||
field: HookDirectoryField,
|
||||
existing: &mut Option<PathBuf>,
|
||||
incoming: Option<PathBuf>,
|
||||
incoming_source: &RequirementSource,
|
||||
) -> Result<bool, super::stack::RequirementsCompositionError> {
|
||||
let Some(incoming) = incoming else {
|
||||
return Ok(false);
|
||||
};
|
||||
|
||||
match existing {
|
||||
Some(existing_value) if existing_value != &incoming => {
|
||||
let existing_source = self
|
||||
.dir_sources
|
||||
.get(&field)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| incoming_source.clone());
|
||||
Err(composition_conflict(
|
||||
field.field_name().to_string(),
|
||||
existing_source,
|
||||
incoming_source.clone(),
|
||||
format!(
|
||||
"`{}` conflicts with `{}`",
|
||||
existing_value.display(),
|
||||
incoming.display()
|
||||
),
|
||||
))
|
||||
}
|
||||
Some(_) => Ok(false),
|
||||
None => {
|
||||
*existing = Some(incoming);
|
||||
self.dir_sources
|
||||
.entry(field)
|
||||
.or_insert_with(|| incoming_source.clone());
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fill_singleton(
|
||||
&mut self,
|
||||
field: HookDirectoryField,
|
||||
existing: &mut Option<PathBuf>,
|
||||
incoming: Option<PathBuf>,
|
||||
incoming_source: &RequirementSource,
|
||||
) -> bool {
|
||||
if existing.is_none()
|
||||
&& let Some(incoming) = incoming
|
||||
{
|
||||
*existing = Some(incoming);
|
||||
self.dir_sources
|
||||
.entry(field)
|
||||
.or_insert_with(|| incoming_source.clone());
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_hook_dir(
|
||||
hooks: &mut ManagedHooksRequirementsToml,
|
||||
field: HookDirectoryField,
|
||||
) -> Option<PathBuf> {
|
||||
match field {
|
||||
HookDirectoryField::ManagedDir => hooks.managed_dir.take(),
|
||||
HookDirectoryField::WindowsManagedDir => hooks.windows_managed_dir.take(),
|
||||
}
|
||||
}
|
||||
|
||||
fn hook_dir_mut(
|
||||
hooks: &mut ManagedHooksRequirementsToml,
|
||||
field: HookDirectoryField,
|
||||
) -> &mut Option<PathBuf> {
|
||||
match field {
|
||||
HookDirectoryField::ManagedDir => &mut hooks.managed_dir,
|
||||
HookDirectoryField::WindowsManagedDir => &mut hooks.windows_managed_dir,
|
||||
}
|
||||
}
|
||||
|
||||
fn append_hook_events(existing: &mut HookEventsToml, incoming: HookEventsToml) -> bool {
|
||||
// Destructure without `..` so new hook events cannot be introduced without
|
||||
// deciding whether requirements layer merging should append them.
|
||||
let HookEventsToml {
|
||||
pre_model_request,
|
||||
post_model_request,
|
||||
pre_tool_use,
|
||||
permission_request,
|
||||
post_tool_use,
|
||||
pre_compact,
|
||||
post_compact,
|
||||
session_start,
|
||||
session_end,
|
||||
user_prompt_submit,
|
||||
subagent_start,
|
||||
subagent_stop,
|
||||
stop,
|
||||
interrupt,
|
||||
} = incoming;
|
||||
|
||||
let mut changed = false;
|
||||
changed |= append_vec(&mut existing.pre_model_request, pre_model_request);
|
||||
changed |= append_vec(&mut existing.post_model_request, post_model_request);
|
||||
changed |= append_vec(&mut existing.pre_tool_use, pre_tool_use);
|
||||
changed |= append_vec(&mut existing.permission_request, permission_request);
|
||||
changed |= append_vec(&mut existing.post_tool_use, post_tool_use);
|
||||
changed |= append_vec(&mut existing.pre_compact, pre_compact);
|
||||
changed |= append_vec(&mut existing.post_compact, post_compact);
|
||||
changed |= append_vec(&mut existing.session_start, session_start);
|
||||
changed |= append_vec(&mut existing.session_end, session_end);
|
||||
changed |= append_vec(&mut existing.user_prompt_submit, user_prompt_submit);
|
||||
changed |= append_vec(&mut existing.subagent_start, subagent_start);
|
||||
changed |= append_vec(&mut existing.subagent_stop, subagent_stop);
|
||||
changed |= append_vec(&mut existing.stop, stop);
|
||||
changed |= append_vec(&mut existing.interrupt, interrupt);
|
||||
changed
|
||||
}
|
||||
|
||||
fn append_vec<T>(existing: &mut Vec<T>, mut incoming: Vec<T>) -> bool {
|
||||
let changed = !incoming.is_empty();
|
||||
existing.append(&mut incoming);
|
||||
changed
|
||||
}
|
||||
326
codex-rs/config/src/requirements_layers/layer.rs
Normal file
326
codex-rs/config/src/requirements_layers/layer.rs
Normal file
@@ -0,0 +1,326 @@
|
||||
use crate::ConfigPathContext;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::ManagedHooksRequirementsToml;
|
||||
use crate::OtelRequirementsToml;
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsExecPolicyToml;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
use super::stack::RequirementsCompositionError;
|
||||
|
||||
// Authentication requirements that cloud-managed layers cannot set.
|
||||
const LOCAL_ONLY_AUTH_REQUIREMENTS: &[&str] = &[
|
||||
"allowed_login_methods",
|
||||
"allowed_chatgpt_workspaces",
|
||||
"cli_auth_credentials_store",
|
||||
"chatgpt_base_url",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RequirementsLayerEntry {
|
||||
pub(super) source: RequirementSource,
|
||||
toml: RequirementsLayerToml,
|
||||
base_dir: Option<AbsolutePathBuf>,
|
||||
path_context: Option<ConfigPathContext>,
|
||||
}
|
||||
|
||||
impl RequirementsLayerEntry {
|
||||
pub fn from_toml(source: RequirementSource, contents: impl Into<String>) -> Self {
|
||||
Self {
|
||||
source,
|
||||
toml: RequirementsLayerToml::String(contents.into()),
|
||||
base_dir: None,
|
||||
path_context: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_toml_value(source: RequirementSource, value: TomlValue) -> Self {
|
||||
Self {
|
||||
source,
|
||||
toml: RequirementsLayerToml::Value(value),
|
||||
base_dir: None,
|
||||
path_context: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_base_dir(mut self, base_dir: AbsolutePathBuf) -> Self {
|
||||
self.base_dir = Some(base_dir);
|
||||
self
|
||||
}
|
||||
|
||||
/// Supplies the owning environment's facts for filesystem denial paths.
|
||||
/// Other path fields keep their existing native deserialization behavior.
|
||||
pub fn with_path_context(mut self, context: ConfigPathContext) -> Self {
|
||||
self.path_context = Some(context);
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn into_raw_parts(
|
||||
self,
|
||||
) -> Result<(RequirementSource, TomlValue, Option<AbsolutePathBuf>), RequirementsCompositionError>
|
||||
{
|
||||
let Self {
|
||||
source,
|
||||
toml,
|
||||
base_dir,
|
||||
path_context: _,
|
||||
} = self;
|
||||
let toml = parse_layer_toml(&toml, &source)?;
|
||||
Ok((source, toml, base_dir))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
enum RequirementsLayerToml {
|
||||
String(String),
|
||||
Value(TomlValue),
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct ComposableRequirementsLayer {
|
||||
pub(super) source: RequirementSource,
|
||||
pub(super) regular_toml: TomlValue,
|
||||
pub(super) domain_fields: DomainMergedRequirementsFields,
|
||||
}
|
||||
|
||||
impl ComposableRequirementsLayer {
|
||||
pub(super) fn from_entry(
|
||||
layer: RequirementsLayerEntry,
|
||||
hostname_resolver: &dyn Fn() -> Option<String>,
|
||||
) -> Result<Self, RequirementsCompositionError> {
|
||||
let RequirementsLayerEntry {
|
||||
source,
|
||||
toml,
|
||||
base_dir,
|
||||
path_context,
|
||||
} = layer;
|
||||
let (mut regular_toml, mut requirements) = {
|
||||
let _guard = base_dir
|
||||
.as_ref()
|
||||
.map(|base_dir| AbsolutePathBufGuard::new(base_dir.as_path()));
|
||||
let mut regular_toml = parse_layer_toml(&toml, &source)?;
|
||||
|
||||
if matches!(source, RequirementSource::EnterpriseManaged { .. })
|
||||
&& regular_toml.get("config_server").is_some()
|
||||
{
|
||||
return Err(RequirementsCompositionError::Parse {
|
||||
layer_source: source.clone(),
|
||||
message: "config_server may only be configured in local managed requirements"
|
||||
.into(),
|
||||
});
|
||||
}
|
||||
|
||||
// These fields can only be set locally; ignore them before validating cloud policy.
|
||||
strip_cloud_auth_requirements(&source, &mut regular_toml);
|
||||
|
||||
// Provider fragments can be incomplete until all requirements layers
|
||||
// are merged. Resolve explicit paths while their source base is still
|
||||
// available, without deserializing complete auth command objects.
|
||||
if let Some(providers) = regular_toml
|
||||
.get_mut("model_providers")
|
||||
.and_then(TomlValue::as_table_mut)
|
||||
{
|
||||
for (id, provider) in providers.iter_mut() {
|
||||
if let Some(cwd) = provider
|
||||
.get_mut("auth")
|
||||
.and_then(|auth| auth.get_mut("cwd"))
|
||||
{
|
||||
let resolved: AbsolutePathBuf =
|
||||
cwd.clone().try_into().map_err(|err: toml::de::Error| {
|
||||
RequirementsCompositionError::Parse {
|
||||
layer_source: source.clone(),
|
||||
message: format!("model_providers.{id}.auth.cwd: {err}"),
|
||||
}
|
||||
})?;
|
||||
*cwd = toml_value_from_serializable(resolved)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut layer_requirements_toml = regular_toml.clone();
|
||||
remove_top_level_field(&mut layer_requirements_toml, "model_providers");
|
||||
let _path_context = path_context.as_ref().map(ConfigPathContext::enter);
|
||||
let requirements = parse_layer_requirements(
|
||||
&RequirementsLayerToml::Value(layer_requirements_toml),
|
||||
&source,
|
||||
)?;
|
||||
(regular_toml, requirements)
|
||||
};
|
||||
|
||||
// Merge aliases under one key after validating each individual layer.
|
||||
if let Some(table) = regular_toml.as_table_mut()
|
||||
&& let Some(features) = table.remove("feature_requirements")
|
||||
{
|
||||
table.insert("features".to_string(), features);
|
||||
}
|
||||
if let Some(table) = regular_toml.as_table_mut()
|
||||
&& let Some(network) = table.remove("experimental_network")
|
||||
{
|
||||
table.insert("network_proxy".to_string(), network);
|
||||
}
|
||||
|
||||
// Hostname lookup is configuration-driven and may block on DNS, so only
|
||||
// resolve it when this layer contains hostname-based sandbox selectors.
|
||||
let hostname = requirements
|
||||
.remote_sandbox_config
|
||||
.as_ref()
|
||||
.and_then(|_| hostname_resolver());
|
||||
requirements.apply_remote_sandbox_config(hostname.as_deref());
|
||||
materialize_resolved_path_requirements(&mut regular_toml, &requirements)?;
|
||||
materialize_remote_sandbox_config(&mut regular_toml, &requirements)?;
|
||||
strip_special_fields(&mut regular_toml);
|
||||
|
||||
Ok(Self {
|
||||
source,
|
||||
regular_toml,
|
||||
domain_fields: DomainMergedRequirementsFields {
|
||||
rules: requirements.rules,
|
||||
hooks: requirements.hooks,
|
||||
permissions: requirements.permissions,
|
||||
auto_review: requirements.auto_review,
|
||||
otel: requirements.otel,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct DomainMergedRequirementsFields {
|
||||
pub(super) rules: Option<RequirementsExecPolicyToml>,
|
||||
pub(super) hooks: Option<ManagedHooksRequirementsToml>,
|
||||
pub(super) permissions: Option<crate::config_requirements::PermissionsRequirementsToml>,
|
||||
pub(super) auto_review: Option<crate::config_requirements::AutoReviewRequirementsToml>,
|
||||
pub(super) otel: Option<Box<OtelRequirementsToml>>,
|
||||
}
|
||||
|
||||
fn parse_layer_toml(
|
||||
toml: &RequirementsLayerToml,
|
||||
source: &RequirementSource,
|
||||
) -> Result<TomlValue, RequirementsCompositionError> {
|
||||
match toml {
|
||||
RequirementsLayerToml::String(contents) => {
|
||||
toml::from_str(contents).map_err(|err: toml::de::Error| {
|
||||
RequirementsCompositionError::Parse {
|
||||
layer_source: source.clone(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})
|
||||
}
|
||||
RequirementsLayerToml::Value(value) => Ok(value.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_layer_requirements(
|
||||
toml: &RequirementsLayerToml,
|
||||
source: &RequirementSource,
|
||||
) -> Result<ConfigRequirementsToml, RequirementsCompositionError> {
|
||||
match toml {
|
||||
RequirementsLayerToml::String(contents) => {
|
||||
toml::from_str(contents).map_err(|err: toml::de::Error| {
|
||||
RequirementsCompositionError::Parse {
|
||||
layer_source: source.clone(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})
|
||||
}
|
||||
RequirementsLayerToml::Value(value) => {
|
||||
value.clone().try_into().map_err(|err: toml::de::Error| {
|
||||
RequirementsCompositionError::Parse {
|
||||
layer_source: source.clone(),
|
||||
message: err.to_string(),
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn materialize_resolved_path_requirements(
|
||||
layer_toml: &mut TomlValue,
|
||||
requirements: &ConfigRequirementsToml,
|
||||
) -> Result<(), RequirementsCompositionError> {
|
||||
let Some(table) = layer_toml.as_table_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
for (key, value) in [
|
||||
("sqlite_home", requirements.sqlite_home.as_ref()),
|
||||
("log_dir", requirements.log_dir.as_ref()),
|
||||
(
|
||||
"model_catalog_json",
|
||||
requirements.model_catalog_json.as_ref(),
|
||||
),
|
||||
] {
|
||||
if let Some(value) = value {
|
||||
table.insert(key.to_string(), toml_value_from_serializable(value)?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn materialize_remote_sandbox_config(
|
||||
layer_toml: &mut TomlValue,
|
||||
requirements: &ConfigRequirementsToml,
|
||||
) -> Result<(), RequirementsCompositionError> {
|
||||
remove_top_level_field(layer_toml, "remote_sandbox_config");
|
||||
let Some(allowed_sandbox_modes) = requirements.allowed_sandbox_modes.as_ref() else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(table) = layer_toml.as_table_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
table.insert(
|
||||
"allowed_sandbox_modes".to_string(),
|
||||
toml_value_from_serializable(allowed_sandbox_modes)?,
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn toml_value_from_serializable<T: serde::Serialize>(
|
||||
value: T,
|
||||
) -> Result<TomlValue, RequirementsCompositionError> {
|
||||
TomlValue::try_from(value).map_err(|err| RequirementsCompositionError::ComposedParse {
|
||||
message: err.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn strip_special_fields(layer_toml: &mut TomlValue) {
|
||||
remove_top_level_field(layer_toml, "rules");
|
||||
remove_top_level_field(layer_toml, "hooks");
|
||||
remove_top_level_field(layer_toml, "otel");
|
||||
remove_nested_field_and_prune_empty(layer_toml, &["permissions", "filesystem", "deny_read"]);
|
||||
remove_nested_field_and_prune_empty(layer_toml, &["auto_review", "required_on_models"]);
|
||||
}
|
||||
|
||||
pub(crate) fn strip_cloud_auth_requirements(source: &RequirementSource, value: &mut TomlValue) {
|
||||
if matches!(source, RequirementSource::EnterpriseManaged { .. }) {
|
||||
for field in LOCAL_ONLY_AUTH_REQUIREMENTS {
|
||||
remove_top_level_field(value, field);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_top_level_field(value: &mut TomlValue, key: &str) -> Option<TomlValue> {
|
||||
value.as_table_mut()?.remove(key)
|
||||
}
|
||||
|
||||
fn remove_nested_field_and_prune_empty(value: &mut TomlValue, path: &[&str]) -> Option<TomlValue> {
|
||||
let (key, remaining) = path.split_first()?;
|
||||
let table = value.as_table_mut()?;
|
||||
if remaining.is_empty() {
|
||||
return table.remove(*key);
|
||||
}
|
||||
|
||||
let removed = table
|
||||
.get_mut(*key)
|
||||
.and_then(|child| remove_nested_field_and_prune_empty(child, remaining));
|
||||
if table
|
||||
.get(*key)
|
||||
.and_then(TomlValue::as_table)
|
||||
.is_some_and(toml::map::Map::is_empty)
|
||||
{
|
||||
table.remove(*key);
|
||||
}
|
||||
removed
|
||||
}
|
||||
11
codex-rs/config/src/requirements_layers/mod.rs
Normal file
11
codex-rs/config/src/requirements_layers/mod.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
mod hooks;
|
||||
mod layer;
|
||||
mod models;
|
||||
mod permissions;
|
||||
mod rules;
|
||||
mod stack;
|
||||
|
||||
pub use layer::RequirementsLayerEntry;
|
||||
pub(crate) use layer::strip_cloud_auth_requirements;
|
||||
pub use stack::compose_requirements;
|
||||
pub use stack::compose_requirements_for_hostname;
|
||||
60
codex-rs/config/src/requirements_layers/models.rs
Normal file
60
codex-rs/config/src/requirements_layers/models.rs
Normal file
@@ -0,0 +1,60 @@
|
||||
//! Model slugs requiring auto-review remain protected across all policy layers.
|
||||
|
||||
use crate::AutoReviewRequirementsToml;
|
||||
use crate::RequirementSource;
|
||||
use crate::Sourced;
|
||||
|
||||
use super::stack::merge_output_source;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct AutoReviewModelsMergeState {
|
||||
slugs: Vec<String>,
|
||||
source: Option<RequirementSource>,
|
||||
}
|
||||
|
||||
impl AutoReviewModelsMergeState {
|
||||
pub(super) fn merge(
|
||||
&mut self,
|
||||
incoming: Option<AutoReviewRequirementsToml>,
|
||||
source: &RequirementSource,
|
||||
) {
|
||||
let Some(incoming_slugs) = incoming
|
||||
.and_then(|auto_review| auto_review.required_on_models)
|
||||
.filter(|slugs| !slugs.is_empty())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
for slug in incoming_slugs {
|
||||
if !self.slugs.contains(&slug) {
|
||||
self.slugs.push(slug);
|
||||
if let Some(existing_source) = self.source.as_mut() {
|
||||
merge_output_source(existing_source, source);
|
||||
} else {
|
||||
self.source = Some(source.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_to(self, target: &mut Option<Sourced<AutoReviewRequirementsToml>>) {
|
||||
if self.slugs.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let source = self.source.unwrap_or(RequirementSource::Unknown);
|
||||
let Some(existing) = target.as_mut() else {
|
||||
*target = Some(Sourced::new(
|
||||
AutoReviewRequirementsToml {
|
||||
required_on_models: Some(self.slugs),
|
||||
ignore_rules: None,
|
||||
},
|
||||
source,
|
||||
));
|
||||
return;
|
||||
};
|
||||
|
||||
existing.value.required_on_models = Some(self.slugs);
|
||||
merge_output_source(&mut existing.source, &source);
|
||||
}
|
||||
}
|
||||
83
codex-rs/config/src/requirements_layers/permissions.rs
Normal file
83
codex-rs/config/src/requirements_layers/permissions.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
//! `permissions.filesystem.deny_read` is intentionally additive across
|
||||
//! requirements layers. Other `[permissions]` content stays in the regular TOML
|
||||
//! merge path so permission profile tables follow config-style precedence.
|
||||
|
||||
use crate::FilesystemDenyReadPattern;
|
||||
use crate::RequirementSource;
|
||||
use crate::Sourced;
|
||||
use crate::config_requirements::FilesystemRequirementsToml;
|
||||
use crate::config_requirements::PermissionsRequirementsToml;
|
||||
|
||||
use super::stack::merge_output_source;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct DenyReadMergeState {
|
||||
deny_read: Vec<FilesystemDenyReadPattern>,
|
||||
source: Option<RequirementSource>,
|
||||
}
|
||||
|
||||
impl DenyReadMergeState {
|
||||
pub(super) fn merge(
|
||||
&mut self,
|
||||
incoming: Option<PermissionsRequirementsToml>,
|
||||
source: &RequirementSource,
|
||||
) {
|
||||
let Some(incoming_deny_read) = incoming
|
||||
.and_then(|permissions| permissions.filesystem)
|
||||
.and_then(|filesystem| filesystem.deny_read)
|
||||
.filter(|deny_read| !deny_read.is_empty())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
for pattern in incoming_deny_read {
|
||||
if !self.deny_read.contains(&pattern) {
|
||||
self.deny_read.push(pattern);
|
||||
self.merge_source(source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn apply_to(self, target: &mut Option<Sourced<PermissionsRequirementsToml>>) {
|
||||
if self.deny_read.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let source = self.source.unwrap_or(RequirementSource::Unknown);
|
||||
let Some(existing) = target.as_mut() else {
|
||||
*target = Some(Sourced::new(
|
||||
PermissionsRequirementsToml {
|
||||
filesystem: Some(FilesystemRequirementsToml {
|
||||
deny_read: Some(self.deny_read),
|
||||
}),
|
||||
network: None,
|
||||
profiles: Default::default(),
|
||||
},
|
||||
source,
|
||||
));
|
||||
return;
|
||||
};
|
||||
|
||||
let filesystem = existing
|
||||
.value
|
||||
.filesystem
|
||||
.get_or_insert_with(Default::default);
|
||||
let deny_read = filesystem.deny_read.get_or_insert_with(Vec::new);
|
||||
for pattern in self.deny_read {
|
||||
if !deny_read.contains(&pattern) {
|
||||
deny_read.push(pattern);
|
||||
}
|
||||
}
|
||||
// The normalized filesystem constraint must name the layers that supplied denials,
|
||||
// not layers that only supplied sibling profiles.
|
||||
existing.source = source;
|
||||
}
|
||||
|
||||
fn merge_source(&mut self, source: &RequirementSource) {
|
||||
let Some(existing) = self.source.as_mut() else {
|
||||
self.source = Some(source.clone());
|
||||
return;
|
||||
};
|
||||
merge_output_source(existing, source);
|
||||
}
|
||||
}
|
||||
26
codex-rs/config/src/requirements_layers/rules.rs
Normal file
26
codex-rs/config/src/requirements_layers/rules.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
//! Requirements rules are additive across layers. Higher-priority rules are
|
||||
//! appended first so the final rule order keeps priority visible.
|
||||
|
||||
use crate::RequirementSource;
|
||||
use crate::RequirementsExecPolicyToml;
|
||||
use crate::Sourced;
|
||||
|
||||
use super::stack::merge_output_source;
|
||||
|
||||
pub(super) fn merge(
|
||||
target: &mut Option<Sourced<RequirementsExecPolicyToml>>,
|
||||
incoming: Option<RequirementsExecPolicyToml>,
|
||||
source: &RequirementSource,
|
||||
) {
|
||||
let Some(incoming) = incoming else {
|
||||
return;
|
||||
};
|
||||
let Some(existing) = target.as_mut() else {
|
||||
*target = Some(Sourced::new(incoming, source.clone()));
|
||||
return;
|
||||
};
|
||||
|
||||
let RequirementsExecPolicyToml { prefix_rules } = incoming;
|
||||
existing.value.prefix_rules.extend(prefix_rules);
|
||||
merge_output_source(&mut existing.source, source);
|
||||
}
|
||||
458
codex-rs/config/src/requirements_layers/stack.rs
Normal file
458
codex-rs/config/src/requirements_layers/stack.rs
Normal file
@@ -0,0 +1,458 @@
|
||||
//! Requirements layers are composed in the same order as config layers: lowest
|
||||
//! precedence first, highest precedence last. Most fields use the same
|
||||
//! TOML-level merge policy as config: lower-priority layers provide defaults,
|
||||
//! and higher-priority layers override scalar/list values while recursively
|
||||
//! extending tables.
|
||||
//!
|
||||
//! A few fields carry domain-specific meaning that raw TOML replacement would
|
||||
//! break:
|
||||
//! - `remote_sandbox_config` is evaluated within each layer before merging.
|
||||
//! - `rules.prefix_rules` append high-priority rules first.
|
||||
//! - `hooks` append high-priority event groups first while failing closed on
|
||||
//! active managed-dir conflicts.
|
||||
//! - `otel` replaces exact managed values, treats exporters atomically, and
|
||||
//! merges span attributes and fields within each tracestate member by key.
|
||||
//! - `permissions.filesystem.deny_read` is a high-priority-first union across
|
||||
//! layers.
|
||||
//! - `auto_review.required_on_models` is a high-priority-first union across layers.
|
||||
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::ConfigRequirementsWithSources;
|
||||
use crate::RequirementSource;
|
||||
use crate::Sourced;
|
||||
use crate::config_requirements::PermissionsRequirementsToml;
|
||||
use crate::config_requirements::merge_otel_requirements;
|
||||
use crate::merge::merge_toml_values;
|
||||
use std::cell::OnceCell;
|
||||
use std::io;
|
||||
use thiserror::Error;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
use super::hooks::HookDirectoryField;
|
||||
use super::hooks::HookMergeState;
|
||||
use super::layer::ComposableRequirementsLayer;
|
||||
use super::layer::RequirementsLayerEntry;
|
||||
use super::models::AutoReviewModelsMergeState;
|
||||
use super::permissions::DenyReadMergeState;
|
||||
|
||||
#[derive(Debug, Error, PartialEq, Eq)]
|
||||
pub enum RequirementsCompositionError {
|
||||
#[error("failed to parse requirements layer {layer_source}: {message}")]
|
||||
Parse {
|
||||
layer_source: RequirementSource,
|
||||
message: String,
|
||||
},
|
||||
#[error("failed to parse merged requirements: {message}")]
|
||||
ComposedParse { message: String },
|
||||
#[error(
|
||||
"failed to compose requirements field `{field}` between {existing_source} and {incoming_source}: {message}"
|
||||
)]
|
||||
Conflict {
|
||||
field: String,
|
||||
existing_source: RequirementSource,
|
||||
incoming_source: RequirementSource,
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl From<RequirementsCompositionError> for io::Error {
|
||||
fn from(error: RequirementsCompositionError) -> Self {
|
||||
io::Error::new(io::ErrorKind::InvalidData, error)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn compose_requirements(
|
||||
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
|
||||
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
|
||||
compose_requirements_with_hostname_resolver(layers, crate::host_name)
|
||||
}
|
||||
|
||||
/// Composes requirements using an explicitly supplied execution-host hostname.
|
||||
pub fn compose_requirements_for_hostname(
|
||||
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
|
||||
hostname: Option<&str>,
|
||||
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
|
||||
let hostname = hostname.map(str::to_string);
|
||||
compose_requirements_with_hostname_resolver_and_hook_directory(
|
||||
layers,
|
||||
move || hostname.clone(),
|
||||
HookDirectoryField::current_platform(),
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn compose_requirements_for_hostname_and_hook_directory(
|
||||
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
|
||||
hostname: Option<&str>,
|
||||
hook_directory_field: HookDirectoryField,
|
||||
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
|
||||
let hostname = hostname.map(str::to_string);
|
||||
compose_requirements_with_hostname_resolver_and_hook_directory(
|
||||
layers,
|
||||
move || hostname.clone(),
|
||||
hook_directory_field,
|
||||
)
|
||||
}
|
||||
|
||||
fn compose_requirements_with_hostname_resolver(
|
||||
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
|
||||
hostname_resolver: impl Fn() -> Option<String>,
|
||||
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
|
||||
compose_requirements_with_hostname_resolver_and_hook_directory(
|
||||
layers,
|
||||
hostname_resolver,
|
||||
HookDirectoryField::current_platform(),
|
||||
)
|
||||
}
|
||||
|
||||
fn compose_requirements_with_hostname_resolver_and_hook_directory(
|
||||
layers: impl IntoIterator<Item = RequirementsLayerEntry>,
|
||||
hostname_resolver: impl Fn() -> Option<String>,
|
||||
hook_directory_field: HookDirectoryField,
|
||||
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
|
||||
// Evaluate every layer in this composition against the same hostname while
|
||||
// keeping resolution lazy when no layer needs remote sandbox matching.
|
||||
let hostname = OnceCell::new();
|
||||
let cached_hostname_resolver = || hostname.get_or_init(&hostname_resolver).clone();
|
||||
let mut stack = RequirementsLayerStack::new(hook_directory_field);
|
||||
for layer in layers {
|
||||
stack.add_layer(layer, &cached_hostname_resolver)?;
|
||||
}
|
||||
stack.compose()
|
||||
}
|
||||
|
||||
struct RequirementsLayerStack {
|
||||
layers: Vec<ComposableRequirementsLayer>,
|
||||
hook_directory_field: HookDirectoryField,
|
||||
}
|
||||
|
||||
impl RequirementsLayerStack {
|
||||
fn new(hook_directory_field: HookDirectoryField) -> Self {
|
||||
Self {
|
||||
layers: Vec::new(),
|
||||
hook_directory_field,
|
||||
}
|
||||
}
|
||||
|
||||
fn add_layer(
|
||||
&mut self,
|
||||
layer: RequirementsLayerEntry,
|
||||
hostname_resolver: &dyn Fn() -> Option<String>,
|
||||
) -> Result<(), RequirementsCompositionError> {
|
||||
self.layers.push(ComposableRequirementsLayer::from_entry(
|
||||
layer,
|
||||
hostname_resolver,
|
||||
)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn compose(
|
||||
self,
|
||||
) -> Result<Option<ConfigRequirementsWithSources>, RequirementsCompositionError> {
|
||||
let Self {
|
||||
layers,
|
||||
hook_directory_field,
|
||||
} = self;
|
||||
|
||||
let mut merged_toml = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in &layers {
|
||||
// An endpoint and its credentials must come from the same requirements layer.
|
||||
if layer.regular_toml.get("config_server").is_some()
|
||||
&& let Some(table) = merged_toml.as_table_mut()
|
||||
{
|
||||
table.remove("config_server");
|
||||
}
|
||||
merge_toml_values(&mut merged_toml, &layer.regular_toml);
|
||||
}
|
||||
|
||||
let requirements: ConfigRequirementsToml =
|
||||
merged_toml.try_into().map_err(|err: toml::de::Error| {
|
||||
RequirementsCompositionError::ComposedParse {
|
||||
message: err.to_string(),
|
||||
}
|
||||
})?;
|
||||
let mut output = ConfigRequirementsWithSources::default();
|
||||
populate_merged_regular_fields_with_sources(&mut output, requirements, &layers);
|
||||
output.validate_network_spelling().map_err(|err| {
|
||||
RequirementsCompositionError::ComposedParse {
|
||||
message: err.to_string(),
|
||||
}
|
||||
})?;
|
||||
// Merge OTEL requirements so higher-priority exact values replace
|
||||
// lower-priority values while exporters stay atomic.
|
||||
let mut otel = None;
|
||||
let mut otel_sources = Vec::new();
|
||||
for layer in &layers {
|
||||
if let Some(incoming) = layer.domain_fields.otel.as_deref()
|
||||
&& merge_otel_requirements(&mut otel, incoming)
|
||||
{
|
||||
otel_sources.push(layer.source.clone());
|
||||
}
|
||||
}
|
||||
output.otel = otel.map(|value| {
|
||||
Box::new(Sourced::new(
|
||||
value,
|
||||
RequirementSource::composite(otel_sources.into_iter().rev()),
|
||||
))
|
||||
});
|
||||
let mut rules = None;
|
||||
let mut hooks = HookMergeState::new(hook_directory_field);
|
||||
let mut hooks_output = None;
|
||||
let mut deny_read = DenyReadMergeState::default();
|
||||
let mut auto_review_models = AutoReviewModelsMergeState::default();
|
||||
// Regular TOML fields are folded low-to-high like config. These custom
|
||||
// fields append or union values, so process them high-to-low to keep
|
||||
// priority order visible in the output.
|
||||
for layer in layers.iter().rev() {
|
||||
let domain_fields = &layer.domain_fields;
|
||||
super::rules::merge(&mut rules, domain_fields.rules.clone(), &layer.source);
|
||||
hooks.merge(
|
||||
&mut hooks_output,
|
||||
domain_fields.hooks.clone(),
|
||||
&layer.source,
|
||||
)?;
|
||||
deny_read.merge(domain_fields.permissions.clone(), &layer.source);
|
||||
auto_review_models.merge(domain_fields.auto_review.clone(), &layer.source);
|
||||
}
|
||||
output.rules = rules;
|
||||
output.hooks = hooks_output;
|
||||
deny_read.apply_to(&mut output.permissions);
|
||||
auto_review_models.apply_to(&mut output.auto_review);
|
||||
|
||||
let output_is_empty = output.clone().into_toml().is_empty();
|
||||
Ok((!output_is_empty).then_some(output))
|
||||
}
|
||||
}
|
||||
|
||||
fn populate_merged_regular_fields_with_sources(
|
||||
output: &mut ConfigRequirementsWithSources,
|
||||
requirements: ConfigRequirementsToml,
|
||||
layers: &[ComposableRequirementsLayer],
|
||||
) {
|
||||
macro_rules! set_sourced {
|
||||
($field:ident, $keys:expr) => {
|
||||
if let Some(value) = $field {
|
||||
output.$field = Some(Sourced::new(
|
||||
value,
|
||||
source_for_top_level_keys(layers, $keys),
|
||||
));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Destructure without `..` so every new requirements field must choose
|
||||
// whether it belongs in the regular TOML merge path or in a special merger.
|
||||
let ConfigRequirementsToml {
|
||||
config_server,
|
||||
allowed_login_methods,
|
||||
allowed_chatgpt_workspaces,
|
||||
cli_auth_credentials_store,
|
||||
chatgpt_base_url,
|
||||
sqlite_home,
|
||||
unsafe_enforce_sqlite_journal_mode,
|
||||
log_dir,
|
||||
model_catalog_json,
|
||||
model_provider,
|
||||
model_providers,
|
||||
check_for_update_on_startup,
|
||||
allow_login_shell,
|
||||
feedback,
|
||||
allowed_approval_policies,
|
||||
allowed_approvals_reviewers,
|
||||
allowed_sandbox_modes,
|
||||
allowed_permission_profiles,
|
||||
default_permissions,
|
||||
remote_sandbox_config: _,
|
||||
allowed_web_search_modes,
|
||||
allow_managed_hooks_only,
|
||||
allow_browser_and_computer_use,
|
||||
allow_appshots,
|
||||
allow_remote_control,
|
||||
computer_use,
|
||||
browser_use,
|
||||
in_app_browser,
|
||||
windows,
|
||||
feature_requirements,
|
||||
hooks: _,
|
||||
mcp_servers,
|
||||
plugins,
|
||||
marketplaces,
|
||||
otel: _,
|
||||
apps,
|
||||
rules: _,
|
||||
enforce_residency,
|
||||
network,
|
||||
application,
|
||||
mut permissions,
|
||||
auto_review,
|
||||
models,
|
||||
additional_developer_instructions,
|
||||
guardian_policy_config,
|
||||
guardian_extra_policy,
|
||||
} = requirements;
|
||||
|
||||
set_sourced!(config_server, &["config_server"]);
|
||||
set_sourced!(allowed_login_methods, &["allowed_login_methods"]);
|
||||
set_sourced!(allowed_chatgpt_workspaces, &["allowed_chatgpt_workspaces"]);
|
||||
set_sourced!(cli_auth_credentials_store, &["cli_auth_credentials_store"]);
|
||||
set_sourced!(chatgpt_base_url, &["chatgpt_base_url"]);
|
||||
set_sourced!(sqlite_home, &["sqlite_home"]);
|
||||
set_sourced!(
|
||||
unsafe_enforce_sqlite_journal_mode,
|
||||
&["unsafe_enforce_sqlite_journal_mode"]
|
||||
);
|
||||
set_sourced!(log_dir, &["log_dir"]);
|
||||
set_sourced!(model_catalog_json, &["model_catalog_json"]);
|
||||
set_sourced!(model_provider, &["model_provider"]);
|
||||
set_sourced!(model_providers, &["model_providers"]);
|
||||
set_sourced!(
|
||||
check_for_update_on_startup,
|
||||
&["check_for_update_on_startup"]
|
||||
);
|
||||
set_sourced!(allow_login_shell, &["allow_login_shell"]);
|
||||
set_sourced!(feedback, &["feedback"]);
|
||||
set_sourced!(allowed_approval_policies, &["allowed_approval_policies"]);
|
||||
set_sourced!(
|
||||
allowed_approvals_reviewers,
|
||||
&["allowed_approvals_reviewers"]
|
||||
);
|
||||
set_sourced!(allowed_sandbox_modes, &["allowed_sandbox_modes"]);
|
||||
set_sourced!(
|
||||
allowed_permission_profiles,
|
||||
&["allowed_permission_profiles"]
|
||||
);
|
||||
set_sourced!(default_permissions, &["default_permissions"]);
|
||||
set_sourced!(allowed_web_search_modes, &["allowed_web_search_modes"]);
|
||||
set_sourced!(allow_managed_hooks_only, &["allow_managed_hooks_only"]);
|
||||
set_sourced!(
|
||||
allow_browser_and_computer_use,
|
||||
&["allow_browser_and_computer_use"]
|
||||
);
|
||||
set_sourced!(allow_appshots, &["allow_appshots"]);
|
||||
set_sourced!(allow_remote_control, &["allow_remote_control"]);
|
||||
set_sourced!(auto_review, &["auto_review"]);
|
||||
set_sourced!(computer_use, &["computer_use"]);
|
||||
set_sourced!(browser_use, &["browser_use"]);
|
||||
set_sourced!(in_app_browser, &["in_app_browser"]);
|
||||
set_sourced!(windows, &["windows"]);
|
||||
set_sourced!(feature_requirements, &["features", "feature_requirements"]);
|
||||
set_sourced!(mcp_servers, &["mcp_servers"]);
|
||||
set_sourced!(plugins, &["plugins"]);
|
||||
set_sourced!(marketplaces, &["marketplaces"]);
|
||||
set_sourced!(apps, &["apps"]);
|
||||
set_sourced!(enforce_residency, &["enforce_residency"]);
|
||||
set_sourced!(network, &["network_proxy"]);
|
||||
set_sourced!(application, &["application"]);
|
||||
let permission_sources = |contributes: fn(&toml::Table) -> bool| {
|
||||
RequirementSource::composite(
|
||||
layers
|
||||
.iter()
|
||||
.rev()
|
||||
.filter(|layer| {
|
||||
layer
|
||||
.regular_toml
|
||||
.get("permissions")
|
||||
.and_then(TomlValue::as_table)
|
||||
.is_some_and(contributes)
|
||||
})
|
||||
.map(|layer| layer.source.clone()),
|
||||
)
|
||||
};
|
||||
if let Some(network) = PermissionsRequirementsToml::take_network(&mut permissions) {
|
||||
output.permissions_network = Some(Box::new(Sourced::new(
|
||||
*network,
|
||||
permission_sources(|table| table.contains_key("network")),
|
||||
)));
|
||||
}
|
||||
output.permissions = permissions.map(|value| {
|
||||
let source = if value.filesystem.is_some() {
|
||||
permission_sources(|table| table.contains_key("filesystem"))
|
||||
} else {
|
||||
permission_sources(|table| table.keys().any(|key| key != "network"))
|
||||
};
|
||||
Sourced::new(value, source)
|
||||
});
|
||||
set_sourced!(models, &["models"]);
|
||||
set_sourced!(
|
||||
additional_developer_instructions,
|
||||
&["additional_developer_instructions"]
|
||||
);
|
||||
|
||||
if let Some(guardian_policy_config) =
|
||||
guardian_policy_config.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
output.guardian_policy_config = Some(Sourced::new(
|
||||
guardian_policy_config,
|
||||
source_for_top_level_keys(layers, &["guardian_policy_config"]),
|
||||
));
|
||||
}
|
||||
if let Some(guardian_extra_policy) =
|
||||
guardian_extra_policy.filter(|value| !value.trim().is_empty())
|
||||
{
|
||||
output.guardian_extra_policy = Some(Sourced::new(
|
||||
guardian_extra_policy,
|
||||
source_for_top_level_keys(layers, &["guardian_extra_policy"]),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn source_for_top_level_keys(
|
||||
layers: &[ComposableRequirementsLayer],
|
||||
keys: &[&str],
|
||||
) -> RequirementSource {
|
||||
let matching_layers = layers
|
||||
.iter()
|
||||
.filter_map(|layer| {
|
||||
top_level_value_for_keys(&layer.regular_toml, keys).map(|value| (&layer.source, value))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let Some((winning_source, winning_value)) = matching_layers.last() else {
|
||||
return RequirementSource::Unknown;
|
||||
};
|
||||
let winning_source = (*winning_source).clone();
|
||||
|
||||
// The config_server block is replaced as a whole, including its source attribution.
|
||||
if keys == ["config_server"] || !winning_value.is_table() {
|
||||
return winning_source;
|
||||
}
|
||||
|
||||
let table_sources = matching_layers
|
||||
.into_iter()
|
||||
.rev()
|
||||
.filter_map(|(source, value)| value.is_table().then_some(source.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
if table_sources.len() > 1 {
|
||||
RequirementSource::composite(table_sources)
|
||||
} else {
|
||||
winning_source
|
||||
}
|
||||
}
|
||||
|
||||
fn top_level_value_for_keys<'a>(value: &'a TomlValue, keys: &[&str]) -> Option<&'a TomlValue> {
|
||||
let table = value.as_table()?;
|
||||
keys.iter().find_map(|key| table.get(*key))
|
||||
}
|
||||
|
||||
pub(super) fn merge_output_source(existing: &mut RequirementSource, incoming: &RequirementSource) {
|
||||
if existing != incoming {
|
||||
*existing = RequirementSource::composite([existing.clone(), incoming.clone()]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn composition_conflict(
|
||||
field: String,
|
||||
existing_source: RequirementSource,
|
||||
incoming_source: RequirementSource,
|
||||
message: impl Into<String>,
|
||||
) -> RequirementsCompositionError {
|
||||
RequirementsCompositionError::Conflict {
|
||||
field,
|
||||
existing_source,
|
||||
incoming_source,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "stack_tests.rs"]
|
||||
mod tests;
|
||||
1916
codex-rs/config/src/requirements_layers/stack_tests.rs
Normal file
1916
codex-rs/config/src/requirements_layers/stack_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
319
codex-rs/config/src/schema.rs
Normal file
319
codex-rs/config/src/schema.rs
Normal file
@@ -0,0 +1,319 @@
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::types::RawMcpServerConfig;
|
||||
use codex_features::FEATURES;
|
||||
use codex_features::legacy_feature_keys;
|
||||
use codex_protocol::protocol::GranularApprovalConfig;
|
||||
use schemars::JsonSchema;
|
||||
use schemars::r#gen::SchemaGenerator;
|
||||
use schemars::r#gen::SchemaSettings;
|
||||
use schemars::schema::InstanceType;
|
||||
use schemars::schema::ObjectValidation;
|
||||
use schemars::schema::RootSchema;
|
||||
use schemars::schema::Schema;
|
||||
use schemars::schema::SchemaObject;
|
||||
use schemars::schema::SubschemaValidation;
|
||||
use serde_json::Map;
|
||||
use serde_json::Value;
|
||||
use std::path::Path;
|
||||
|
||||
/// Determines the conditions under which the user is consulted to approve
|
||||
/// running the command proposed by Codex.
|
||||
#[allow(dead_code)]
|
||||
#[derive(JsonSchema)]
|
||||
#[schemars(rename = "AskForApproval")]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub(crate) enum ConfigAskForApproval {
|
||||
/// The model decides when to ask the user for approval.
|
||||
OnRequest,
|
||||
|
||||
/// Fine-grained controls for individual approval flows.
|
||||
///
|
||||
/// When a field is `true`, commands in that category are allowed. When it
|
||||
/// is `false`, those requests are automatically rejected instead of shown
|
||||
/// to the user.
|
||||
Granular(GranularApprovalConfig),
|
||||
|
||||
/// Never ask the user to approve commands. Failures are immediately returned
|
||||
/// to the model, and never escalated to the user for approval.
|
||||
Never,
|
||||
}
|
||||
|
||||
/// Schema for the `[features]` map with known + legacy keys only.
|
||||
pub fn features_schema(schema_gen: &mut SchemaGenerator) -> Schema {
|
||||
let mut object = SchemaObject {
|
||||
instance_type: Some(InstanceType::Object.into()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut validation = ObjectValidation::default();
|
||||
for feature in FEATURES {
|
||||
if feature.id == codex_features::Feature::Artifact {
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::CodeMode {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::CodeModeConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::CodeModeHost {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::CodeModeHostConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::NonPrefixedMcpToolNames {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::NonPrefixedMcpToolNamesConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::GuardianThreadContext {
|
||||
// This setting is already part of the guardianv2 feature table.
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::GuardianV2 {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::GuardianV2ConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::GuardianV3 {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::GuardianV3ConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::MultiAgentV2 {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::MultiAgentV2ConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::AsyncCompaction {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::AsyncCompactionConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::TokenBudget {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::TokenBudgetConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::ContextManagement {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::ContextManagementConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::RolloutBudget {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::RolloutBudgetConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::CurrentTimeReminder {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::CurrentTimeReminderConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::SleepTool {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::SleepToolConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::RuntimeAgentInstances {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::RuntimeAgentInstancesConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::AppsMcpPathOverride {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
removed_apps_mcp_path_override_schema(schema_gen),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if feature.id == codex_features::Feature::NetworkProxy {
|
||||
validation.properties.insert(
|
||||
feature.key.to_string(),
|
||||
schema_gen.subschema_for::<codex_features::FeatureToml<
|
||||
codex_features::NetworkProxyConfigToml,
|
||||
>>(),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
validation
|
||||
.properties
|
||||
.insert(feature.key.to_string(), schema_gen.subschema_for::<bool>());
|
||||
}
|
||||
for legacy_key in legacy_feature_keys() {
|
||||
validation
|
||||
.properties
|
||||
.insert(legacy_key.to_string(), schema_gen.subschema_for::<bool>());
|
||||
}
|
||||
validation.properties.insert(
|
||||
"tool_registry".to_string(),
|
||||
schema_gen.subschema_for::<codex_features::ToolRegistryConfigToml>(),
|
||||
);
|
||||
validation.additional_properties = Some(Box::new(Schema::Bool(false)));
|
||||
object.object = Some(Box::new(validation));
|
||||
|
||||
Schema::Object(object)
|
||||
}
|
||||
|
||||
fn removed_apps_mcp_path_override_schema(schema_gen: &mut SchemaGenerator) -> Schema {
|
||||
let mut config_validation = ObjectValidation::default();
|
||||
config_validation
|
||||
.properties
|
||||
.insert("enabled".to_string(), schema_gen.subschema_for::<bool>());
|
||||
config_validation
|
||||
.properties
|
||||
.insert("path".to_string(), schema_gen.subschema_for::<String>());
|
||||
config_validation.additional_properties = Some(Box::new(Schema::Bool(false)));
|
||||
|
||||
let config = Schema::Object(SchemaObject {
|
||||
instance_type: Some(InstanceType::Object.into()),
|
||||
object: Some(Box::new(config_validation)),
|
||||
..Default::default()
|
||||
});
|
||||
Schema::Object(SchemaObject {
|
||||
subschemas: Some(Box::new(SubschemaValidation {
|
||||
any_of: Some(vec![schema_gen.subschema_for::<bool>(), config]),
|
||||
..Default::default()
|
||||
})),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Schema for the `[mcp_servers]` map using the raw input shape.
|
||||
pub fn mcp_servers_schema(schema_gen: &mut SchemaGenerator) -> Schema {
|
||||
let mut object = SchemaObject {
|
||||
instance_type: Some(InstanceType::Object.into()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let validation = ObjectValidation {
|
||||
additional_properties: Some(Box::new(schema_gen.subschema_for::<RawMcpServerConfig>())),
|
||||
..Default::default()
|
||||
};
|
||||
object.object = Some(Box::new(validation));
|
||||
|
||||
Schema::Object(object)
|
||||
}
|
||||
|
||||
/// Build the config schema for `config.toml`.
|
||||
pub fn config_schema() -> RootSchema {
|
||||
let mut schema = SchemaSettings::draft07()
|
||||
.with(|settings| {
|
||||
settings.option_add_null_type = false;
|
||||
})
|
||||
.into_generator()
|
||||
.into_root_schema_for::<ConfigToml>();
|
||||
add_shell_environment_policy_constraints(&mut schema);
|
||||
schema
|
||||
}
|
||||
|
||||
fn add_shell_environment_policy_constraints(schema: &mut RootSchema) {
|
||||
let Some(Schema::Object(policy)) = schema.definitions.get_mut("ShellEnvironmentPolicyToml")
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let all_of = policy
|
||||
.subschemas
|
||||
.get_or_insert_default()
|
||||
.all_of
|
||||
.get_or_insert_default();
|
||||
for fields in [["exclude", "filters"], ["filters", "include_only"]] {
|
||||
all_of.push(Schema::Object(SchemaObject {
|
||||
subschemas: Some(Box::new(SubschemaValidation {
|
||||
not: Some(Box::new(Schema::Object(SchemaObject {
|
||||
object: Some(Box::new(ObjectValidation {
|
||||
required: fields.into_iter().map(str::to_string).collect(),
|
||||
..Default::default()
|
||||
})),
|
||||
..Default::default()
|
||||
}))),
|
||||
..Default::default()
|
||||
})),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonicalize a JSON value by sorting its keys.
|
||||
pub fn canonicalize(value: &Value) -> Value {
|
||||
match value {
|
||||
Value::Array(items) => Value::Array(items.iter().map(canonicalize).collect()),
|
||||
Value::Object(map) => {
|
||||
let mut entries: Vec<_> = map.iter().collect();
|
||||
entries.sort_by_key(|(key, _)| *key);
|
||||
let mut sorted = Map::with_capacity(map.len());
|
||||
for (key, child) in entries {
|
||||
sorted.insert(key.clone(), canonicalize(child));
|
||||
}
|
||||
Value::Object(sorted)
|
||||
}
|
||||
_ => value.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the config schema as pretty-printed JSON.
|
||||
pub fn config_schema_json() -> anyhow::Result<Vec<u8>> {
|
||||
let schema = config_schema();
|
||||
let value = serde_json::to_value(schema)?;
|
||||
let value = canonicalize(&value);
|
||||
let json = serde_json::to_vec_pretty(&value)?;
|
||||
Ok(json)
|
||||
}
|
||||
|
||||
/// Write the config schema fixture to disk.
|
||||
pub fn write_config_schema(out_path: &Path) -> anyhow::Result<()> {
|
||||
let json = config_schema_json()?;
|
||||
std::fs::write(out_path, json)?;
|
||||
Ok(())
|
||||
}
|
||||
173
codex-rs/config/src/shell_environment_policy.rs
Normal file
173
codex-rs/config/src/shell_environment_policy.rs
Normal file
@@ -0,0 +1,173 @@
|
||||
use codex_protocol::config_types::EnvironmentVariablePattern;
|
||||
use codex_protocol::config_types::ShellEnvironmentPolicy;
|
||||
use codex_protocol::config_types::ShellEnvironmentPolicyFilter;
|
||||
use codex_protocol::config_types::ShellEnvironmentPolicyInherit;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
/// Policy for building the `env` when spawning a process via shell-like tools.
|
||||
#[derive(Serialize, Debug, Clone, PartialEq, Default, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct ShellEnvironmentPolicyToml {
|
||||
pub inherit: Option<ShellEnvironmentPolicyInherit>,
|
||||
|
||||
pub ignore_default_excludes: Option<bool>,
|
||||
|
||||
/// Legacy list of regular expressions to exclude.
|
||||
pub exclude: Option<Vec<String>>,
|
||||
|
||||
pub r#set: Option<HashMap<String, String>>,
|
||||
|
||||
/// Legacy list of regular expressions to include.
|
||||
pub include_only: Option<Vec<String>>,
|
||||
|
||||
/// Pattern actions used by the canonical table representation.
|
||||
///
|
||||
/// Ordinary config keeps accepting the legacy arrays above during the
|
||||
/// migration. Requirements will accept only this keyed form, keeping array
|
||||
/// compatibility isolated so the legacy fields can be deprecated later.
|
||||
/// Pattern keys merge case-insensitively across config layers, matching how
|
||||
/// the resulting patterns match environment variable names.
|
||||
pub filters: Option<BTreeMap<String, ShellEnvironmentPolicyFilter>>,
|
||||
|
||||
pub experimental_use_profile: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ShellEnvironmentPolicyTomlRaw {
|
||||
inherit: Option<ShellEnvironmentPolicyInherit>,
|
||||
ignore_default_excludes: Option<bool>,
|
||||
exclude: Option<Vec<String>>,
|
||||
r#set: Option<HashMap<String, String>>,
|
||||
include_only: Option<Vec<String>>,
|
||||
filters: Option<BTreeMap<String, ShellEnvironmentPolicyFilter>>,
|
||||
experimental_use_profile: Option<bool>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub(crate) struct ShellEnvironmentPolicyFilterConfigToml {
|
||||
#[serde(
|
||||
default,
|
||||
rename = "shell_environment_policy",
|
||||
deserialize_with = "deserialize_shell_environment_policy_filters"
|
||||
)]
|
||||
_shell_environment_policy: (),
|
||||
}
|
||||
|
||||
/// Validates only the shell-environment filter representation in a raw config overlay.
|
||||
pub fn validate_shell_environment_policy_filter_config(
|
||||
value: &TomlValue,
|
||||
) -> Result<(), toml::de::Error> {
|
||||
let _: ShellEnvironmentPolicyFilterConfigToml = value.clone().try_into()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn deserialize_shell_environment_policy_filters<'de, D>(deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let value = TomlValue::deserialize(deserializer)?;
|
||||
let Some(policy) = value.as_table() else {
|
||||
return Ok(());
|
||||
};
|
||||
let filter_fields = ["exclude", "include_only", "filters"]
|
||||
.into_iter()
|
||||
.filter_map(|field| {
|
||||
policy
|
||||
.get(field)
|
||||
.cloned()
|
||||
.map(|value| (field.to_string(), value))
|
||||
})
|
||||
.collect();
|
||||
let _: ShellEnvironmentPolicyToml = TomlValue::Table(filter_fields)
|
||||
.try_into()
|
||||
.map_err(|error: toml::de::Error| serde::de::Error::custom(error.message()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ShellEnvironmentPolicyToml {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let ShellEnvironmentPolicyTomlRaw {
|
||||
inherit,
|
||||
ignore_default_excludes,
|
||||
exclude,
|
||||
r#set,
|
||||
include_only,
|
||||
filters,
|
||||
experimental_use_profile,
|
||||
} = ShellEnvironmentPolicyTomlRaw::deserialize(deserializer)?;
|
||||
if filters.is_some() && (exclude.is_some() || include_only.is_some()) {
|
||||
return Err(serde::de::Error::custom(
|
||||
"cannot mix `filters` with legacy `exclude` or `include_only`",
|
||||
));
|
||||
}
|
||||
if let Some(filters) = filters.as_ref() {
|
||||
let mut patterns = std::collections::HashSet::new();
|
||||
for pattern in filters.keys() {
|
||||
if !patterns.insert(pattern.to_lowercase()) {
|
||||
return Err(serde::de::Error::custom(format!(
|
||||
"duplicate shell environment filter `{pattern}` ignoring case"
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self {
|
||||
inherit,
|
||||
ignore_default_excludes,
|
||||
exclude,
|
||||
r#set,
|
||||
include_only,
|
||||
filters,
|
||||
experimental_use_profile,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ShellEnvironmentPolicyToml> for ShellEnvironmentPolicy {
|
||||
fn from(toml: ShellEnvironmentPolicyToml) -> Self {
|
||||
let inherit = toml.inherit.unwrap_or(ShellEnvironmentPolicyInherit::All);
|
||||
let ignore_default_excludes = toml.ignore_default_excludes.unwrap_or(true);
|
||||
let (exclude, include_only) = match toml.filters {
|
||||
Some(filters) => filters.into_iter().fold(
|
||||
(Vec::new(), Vec::new()),
|
||||
|(mut exclude, mut include_only), (pattern, filter)| {
|
||||
match filter {
|
||||
ShellEnvironmentPolicyFilter::Include => include_only.push(pattern),
|
||||
ShellEnvironmentPolicyFilter::Exclude => exclude.push(pattern),
|
||||
}
|
||||
(exclude, include_only)
|
||||
},
|
||||
),
|
||||
None => (
|
||||
toml.exclude.unwrap_or_default(),
|
||||
toml.include_only.unwrap_or_default(),
|
||||
),
|
||||
};
|
||||
|
||||
Self {
|
||||
inherit,
|
||||
ignore_default_excludes,
|
||||
exclude: exclude
|
||||
.into_iter()
|
||||
.map(|pattern| EnvironmentVariablePattern::new_case_insensitive(&pattern))
|
||||
.collect(),
|
||||
r#set: toml.r#set.unwrap_or_default(),
|
||||
include_only: include_only
|
||||
.into_iter()
|
||||
.map(|pattern| EnvironmentVariablePattern::new_case_insensitive(&pattern))
|
||||
.collect(),
|
||||
use_profile: toml.experimental_use_profile.unwrap_or(false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "shell_environment_policy_tests.rs"]
|
||||
mod tests;
|
||||
109
codex-rs/config/src/shell_environment_policy_tests.rs
Normal file
109
codex-rs/config/src/shell_environment_policy_tests.rs
Normal file
@@ -0,0 +1,109 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_accepts_legacy_lists_or_filters() {
|
||||
let legacy: ShellEnvironmentPolicyToml = toml::from_str(
|
||||
r#"
|
||||
exclude = ["LEGACY_*", "SHARED_*"]
|
||||
include_only = ["PATH", "HOME"]
|
||||
"#,
|
||||
)
|
||||
.expect("legacy arrays should remain valid in config.toml");
|
||||
assert_eq!(
|
||||
legacy,
|
||||
ShellEnvironmentPolicyToml {
|
||||
exclude: Some(vec!["LEGACY_*".to_string(), "SHARED_*".to_string()]),
|
||||
include_only: Some(vec!["PATH".to_string(), "HOME".to_string()]),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
|
||||
let filtered: ShellEnvironmentPolicyToml = toml::from_str(
|
||||
r#"
|
||||
[filters]
|
||||
"FLIP_TO_EXCLUDE" = "exclude"
|
||||
"FLIP_TO_INCLUDE" = "include"
|
||||
"#,
|
||||
)
|
||||
.expect("filters should be valid in config.toml");
|
||||
assert_eq!(
|
||||
filtered,
|
||||
ShellEnvironmentPolicyToml {
|
||||
filters: Some(BTreeMap::from([
|
||||
(
|
||||
"FLIP_TO_EXCLUDE".to_string(),
|
||||
ShellEnvironmentPolicyFilter::Exclude,
|
||||
),
|
||||
(
|
||||
"FLIP_TO_INCLUDE".to_string(),
|
||||
ShellEnvironmentPolicyFilter::Include,
|
||||
),
|
||||
])),
|
||||
..Default::default()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
ShellEnvironmentPolicy::from(filtered),
|
||||
ShellEnvironmentPolicy::from(ShellEnvironmentPolicyToml {
|
||||
exclude: Some(vec!["FLIP_TO_EXCLUDE".to_string()]),
|
||||
include_only: Some(vec!["FLIP_TO_INCLUDE".to_string()]),
|
||||
..Default::default()
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_rejects_mixed_legacy_lists_and_filters() {
|
||||
let error = toml::from_str::<ShellEnvironmentPolicyToml>(
|
||||
r#"
|
||||
exclude = ["LEGACY_*"]
|
||||
|
||||
[filters]
|
||||
"CANONICAL_*" = "include"
|
||||
"#,
|
||||
)
|
||||
.expect_err("one config layer must not mix legacy lists and filters");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("cannot mix `filters` with legacy `exclude` or `include_only`")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_rejects_case_variant_filters_within_layer() {
|
||||
let error = toml::from_str::<ShellEnvironmentPolicyToml>(
|
||||
r#"
|
||||
[filters]
|
||||
"AWS_*" = "exclude"
|
||||
"aws_*" = "include"
|
||||
"#,
|
||||
)
|
||||
.expect_err("case-variant filters in one layer should be rejected");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("duplicate shell environment filter")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shell_environment_policy_rejects_unicode_case_variant_filters_within_layer() {
|
||||
let error = toml::from_str::<ShellEnvironmentPolicyToml>(
|
||||
r#"
|
||||
[filters]
|
||||
"СЕКРЕТ_*" = "exclude"
|
||||
"секрет_*" = "include"
|
||||
"#,
|
||||
)
|
||||
.expect_err("Unicode case-variant filters in one layer should be rejected");
|
||||
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("duplicate shell environment filter")
|
||||
);
|
||||
}
|
||||
224
codex-rs/config/src/skills_config.rs
Normal file
224
codex-rs/config/src/skills_config.rs
Normal file
@@ -0,0 +1,224 @@
|
||||
//! Skill-related configuration types shared across crates.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::num::NonZeroUsize;
|
||||
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use schemars::JsonSchema;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
use tracing::warn;
|
||||
|
||||
const fn default_enabled() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct SkillConfig {
|
||||
/// Path-based selector.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub path: Option<AbsolutePathBuf>,
|
||||
/// Name-based selector.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub name: Option<String>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// Skills required from one environment or plugin before inference.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ScopedSkillsConfig {
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub required: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct SkillsConfig {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub bundled: Option<BundledSkillsConfig>,
|
||||
|
||||
/// Whether turns receive the automatic skills instructions block.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub include_instructions: Option<bool>,
|
||||
|
||||
/// Maximum tokens used by the available-skills catalog. Defaults to 2% of
|
||||
/// the model context window and is capped at 10,000 tokens when set.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub max_context_tokens: Option<NonZeroUsize>,
|
||||
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub config: Vec<SkillConfig>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct BundledSkillsConfig {
|
||||
#[serde(default = "default_enabled")]
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for BundledSkillsConfig {
|
||||
fn default() -> Self {
|
||||
Self { enabled: true }
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<toml::Value> for SkillsConfig {
|
||||
type Error = toml::de::Error;
|
||||
|
||||
fn try_from(value: toml::Value) -> Result<Self, Self::Error> {
|
||||
SkillsConfig::deserialize(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Selects configured skills by their name or canonical document path.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub enum SkillConfigRuleSelector {
|
||||
Name(String),
|
||||
Path(PathUri),
|
||||
}
|
||||
|
||||
/// Enables or disables every skill matched by its selector.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct SkillConfigRule {
|
||||
pub selector: SkillConfigRuleSelector,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
/// Ordered effective skill enablement rules from configuration layers.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
|
||||
pub struct SkillConfigRules {
|
||||
pub entries: Vec<SkillConfigRule>,
|
||||
}
|
||||
|
||||
impl SkillConfigRules {
|
||||
/// Applies rules in order; later rules override earlier rules for matching skills.
|
||||
///
|
||||
/// Explicit path selectors remain effective even when no current skill matches.
|
||||
pub fn resolve_disabled_paths<'a>(
|
||||
&self,
|
||||
skills: impl IntoIterator<Item = (&'a str, &'a PathUri)> + Clone,
|
||||
) -> HashSet<PathUri> {
|
||||
let mut disabled_paths = HashSet::new();
|
||||
|
||||
for entry in &self.entries {
|
||||
match &entry.selector {
|
||||
SkillConfigRuleSelector::Path(path) => {
|
||||
if entry.enabled {
|
||||
disabled_paths.remove(path);
|
||||
} else {
|
||||
disabled_paths.insert(path.clone());
|
||||
}
|
||||
}
|
||||
SkillConfigRuleSelector::Name(name) => {
|
||||
for (skill_name, path) in skills.clone() {
|
||||
if skill_name != name {
|
||||
continue;
|
||||
}
|
||||
if entry.enabled {
|
||||
disabled_paths.remove(path);
|
||||
} else {
|
||||
disabled_paths.insert(path.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
disabled_paths
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns whether bundled skills are enabled by the effective configuration.
|
||||
pub fn bundled_skills_enabled_from_stack(config_layer_stack: &ConfigLayerStack) -> bool {
|
||||
let effective_config = config_layer_stack.effective_config();
|
||||
let Some(skills_value) = effective_config
|
||||
.as_table()
|
||||
.and_then(|table| table.get("skills"))
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
|
||||
let skills: SkillsConfig = match skills_value.clone().try_into() {
|
||||
Ok(skills) => skills,
|
||||
Err(err) => {
|
||||
warn!("invalid skills config: {err}");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
skills.bundled.unwrap_or_default().enabled
|
||||
}
|
||||
|
||||
/// Resolves skill enablement rules from user and session configuration layers.
|
||||
pub fn skill_config_rules_from_stack(config_layer_stack: &ConfigLayerStack) -> SkillConfigRules {
|
||||
let mut entries = Vec::new();
|
||||
for layer in config_layer_stack.all_layers_low_to_high() {
|
||||
if !matches!(
|
||||
layer.name,
|
||||
ConfigLayerSource::User { .. } | ConfigLayerSource::SessionFlags
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(skills_value) = layer.config.get("skills") else {
|
||||
continue;
|
||||
};
|
||||
let skills: SkillsConfig = match skills_value.clone().try_into() {
|
||||
Ok(skills) => skills,
|
||||
Err(err) => {
|
||||
warn!("invalid skills config: {err}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
for entry in skills.config {
|
||||
let Some(selector) = skill_config_rule_selector(&entry) else {
|
||||
continue;
|
||||
};
|
||||
// Preserve layer order so a later name selector can override an earlier path selector
|
||||
// for the same loaded skill.
|
||||
entries.retain(|entry: &SkillConfigRule| entry.selector != selector);
|
||||
entries.push(SkillConfigRule {
|
||||
selector,
|
||||
enabled: entry.enabled,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
SkillConfigRules { entries }
|
||||
}
|
||||
|
||||
fn skill_config_rule_selector(entry: &SkillConfig) -> Option<SkillConfigRuleSelector> {
|
||||
match (entry.path.as_ref(), entry.name.as_deref()) {
|
||||
(Some(path), None) => Some(SkillConfigRuleSelector::Path(PathUri::from_abs_path(
|
||||
&path.canonicalize().unwrap_or_else(|_| path.clone()),
|
||||
))),
|
||||
(None, Some(name)) => {
|
||||
let name = name.trim();
|
||||
if name.is_empty() {
|
||||
warn!("ignoring empty skills.config name override");
|
||||
None
|
||||
} else {
|
||||
Some(SkillConfigRuleSelector::Name(name.to_string()))
|
||||
}
|
||||
}
|
||||
(Some(_), Some(_)) => {
|
||||
warn!("ignoring skills.config entry with both path and name selectors");
|
||||
None
|
||||
}
|
||||
(None, None) => {
|
||||
warn!("ignoring skills.config entry without a path or name selector");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "skills_config_tests.rs"]
|
||||
mod tests;
|
||||
248
codex-rs/config/src/skills_config_tests.rs
Normal file
248
codex-rs/config/src/skills_config_tests.rs
Normal file
@@ -0,0 +1,248 @@
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_absolute_path::test_support::PathBufExt;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::SkillConfigRule;
|
||||
use super::SkillConfigRuleSelector;
|
||||
use super::SkillConfigRules;
|
||||
use super::bundled_skills_enabled_from_stack;
|
||||
use super::skill_config_rules_from_stack;
|
||||
|
||||
fn user_layer(codex_home: &TempDir, config: &str) -> ConfigLayerEntry {
|
||||
let config_path = AbsolutePathBuf::try_from(codex_home.path().join(CONFIG_TOML_FILE))
|
||||
.expect("absolute config path");
|
||||
ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: config_path,
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(config).expect("valid user config"),
|
||||
)
|
||||
}
|
||||
|
||||
fn stack(codex_home: &TempDir, user: &str, session: &str) -> ConfigLayerStack {
|
||||
ConfigLayerStack::new(
|
||||
vec![
|
||||
user_layer(codex_home, user),
|
||||
ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str(session).expect("valid session config"),
|
||||
),
|
||||
],
|
||||
Default::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("valid config stack")
|
||||
}
|
||||
|
||||
fn path_toggle_config(path: &std::path::Path, enabled: bool) -> String {
|
||||
let path = toml::Value::String(path.display().to_string());
|
||||
format!(
|
||||
r#"[[skills.config]]
|
||||
path = {path}
|
||||
enabled = {enabled}
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bundled_skills_follow_effective_configuration() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
|
||||
assert!(bundled_skills_enabled_from_stack(&stack(
|
||||
&codex_home,
|
||||
"",
|
||||
""
|
||||
)));
|
||||
assert!(!bundled_skills_enabled_from_stack(&stack(
|
||||
&codex_home,
|
||||
"[skills.bundled]\nenabled = false\n",
|
||||
""
|
||||
)));
|
||||
assert!(bundled_skills_enabled_from_stack(&stack(
|
||||
&codex_home,
|
||||
"[skills.bundled]\nenabled = false\n",
|
||||
"[skills.bundled]\nenabled = true\n"
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_bundled_skills_config_defaults_to_enabled() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
|
||||
assert!(bundled_skills_enabled_from_stack(&stack(
|
||||
&codex_home,
|
||||
"[skills]\nbundled = 'invalid'\n",
|
||||
""
|
||||
)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_flags_can_reenable_user_disabled_path() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
let skill_path = codex_home.path().join("skills/demo/SKILL.md");
|
||||
|
||||
assert_eq!(
|
||||
skill_config_rules_from_stack(&stack(
|
||||
&codex_home,
|
||||
&path_toggle_config(&skill_path, /*enabled*/ false),
|
||||
&path_toggle_config(&skill_path, /*enabled*/ true),
|
||||
)),
|
||||
SkillConfigRules {
|
||||
entries: vec![SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Path(PathUri::from_abs_path(&skill_path.abs())),
|
||||
enabled: true,
|
||||
}],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_flags_can_disable_user_enabled_path() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
let skill_path = codex_home.path().join("skills/demo/SKILL.md");
|
||||
|
||||
assert_eq!(
|
||||
skill_config_rules_from_stack(&stack(
|
||||
&codex_home,
|
||||
&path_toggle_config(&skill_path, /*enabled*/ true),
|
||||
&path_toggle_config(&skill_path, /*enabled*/ false),
|
||||
)),
|
||||
SkillConfigRules {
|
||||
entries: vec![SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Path(PathUri::from_abs_path(&skill_path.abs())),
|
||||
enabled: false,
|
||||
}],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_name_selectors() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
|
||||
assert_eq!(
|
||||
skill_config_rules_from_stack(&stack(
|
||||
&codex_home,
|
||||
r#"
|
||||
[[skills.config]]
|
||||
name = "github:yeet"
|
||||
enabled = false
|
||||
"#,
|
||||
"",
|
||||
)),
|
||||
SkillConfigRules {
|
||||
entries: vec![SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Name("github:yeet".to_string()),
|
||||
enabled: false,
|
||||
}],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_order_across_path_and_name_selectors() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
let skill_path = codex_home.path().join("skills/demo/SKILL.md");
|
||||
|
||||
assert_eq!(
|
||||
skill_config_rules_from_stack(&stack(
|
||||
&codex_home,
|
||||
&path_toggle_config(&skill_path, /*enabled*/ false),
|
||||
r#"
|
||||
[[skills.config]]
|
||||
name = "github:yeet"
|
||||
enabled = true
|
||||
"#,
|
||||
)),
|
||||
SkillConfigRules {
|
||||
entries: vec![
|
||||
SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Path(PathUri::from_abs_path(
|
||||
&skill_path.abs()
|
||||
)),
|
||||
enabled: false,
|
||||
},
|
||||
SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Name("github:yeet".to_string()),
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn path_rule_disables_selected_path() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
let path = codex_home.path().join("disable-by-path/SKILL.md").abs();
|
||||
let rules = SkillConfigRules {
|
||||
entries: vec![SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Path(PathUri::from_abs_path(&path)),
|
||||
enabled: false,
|
||||
}],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
rules.resolve_disabled_paths(std::iter::empty()),
|
||||
[PathUri::from_abs_path(&path)].into_iter().collect()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_name_rule_reenables_path_disabled_skill() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
let path = codex_home.path().join("reenable-by-name/SKILL.md").abs();
|
||||
let rules = SkillConfigRules {
|
||||
entries: vec![
|
||||
SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Path(PathUri::from_abs_path(&path)),
|
||||
enabled: false,
|
||||
},
|
||||
SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Name("demo".to_string()),
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
rules.resolve_disabled_paths([("demo", &PathUri::from_abs_path(&path))]),
|
||||
Default::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_path_rule_reenables_one_skill_disabled_by_name() {
|
||||
let codex_home = TempDir::new().expect("temp dir");
|
||||
let root = codex_home.path().join("reenable-by-path");
|
||||
let first_path = root.join("first/SKILL.md").abs();
|
||||
let second_path = root.join("second/SKILL.md").abs();
|
||||
let rules = SkillConfigRules {
|
||||
entries: vec![
|
||||
SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Name("demo".to_string()),
|
||||
enabled: false,
|
||||
},
|
||||
SkillConfigRule {
|
||||
selector: SkillConfigRuleSelector::Path(PathUri::from_abs_path(&first_path)),
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
rules.resolve_disabled_paths([
|
||||
("demo", &PathUri::from_abs_path(&first_path)),
|
||||
("demo", &PathUri::from_abs_path(&second_path)),
|
||||
]),
|
||||
[PathUri::from_abs_path(&second_path)].into_iter().collect()
|
||||
);
|
||||
}
|
||||
822
codex-rs/config/src/state.rs
Normal file
822
codex-rs/config/src/state.rs
Normal file
@@ -0,0 +1,822 @@
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::config_requirements::ConfigRequirements;
|
||||
use crate::config_requirements::ConfigRequirementsToml;
|
||||
use crate::format_config_layer_source;
|
||||
|
||||
use super::fingerprint::record_origins;
|
||||
use super::fingerprint::version_for_toml;
|
||||
use super::key_aliases::normalize_key_aliases;
|
||||
use super::merge::merge_toml_values;
|
||||
use crate::CloudConfigBundleLoader;
|
||||
use crate::ConfigLayer;
|
||||
use crate::ConfigLayerMetadata;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ProfileV2Name;
|
||||
use crate::shell_environment_policy::validate_shell_environment_policy_filter_config;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use serde_json::Value as JsonValue;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
/// User-facing config loading behavior that is not part of the config document.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct ConfigLoadOptions {
|
||||
pub loader_overrides: LoaderOverrides,
|
||||
pub strict_config: bool,
|
||||
pub cloud_config_bundle: CloudConfigBundleLoader,
|
||||
}
|
||||
|
||||
impl From<LoaderOverrides> for ConfigLoadOptions {
|
||||
fn from(loader_overrides: LoaderOverrides) -> Self {
|
||||
Self {
|
||||
loader_overrides,
|
||||
strict_config: false,
|
||||
cloud_config_bundle: CloudConfigBundleLoader::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// LoaderOverrides overrides managed configuration inputs (primarily for tests).
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct LoaderOverrides {
|
||||
/// Optional configuration file supplied with the installed Codex package.
|
||||
pub packaged_defaults_path: Option<AbsolutePathBuf>,
|
||||
/// Working directory to use when a client request supplies none.
|
||||
pub default_cwd: Option<AbsolutePathBuf>,
|
||||
pub user_config_path: Option<AbsolutePathBuf>,
|
||||
pub user_config_profile: Option<ProfileV2Name>,
|
||||
pub managed_config_path: Option<PathBuf>,
|
||||
pub system_config_path: Option<PathBuf>,
|
||||
pub system_requirements_path: Option<PathBuf>,
|
||||
pub ignore_managed_requirements: bool,
|
||||
/// Remote app servers own their authentication policy independently.
|
||||
pub ignore_login_requirements: bool,
|
||||
pub ignore_user_config: bool,
|
||||
/// Skip project-root discovery and all project configuration layers.
|
||||
pub ignore_project_config: bool,
|
||||
pub ignore_user_and_project_exec_policy_rules: bool,
|
||||
//TODO(gt): Add a macos_ prefix to this field and remove the target_os check.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub managed_preferences_base64: Option<String>,
|
||||
pub macos_managed_config_requirements_base64: Option<String>,
|
||||
}
|
||||
|
||||
impl LoaderOverrides {
|
||||
/// Returns overrides that ignore host-managed configuration.
|
||||
///
|
||||
/// This is intended for tests that should load only repo-controlled config fixtures.
|
||||
pub fn without_managed_config_for_tests() -> Self {
|
||||
let base = std::env::temp_dir().join("codex-config-tests");
|
||||
Self {
|
||||
packaged_defaults_path: None,
|
||||
default_cwd: None,
|
||||
user_config_path: None,
|
||||
user_config_profile: None,
|
||||
managed_config_path: Some(base.join("managed_config.toml")),
|
||||
system_config_path: Some(base.join("config.toml")),
|
||||
system_requirements_path: Some(base.join("requirements.toml")),
|
||||
ignore_managed_requirements: false,
|
||||
ignore_login_requirements: false,
|
||||
ignore_user_config: false,
|
||||
ignore_project_config: false,
|
||||
ignore_user_and_project_exec_policy_rules: false,
|
||||
#[cfg(target_os = "macos")]
|
||||
managed_preferences_base64: Some(String::new()),
|
||||
macos_managed_config_requirements_base64: Some(String::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns overrides with host MDM disabled and managed config loaded from
|
||||
/// `managed_config_path`. System requirements are loaded from a sibling
|
||||
/// `requirements.toml` fixture.
|
||||
///
|
||||
/// This is intended for tests that supply an explicit managed config fixture.
|
||||
pub fn with_managed_config_path_for_tests(managed_config_path: PathBuf) -> Self {
|
||||
let system_requirements_path = managed_config_path.with_file_name("requirements.toml");
|
||||
Self {
|
||||
user_config_path: None,
|
||||
user_config_profile: None,
|
||||
managed_config_path: Some(managed_config_path),
|
||||
system_requirements_path: Some(system_requirements_path),
|
||||
..Self::without_managed_config_for_tests()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn user_config_path(&self, codex_home: &Path) -> std::io::Result<AbsolutePathBuf> {
|
||||
match self.user_config_path.as_ref() {
|
||||
Some(path) => Ok(path.clone()),
|
||||
None => Ok(AbsolutePathBuf::resolve_path_against_base(
|
||||
crate::CONFIG_TOML_FILE,
|
||||
codex_home,
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ConfigLayerEntry {
|
||||
pub name: ConfigLayerSource,
|
||||
pub config: TomlValue,
|
||||
pub version: String,
|
||||
pub disabled_reason: Option<String>,
|
||||
raw_toml: Option<RawTomlLayer>,
|
||||
hooks_config_folder_override: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
struct RawTomlLayer {
|
||||
contents: String,
|
||||
base_dir: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
impl ConfigLayerEntry {
|
||||
pub fn new(name: ConfigLayerSource, config: TomlValue) -> Self {
|
||||
let version = version_for_toml(&config);
|
||||
Self {
|
||||
name,
|
||||
config,
|
||||
version,
|
||||
disabled_reason: None,
|
||||
raw_toml: None,
|
||||
hooks_config_folder_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_with_raw_toml(
|
||||
name: ConfigLayerSource,
|
||||
config: TomlValue,
|
||||
raw_toml: String,
|
||||
raw_toml_base_dir: AbsolutePathBuf,
|
||||
) -> Self {
|
||||
let version = version_for_toml(&config);
|
||||
Self {
|
||||
name,
|
||||
config,
|
||||
version,
|
||||
disabled_reason: None,
|
||||
raw_toml: Some(RawTomlLayer {
|
||||
contents: raw_toml,
|
||||
base_dir: raw_toml_base_dir,
|
||||
}),
|
||||
hooks_config_folder_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_disabled(
|
||||
name: ConfigLayerSource,
|
||||
config: TomlValue,
|
||||
disabled_reason: impl Into<String>,
|
||||
) -> Self {
|
||||
let version = version_for_toml(&config);
|
||||
Self {
|
||||
name,
|
||||
config,
|
||||
version,
|
||||
disabled_reason: Some(disabled_reason.into()),
|
||||
raw_toml: None,
|
||||
hooks_config_folder_override: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_disabled(&self) -> bool {
|
||||
self.disabled_reason.is_some()
|
||||
}
|
||||
|
||||
pub fn raw_toml(&self) -> Option<&str> {
|
||||
self.raw_toml
|
||||
.as_ref()
|
||||
.map(|raw_toml| raw_toml.contents.as_str())
|
||||
}
|
||||
|
||||
pub fn raw_toml_base_dir(&self) -> Option<&AbsolutePathBuf> {
|
||||
self.raw_toml.as_ref().map(|raw_toml| &raw_toml.base_dir)
|
||||
}
|
||||
|
||||
pub(crate) fn with_hooks_config_folder_override(
|
||||
mut self,
|
||||
hooks_config_folder_override: Option<AbsolutePathBuf>,
|
||||
) -> Self {
|
||||
self.hooks_config_folder_override = hooks_config_folder_override;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> ConfigLayerMetadata {
|
||||
ConfigLayerMetadata {
|
||||
name: self.name.clone(),
|
||||
version: self.version.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn as_layer(&self) -> ConfigLayer {
|
||||
ConfigLayer {
|
||||
name: self.name.clone(),
|
||||
version: self.version.clone(),
|
||||
config: serde_json::to_value(&self.config).unwrap_or(JsonValue::Null),
|
||||
disabled_reason: self.disabled_reason.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
// Get the `.codex/` folder associated with this config layer, if any.
|
||||
pub fn config_folder(&self) -> Option<AbsolutePathBuf> {
|
||||
match &self.name {
|
||||
ConfigLayerSource::PackagedDefaults { .. } => None,
|
||||
ConfigLayerSource::Mdm { .. } => None,
|
||||
ConfigLayerSource::System { file } => file.parent(),
|
||||
ConfigLayerSource::EnterpriseManaged { .. } => None,
|
||||
ConfigLayerSource::User { file, .. } => file.parent(),
|
||||
ConfigLayerSource::Project { dot_codex_folder } => Some(dot_codex_folder.clone()),
|
||||
ConfigLayerSource::SessionFlags => None,
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromFile { .. } => None,
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromMdm => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the `.codex/` folder that should be used for hook declarations.
|
||||
///
|
||||
/// Project layers normally use their own config folder. Linked Git worktrees
|
||||
/// can instead point hook discovery at the matching folder from the root
|
||||
/// checkout while the rest of the project config still comes from the
|
||||
/// worktree.
|
||||
pub fn hooks_config_folder(&self) -> Option<AbsolutePathBuf> {
|
||||
self.hooks_config_folder_override
|
||||
.clone()
|
||||
.or_else(|| self.config_folder())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ConfigLayerStack {
|
||||
/// Runtime-only EMA authority; it does not change the configuration's contents.
|
||||
cloud_config_binding: Option<crate::CloudConfigBundleBinding>,
|
||||
/// Runtime-only cancellation inherited by config snapshots and pending EMA startups.
|
||||
mcp_ema_cancellation: crate::McpEmaCancellation,
|
||||
/// Identifies the service that supplied the loaded configuration, for comparison with the configured service.
|
||||
applied_config_server: Option<std::sync::Arc<crate::ConfigServer>>,
|
||||
/// Cached TOML projection derived only from `requirements_toml`.
|
||||
/// Construction validates provider definitions and reports serialization errors,
|
||||
/// so `effective_config()` can replace complete entries without a fallible conversion.
|
||||
model_provider_requirements: Option<TomlValue>,
|
||||
/// Layers are listed from lowest precedence (base) to highest (top), so
|
||||
/// later entries in the Vec override earlier ones.
|
||||
layers: Vec<ConfigLayerEntry>,
|
||||
|
||||
/// Constraints that must be enforced when deriving a [Config] from the
|
||||
/// layers.
|
||||
requirements: ConfigRequirements,
|
||||
|
||||
/// Raw requirements data as loaded from requirements.toml/MDM/legacy
|
||||
/// sources. This preserves the original allow-lists so they can be
|
||||
/// surfaced via APIs. Keep it off the stack of futures that carry a config.
|
||||
requirements_toml: Box<ConfigRequirementsToml>,
|
||||
|
||||
/// Whether execpolicy should skip `.rules` files from user and project config-layer folders.
|
||||
ignore_user_and_project_exec_policy_rules: bool,
|
||||
|
||||
/// Startup warnings discovered while building this stack.
|
||||
///
|
||||
/// `None` means the loader did not check for stack-level warnings, while
|
||||
/// `Some(vec![])` means it checked and found nothing to report.
|
||||
startup_warnings: Option<Vec<String>>,
|
||||
pub(crate) is_projectless: bool,
|
||||
/// Effective decision and config key selected during project discovery.
|
||||
pub project_trust: Option<crate::loader::ProjectTrustDecision>,
|
||||
}
|
||||
|
||||
impl PartialEq for ConfigLayerStack {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let Self {
|
||||
cloud_config_binding: _,
|
||||
mcp_ema_cancellation: _,
|
||||
applied_config_server,
|
||||
model_provider_requirements,
|
||||
layers,
|
||||
requirements,
|
||||
requirements_toml,
|
||||
ignore_user_and_project_exec_policy_rules,
|
||||
startup_warnings,
|
||||
is_projectless,
|
||||
project_trust,
|
||||
} = self;
|
||||
applied_config_server == &other.applied_config_server
|
||||
&& model_provider_requirements == &other.model_provider_requirements
|
||||
&& layers == &other.layers
|
||||
&& requirements == &other.requirements
|
||||
&& requirements_toml == &other.requirements_toml
|
||||
&& *ignore_user_and_project_exec_policy_rules
|
||||
== other.ignore_user_and_project_exec_policy_rules
|
||||
&& startup_warnings == &other.startup_warnings
|
||||
&& is_projectless == &other.is_projectless
|
||||
&& project_trust == &other.project_trust
|
||||
}
|
||||
}
|
||||
|
||||
impl ConfigLayerStack {
|
||||
pub fn new(
|
||||
layers: Vec<ConfigLayerEntry>,
|
||||
requirements: ConfigRequirements,
|
||||
requirements_toml: ConfigRequirementsToml,
|
||||
) -> std::io::Result<Self> {
|
||||
validate_enabled_config_layers(&layers)?;
|
||||
verify_layer_ordering(&layers)?;
|
||||
let model_provider_requirements = Some(crate::model_provider_requirements::to_config(
|
||||
&requirements_toml,
|
||||
)?);
|
||||
let stack = Self {
|
||||
cloud_config_binding: None,
|
||||
mcp_ema_cancellation: crate::McpEmaCancellation::default(),
|
||||
applied_config_server: None,
|
||||
model_provider_requirements,
|
||||
layers,
|
||||
requirements,
|
||||
requirements_toml: Box::new(requirements_toml),
|
||||
ignore_user_and_project_exec_policy_rules: false,
|
||||
startup_warnings: None,
|
||||
is_projectless: false,
|
||||
project_trust: None,
|
||||
};
|
||||
stack.validate_project_mitm_profiles()?;
|
||||
Ok(stack)
|
||||
}
|
||||
|
||||
/// Recheck project provenance after combining layer snapshots as well as on initial load.
|
||||
pub fn validate_project_mitm_profiles(&self) -> std::io::Result<()> {
|
||||
crate::loader::validate_project_mitm_profiles(
|
||||
self.layers_low_to_high()
|
||||
.map(|layer| (&layer.name, &layer.config)),
|
||||
self.requirements_toml
|
||||
.permissions
|
||||
.iter()
|
||||
.flat_map(|permissions| permissions.profiles.iter())
|
||||
.map(|(name, profile)| {
|
||||
(
|
||||
name.clone(),
|
||||
profile.extends.clone(),
|
||||
profile
|
||||
.network
|
||||
.as_ref()
|
||||
.is_some_and(|network| network.mitm.is_some()),
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn with_user_and_project_exec_policy_rules_ignored(
|
||||
mut self,
|
||||
ignore_user_and_project_exec_policy_rules: bool,
|
||||
) -> Self {
|
||||
self.ignore_user_and_project_exec_policy_rules = ignore_user_and_project_exec_policy_rules;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn ignore_user_and_project_exec_policy_rules(&self) -> bool {
|
||||
self.ignore_user_and_project_exec_policy_rules
|
||||
}
|
||||
|
||||
pub fn with_cloud_config_binding(
|
||||
mut self,
|
||||
binding: Option<crate::CloudConfigBundleBinding>,
|
||||
) -> Self {
|
||||
self.cloud_config_binding = binding;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn cloud_config_binding(&self) -> Option<&crate::CloudConfigBundleBinding> {
|
||||
self.cloud_config_binding.as_ref()
|
||||
}
|
||||
|
||||
pub fn with_mcp_ema_cancellation(mut self, cancellation: crate::McpEmaCancellation) -> Self {
|
||||
self.mcp_ema_cancellation = cancellation;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn mcp_ema_cancellation(&self) -> &crate::McpEmaCancellation {
|
||||
&self.mcp_ema_cancellation
|
||||
}
|
||||
|
||||
pub fn with_applied_config_server(
|
||||
mut self,
|
||||
service_config: Option<crate::ConfigServer>,
|
||||
) -> Self {
|
||||
self.applied_config_server = service_config.map(std::sync::Arc::new);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn applied_config_server(&self) -> Option<&crate::ConfigServer> {
|
||||
self.applied_config_server.as_deref()
|
||||
}
|
||||
|
||||
/// Require configuration from the configured service before starting a session.
|
||||
pub fn ensure_config_server_applied(&self) -> std::io::Result<()> {
|
||||
if self.requirements_toml.config_server.as_ref() != self.applied_config_server() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::PermissionDenied,
|
||||
"Required managed configuration has not been loaded; authenticate and reload configuration before starting a session",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retains session layers while adopting current MCP, plugin, and feature restrictions.
|
||||
/// Rejected refreshes must not restore an earlier policy on the next user reload.
|
||||
pub fn with_mcp_requirements_from(&self, incoming: &Self) -> Self {
|
||||
let mut stack = self.clone();
|
||||
stack.requirements.mcp_servers = incoming.requirements.mcp_servers.clone();
|
||||
stack.requirements.plugins = incoming.requirements.plugins.clone();
|
||||
stack.requirements.feature_requirements =
|
||||
incoming.requirements.feature_requirements.clone();
|
||||
stack.requirements_toml.mcp_servers = incoming.requirements_toml.mcp_servers.clone();
|
||||
stack.requirements_toml.plugins = incoming.requirements_toml.plugins.clone();
|
||||
stack.requirements_toml.feature_requirements =
|
||||
incoming.requirements_toml.feature_requirements.clone();
|
||||
stack
|
||||
}
|
||||
|
||||
pub(crate) fn with_startup_warnings(mut self, startup_warnings: Vec<String>) -> Self {
|
||||
self.startup_warnings = Some(startup_warnings);
|
||||
self
|
||||
}
|
||||
|
||||
pub fn startup_warnings(&self) -> Option<&[String]> {
|
||||
self.startup_warnings.as_deref()
|
||||
}
|
||||
|
||||
/// Whether discovery found no project markers or project-local configuration.
|
||||
/// Returns false when project discovery was skipped.
|
||||
pub fn is_projectless(&self) -> bool {
|
||||
self.is_projectless
|
||||
}
|
||||
|
||||
/// Returns the active raw user config layer, if any.
|
||||
///
|
||||
/// This does not merge other config layers or apply any requirements. When
|
||||
/// a profile-v2 layer is active, this returns that profile layer rather than
|
||||
/// the base `$CODEX_HOME/config.toml` layer because the active layer is the
|
||||
/// writable target for profile-aware edits.
|
||||
pub fn get_active_user_layer(&self) -> Option<&ConfigLayerEntry> {
|
||||
self.layers
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|layer| matches!(layer.name, ConfigLayerSource::User { .. }))
|
||||
}
|
||||
|
||||
pub fn get_user_config_file(&self) -> Option<&AbsolutePathBuf> {
|
||||
let layer = self.get_active_user_layer()?;
|
||||
let ConfigLayerSource::User { file, .. } = &layer.name else {
|
||||
return None;
|
||||
};
|
||||
Some(file)
|
||||
}
|
||||
|
||||
/// Returns the merged config from enabled user layers only.
|
||||
///
|
||||
/// When profile config is active, this includes the base user config followed
|
||||
/// by the profile override config.
|
||||
pub fn effective_user_config(&self) -> Option<TomlValue> {
|
||||
let mut user_layers = self
|
||||
.layers_low_to_high()
|
||||
.filter(|layer| matches!(layer.name, ConfigLayerSource::User { .. }))
|
||||
.peekable();
|
||||
user_layers.peek()?;
|
||||
|
||||
let mut merged = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in user_layers {
|
||||
merge_toml_values(&mut merged, &layer.config);
|
||||
}
|
||||
Some(merged)
|
||||
}
|
||||
|
||||
pub fn requirements(&self) -> &ConfigRequirements {
|
||||
&self.requirements
|
||||
}
|
||||
|
||||
pub fn requirements_toml(&self) -> &ConfigRequirementsToml {
|
||||
&self.requirements_toml
|
||||
}
|
||||
|
||||
/// Creates a new [ConfigLayerStack] using the specified values to inject one
|
||||
/// user layer into the stack. If such a layer already exists, it is replaced;
|
||||
/// otherwise, it is inserted into the stack at the appropriate position
|
||||
/// based on precedence rules. When the stack has both base and profile-v2
|
||||
/// user layers, this updates only the layer whose file matches
|
||||
/// `config_toml`.
|
||||
pub fn with_user_config(
|
||||
&self,
|
||||
config_toml: &AbsolutePathBuf,
|
||||
user_config: TomlValue,
|
||||
) -> std::io::Result<Self> {
|
||||
let profile = self.layers.iter().find_map(|layer| match &layer.name {
|
||||
ConfigLayerSource::User { file, profile } if file == config_toml => profile
|
||||
.as_deref()
|
||||
.and_then(|profile| profile.parse::<ProfileV2Name>().ok()),
|
||||
_ => None,
|
||||
});
|
||||
self.with_user_config_profile(config_toml, profile.as_ref(), user_config)
|
||||
}
|
||||
|
||||
pub fn with_user_config_profile(
|
||||
&self,
|
||||
config_toml: &AbsolutePathBuf,
|
||||
profile: Option<&ProfileV2Name>,
|
||||
user_config: TomlValue,
|
||||
) -> std::io::Result<Self> {
|
||||
let user_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: config_toml.clone(),
|
||||
profile: profile.map(ToString::to_string),
|
||||
},
|
||||
user_config,
|
||||
);
|
||||
validate_enabled_config_layers(std::slice::from_ref(&user_layer))?;
|
||||
|
||||
let mut layers = self.layers.clone();
|
||||
if let Some(index) = layers.iter().position(|layer| {
|
||||
matches!(
|
||||
&layer.name,
|
||||
ConfigLayerSource::User { file, .. } if file == config_toml
|
||||
)
|
||||
}) {
|
||||
layers.remove(index);
|
||||
}
|
||||
match layers
|
||||
.iter()
|
||||
.position(|layer| layer.name.precedence() > user_layer.name.precedence())
|
||||
{
|
||||
Some(index) => layers.insert(index, user_layer),
|
||||
None => layers.push(user_layer),
|
||||
}
|
||||
Ok(Self {
|
||||
layers,
|
||||
cloud_config_binding: self.cloud_config_binding.clone(),
|
||||
mcp_ema_cancellation: self.mcp_ema_cancellation.clone(),
|
||||
applied_config_server: self.applied_config_server.clone(),
|
||||
model_provider_requirements: self.model_provider_requirements.clone(),
|
||||
requirements: self.requirements.clone(),
|
||||
requirements_toml: self.requirements_toml.clone(),
|
||||
ignore_user_and_project_exec_policy_rules: self
|
||||
.ignore_user_and_project_exec_policy_rules,
|
||||
startup_warnings: self.startup_warnings.clone(),
|
||||
is_projectless: self.is_projectless,
|
||||
project_trust: self.project_trust.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds local session configuration while retaining independently owned runtime snapshots.
|
||||
pub fn with_session_config(mut self, config: TomlValue) -> std::io::Result<Self> {
|
||||
let index = self.layers.partition_point(|layer| {
|
||||
layer.name.precedence() <= ConfigLayerSource::SessionFlags.precedence()
|
||||
});
|
||||
self.layers.insert(
|
||||
index,
|
||||
ConfigLayerEntry::new(ConfigLayerSource::SessionFlags, config),
|
||||
);
|
||||
validate_enabled_config_layers(&self.layers)?;
|
||||
self.validate_project_mitm_profiles()?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
pub fn with_session_plugins(mut self, plugins: TomlValue) -> std::io::Result<Self> {
|
||||
let session_index = self.layers.iter().rposition(|layer| {
|
||||
layer.name == ConfigLayerSource::SessionFlags && !layer.is_disabled()
|
||||
});
|
||||
if let Some(session_index) = session_index {
|
||||
for (index, layer) in self.layers.iter_mut().enumerate() {
|
||||
if layer.name != ConfigLayerSource::SessionFlags || layer.is_disabled() {
|
||||
continue;
|
||||
}
|
||||
let mut config = layer.config.clone();
|
||||
let table = config.as_table_mut().ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"session config must be a table",
|
||||
)
|
||||
})?;
|
||||
if index == session_index {
|
||||
table.insert("plugins".to_owned(), plugins.clone());
|
||||
} else if table.remove("plugins").is_none() {
|
||||
continue;
|
||||
}
|
||||
*layer = ConfigLayerEntry::new(ConfigLayerSource::SessionFlags, config);
|
||||
}
|
||||
} else {
|
||||
return self.with_session_config(TomlValue::Table(
|
||||
[("plugins".to_owned(), plugins)].into_iter().collect(),
|
||||
));
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Returns a new stack with the user layer copied from `other`, preserving
|
||||
/// every non-user layer already present in this stack.
|
||||
pub fn with_user_layer_from(&self, other: &Self) -> Self {
|
||||
let user_layers = other
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|layer| matches!(layer.name, ConfigLayerSource::User { .. }))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let mut layers = self
|
||||
.layers
|
||||
.iter()
|
||||
.filter(|layer| !matches!(layer.name, ConfigLayerSource::User { .. }))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
for user_layer in user_layers {
|
||||
match layers
|
||||
.iter()
|
||||
.position(|layer| layer.name.precedence() > user_layer.name.precedence())
|
||||
{
|
||||
Some(index) => layers.insert(index, user_layer),
|
||||
None => layers.push(user_layer),
|
||||
}
|
||||
}
|
||||
Self {
|
||||
layers,
|
||||
cloud_config_binding: self.cloud_config_binding.clone(),
|
||||
mcp_ema_cancellation: self.mcp_ema_cancellation.clone(),
|
||||
applied_config_server: self.applied_config_server.clone(),
|
||||
model_provider_requirements: self.model_provider_requirements.clone(),
|
||||
requirements: self.requirements.clone(),
|
||||
requirements_toml: self.requirements_toml.clone(),
|
||||
ignore_user_and_project_exec_policy_rules: self
|
||||
.ignore_user_and_project_exec_policy_rules,
|
||||
startup_warnings: self.startup_warnings.clone(),
|
||||
is_projectless: self.is_projectless,
|
||||
project_trust: self.project_trust.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the merged config-layer view.
|
||||
///
|
||||
/// Required provider definitions replace local entries before deserialization.
|
||||
/// Selection and other requirements are applied when constructing the final config.
|
||||
pub fn effective_config(&self) -> TomlValue {
|
||||
let mut merged = TomlValue::Table(toml::map::Map::new());
|
||||
for layer in self.layers_low_to_high() {
|
||||
merge_toml_values(&mut merged, &layer.config);
|
||||
}
|
||||
if let Some(requirements) = &self.model_provider_requirements {
|
||||
crate::model_provider_requirements::apply(&mut merged, requirements);
|
||||
}
|
||||
merged
|
||||
}
|
||||
|
||||
/// Required provider selection used when building the effective configuration.
|
||||
pub fn required_model_provider(&self) -> Option<&str> {
|
||||
self.requirements_toml.model_provider.as_deref()
|
||||
}
|
||||
|
||||
/// Returns field origins for the merged config-layer view.
|
||||
///
|
||||
/// Requirement sources are tracked separately and are not included here.
|
||||
pub fn origins(&self) -> HashMap<String, ConfigLayerMetadata> {
|
||||
self.origins_with_path_filter(|_| true)
|
||||
}
|
||||
|
||||
/// Filters origins using their original TOML key segments before formatting
|
||||
/// them for the public API, where dots in quoted keys are ambiguous.
|
||||
pub fn origins_with_path_filter(
|
||||
&self,
|
||||
include: impl Fn(&[String]) -> bool,
|
||||
) -> HashMap<String, ConfigLayerMetadata> {
|
||||
let mut origins = HashMap::new();
|
||||
let mut path = Vec::new();
|
||||
let mut provider_paths = vec!["features.network_proxy.credentials.".to_string()];
|
||||
|
||||
for layer in self.layers_low_to_high() {
|
||||
let config = normalize_key_aliases(&layer.config);
|
||||
if let Some(profiles) = config.get("profiles").and_then(TomlValue::as_table) {
|
||||
provider_paths.extend(
|
||||
profiles
|
||||
.keys()
|
||||
.map(|name| format!("profiles.{name}.features.network_proxy.credentials.")),
|
||||
);
|
||||
}
|
||||
record_origins(
|
||||
&config,
|
||||
&layer.metadata(),
|
||||
&mut path,
|
||||
&mut origins,
|
||||
&include,
|
||||
);
|
||||
}
|
||||
|
||||
let is_credential_origin =
|
||||
|path: &str| provider_paths.iter().any(|prefix| path.starts_with(prefix));
|
||||
if origins.keys().any(|path| is_credential_origin(path))
|
||||
&& let Some(layer) = self.layers_low_to_high().next_back()
|
||||
{
|
||||
let effective = self.effective_config();
|
||||
let mut effective_origins = HashMap::new();
|
||||
record_origins(
|
||||
&effective,
|
||||
&layer.metadata(),
|
||||
&mut path,
|
||||
&mut effective_origins,
|
||||
&include,
|
||||
);
|
||||
origins.retain(|path, _| {
|
||||
!is_credential_origin(path) || effective_origins.contains_key(path)
|
||||
});
|
||||
}
|
||||
|
||||
origins
|
||||
}
|
||||
|
||||
/// Returns enabled config layers from lowest precedence to highest.
|
||||
///
|
||||
/// Requirement sources are tracked separately and are not included here.
|
||||
pub fn layers_low_to_high(&self) -> impl DoubleEndedIterator<Item = &ConfigLayerEntry> {
|
||||
self.all_layers_low_to_high()
|
||||
.filter(|layer| !layer.is_disabled())
|
||||
}
|
||||
|
||||
/// Returns enabled config layers from highest precedence to lowest.
|
||||
///
|
||||
/// Requirement sources are tracked separately and are not included here.
|
||||
pub fn layers_high_to_low(&self) -> impl DoubleEndedIterator<Item = &ConfigLayerEntry> {
|
||||
self.layers_low_to_high().rev()
|
||||
}
|
||||
|
||||
/// Returns all config layers, including disabled layers, from lowest
|
||||
/// precedence to highest.
|
||||
///
|
||||
/// Requirement sources are tracked separately and are not included here.
|
||||
pub fn all_layers_low_to_high(&self) -> impl DoubleEndedIterator<Item = &ConfigLayerEntry> {
|
||||
self.layers.iter()
|
||||
}
|
||||
|
||||
/// Returns all config layers, including disabled layers, from highest
|
||||
/// precedence to lowest.
|
||||
///
|
||||
/// Requirement sources are tracked separately and are not included here.
|
||||
pub fn all_layers_high_to_low(&self) -> impl DoubleEndedIterator<Item = &ConfigLayerEntry> {
|
||||
self.all_layers_low_to_high().rev()
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates before merging so mixed forms and malformed filter entries cannot be normalized away.
|
||||
pub(crate) fn validate_enabled_config_layers(layers: &[ConfigLayerEntry]) -> std::io::Result<()> {
|
||||
for layer in layers.iter().filter(|layer| !layer.is_disabled()) {
|
||||
validate_shell_environment_policy_filter_config(&layer.config).map_err(|error| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
format!(
|
||||
"invalid shell environment policy in {}: {error}",
|
||||
format_config_layer_source(&layer.name, CONFIG_TOML_FILE)
|
||||
),
|
||||
)
|
||||
})?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ensures precedence ordering of config layers is correct.
|
||||
fn verify_layer_ordering(layers: &[ConfigLayerEntry]) -> std::io::Result<()> {
|
||||
if !layers.iter().map(|layer| &layer.name).is_sorted() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"config layers are not in correct precedence order",
|
||||
));
|
||||
}
|
||||
|
||||
// The previous check ensured `layers` is sorted by precedence, so now we
|
||||
// further verify that project layers are ordered from root to cwd. Multiple
|
||||
// user layers are allowed so a profile override can layer on top of the base
|
||||
// user config.
|
||||
let mut previous_project_dot_codex_folder: Option<&AbsolutePathBuf> = None;
|
||||
for layer in layers {
|
||||
if let ConfigLayerSource::Project {
|
||||
dot_codex_folder: current_project_dot_codex_folder,
|
||||
} = &layer.name
|
||||
{
|
||||
if let Some(previous) = previous_project_dot_codex_folder {
|
||||
let Some(parent) = previous.as_path().parent() else {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"project layer has no parent directory",
|
||||
));
|
||||
};
|
||||
if previous == current_project_dot_codex_folder
|
||||
|| !current_project_dot_codex_folder
|
||||
.as_path()
|
||||
.ancestors()
|
||||
.any(|ancestor| ancestor == parent)
|
||||
{
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::InvalidData,
|
||||
"project layers are not ordered from root to cwd",
|
||||
));
|
||||
}
|
||||
}
|
||||
previous_project_dot_codex_folder = Some(current_project_dot_codex_folder);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "state_tests.rs"]
|
||||
mod tests;
|
||||
398
codex-rs/config/src/state_tests.rs
Normal file
398
codex-rs/config/src/state_tests.rs
Normal file
@@ -0,0 +1,398 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
fn test_user_config_path(temp_dir: &TempDir, file_name: &str) -> AbsolutePathBuf {
|
||||
AbsolutePathBuf::from_absolute_path(temp_dir.path().join(file_name))
|
||||
.expect("test user config path should be absolute")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origins_use_canonical_key_aliases() {
|
||||
let layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str(
|
||||
r#"
|
||||
[memories]
|
||||
no_memories_if_mcp_or_web_search = true
|
||||
"#,
|
||||
)
|
||||
.expect("config TOML should parse"),
|
||||
);
|
||||
let metadata = layer.metadata();
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("single layer stack should be valid");
|
||||
|
||||
let origins = stack.origins();
|
||||
|
||||
assert_eq!(
|
||||
origins.get("memories.disable_on_external_context"),
|
||||
Some(&metadata)
|
||||
);
|
||||
assert!(
|
||||
!origins.contains_key("memories.no_memories_if_mcp_or_web_search"),
|
||||
"legacy key should be canonicalized before origin recording"
|
||||
);
|
||||
}
|
||||
|
||||
/// Legacy feature toggles own the semantic enabled leaf after layered merging.
|
||||
#[test]
|
||||
fn origins_attribute_multi_agent_v2_enabled_to_overriding_boolean_layer() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let user_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: test_user_config_path(&temp_dir, "config.toml"),
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(
|
||||
"[features.multi_agent_v2]\nenabled = true\nsubagent_usage_hint_text = \"keep\"\n",
|
||||
)
|
||||
.expect("user config"),
|
||||
);
|
||||
let user_metadata = user_layer.metadata();
|
||||
let session_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str("[features]\nmulti_agent_v2 = false\n").expect("session config"),
|
||||
);
|
||||
let session_metadata = session_layer.metadata();
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![user_layer, session_layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("layer stack should be valid");
|
||||
|
||||
let origins = stack.origins();
|
||||
|
||||
assert_eq!(
|
||||
origins.get("features.multi_agent_v2.enabled"),
|
||||
Some(&session_metadata)
|
||||
);
|
||||
assert_eq!(
|
||||
origins.get("features.multi_agent_v2.subagent_usage_hint_text"),
|
||||
Some(&user_metadata)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origins_omit_displaced_credential_providers() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
for scope in ["", "profiles.work."] {
|
||||
let user = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: test_user_config_path(&temp_dir, "config.toml"),
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(&format!(
|
||||
"[{scope}features.network_proxy.credentials.user_provider]\nenv = ['VENDOR_TOKEN']\n",
|
||||
))
|
||||
.expect("user config"),
|
||||
);
|
||||
let session = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str(&format!(
|
||||
"[{scope}features.network_proxy.credentials.session_provider]\nenv = ['VENDOR_TOKEN']\n",
|
||||
))
|
||||
.expect("session config"),
|
||||
);
|
||||
let metadata = session.metadata();
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![user, session],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("valid layers");
|
||||
assert_eq!(
|
||||
stack.origins(),
|
||||
HashMap::from([(
|
||||
format!("{scope}features.network_proxy.credentials.session_provider.env.0"),
|
||||
metadata
|
||||
)])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabled_layers_validate_shell_environment_policy() {
|
||||
let layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["LEGACY_*"]
|
||||
|
||||
[shell_environment_policy.filters]
|
||||
"CANONICAL_*" = "include"
|
||||
"#,
|
||||
)
|
||||
.expect("session config"),
|
||||
);
|
||||
|
||||
let error = ConfigLayerStack::new(
|
||||
vec![layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect_err("enabled layers should be validated");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("cannot mix `filters` with legacy `exclude` or `include_only`")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_layers_do_not_validate_shell_environment_policy() {
|
||||
let layer = ConfigLayerEntry::new_disabled(
|
||||
ConfigLayerSource::Project {
|
||||
dot_codex_folder: AbsolutePathBuf::from_absolute_path("/untrusted/.codex")
|
||||
.expect("project path should be absolute"),
|
||||
},
|
||||
toml::from_str(
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["LEGACY_*"]
|
||||
|
||||
[shell_environment_policy.filters]
|
||||
"CANONICAL_*" = "include"
|
||||
"#,
|
||||
)
|
||||
.expect("project config"),
|
||||
"project is untrusted",
|
||||
);
|
||||
|
||||
ConfigLayerStack::new(
|
||||
vec![layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("disabled layers should not be validated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enabled_layers_only_validate_representation_sensitive_shell_policy_fields() {
|
||||
let cases = [
|
||||
r#"shell_environment_policy = 17"#,
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
inherit = "invalid"
|
||||
set = ["invalid"]
|
||||
"#,
|
||||
];
|
||||
|
||||
for contents in cases {
|
||||
let layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str(contents).expect("session config"),
|
||||
);
|
||||
|
||||
ConfigLayerStack::new(
|
||||
vec![layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("unrelated shell policy fields should retain normal overlay semantics");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_user_config_rejects_malformed_shell_policy_filter_fields() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let config_file = test_user_config_path(&temp_dir, "config.toml");
|
||||
let cases = [
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["SECRET_*", 17]
|
||||
"#,
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"SECRET_*" = "keep"
|
||||
"#,
|
||||
r#"
|
||||
[shell_environment_policy]
|
||||
exclude = ["SECRET_*"]
|
||||
|
||||
[shell_environment_policy.filters]
|
||||
"PATH" = "include"
|
||||
"#,
|
||||
r#"
|
||||
[shell_environment_policy.filters]
|
||||
"SECRET_*" = "exclude"
|
||||
"secret_*" = "include"
|
||||
"#,
|
||||
];
|
||||
|
||||
for contents in cases {
|
||||
let error = ConfigLayerStack::default()
|
||||
.with_user_config(&config_file, toml::from_str(contents).expect("user config"))
|
||||
.expect_err("malformed shell policy filter fields should be rejected");
|
||||
|
||||
assert_eq!(error.kind(), std::io::ErrorKind::InvalidData);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_user_layer_is_highest_precedence_user_layer() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let base_file = test_user_config_path(&temp_dir, "config.toml");
|
||||
let profile_file = test_user_config_path(&temp_dir, "work.config.toml");
|
||||
let base_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: base_file,
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(
|
||||
r#"
|
||||
model = "base"
|
||||
approval_policy = "on-request"
|
||||
"#,
|
||||
)
|
||||
.expect("base config"),
|
||||
);
|
||||
let profile_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: profile_file.clone(),
|
||||
profile: Some("work".to_string()),
|
||||
},
|
||||
toml::from_str(r#"model = "profile""#).expect("profile config"),
|
||||
);
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![base_layer, profile_layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("multiple user layers should be valid");
|
||||
|
||||
assert_eq!(stack.get_user_config_file(), Some(&profile_file));
|
||||
assert_eq!(
|
||||
stack
|
||||
.effective_user_config()
|
||||
.expect("merged user config")
|
||||
.get("model")
|
||||
.and_then(toml::Value::as_str),
|
||||
Some("profile")
|
||||
);
|
||||
assert_eq!(
|
||||
stack
|
||||
.effective_user_config()
|
||||
.expect("merged user config")
|
||||
.get("approval_policy")
|
||||
.and_then(toml::Value::as_str),
|
||||
Some("on-request")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_iterators_preserve_precedence_and_disabled_layers() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let user_source = ConfigLayerSource::User {
|
||||
file: test_user_config_path(&temp_dir, "config.toml"),
|
||||
profile: None,
|
||||
};
|
||||
let project_source = ConfigLayerSource::Project {
|
||||
dot_codex_folder: test_user_config_path(&temp_dir, ".codex"),
|
||||
};
|
||||
let session_source = ConfigLayerSource::SessionFlags;
|
||||
let empty_config = TomlValue::Table(toml::map::Map::new());
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![
|
||||
ConfigLayerEntry::new(user_source.clone(), empty_config.clone()),
|
||||
ConfigLayerEntry::new_disabled(
|
||||
project_source.clone(),
|
||||
empty_config.clone(),
|
||||
"project is untrusted",
|
||||
),
|
||||
ConfigLayerEntry::new(session_source.clone(), empty_config),
|
||||
],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("layer stack should be valid");
|
||||
|
||||
assert_eq!(
|
||||
stack
|
||||
.layers_low_to_high()
|
||||
.map(|layer| &layer.name)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&user_source, &session_source]
|
||||
);
|
||||
assert_eq!(
|
||||
stack
|
||||
.layers_high_to_low()
|
||||
.map(|layer| &layer.name)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&session_source, &user_source]
|
||||
);
|
||||
assert_eq!(
|
||||
stack
|
||||
.all_layers_low_to_high()
|
||||
.map(|layer| &layer.name)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&user_source, &project_source, &session_source]
|
||||
);
|
||||
assert_eq!(
|
||||
stack
|
||||
.all_layers_high_to_low()
|
||||
.map(|layer| &layer.name)
|
||||
.collect::<Vec<_>>(),
|
||||
vec![&session_source, &project_source, &user_source]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn with_user_config_updates_matching_user_layer_without_replacing_active_profile() {
|
||||
let temp_dir = TempDir::new().expect("tempdir");
|
||||
let base_file = test_user_config_path(&temp_dir, "config.toml");
|
||||
let profile_file = test_user_config_path(&temp_dir, "work.config.toml");
|
||||
let base_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: base_file.clone(),
|
||||
profile: None,
|
||||
},
|
||||
toml::from_str(r#"model = "base""#).expect("base config"),
|
||||
);
|
||||
let profile_layer = ConfigLayerEntry::new(
|
||||
ConfigLayerSource::User {
|
||||
file: profile_file.clone(),
|
||||
profile: Some("work".to_string()),
|
||||
},
|
||||
toml::from_str(r#"approval_policy = "on-request""#).expect("profile config"),
|
||||
);
|
||||
let stack = ConfigLayerStack::new(
|
||||
vec![base_layer, profile_layer],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.expect("multiple user layers should be valid");
|
||||
|
||||
let updated = stack
|
||||
.with_user_config(
|
||||
&base_file,
|
||||
toml::from_str(r#"model = "updated-base""#).expect("updated base config"),
|
||||
)
|
||||
.expect("updated user layer should be valid");
|
||||
|
||||
assert_eq!(updated.get_user_config_file(), Some(&profile_file));
|
||||
assert_eq!(
|
||||
updated
|
||||
.effective_user_config()
|
||||
.expect("merged user config")
|
||||
.get("model")
|
||||
.and_then(toml::Value::as_str),
|
||||
Some("updated-base")
|
||||
);
|
||||
assert_eq!(
|
||||
updated
|
||||
.effective_user_config()
|
||||
.expect("merged user config")
|
||||
.get("approval_policy")
|
||||
.and_then(toml::Value::as_str),
|
||||
Some("on-request")
|
||||
);
|
||||
}
|
||||
362
codex-rs/config/src/strict_config.rs
Normal file
362
codex-rs/config/src/strict_config.rs
Normal file
@@ -0,0 +1,362 @@
|
||||
//! Strict config validation built on top of serde's ignored-field tracking.
|
||||
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::ConfigLayerStack;
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::NetworkRequirementsToml;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::diagnostics::ConfigDiagnosticSource;
|
||||
use crate::diagnostics::ConfigError;
|
||||
use crate::diagnostics::config_error_from_toml_for_source;
|
||||
use crate::diagnostics::default_range;
|
||||
use crate::diagnostics::span_for_config_path;
|
||||
use crate::diagnostics::span_for_toml_key_path;
|
||||
use crate::diagnostics::text_range_from_span;
|
||||
use crate::format_config_layer_source;
|
||||
use crate::requirements_layers::strip_cloud_auth_requirements;
|
||||
use crate::types::Tui;
|
||||
use codex_features::is_known_feature_key;
|
||||
use codex_utils_absolute_path::AbsolutePathBufGuard;
|
||||
use serde::de::DeserializeOwned;
|
||||
use std::any::TypeId;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fmt::Write;
|
||||
use std::path::Path;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
pub fn config_error_from_ignored_toml_fields<T: DeserializeOwned + 'static>(
|
||||
path: impl AsRef<Path>,
|
||||
contents: &str,
|
||||
) -> Option<ConfigError> {
|
||||
let source = ConfigDiagnosticSource::Path(path.as_ref());
|
||||
match toml::from_str::<TomlValue>(contents) {
|
||||
Ok(value) => {
|
||||
config_error_from_ignored_toml_value_fields_for_source::<T>(source, contents, value)
|
||||
}
|
||||
Err(err) => Some(config_error_from_toml_for_source(source, contents, err)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn config_error_from_ignored_toml_value_fields<T: DeserializeOwned + 'static>(
|
||||
path: impl AsRef<Path>,
|
||||
contents: &str,
|
||||
value: TomlValue,
|
||||
) -> Option<ConfigError> {
|
||||
config_error_from_ignored_toml_value_fields_for_source::<T>(
|
||||
ConfigDiagnosticSource::Path(path.as_ref()),
|
||||
contents,
|
||||
value,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn config_error_from_ignored_toml_value_fields_for_source_name<
|
||||
T: DeserializeOwned + 'static,
|
||||
>(
|
||||
source_name: &str,
|
||||
contents: &str,
|
||||
value: TomlValue,
|
||||
) -> Option<ConfigError> {
|
||||
config_error_from_ignored_toml_value_fields_for_source::<T>(
|
||||
ConfigDiagnosticSource::DisplayName(source_name),
|
||||
contents,
|
||||
value,
|
||||
)
|
||||
}
|
||||
|
||||
fn config_error_from_ignored_toml_value_fields_for_source<T: DeserializeOwned + 'static>(
|
||||
source: ConfigDiagnosticSource<'_>,
|
||||
contents: &str,
|
||||
value: TomlValue,
|
||||
) -> Option<ConfigError> {
|
||||
let unknown_feature_paths = unknown_feature_toml_value_path(&value);
|
||||
let unknown_tui_paths = if TypeId::of::<T>() == TypeId::of::<ConfigToml>() {
|
||||
unknown_tui_toml_value_path(&value)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
match ignored_toml_value_fields::<T>(value) {
|
||||
Ok(ignored_paths) => unknown_field_error_from_paths(source, contents, ignored_paths)
|
||||
.or_else(|| unknown_field_error_from_paths(source, contents, unknown_tui_paths))
|
||||
.or_else(|| unknown_field_error_from_paths(source, contents, unknown_feature_paths)),
|
||||
Err(err) => {
|
||||
let path_hint = err.path().clone();
|
||||
let toml_err = err.into_inner();
|
||||
let range = span_for_config_path(contents, &path_hint)
|
||||
.or_else(|| toml_err.span())
|
||||
.map(|span| text_range_from_span(contents, span))
|
||||
.unwrap_or_else(default_range);
|
||||
Some(ConfigError::new(
|
||||
source.to_path_buf(),
|
||||
range,
|
||||
toml_err.message(),
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn unknown_tui_toml_value_path(value: &TomlValue) -> Vec<Vec<String>> {
|
||||
// `serde_ignored` cannot observe keys consumed by the flattened notification settings.
|
||||
// Round-trip the TUI config so accepted input keys stay derived from `Tui` itself.
|
||||
let Some(tui_value) = value.as_table().and_then(|root| root.get("tui")) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(configured_tui) = tui_value.as_table() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(tui) = tui_value.clone().try_into::<Tui>() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Ok(TomlValue::Table(serialized_tui)) = TomlValue::try_from(tui) else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
configured_tui
|
||||
.keys()
|
||||
.filter(|key| !serialized_tui.contains_key(*key))
|
||||
.map(|key| vec!["tui".to_string(), key.clone()])
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn ignored_toml_value_fields<T: DeserializeOwned>(
|
||||
value: TomlValue,
|
||||
) -> Result<Vec<Vec<String>>, serde_path_to_error::Error<toml::de::Error>> {
|
||||
let mut ignored_paths = Vec::new();
|
||||
let mut record_path = |path: serde_ignored::Path<'_>| {
|
||||
let segments = ignored_path_segments(&path);
|
||||
if !segments.is_empty() {
|
||||
ignored_paths.push(segments);
|
||||
}
|
||||
};
|
||||
let deserializer = serde_ignored::Deserializer::new(value, &mut record_path);
|
||||
serde_path_to_error::deserialize::<_, T>(deserializer)?;
|
||||
Ok(ignored_paths)
|
||||
}
|
||||
|
||||
pub(crate) fn unknown_feature_toml_value_field(value: &TomlValue) -> Option<String> {
|
||||
unknown_feature_toml_value_path(value)
|
||||
.into_iter()
|
||||
.next()
|
||||
.map(|path_segments| path_segments.join("."))
|
||||
}
|
||||
|
||||
fn unknown_field_error_from_paths(
|
||||
source: ConfigDiagnosticSource<'_>,
|
||||
contents: &str,
|
||||
ignored_paths: Vec<Vec<String>>,
|
||||
) -> Option<ConfigError> {
|
||||
let path_segments = ignored_paths.into_iter().next()?;
|
||||
let ignored_path = path_segments.join(".");
|
||||
let range = span_for_toml_key_path(contents, &path_segments)
|
||||
.map(|span| text_range_from_span(contents, span))
|
||||
.unwrap_or_else(default_range);
|
||||
Some(ConfigError::new(
|
||||
source.to_path_buf(),
|
||||
range,
|
||||
format!("unknown configuration field `{ignored_path}`"),
|
||||
))
|
||||
}
|
||||
|
||||
fn unknown_feature_toml_value_path(value: &TomlValue) -> Vec<Vec<String>> {
|
||||
let Some(root) = value.as_table() else {
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut paths = Vec::new();
|
||||
push_unknown_feature_paths(&mut paths, &["features"], root.get("features"));
|
||||
|
||||
if let Some(profiles) = root.get("profiles").and_then(TomlValue::as_table) {
|
||||
for (profile_name, profile) in profiles {
|
||||
let prefix = ["profiles", profile_name.as_str(), "features"];
|
||||
let features = profile
|
||||
.as_table()
|
||||
.and_then(|profile| profile.get("features"));
|
||||
push_unknown_feature_paths(&mut paths, &prefix, features);
|
||||
}
|
||||
}
|
||||
|
||||
paths
|
||||
}
|
||||
|
||||
fn push_unknown_feature_paths(
|
||||
paths: &mut Vec<Vec<String>>,
|
||||
prefix: &[&str],
|
||||
features: Option<&TomlValue>,
|
||||
) {
|
||||
let Some(features) = features.and_then(TomlValue::as_table) else {
|
||||
return;
|
||||
};
|
||||
|
||||
for feature_key in features
|
||||
.keys()
|
||||
.map(String::as_str)
|
||||
.filter(|key| !is_known_feature_key(key))
|
||||
{
|
||||
let mut path = prefix
|
||||
.iter()
|
||||
.map(|segment| (*segment).to_string())
|
||||
.collect::<Vec<_>>();
|
||||
path.push(feature_key.to_string());
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
fn ignored_path_segments(path: &serde_ignored::Path<'_>) -> Vec<String> {
|
||||
let mut segments = Vec::new();
|
||||
push_ignored_path_segments(path, &mut segments);
|
||||
segments
|
||||
}
|
||||
|
||||
fn push_ignored_path_segments(path: &serde_ignored::Path<'_>, segments: &mut Vec<String>) {
|
||||
match path {
|
||||
serde_ignored::Path::Root => {}
|
||||
serde_ignored::Path::Seq { parent, index } => {
|
||||
push_ignored_path_segments(parent, segments);
|
||||
segments.push(index.to_string());
|
||||
}
|
||||
serde_ignored::Path::Map { parent, key } => {
|
||||
push_ignored_path_segments(parent, segments);
|
||||
segments.push(key.clone());
|
||||
}
|
||||
serde_ignored::Path::Some { parent }
|
||||
| serde_ignored::Path::NewtypeStruct { parent }
|
||||
| serde_ignored::Path::NewtypeVariant { parent } => {
|
||||
push_ignored_path_segments(parent, segments);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn ignored_config_warning(
|
||||
config: &ConfigLayerStack,
|
||||
requirements: &[RequirementsLayerEntry],
|
||||
) -> Option<String> {
|
||||
let mut fields = BTreeSet::new();
|
||||
// Validate the merged config so incomplete layer fragments (e.g. a provider
|
||||
// override) do not hide diagnostics.
|
||||
let effective = config.effective_config();
|
||||
let unknown_features = unknown_feature_toml_value_path(&effective);
|
||||
for path in ignored_toml_value_fields::<ConfigToml>(effective)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.chain(unknown_features)
|
||||
{
|
||||
// Origins only track leaf values; an ignored field can be a whole table.
|
||||
for layer in config.layers_high_to_low().filter(|layer| {
|
||||
path.iter()
|
||||
.try_fold(&layer.config, |value, key| match value {
|
||||
toml::Value::Array(items) => {
|
||||
key.parse::<usize>().ok().and_then(|i| items.get(i))
|
||||
}
|
||||
_ => value.get(key),
|
||||
})
|
||||
.is_some()
|
||||
}) {
|
||||
fields.insert((
|
||||
format_config_layer_source(&layer.name, CONFIG_TOML_FILE),
|
||||
path.clone(),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Requirements use a different schema and lose unknown fields during
|
||||
// composition. Inspect their original layers, with the same path bases.
|
||||
// Normal loading remains responsible for reporting parse/type errors.
|
||||
for layer in requirements {
|
||||
let Ok((source, mut value, base_dir)) = layer.clone().into_raw_parts() else {
|
||||
continue;
|
||||
};
|
||||
let _guard = base_dir
|
||||
.as_ref()
|
||||
.map(|base_dir| AbsolutePathBufGuard::new(base_dir.as_path()));
|
||||
strip_cloud_auth_requirements(&source, &mut value);
|
||||
// The flattened permissions deserializer consumes unknown network keys.
|
||||
// Inspect that table separately to retain the usual typo diagnostics.
|
||||
let permissions_network = value
|
||||
.get("permissions")
|
||||
.and_then(|permissions| permissions.get("network"))
|
||||
.cloned();
|
||||
fields.extend(
|
||||
ignored_toml_value_fields::<ConfigRequirementsToml>(value)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|path| (format!("requirements ({source})"), path)),
|
||||
);
|
||||
if let Some(network) = permissions_network {
|
||||
fields.extend(
|
||||
ignored_toml_value_fields::<NetworkRequirementsToml>(network)
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.map(|path| {
|
||||
let mut full_path = vec!["permissions".to_string(), "network".to_string()];
|
||||
full_path.extend(path);
|
||||
(format!("requirements ({source})"), full_path)
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if fields.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let count = fields.len();
|
||||
let setting = if count == 1 { "setting" } else { "settings" };
|
||||
let mut warning = format!(
|
||||
"Codex is ignoring {count} unrecognized configuration {setting}. Check for typos or deprecated settings."
|
||||
);
|
||||
for (source, path) in fields.iter().take(3) {
|
||||
let source = bounded_label(source);
|
||||
let key = bounded_label(&path.join("."));
|
||||
let hint = match path
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.collect::<Vec<_>>()
|
||||
.as_slice()
|
||||
{
|
||||
["auto_review", "experimental_denial_reconsideration_prompt"] => {
|
||||
" Remove auto_review.experimental_denial_reconsideration_prompt from config.toml; Guardian retries replay the original request without a reconsideration prompt."
|
||||
}
|
||||
["windows", "sandbox_private_desktop"] => {
|
||||
" Remove windows.sandbox_private_desktop; legacy Windows sandboxes always use a private desktop."
|
||||
}
|
||||
["network_proxy"] => {
|
||||
" Use [features.network_proxy] or [permissions.<name>.network] for settings in config.toml, or [network_proxy], [permissions.network], or [experimental_network] for enforced policy in requirements.toml."
|
||||
}
|
||||
["allowed_permissions"] => {
|
||||
" Use [allowed_permission_profiles] and default_permissions; the old allowlist is ignored even when both forms are present."
|
||||
}
|
||||
["include_view_image_tool"]
|
||||
| ["features", "include_view_image_tool"]
|
||||
| ["profiles", _, "include_view_image_tool"]
|
||||
| ["profiles", _, "features", "include_view_image_tool"] => {
|
||||
" Use [features].view_image to configure the image tool."
|
||||
}
|
||||
_ => "",
|
||||
};
|
||||
let _ = write!(warning, "\n {source}: `{key}` is ignored.{hint}");
|
||||
}
|
||||
if fields.len() > 3 {
|
||||
let remaining = fields.len() - 3;
|
||||
let _ = write!(warning, "\n ... and {remaining} more ignored settings.");
|
||||
}
|
||||
Some(warning)
|
||||
}
|
||||
|
||||
fn bounded_label(value: &str) -> String {
|
||||
let mut label = String::new();
|
||||
for character in value.chars() {
|
||||
if label.len() >= 200 {
|
||||
label.push('…');
|
||||
break;
|
||||
}
|
||||
if character.is_control() {
|
||||
label.extend(character.escape_default());
|
||||
} else {
|
||||
label.push(character);
|
||||
}
|
||||
}
|
||||
label
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "strict_config_tests.rs"]
|
||||
mod tests;
|
||||
328
codex-rs/config/src/strict_config_tests.rs
Normal file
328
codex-rs/config/src/strict_config_tests.rs
Normal file
@@ -0,0 +1,328 @@
|
||||
use super::*;
|
||||
use crate::ConfigLayerEntry;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::config_toml::ConfigToml;
|
||||
use crate::diagnostics::TextPosition;
|
||||
use crate::diagnostics::TextRange;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn ignored_toml_field_errors_accept_non_file_source_names() {
|
||||
let source_name = "com.openai.codex:config_toml_base64";
|
||||
let contents = r#"
|
||||
model = "gpt-5"
|
||||
unknown_key = true"#;
|
||||
|
||||
let value = toml::from_str::<TomlValue>(contents).expect("valid TOML");
|
||||
let error = config_error_from_ignored_toml_value_fields_for_source_name::<ConfigToml>(
|
||||
source_name,
|
||||
contents,
|
||||
value,
|
||||
)
|
||||
.expect("unknown field error");
|
||||
|
||||
assert_eq!(
|
||||
error,
|
||||
ConfigError::new(
|
||||
PathBuf::from(source_name),
|
||||
TextRange {
|
||||
start: TextPosition { line: 3, column: 1 },
|
||||
end: TextPosition {
|
||||
line: 3,
|
||||
column: 11,
|
||||
},
|
||||
},
|
||||
"unknown configuration field `unknown_key`",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_errors_take_precedence_over_ignored_fields() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = r#"
|
||||
model_context_window = "wide"
|
||||
unknown_key = true"#;
|
||||
|
||||
let error =
|
||||
config_error_from_ignored_toml_fields::<ConfigToml>(path, contents).expect("type error");
|
||||
|
||||
assert_eq!(
|
||||
error,
|
||||
ConfigError::new(
|
||||
path.to_path_buf(),
|
||||
TextRange {
|
||||
start: TextPosition {
|
||||
line: 2,
|
||||
column: 24,
|
||||
},
|
||||
end: TextPosition {
|
||||
line: 2,
|
||||
column: 29,
|
||||
},
|
||||
},
|
||||
"invalid type: string \"wide\", expected i64",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_rejects_unknown_feature_key() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = r#"
|
||||
[features]
|
||||
foo = true"#;
|
||||
|
||||
let error = config_error_from_ignored_toml_fields::<ConfigToml>(path, contents)
|
||||
.expect("unknown feature error");
|
||||
|
||||
assert_eq!(
|
||||
error,
|
||||
ConfigError::new(
|
||||
path.to_path_buf(),
|
||||
TextRange {
|
||||
start: TextPosition { line: 3, column: 1 },
|
||||
end: TextPosition { line: 3, column: 3 },
|
||||
},
|
||||
"unknown configuration field `features.foo`",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_rejects_unknown_tui_key() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = r#"
|
||||
[tui]
|
||||
bogus_key_xyz = 1"#;
|
||||
|
||||
let error = config_error_from_ignored_toml_fields::<ConfigToml>(path, contents)
|
||||
.expect("unknown TUI key error");
|
||||
|
||||
assert_eq!(
|
||||
error,
|
||||
ConfigError::new(
|
||||
path.to_path_buf(),
|
||||
TextRange {
|
||||
start: TextPosition { line: 3, column: 1 },
|
||||
end: TextPosition {
|
||||
line: 3,
|
||||
column: 13,
|
||||
},
|
||||
},
|
||||
"unknown configuration field `tui.bogus_key_xyz`",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_accepts_tui_notification_settings() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
|
||||
for contents in [
|
||||
"[tui]\nnotifications = false\n",
|
||||
"[tui]\nnotification_method = \"bel\"\n",
|
||||
"[tui]\nnotification_condition = \"always\"\n",
|
||||
] {
|
||||
assert_eq!(
|
||||
config_error_from_ignored_toml_fields::<ConfigToml>(path, contents),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generic_validation_does_not_apply_config_toml_tui_fields() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = "[tui]\nplugin_key = 1\n";
|
||||
|
||||
assert_eq!(
|
||||
config_error_from_ignored_toml_fields::<BTreeMap<String, BTreeMap<String, i32>>>(
|
||||
path, contents,
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapped_config_toml_still_rejects_unknown_feature_key() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = "[features]\nfoo = true\n";
|
||||
|
||||
let error = config_error_from_ignored_toml_fields::<Box<ConfigToml>>(path, contents)
|
||||
.expect("unknown feature error");
|
||||
|
||||
assert_eq!(
|
||||
error,
|
||||
ConfigError::new(
|
||||
path.to_path_buf(),
|
||||
TextRange {
|
||||
start: TextPosition { line: 2, column: 1 },
|
||||
end: TextPosition { line: 2, column: 3 },
|
||||
},
|
||||
"unknown configuration field `features.foo`",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_accepts_tool_registry_config() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
|
||||
for contents in [
|
||||
"[features.tool_registry]\nerror_on_tool_collisions = true\n",
|
||||
"[profiles.work.features.tool_registry]\nerror_on_tool_collisions = true\n",
|
||||
"[features.tool_registry]\nturn_metadata_includes_tool_info = true\n",
|
||||
"[profiles.work.features.tool_registry]\nturn_metadata_includes_tool_info = true\n",
|
||||
] {
|
||||
assert_eq!(
|
||||
config_error_from_ignored_toml_fields::<ConfigToml>(path, contents),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
assert!(
|
||||
config_error_from_ignored_toml_fields::<ConfigToml>(
|
||||
path,
|
||||
"[features.tool_registry]\nunknown = true\n",
|
||||
)
|
||||
.is_some()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_rejects_unknown_profile_feature_key() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = r#"
|
||||
[profiles.work.features]
|
||||
foo = true"#;
|
||||
|
||||
let error = config_error_from_ignored_toml_fields::<ConfigToml>(path, contents)
|
||||
.expect("unknown feature error");
|
||||
|
||||
assert_eq!(
|
||||
error,
|
||||
ConfigError::new(
|
||||
path.to_path_buf(),
|
||||
TextRange {
|
||||
start: TextPosition { line: 3, column: 1 },
|
||||
end: TextPosition { line: 3, column: 3 },
|
||||
},
|
||||
"unknown configuration field `profiles.work.features.foo`",
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_config_accepts_opaque_desktop_keys() {
|
||||
let path = Path::new("/tmp/config.toml");
|
||||
let contents = r#"
|
||||
[desktop]
|
||||
appearanceTheme = "dark"
|
||||
|
||||
[desktop.workspace]
|
||||
collapsed = true"#;
|
||||
|
||||
let error = config_error_from_ignored_toml_fields::<ConfigToml>(path, contents);
|
||||
|
||||
assert_eq!(error, None);
|
||||
}
|
||||
|
||||
fn layer(source: ConfigLayerSource, contents: &str) -> ConfigLayerEntry {
|
||||
ConfigLayerEntry::new(source, toml::from_str(contents).unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checks_merged_config_and_ignores_disabled_layers() {
|
||||
let layers = vec![
|
||||
layer(
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "cfg".into(),
|
||||
name: "Defaults".into(),
|
||||
},
|
||||
r#"
|
||||
[model_providers.custom]
|
||||
name = "Custom"
|
||||
wire_api = "responses"
|
||||
unknown_timeout = 1
|
||||
[model_providers.custom.http_headers]
|
||||
custom_header = "accepted"
|
||||
"#,
|
||||
),
|
||||
ConfigLayerEntry::new_disabled(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::from_str("disabled_unknown = true").unwrap(),
|
||||
"not trusted",
|
||||
),
|
||||
layer(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
r#"
|
||||
[model_providers.custom]
|
||||
unknown_timeout = 42
|
||||
[profiles.work.features]
|
||||
include_view_image_tool = false
|
||||
"#,
|
||||
),
|
||||
];
|
||||
let config = ConfigLayerStack::new(
|
||||
layers,
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ignored_config_warning(&config, &[]).unwrap(),
|
||||
"Codex is ignoring 3 unrecognized configuration settings. Check for typos or deprecated settings.\n enterprise-managed (Defaults, cfg): `model_providers.custom.unknown_timeout` is ignored.\n session-flags: `model_providers.custom.unknown_timeout` is ignored.\n session-flags: `profiles.work.features.include_view_image_tool` is ignored. Use [features].view_image to configure the image tool."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn removed_private_desktop_setting_has_migration_hint() {
|
||||
let config = ConfigLayerStack::new(
|
||||
vec![layer(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
"[windows]\nsandbox_private_desktop = false",
|
||||
)],
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ignored_config_warning(&config, &[]).unwrap(),
|
||||
"Codex is ignoring 1 unrecognized configuration setting. Check for typos or deprecated settings.\n session-flags: `windows.sandbox_private_desktop` is ignored. Remove windows.sandbox_private_desktop; legacy Windows sandboxes always use a private desktop."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_network_unknown_fields_are_reported_for_each_spelling() {
|
||||
let config = ConfigLayerStack::new(
|
||||
Vec::new(),
|
||||
ConfigRequirements::default(),
|
||||
ConfigRequirementsToml::default(),
|
||||
)
|
||||
.unwrap();
|
||||
for table in [
|
||||
"network_proxy",
|
||||
"experimental_network",
|
||||
"permissions.network",
|
||||
] {
|
||||
let requirements = RequirementsLayerEntry::from_toml(
|
||||
crate::RequirementSource::Unknown,
|
||||
format!(
|
||||
"[{table}]\nenabld = true\n[{table}.domains]\n'example.com' = 'allow'\n\
|
||||
[[{table}.header_injections]]\nhost = 'example.com'\nmethods = ['GET']\n\
|
||||
path_prefixes = ['/']\nheaders = {{}}\nunknown = true\n"
|
||||
),
|
||||
);
|
||||
assert_eq!(
|
||||
ignored_config_warning(&config, &[requirements]),
|
||||
Some(format!(
|
||||
"Codex is ignoring 2 unrecognized configuration settings. Check for typos or deprecated settings.\n requirements (<unspecified>): `{table}.enabld` is ignored.\n requirements (<unspecified>): `{table}.header_injections.0.unknown` is ignored."
|
||||
)),
|
||||
"{table}"
|
||||
);
|
||||
}
|
||||
}
|
||||
80
codex-rs/config/src/test_support.rs
Normal file
80
codex-rs/config/src/test_support.rs
Normal file
@@ -0,0 +1,80 @@
|
||||
//! Test-only helpers exposed for cross-crate integration tests.
|
||||
//!
|
||||
//! Production code should not depend on this module.
|
||||
|
||||
use crate::CloudConfigBundle;
|
||||
use crate::CloudConfigBundleLoader;
|
||||
use crate::CloudConfigFragment;
|
||||
use crate::CloudRequirementsFragment;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CloudConfigBundleFixture {
|
||||
bundle: CloudConfigBundle,
|
||||
}
|
||||
|
||||
impl CloudConfigBundleFixture {
|
||||
pub fn enterprise_requirement(contents: impl Into<String>) -> Self {
|
||||
Self::default().add_enterprise_requirement(contents)
|
||||
}
|
||||
|
||||
pub fn enterprise_config(contents: impl Into<String>) -> Self {
|
||||
Self::default().add_enterprise_config(contents)
|
||||
}
|
||||
|
||||
pub fn loader_with_enterprise_requirement(
|
||||
contents: impl Into<String>,
|
||||
) -> CloudConfigBundleLoader {
|
||||
Self::enterprise_requirement(contents).into_loader()
|
||||
}
|
||||
|
||||
pub fn loader_with_enterprise_config(contents: impl Into<String>) -> CloudConfigBundleLoader {
|
||||
Self::enterprise_config(contents).into_loader()
|
||||
}
|
||||
|
||||
pub fn add_enterprise_requirement(mut self, contents: impl Into<String>) -> Self {
|
||||
let index = self.bundle.requirements_toml.enterprise_managed.len() + 1;
|
||||
self.bundle
|
||||
.requirements_toml
|
||||
.enterprise_managed
|
||||
.push(CloudRequirementsFragment {
|
||||
id: format!("req_{index}"),
|
||||
name: if index == 1 {
|
||||
"Base requirements".to_string()
|
||||
} else {
|
||||
format!("Requirements {index}")
|
||||
},
|
||||
contents: contents.into(),
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn add_enterprise_config(mut self, contents: impl Into<String>) -> Self {
|
||||
let index = self.bundle.config_toml.enterprise_managed.len() + 1;
|
||||
self.bundle
|
||||
.config_toml
|
||||
.enterprise_managed
|
||||
.push(CloudConfigFragment {
|
||||
id: format!("cfg_{index}"),
|
||||
name: if index == 1 {
|
||||
"Base config".to_string()
|
||||
} else {
|
||||
format!("Config {index}")
|
||||
},
|
||||
contents: contents.into(),
|
||||
});
|
||||
self
|
||||
}
|
||||
|
||||
pub fn into_bundle(self) -> CloudConfigBundle {
|
||||
self.bundle
|
||||
}
|
||||
|
||||
pub fn into_loader(self) -> CloudConfigBundleLoader {
|
||||
let bundle = self.into_bundle();
|
||||
CloudConfigBundleLoader::new(async move { Ok(Some(bundle)) })
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "test_support_tests.rs"]
|
||||
mod tests;
|
||||
25
codex-rs/config/src/test_support_tests.rs
Normal file
25
codex-rs/config/src/test_support_tests.rs
Normal file
@@ -0,0 +1,25 @@
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn adds_enterprise_requirements_in_order() {
|
||||
let bundle = CloudConfigBundleFixture::enterprise_requirement("first")
|
||||
.add_enterprise_requirement("second")
|
||||
.into_bundle();
|
||||
|
||||
assert_eq!(
|
||||
bundle.requirements_toml.enterprise_managed,
|
||||
vec![
|
||||
CloudRequirementsFragment {
|
||||
id: "req_1".to_string(),
|
||||
name: "Base requirements".to_string(),
|
||||
contents: "first".to_string(),
|
||||
},
|
||||
CloudRequirementsFragment {
|
||||
id: "req_2".to_string(),
|
||||
name: "Requirements 2".to_string(),
|
||||
contents: "second".to_string(),
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
326
codex-rs/config/src/thread_config.rs
Normal file
326
codex-rs/config/src/thread_config.rs
Normal file
@@ -0,0 +1,326 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
|
||||
use crate::ConfigLayerSource;
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use thiserror::Error;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
use crate::ConfigLayerEntry;
|
||||
|
||||
mod remote;
|
||||
|
||||
pub use remote::RemoteThreadConfigLoader;
|
||||
|
||||
/// Context available to implementations when loading thread-scoped config.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct ThreadConfigContext {
|
||||
pub thread_id: Option<String>,
|
||||
pub cwd: Option<AbsolutePathBuf>,
|
||||
}
|
||||
|
||||
/// Config values owned by the service that starts or manages the session.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SessionThreadConfig {
|
||||
pub model_provider: Option<String>,
|
||||
pub model_providers: HashMap<String, ModelProviderInfo>,
|
||||
pub features: BTreeMap<String, bool>,
|
||||
}
|
||||
|
||||
/// Config values owned by the authenticated user.
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct UserThreadConfig {}
|
||||
|
||||
/// A typed config payload paired with the authority that produced it.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ThreadConfigSource {
|
||||
Session(SessionThreadConfig),
|
||||
User(UserThreadConfig),
|
||||
}
|
||||
|
||||
/// Stable category for failures returned while loading thread config.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ThreadConfigLoadErrorCode {
|
||||
Auth,
|
||||
Timeout,
|
||||
Parse,
|
||||
RequestFailed,
|
||||
Internal,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Error, PartialEq)]
|
||||
#[error("{message}")]
|
||||
pub struct ThreadConfigLoadError {
|
||||
code: ThreadConfigLoadErrorCode,
|
||||
message: String,
|
||||
status_code: Option<u16>,
|
||||
}
|
||||
|
||||
impl ThreadConfigLoadError {
|
||||
pub fn new(
|
||||
code: ThreadConfigLoadErrorCode,
|
||||
status_code: Option<u16>,
|
||||
message: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
code,
|
||||
message: message.into(),
|
||||
status_code,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn code(&self) -> ThreadConfigLoadErrorCode {
|
||||
self.code
|
||||
}
|
||||
}
|
||||
|
||||
/// Loads typed config sources for a new thread.
|
||||
///
|
||||
/// Implementations should fetch only the source-specific config they own and
|
||||
/// return typed payloads without applying precedence or merge rules. Callers
|
||||
/// are responsible for resolving the returned sources into the effective
|
||||
/// runtime config.
|
||||
pub trait ThreadConfigLoader: Send + Sync {
|
||||
/// Load source-specific typed config.
|
||||
///
|
||||
/// Implementations should keep this method focused on fetching and parsing
|
||||
/// their owned sources. Most callers should use [`Self::load_config_layers`]
|
||||
/// so precedence and merging continue through the ordinary config layer
|
||||
/// stack.
|
||||
fn load(
|
||||
&self,
|
||||
context: ThreadConfigContext,
|
||||
) -> ThreadConfigLoaderFuture<'_, Vec<ThreadConfigSource>>;
|
||||
|
||||
fn load_config_layers(
|
||||
&self,
|
||||
context: ThreadConfigContext,
|
||||
) -> ThreadConfigLoaderFuture<'_, Vec<ConfigLayerEntry>> {
|
||||
Box::pin(async move {
|
||||
let sources = self.load(context).await?;
|
||||
sources
|
||||
.into_iter()
|
||||
.map(thread_config_source_to_layer)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map(|layers| layers.into_iter().flatten().collect())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub type ThreadConfigLoaderFuture<'a, T> =
|
||||
Pin<Box<dyn Future<Output = Result<T, ThreadConfigLoadError>> + Send + 'a>>;
|
||||
|
||||
/// Loader backed by a static set of typed thread config sources.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct StaticThreadConfigLoader {
|
||||
sources: Vec<ThreadConfigSource>,
|
||||
}
|
||||
|
||||
impl StaticThreadConfigLoader {
|
||||
pub fn new(sources: Vec<ThreadConfigSource>) -> Self {
|
||||
Self { sources }
|
||||
}
|
||||
}
|
||||
|
||||
impl ThreadConfigLoader for StaticThreadConfigLoader {
|
||||
fn load(
|
||||
&self,
|
||||
_context: ThreadConfigContext,
|
||||
) -> ThreadConfigLoaderFuture<'_, Vec<ThreadConfigSource>> {
|
||||
Box::pin(async { Ok(self.sources.clone()) })
|
||||
}
|
||||
}
|
||||
|
||||
/// Loader used when no external thread config source is configured.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct NoopThreadConfigLoader;
|
||||
|
||||
impl ThreadConfigLoader for NoopThreadConfigLoader {
|
||||
fn load(
|
||||
&self,
|
||||
_context: ThreadConfigContext,
|
||||
) -> ThreadConfigLoaderFuture<'_, Vec<ThreadConfigSource>> {
|
||||
Box::pin(async { Ok(Vec::new()) })
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_config_source_to_layer(
|
||||
source: ThreadConfigSource,
|
||||
) -> Result<Option<ConfigLayerEntry>, ThreadConfigLoadError> {
|
||||
match source {
|
||||
ThreadConfigSource::Session(config) => {
|
||||
let config = session_thread_config_to_toml(config)?;
|
||||
if is_empty_table(&config) {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some(ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
config,
|
||||
)))
|
||||
}
|
||||
}
|
||||
// UserThreadConfig has no TOML-backed fields yet. When it grows one,
|
||||
// fold it into the existing user layer instead of adding another
|
||||
// ConfigLayerSource variant.
|
||||
ThreadConfigSource::User(_config) => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn is_empty_table(config: &TomlValue) -> bool {
|
||||
config.as_table().is_some_and(toml::map::Map::is_empty)
|
||||
}
|
||||
|
||||
fn session_thread_config_to_toml(
|
||||
config: SessionThreadConfig,
|
||||
) -> Result<TomlValue, ThreadConfigLoadError> {
|
||||
let mut table = toml::map::Map::new();
|
||||
|
||||
if let Some(model_provider) = config.model_provider {
|
||||
table.insert(
|
||||
"model_provider".to_string(),
|
||||
TomlValue::String(model_provider),
|
||||
);
|
||||
}
|
||||
|
||||
if !config.model_providers.is_empty() {
|
||||
let model_providers = TomlValue::try_from(config.model_providers).map_err(|err| {
|
||||
ThreadConfigLoadError::new(
|
||||
ThreadConfigLoadErrorCode::Parse,
|
||||
/*status_code*/ None,
|
||||
format!("failed to convert session model providers to config TOML: {err}"),
|
||||
)
|
||||
})?;
|
||||
table.insert("model_providers".to_string(), model_providers);
|
||||
}
|
||||
|
||||
if !config.features.is_empty() {
|
||||
let features = config
|
||||
.features
|
||||
.into_iter()
|
||||
.map(|(feature, enabled)| (feature, TomlValue::Boolean(enabled)))
|
||||
.collect();
|
||||
table.insert("features".to_string(), TomlValue::Table(features));
|
||||
}
|
||||
|
||||
Ok(TomlValue::Table(table))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use codex_model_provider_info::ModelProviderInfo;
|
||||
use codex_model_provider_info::WireApi;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn loader_returns_session_and_user_sources() {
|
||||
let loader = StaticThreadConfigLoader::new(vec![
|
||||
ThreadConfigSource::Session(SessionThreadConfig {
|
||||
model_provider: Some("local".to_string()),
|
||||
model_providers: HashMap::from([("local".to_string(), test_provider("local"))]),
|
||||
features: BTreeMap::from([("plugins".to_string(), false)]),
|
||||
}),
|
||||
ThreadConfigSource::User(UserThreadConfig::default()),
|
||||
]);
|
||||
|
||||
let sources = loader
|
||||
.load(ThreadConfigContext {
|
||||
thread_id: Some("thread-1".to_string()),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("thread config loads");
|
||||
|
||||
assert_eq!(
|
||||
sources,
|
||||
vec![
|
||||
ThreadConfigSource::Session(SessionThreadConfig {
|
||||
model_provider: Some("local".to_string()),
|
||||
model_providers: HashMap::from([("local".to_string(), test_provider("local"))]),
|
||||
features: BTreeMap::from([("plugins".to_string(), false)]),
|
||||
}),
|
||||
ThreadConfigSource::User(UserThreadConfig::default()),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loader_translates_sources_to_config_layers() {
|
||||
let loader = StaticThreadConfigLoader::new(vec![
|
||||
ThreadConfigSource::User(UserThreadConfig::default()),
|
||||
ThreadConfigSource::Session(SessionThreadConfig {
|
||||
model_provider: Some("local".to_string()),
|
||||
model_providers: HashMap::from([("local".to_string(), test_provider("local"))]),
|
||||
features: BTreeMap::from([("plugins".to_string(), false)]),
|
||||
}),
|
||||
]);
|
||||
let layers = loader
|
||||
.load_config_layers(ThreadConfigContext {
|
||||
cwd: Some(
|
||||
AbsolutePathBuf::from_absolute_path_checked(
|
||||
std::env::temp_dir().join("project"),
|
||||
)
|
||||
.expect("absolute cwd"),
|
||||
),
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.expect("thread config layers load");
|
||||
|
||||
assert_eq!(
|
||||
layers,
|
||||
vec![ConfigLayerEntry::new(
|
||||
ConfigLayerSource::SessionFlags,
|
||||
toml::toml! {
|
||||
model_provider = "local"
|
||||
|
||||
[model_providers.local]
|
||||
name = "local"
|
||||
base_url = "http://127.0.0.1:8061/api/codex"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
supports_websockets = true
|
||||
supports_standalone_web_search = true
|
||||
|
||||
[features]
|
||||
plugins = false
|
||||
}
|
||||
.into()
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
fn test_provider(name: &str) -> ModelProviderInfo {
|
||||
ModelProviderInfo {
|
||||
name: name.to_string(),
|
||||
base_url: Some("http://127.0.0.1:8061/api/codex".to_string()),
|
||||
model_catalog_url: None,
|
||||
env_key: None,
|
||||
env_key_instructions: None,
|
||||
experimental_bearer_token: None,
|
||||
auth: None,
|
||||
gateway_oauth: None,
|
||||
aws: None,
|
||||
wire_api: WireApi::Responses,
|
||||
query_params: None,
|
||||
http_headers: None,
|
||||
env_http_headers: None,
|
||||
request_max_retries: None,
|
||||
stream_max_retries: None,
|
||||
stream_idle_timeout_ms: None,
|
||||
websocket_connect_timeout_ms: None,
|
||||
requires_openai_auth: false,
|
||||
supports_websockets: true,
|
||||
supports_standalone_web_search: true,
|
||||
capabilities: None,
|
||||
project_id: None,
|
||||
location: None,
|
||||
credential_file: None,
|
||||
include_internal_metadata: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package codex.thread_config.v1;
|
||||
|
||||
service ThreadConfigLoader {
|
||||
rpc Load(LoadThreadConfigRequest) returns (LoadThreadConfigResponse);
|
||||
}
|
||||
|
||||
message LoadThreadConfigRequest {
|
||||
optional string thread_id = 1;
|
||||
optional string cwd = 2;
|
||||
}
|
||||
|
||||
message LoadThreadConfigResponse {
|
||||
repeated ThreadConfigSource sources = 1;
|
||||
}
|
||||
|
||||
message ThreadConfigSource {
|
||||
oneof source {
|
||||
SessionThreadConfig session = 1;
|
||||
UserThreadConfig user = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message SessionThreadConfig {
|
||||
optional string model_provider = 1;
|
||||
repeated ModelProvider model_providers = 2;
|
||||
map<string, bool> features = 3;
|
||||
}
|
||||
|
||||
message UserThreadConfig {}
|
||||
|
||||
message ModelProvider {
|
||||
string id = 1;
|
||||
string name = 2;
|
||||
optional string base_url = 3;
|
||||
optional string env_key = 4;
|
||||
optional string env_key_instructions = 5;
|
||||
optional string experimental_bearer_token = 6;
|
||||
optional ModelProviderAuthInfo auth = 7;
|
||||
WireApi wire_api = 8;
|
||||
optional StringMap query_params = 9;
|
||||
optional StringMap http_headers = 10;
|
||||
optional StringMap env_http_headers = 11;
|
||||
optional uint64 request_max_retries = 12;
|
||||
optional uint64 stream_max_retries = 13;
|
||||
optional uint64 stream_idle_timeout_ms = 14;
|
||||
optional uint64 websocket_connect_timeout_ms = 15;
|
||||
bool requires_openai_auth = 16;
|
||||
bool supports_websockets = 17;
|
||||
bool supports_standalone_web_search = 18;
|
||||
optional string model_catalog_url = 19;
|
||||
optional string project_id = 20;
|
||||
optional string location = 21;
|
||||
optional string credential_file = 22;
|
||||
optional ModelProviderCapabilities capabilities = 23;
|
||||
}
|
||||
|
||||
message ModelProviderCapabilities {
|
||||
optional bool cyber_access_programs = 1;
|
||||
}
|
||||
|
||||
message StringMap {
|
||||
map<string, string> values = 1;
|
||||
}
|
||||
|
||||
message ModelProviderAuthInfo {
|
||||
string command = 1;
|
||||
repeated string args = 2;
|
||||
uint64 timeout_ms = 3;
|
||||
uint64 refresh_interval_ms = 4;
|
||||
string cwd = 5;
|
||||
}
|
||||
|
||||
enum WireApi {
|
||||
WIRE_API_UNSPECIFIED = 0;
|
||||
WIRE_API_RESPONSES = 1;
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
// This file is @generated by prost-build.
|
||||
#![allow(clippy::trivially_copy_pass_by_ref)]
|
||||
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct LoadThreadConfigRequest {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub thread_id: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "2")]
|
||||
pub cwd: ::core::option::Option<::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct LoadThreadConfigResponse {
|
||||
#[prost(message, repeated, tag = "1")]
|
||||
pub sources: ::prost::alloc::vec::Vec<ThreadConfigSource>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct ThreadConfigSource {
|
||||
#[prost(oneof = "thread_config_source::Source", tags = "1, 2")]
|
||||
pub source: ::core::option::Option<thread_config_source::Source>,
|
||||
}
|
||||
/// Nested message and enum types in `ThreadConfigSource`.
|
||||
pub mod thread_config_source {
|
||||
#[derive(Clone, PartialEq, ::prost::Oneof)]
|
||||
pub enum Source {
|
||||
#[prost(message, tag = "1")]
|
||||
Session(super::SessionThreadConfig),
|
||||
#[prost(message, tag = "2")]
|
||||
User(super::UserThreadConfig),
|
||||
}
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct SessionThreadConfig {
|
||||
#[prost(string, optional, tag = "1")]
|
||||
pub model_provider: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(message, repeated, tag = "2")]
|
||||
pub model_providers: ::prost::alloc::vec::Vec<ModelProvider>,
|
||||
#[prost(map = "string, bool", tag = "3")]
|
||||
pub features: ::std::collections::HashMap<::prost::alloc::string::String, bool>,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct UserThreadConfig {}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct ModelProvider {
|
||||
#[prost(string, tag = "1")]
|
||||
pub id: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "2")]
|
||||
pub name: ::prost::alloc::string::String,
|
||||
#[prost(string, optional, tag = "3")]
|
||||
pub base_url: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "4")]
|
||||
pub env_key: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "5")]
|
||||
pub env_key_instructions: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "6")]
|
||||
pub experimental_bearer_token: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(message, optional, tag = "7")]
|
||||
pub auth: ::core::option::Option<ModelProviderAuthInfo>,
|
||||
#[prost(enumeration = "WireApi", tag = "8")]
|
||||
pub wire_api: i32,
|
||||
#[prost(message, optional, tag = "9")]
|
||||
pub query_params: ::core::option::Option<StringMap>,
|
||||
#[prost(message, optional, tag = "10")]
|
||||
pub http_headers: ::core::option::Option<StringMap>,
|
||||
#[prost(message, optional, tag = "11")]
|
||||
pub env_http_headers: ::core::option::Option<StringMap>,
|
||||
#[prost(uint64, optional, tag = "12")]
|
||||
pub request_max_retries: ::core::option::Option<u64>,
|
||||
#[prost(uint64, optional, tag = "13")]
|
||||
pub stream_max_retries: ::core::option::Option<u64>,
|
||||
#[prost(uint64, optional, tag = "14")]
|
||||
pub stream_idle_timeout_ms: ::core::option::Option<u64>,
|
||||
#[prost(uint64, optional, tag = "15")]
|
||||
pub websocket_connect_timeout_ms: ::core::option::Option<u64>,
|
||||
#[prost(bool, tag = "16")]
|
||||
pub requires_openai_auth: bool,
|
||||
#[prost(bool, tag = "17")]
|
||||
pub supports_websockets: bool,
|
||||
#[prost(bool, tag = "18")]
|
||||
pub supports_standalone_web_search: bool,
|
||||
#[prost(string, optional, tag = "19")]
|
||||
pub model_catalog_url: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "20")]
|
||||
pub project_id: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "21")]
|
||||
pub location: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(string, optional, tag = "22")]
|
||||
pub credential_file: ::core::option::Option<::prost::alloc::string::String>,
|
||||
#[prost(message, optional, tag = "23")]
|
||||
pub capabilities: ::core::option::Option<ModelProviderCapabilities>,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct ModelProviderCapabilities {
|
||||
#[prost(bool, optional, tag = "1")]
|
||||
pub cyber_access_programs: ::core::option::Option<bool>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, ::prost::Message)]
|
||||
pub struct StringMap {
|
||||
#[prost(map = "string, string", tag = "1")]
|
||||
pub values:
|
||||
::std::collections::HashMap<::prost::alloc::string::String, ::prost::alloc::string::String>,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct ModelProviderAuthInfo {
|
||||
#[prost(string, tag = "1")]
|
||||
pub command: ::prost::alloc::string::String,
|
||||
#[prost(string, repeated, tag = "2")]
|
||||
pub args: ::prost::alloc::vec::Vec<::prost::alloc::string::String>,
|
||||
#[prost(uint64, tag = "3")]
|
||||
pub timeout_ms: u64,
|
||||
#[prost(uint64, tag = "4")]
|
||||
pub refresh_interval_ms: u64,
|
||||
#[prost(string, tag = "5")]
|
||||
pub cwd: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)]
|
||||
#[repr(i32)]
|
||||
pub enum WireApi {
|
||||
Unspecified = 0,
|
||||
Responses = 1,
|
||||
}
|
||||
impl WireApi {
|
||||
/// String value of the enum field names used in the ProtoBuf definition.
|
||||
///
|
||||
/// The values are not transformed in any way and thus are considered stable
|
||||
/// (if the ProtoBuf definition does not change) and safe for programmatic use.
|
||||
pub fn as_str_name(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Unspecified => "WIRE_API_UNSPECIFIED",
|
||||
Self::Responses => "WIRE_API_RESPONSES",
|
||||
}
|
||||
}
|
||||
/// Creates an enum from field names used in the ProtoBuf definition.
|
||||
pub fn from_str_name(value: &str) -> ::core::option::Option<Self> {
|
||||
match value {
|
||||
"WIRE_API_UNSPECIFIED" => Some(Self::Unspecified),
|
||||
"WIRE_API_RESPONSES" => Some(Self::Responses),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated client implementations.
|
||||
pub mod thread_config_loader_client {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value
|
||||
)]
|
||||
use tonic::codegen::http::Uri;
|
||||
use tonic::codegen::*;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ThreadConfigLoaderClient<T> {
|
||||
inner: tonic::client::Grpc<T>,
|
||||
}
|
||||
impl ThreadConfigLoaderClient<tonic::transport::Channel> {
|
||||
/// Attempt to create a new client by connecting to a given endpoint.
|
||||
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
|
||||
where
|
||||
D: TryInto<tonic::transport::Endpoint>,
|
||||
D::Error: Into<StdError>,
|
||||
{
|
||||
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
|
||||
Ok(Self::new(conn))
|
||||
}
|
||||
}
|
||||
impl<T> ThreadConfigLoaderClient<T>
|
||||
where
|
||||
T: tonic::client::GrpcService<tonic::body::Body>,
|
||||
T::Error: Into<StdError>,
|
||||
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
|
||||
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
|
||||
{
|
||||
pub fn new(inner: T) -> Self {
|
||||
let inner = tonic::client::Grpc::new(inner);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_origin(inner: T, origin: Uri) -> Self {
|
||||
let inner = tonic::client::Grpc::with_origin(inner, origin);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_interceptor<F>(
|
||||
inner: T,
|
||||
interceptor: F,
|
||||
) -> ThreadConfigLoaderClient<InterceptedService<T, F>>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
T::ResponseBody: Default,
|
||||
T: tonic::codegen::Service<
|
||||
http::Request<tonic::body::Body>,
|
||||
Response = http::Response<
|
||||
<T as tonic::client::GrpcService<tonic::body::Body>>::ResponseBody,
|
||||
>,
|
||||
>,
|
||||
<T as tonic::codegen::Service<http::Request<tonic::body::Body>>>::Error:
|
||||
Into<StdError> + std::marker::Send + std::marker::Sync,
|
||||
{
|
||||
ThreadConfigLoaderClient::new(InterceptedService::new(inner, interceptor))
|
||||
}
|
||||
/// Compress requests with the given encoding.
|
||||
///
|
||||
/// This requires the server to support it otherwise it might respond with an
|
||||
/// error.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.send_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Enable decompressing responses.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.accept_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_decoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_encoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
pub async fn load(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::LoadThreadConfigRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::LoadThreadConfigResponse>, tonic::Status>
|
||||
{
|
||||
self.inner.ready().await.map_err(|e| {
|
||||
tonic::Status::unknown(format!("Service was not ready: {}", e.into()))
|
||||
})?;
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/codex.thread_config.v1.ThreadConfigLoader/Load",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut().insert(GrpcMethod::new(
|
||||
"codex.thread_config.v1.ThreadConfigLoader",
|
||||
"Load",
|
||||
));
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated server implementations.
|
||||
pub mod thread_config_loader_server {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value
|
||||
)]
|
||||
use tonic::codegen::*;
|
||||
/// Generated trait containing gRPC methods that should be implemented for use with ThreadConfigLoaderServer.
|
||||
#[async_trait]
|
||||
pub trait ThreadConfigLoader: std::marker::Send + std::marker::Sync + 'static {
|
||||
async fn load(
|
||||
&self,
|
||||
request: tonic::Request<super::LoadThreadConfigRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::LoadThreadConfigResponse>, tonic::Status>;
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ThreadConfigLoaderServer<T> {
|
||||
inner: Arc<T>,
|
||||
accept_compression_encodings: EnabledCompressionEncodings,
|
||||
send_compression_encodings: EnabledCompressionEncodings,
|
||||
max_decoding_message_size: Option<usize>,
|
||||
max_encoding_message_size: Option<usize>,
|
||||
}
|
||||
impl<T> ThreadConfigLoaderServer<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self::from_arc(Arc::new(inner))
|
||||
}
|
||||
pub fn from_arc(inner: Arc<T>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: Default::default(),
|
||||
send_compression_encodings: Default::default(),
|
||||
max_decoding_message_size: None,
|
||||
max_encoding_message_size: None,
|
||||
}
|
||||
}
|
||||
pub fn with_interceptor<F>(inner: T, interceptor: F) -> InterceptedService<Self, F>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
{
|
||||
InterceptedService::new(Self::new(inner), interceptor)
|
||||
}
|
||||
/// Enable decompressing requests with the given encoding.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.accept_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Compress responses with the given encoding, if the client supports it.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.send_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_decoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_encoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<T, B> tonic::codegen::Service<http::Request<B>> for ThreadConfigLoaderServer<T>
|
||||
where
|
||||
T: ThreadConfigLoader,
|
||||
B: Body + std::marker::Send + 'static,
|
||||
B::Error: Into<StdError> + std::marker::Send + 'static,
|
||||
{
|
||||
type Response = http::Response<tonic::body::Body>;
|
||||
type Error = std::convert::Infallible;
|
||||
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||
fn poll_ready(
|
||||
&mut self,
|
||||
_cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||
match req.uri().path() {
|
||||
"/codex.thread_config.v1.ThreadConfigLoader/Load" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct LoadSvc<T: ThreadConfigLoader>(pub Arc<T>);
|
||||
impl<T: ThreadConfigLoader>
|
||||
tonic::server::UnaryService<super::LoadThreadConfigRequest> for LoadSvc<T>
|
||||
{
|
||||
type Response = super::LoadThreadConfigResponse;
|
||||
type Future = BoxFuture<tonic::Response<Self::Response>, tonic::Status>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::LoadThreadConfigRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as ThreadConfigLoader>::load(&inner, request).await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = LoadSvc(inner);
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
_ => Box::pin(async move {
|
||||
let mut response = http::Response::new(tonic::body::Body::default());
|
||||
let headers = response.headers_mut();
|
||||
headers.insert(
|
||||
tonic::Status::GRPC_STATUS,
|
||||
(tonic::Code::Unimplemented as i32).into(),
|
||||
);
|
||||
headers.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
tonic::metadata::GRPC_CONTENT_TYPE,
|
||||
);
|
||||
Ok(response)
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T> Clone for ThreadConfigLoaderServer<T> {
|
||||
fn clone(&self) -> Self {
|
||||
let inner = self.inner.clone();
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: self.accept_compression_encodings,
|
||||
send_compression_encodings: self.send_compression_encodings,
|
||||
max_decoding_message_size: self.max_decoding_message_size,
|
||||
max_encoding_message_size: self.max_encoding_message_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated gRPC service name
|
||||
pub const SERVICE_NAME: &str = "codex.thread_config.v1.ThreadConfigLoader";
|
||||
impl<T> tonic::server::NamedService for ThreadConfigLoaderServer<T> {
|
||||
const NAME: &'static str = SERVICE_NAME;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user