aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT
- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser, device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity, runtime agent instance, backend-client e openapi-models, workspace routing. - Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin remoti (catalogo, sync, share), cyber access program, daybreak, cloud config e requirements (config_server ora fail-closed), attestation, frozen cloud skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/ routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime. - Messaggi d'errore senza link a chatgpt.com. - Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed. - Test: cancellati solo quelli del codice rimosso; test di sicurezza (sandbox estensioni, permessi, redazione, auth storage, requirements) adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents). - Istruzioni di sistema invariate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -34,10 +34,10 @@ 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 system_source() -> RequirementSource {
|
||||
RequirementSource::SystemRequirementsToml {
|
||||
file: crate::AbsolutePathBuf::try_from(std::env::temp_dir().join("requirements.toml"))
|
||||
.expect("absolute requirements path"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +77,7 @@ fn application_network_is_preserved_from_each_managed_source() {
|
||||
.expect("absolute requirements path"),
|
||||
},
|
||||
managed_source(),
|
||||
cloud_source(),
|
||||
system_source(),
|
||||
] {
|
||||
let requirements = compose_requirements_for_hostname(
|
||||
[RequirementsLayerEntry::from_toml(
|
||||
@@ -147,7 +147,7 @@ fn application_network_uses_regular_toml_precedence() {
|
||||
let composed = compose_requirements_for_hostname(
|
||||
[
|
||||
RequirementsLayerEntry::from_toml(managed_source(), low),
|
||||
RequirementsLayerEntry::from_toml(cloud_source(), high),
|
||||
RequirementsLayerEntry::from_toml(system_source(), high),
|
||||
],
|
||||
/*hostname*/ None,
|
||||
)
|
||||
@@ -171,7 +171,7 @@ fn legacy_application_merge_uses_whole_table_precedence() {
|
||||
] {
|
||||
let mut composed = ConfigRequirementsWithSources::default();
|
||||
composed.merge_unset_fields(managed_source(), parse(high));
|
||||
composed.merge_unset_fields(cloud_source(), parse(low));
|
||||
composed.merge_unset_fields(system_source(), parse(low));
|
||||
assert_eq!(
|
||||
composed,
|
||||
ConfigRequirementsWithSources {
|
||||
@@ -185,7 +185,7 @@ fn legacy_application_merge_uses_whole_table_precedence() {
|
||||
}
|
||||
let mut composed = ConfigRequirementsWithSources::default();
|
||||
composed.merge_unset_fields(managed_source(), parse(""));
|
||||
composed.merge_unset_fields(cloud_source(), parse(INSTALLATION));
|
||||
composed.merge_unset_fields(system_source(), parse(INSTALLATION));
|
||||
assert_eq!(composed.into_toml(), parse(INSTALLATION));
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ fn invalid_application_policy_is_rejected_before_layer_overrides() {
|
||||
assert!(
|
||||
compose_requirements_for_hostname(
|
||||
[
|
||||
RequirementsLayerEntry::from_toml(cloud_source(), invalid),
|
||||
RequirementsLayerEntry::from_toml(system_source(), invalid),
|
||||
RequirementsLayerEntry::from_toml(managed_source(), INSTALLATION),
|
||||
],
|
||||
/*hostname*/ None,
|
||||
@@ -221,28 +221,14 @@ fn invalid_application_policy_is_rejected_before_layer_overrides() {
|
||||
}
|
||||
|
||||
#[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;
|
||||
fn system_application_network_uses_managed_precedence() {
|
||||
let mut layers = vec![RequirementsLayerEntry::from_toml(system_source(), WORKSPACE)];
|
||||
layers.push(RequirementsLayerEntry::from_toml(
|
||||
managed_source(),
|
||||
INSTALLATION,
|
||||
));
|
||||
let composed = compose_requirements_for_hostname(layers, /*hostname*/ None)
|
||||
.expect("compose cloud and installation requirements")
|
||||
.expect("compose system and installation requirements")
|
||||
.expect("requirements");
|
||||
let expected = MERGED.replace(
|
||||
"\"blocked.example.com\" = \"allow\"",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Exercises managed storage projection, validation, and cloud layer precedence.
|
||||
//! Exercises managed storage projection, validation, and layer precedence.
|
||||
|
||||
use crate::ConfigRequirementsToml;
|
||||
use crate::config_toml::ConfigToml;
|
||||
@@ -75,13 +75,10 @@ fn storage_requirements_reject_unknown_keys() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloud fragments merge per setting without losing independent fields from lower-priority layers.
|
||||
/// Managed layers merge per setting without losing independent fields from lower-priority layers.
|
||||
#[test]
|
||||
fn cloud_storage_layers_preserve_independent_fields_and_precedence() {
|
||||
fn managed_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;
|
||||
@@ -90,29 +87,31 @@ fn cloud_storage_layers_preserve_independent_fields_and_precedence() {
|
||||
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!(
|
||||
// Layers are listed lowest precedence first: system requirements, then MDM.
|
||||
let mut layers = vec![
|
||||
RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::SystemRequirementsToml {
|
||||
file: base.join("requirements.toml"),
|
||||
},
|
||||
format!(
|
||||
"[application.storage]\ndefault_project_parent = '{}'\nprojectless_workspace_root = '{}'",
|
||||
home.path().display(),
|
||||
chats.display()
|
||||
),
|
||||
},
|
||||
)
|
||||
.with_base_dir(base.clone()),
|
||||
RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::MdmManagedPreferences {
|
||||
domain: "com.openai.codex".into(),
|
||||
key: "requirements".into(),
|
||||
},
|
||||
format!(
|
||||
"[application.network]\nenabled = false\n[application.storage]\ndefault_project_parent = '{}'",
|
||||
projects.display()
|
||||
),
|
||||
)
|
||||
.with_base_dir(base.clone()),
|
||||
];
|
||||
let mut layers = CloudConfigBundleLayers::from_bundle(bundle, &base)
|
||||
.unwrap()
|
||||
.enterprise_managed_requirements;
|
||||
let requirements = compose_requirements(layers.clone())
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
|
||||
@@ -8,43 +8,12 @@ pub struct ManagedAuthPolicy {
|
||||
}
|
||||
|
||||
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 (
|
||||
/// Narrows the managed workspace allowlist by locally forced workspace IDs, so the
|
||||
/// non-API login method is disabled when no permitted workspace remains.
|
||||
pub fn with_forced_chatgpt_workspaces(mut self, forced_workspaces: Option<&[String]>) -> Self {
|
||||
self.allowed_chatgpt_workspaces = match (
|
||||
forced_workspaces,
|
||||
self.allowed_chatgpt_workspaces.as_deref(),
|
||||
self.allowed_chatgpt_workspaces.take(),
|
||||
) {
|
||||
(Some(forced), Some(allowed)) => Some(
|
||||
forced
|
||||
@@ -54,8 +23,35 @@ impl ManagedAuthPolicy {
|
||||
.collect(),
|
||||
),
|
||||
(Some(forced), None) => Some(forced.to_vec()),
|
||||
(None, Some(allowed)) => Some(allowed.to_vec()),
|
||||
(None, None) => None,
|
||||
}
|
||||
(None, allowed) => allowed,
|
||||
};
|
||||
self
|
||||
}
|
||||
|
||||
pub fn allows_login_method(
|
||||
&self,
|
||||
method: ForcedLoginMethod,
|
||||
forced_login_method: Option<ForcedLoginMethod>,
|
||||
) -> 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
|
||||
.allowed_chatgpt_workspaces
|
||||
.as_ref()
|
||||
.is_none_or(|workspaces| !workspaces.is_empty()))
|
||||
}
|
||||
|
||||
pub fn allowed_login_methods(
|
||||
&self,
|
||||
forced_login_method: Option<ForcedLoginMethod>,
|
||||
) -> Vec<ForcedLoginMethod> {
|
||||
[ForcedLoginMethod::Api, ForcedLoginMethod::Chatgpt]
|
||||
.into_iter()
|
||||
.filter(|method| self.allows_login_method(*method, forced_login_method))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,528 +0,0 @@
|
||||
//! 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;
|
||||
@@ -1,330 +0,0 @@
|
||||
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()
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
//! 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;
|
||||
@@ -1,226 +0,0 @@
|
||||
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`"));
|
||||
}
|
||||
@@ -10,8 +10,6 @@ pub enum ConfigLayerSource {
|
||||
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,
|
||||
@@ -35,7 +33,6 @@ impl ConfigLayerSource {
|
||||
ConfigLayerSource::PackagedDefaults { .. } => -10,
|
||||
ConfigLayerSource::Mdm { .. } => 0,
|
||||
ConfigLayerSource::System { .. } => 10,
|
||||
ConfigLayerSource::EnterpriseManaged { .. } => 15,
|
||||
ConfigLayerSource::User { profile, .. } => {
|
||||
if profile.is_some() {
|
||||
21
|
||||
@@ -86,9 +83,6 @@ pub fn format_config_layer_source(source: &ConfigLayerSource, config_toml_file:
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -57,12 +57,6 @@ pub enum RequirementSource {
|
||||
Composite {
|
||||
sources: Vec<RequirementSource>,
|
||||
},
|
||||
/// A backend-delivered enterprise-managed layer. `id` is the stable backend
|
||||
/// identifier; `name` is the admin-facing display name.
|
||||
EnterpriseManaged {
|
||||
id: String,
|
||||
name: String,
|
||||
},
|
||||
SystemRequirementsToml {
|
||||
file: AbsolutePathBuf,
|
||||
},
|
||||
@@ -119,9 +113,6 @@ impl fmt::Display for RequirementSource {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
RequirementSource::EnterpriseManaged { id, name } => {
|
||||
write!(f, "enterprise-managed requirements {name} ({id})")
|
||||
}
|
||||
RequirementSource::SystemRequirementsToml { file } => {
|
||||
write!(f, "{}", file.as_path().display())
|
||||
}
|
||||
|
||||
@@ -17,7 +17,6 @@ use crate::types::AuthCredentialsStoreMode;
|
||||
use crate::types::FeedbackConfigToml;
|
||||
use crate::types::History;
|
||||
use crate::types::MarketplaceConfig;
|
||||
use crate::types::McpEnterpriseManagedAuthConfig;
|
||||
use crate::types::McpServerConfig;
|
||||
use crate::types::MemoriesToml;
|
||||
use crate::types::Notice;
|
||||
@@ -110,6 +109,18 @@ impl ForcedChatgptWorkspaceIds {
|
||||
Self::Multiple(values) => values,
|
||||
}
|
||||
}
|
||||
|
||||
/// Trimmed, non-empty workspace IDs. An empty selection imposes no restriction.
|
||||
pub fn normalized(self) -> Option<Vec<String>> {
|
||||
Some(
|
||||
self.into_vec()
|
||||
.into_iter()
|
||||
.map(|value| value.trim().to_string())
|
||||
.filter(|value| !value.is_empty())
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
.filter(|values| !values.is_empty())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for ForcedChatgptWorkspaceIds {
|
||||
@@ -141,16 +152,16 @@ of strings; comma-separated strings are not supported. Use \
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct OrchestratorToml {
|
||||
/// Legacy no-op setting retained for compatibility. Use `cloud.skills` to configure cloud skills.
|
||||
/// Legacy no-op setting retained for compatibility.
|
||||
pub skills: Option<FeatureToggleToml>,
|
||||
pub mcp: Option<FeatureToggleToml>,
|
||||
}
|
||||
|
||||
/// Cloud-owned feature settings.
|
||||
/// Removed: cloud-owned feature settings are accepted and ignored.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct CloudToml {
|
||||
/// Cloud skills are permitted by default; the host must supply a cloud provider.
|
||||
/// Removed: cloud skills are no longer supported; accepted and ignored.
|
||||
pub skills: Option<FeatureToggleToml>,
|
||||
}
|
||||
|
||||
@@ -167,7 +178,7 @@ pub struct FeatureToggleToml {
|
||||
pub struct ConfigToml {
|
||||
/// Optional override of model selection.
|
||||
pub model: Option<String>,
|
||||
/// Default Daybreak preference for new threads and non-interactive turns.
|
||||
/// Removed: Daybreak controls were deleted. Accepted and ignored.
|
||||
pub daybreak: Option<bool>,
|
||||
/// Review model override used by the `/review` feature.
|
||||
pub review_model: Option<String>,
|
||||
@@ -299,9 +310,10 @@ pub struct ConfigToml {
|
||||
#[schemars(schema_with = "crate::schema::mcp_servers_schema")]
|
||||
pub mcp_servers: HashMap<String, McpServerConfig>,
|
||||
|
||||
/// Trusted enterprise IdP shared by EMA-enabled MCP servers and plugins.
|
||||
/// Removed: enterprise-managed MCP authorization (EMA) was deleted. Accepted and ignored.
|
||||
#[serde(default)]
|
||||
pub mcp_enterprise_managed_auth: Option<McpEnterpriseManagedAuthConfig>,
|
||||
#[schemars(with = "Option<JsonValue>")]
|
||||
pub mcp_enterprise_managed_auth: Option<toml::Value>,
|
||||
|
||||
/// Preferred backend for storing MCP OAuth credentials.
|
||||
/// keyring: Use an OS-specific keyring service.
|
||||
@@ -427,7 +439,7 @@ pub struct ConfigToml {
|
||||
/// Orchestrator-owned feature settings.
|
||||
pub orchestrator: Option<OrchestratorToml>,
|
||||
|
||||
/// Cloud-owned feature settings.
|
||||
/// Removed: cloud-owned feature settings are accepted and ignored.
|
||||
pub cloud: Option<CloudToml>,
|
||||
|
||||
/// Base URL override for the built-in `openai` model provider.
|
||||
|
||||
@@ -252,7 +252,6 @@ fn config_path_for_layer(layer: &ConfigLayerEntry, config_toml_file: &str) -> Op
|
||||
}
|
||||
ConfigLayerSource::LegacyManagedConfigTomlFromFile { file } => Some(file.to_path_buf()),
|
||||
ConfigLayerSource::Mdm { .. }
|
||||
| ConfigLayerSource::EnterpriseManaged { .. }
|
||||
| ConfigLayerSource::SessionFlags
|
||||
| ConfigLayerSource::LegacyManagedConfigTomlFromMdm => None,
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ fn parse(contents: &str) -> ConfigRequirementsToml {
|
||||
}
|
||||
|
||||
fn source(name: &str) -> RequirementSource {
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: name.to_string(),
|
||||
name: name.to_string(),
|
||||
RequirementSource::MdmManagedPreferences {
|
||||
domain: name.to_string(),
|
||||
key: name.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ 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;
|
||||
@@ -24,9 +22,6 @@ 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;
|
||||
@@ -72,25 +67,6 @@ 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;
|
||||
@@ -184,11 +160,6 @@ 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;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Reads application requirements independently of user, project, and cloud configuration.
|
||||
//! Captured local layers retain their positions around cloud layers during composition.
|
||||
//! Reads application requirements independently of user and project configuration.
|
||||
|
||||
use crate::ApplicationRequirementsToml;
|
||||
use crate::CloudRequirementsTomlBundle;
|
||||
use crate::LoaderOverrides;
|
||||
use crate::RequirementsLayerEntry;
|
||||
use crate::compose_requirements;
|
||||
@@ -10,7 +8,7 @@ use codex_file_system::ExecutorFileSystem;
|
||||
use std::io;
|
||||
use toml::Value;
|
||||
|
||||
/// Local application sources captured without waiting for a cloud request.
|
||||
/// Local application requirement sources.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct LocalApplicationRequirements {
|
||||
system: Option<RequirementsLayerEntry>,
|
||||
@@ -19,18 +17,12 @@ pub struct LocalApplicationRequirements {
|
||||
}
|
||||
|
||||
impl LocalApplicationRequirements {
|
||||
/// Composes system, cloud, and MDM application policy in the normal requirements order.
|
||||
pub fn compose(
|
||||
&self,
|
||||
cloud: CloudRequirementsTomlBundle,
|
||||
) -> io::Result<Option<ApplicationRequirementsToml>> {
|
||||
/// Composes system and MDM application policy in the normal requirements order.
|
||||
pub fn compose(&self) -> 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))
|
||||
@@ -79,8 +71,8 @@ pub async fn load_local_application_requirements(
|
||||
mdm,
|
||||
ignore_managed: false,
|
||||
};
|
||||
// Validate local requirements before cloud loading.
|
||||
local.compose(CloudRequirementsTomlBundle::default())?;
|
||||
// Validate local requirements eagerly.
|
||||
local.compose()?;
|
||||
Ok(local)
|
||||
}
|
||||
|
||||
|
||||
@@ -53,27 +53,20 @@ impl LocalConfigLayers {
|
||||
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() {
|
||||
for layer in self.layers {
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -241,8 +234,6 @@ pub(super) async fn load_local_config_layers_with_overrides(
|
||||
Ok(LocalConfigLayers {
|
||||
config: LocalTomlLayerStack {
|
||||
layers: config_layers,
|
||||
// Cloud config follows the required system layer.
|
||||
cloud_insertion_index: 1,
|
||||
},
|
||||
requirements,
|
||||
})
|
||||
@@ -333,7 +324,6 @@ async fn local_requirements_layers(
|
||||
) -> 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(
|
||||
@@ -359,10 +349,7 @@ async fn local_requirements_layers(
|
||||
for entry in entries {
|
||||
layers.push(local_requirements_layer(entry)?);
|
||||
}
|
||||
Ok(LocalTomlLayerStack {
|
||||
layers,
|
||||
cloud_insertion_index,
|
||||
})
|
||||
Ok(LocalTomlLayerStack { layers })
|
||||
}
|
||||
|
||||
fn local_requirements_layer(
|
||||
|
||||
@@ -31,30 +31,13 @@ pub async fn load_managed_requirements_state(
|
||||
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 (requirements, _, _) =
|
||||
load_requirements_from_sources(fs, codex_home, &overrides, strict_config).await?;
|
||||
let _: ConfigRequirements = requirements.clone().try_into()?;
|
||||
let requirements_toml = requirements.into_toml();
|
||||
// Full config loads also validate required provider definitions when
|
||||
@@ -71,7 +54,6 @@ pub(super) async fn load_requirements_from_sources(
|
||||
codex_home: &Path,
|
||||
overrides: &LoaderOverrides,
|
||||
strict_config: bool,
|
||||
bundle_requirements: Vec<RequirementsLayerEntry>,
|
||||
) -> io::Result<(
|
||||
ConfigRequirementsWithSources,
|
||||
LoadedConfigLayers,
|
||||
@@ -108,7 +90,6 @@ pub(super) async fn load_requirements_from_sources(
|
||||
.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(),
|
||||
|
||||
@@ -19,7 +19,6 @@ pub use application::load_local_application_requirements;
|
||||
|
||||
use self::layer_io::LoadedConfigLayers;
|
||||
use crate::CONFIG_TOML_FILE;
|
||||
use crate::CloudConfigBundleLayers;
|
||||
use crate::ConfigLayerSource;
|
||||
use crate::ConfigRequirements;
|
||||
use crate::ProfileV2Name;
|
||||
@@ -113,7 +112,6 @@ async fn first_layer_config_error_from_entries(layers: &[ConfigLayerEntry]) -> O
|
||||
///
|
||||
/// - system `/etc/codex/requirements.toml` (Unix) or
|
||||
/// `%ProgramData%\OpenAI\Codex\requirements.toml` (Windows)
|
||||
/// - cloud: enterprise-managed cloud config bundle requirements
|
||||
/// - legacy: `/etc/codex/managed_config.toml` (Unix) reinterpreted as
|
||||
/// requirements.toml
|
||||
/// - admin: managed preferences (*)
|
||||
@@ -127,7 +125,6 @@ async fn first_layer_config_error_from_entries(layers: &[ConfigLayerEntry]) -> O
|
||||
/// - admin: managed preferences (*)
|
||||
/// - system `/etc/codex/config.toml` (Unix) or
|
||||
/// `%ProgramData%\OpenAI\Codex\config.toml` (Windows)
|
||||
/// - cloud enterprise-managed cloud config bundle fragments
|
||||
/// - user `${CODEX_HOME}/config.toml`
|
||||
/// - profile `${CODEX_HOME}/<name>.config.toml`, when selected
|
||||
/// - cwd `${PWD}/config.toml` (loaded but disabled when the directory is untrusted)
|
||||
@@ -155,7 +152,6 @@ pub async fn load_config_layers_state(
|
||||
let ConfigLoadOptions {
|
||||
loader_overrides: overrides,
|
||||
strict_config,
|
||||
cloud_config_bundle,
|
||||
} = options.into();
|
||||
let packaged_defaults_layer = if let Some(file) = &overrides.packaged_defaults_path {
|
||||
let config = layer_io::read_config_from_path(
|
||||
@@ -205,38 +201,12 @@ pub async fn load_config_layers_state(
|
||||
let ignore_project_config = overrides.ignore_project_config;
|
||||
let ignore_user_and_project_exec_policy_rules =
|
||||
overrides.ignore_user_and_project_exec_policy_rules;
|
||||
let mut bundle_requirements_layers = Vec::new();
|
||||
let mut cloud_config_layers = Vec::new();
|
||||
let mut cloud_config_binding = None;
|
||||
let mut applied_config_server = None;
|
||||
|
||||
if !overrides.ignore_managed_requirements {
|
||||
let snapshot = cloud_config_bundle.get_snapshot().await;
|
||||
cloud_config_binding = snapshot.binding;
|
||||
applied_config_server = snapshot.config_server;
|
||||
if let Some(bundle) = snapshot.bundle.map_err(io::Error::other)? {
|
||||
let cloud_config_base_dir = AbsolutePathBuf::from_absolute_path(codex_home)?;
|
||||
let bundle_layers = if strict_config {
|
||||
CloudConfigBundleLayers::from_bundle_strict_config(bundle, &cloud_config_base_dir)?
|
||||
} else {
|
||||
CloudConfigBundleLayers::from_bundle(bundle, &cloud_config_base_dir)?
|
||||
};
|
||||
let CloudConfigBundleLayers {
|
||||
enterprise_managed_config,
|
||||
enterprise_managed_requirements,
|
||||
} = bundle_layers;
|
||||
bundle_requirements_layers = enterprise_managed_requirements;
|
||||
cloud_config_layers = enterprise_managed_config;
|
||||
}
|
||||
}
|
||||
|
||||
let (config_requirements_toml, loaded_config_layers, requirements_layers) =
|
||||
managed_requirements::load_requirements_from_sources(
|
||||
fs,
|
||||
codex_home,
|
||||
&overrides,
|
||||
strict_config,
|
||||
bundle_requirements_layers,
|
||||
)
|
||||
.await?;
|
||||
let mut startup_warnings = loaded_config_layers.startup_warnings.clone();
|
||||
@@ -288,7 +258,6 @@ pub async fn load_config_layers_state(
|
||||
)
|
||||
.await?;
|
||||
layers.push(system_layer);
|
||||
layers.extend(cloud_config_layers);
|
||||
|
||||
// Add the base user config layer. When profile-v2 is selected, add the
|
||||
// profile config as a second user layer on top so the profile only needs to
|
||||
@@ -518,8 +487,6 @@ pub async fn load_config_layers_state(
|
||||
|
||||
let mut config_layer_stack =
|
||||
ConfigLayerStack::new(layers, requirements, config_requirements_toml.into_toml())?
|
||||
.with_cloud_config_binding(cloud_config_binding)
|
||||
.with_applied_config_server(applied_config_server)
|
||||
.with_user_and_project_exec_policy_rules_ignored(
|
||||
ignore_user_and_project_exec_policy_rules,
|
||||
);
|
||||
|
||||
@@ -418,7 +418,7 @@ async fn managed_browser_import_denial_survives_user_and_session_config() {
|
||||
let allow = "[in_app_browser]\nallow_external_browser_settings_import = true";
|
||||
let deny = "[in_app_browser]\nallow_external_browser_settings_import = false";
|
||||
let requirements_path = tmp.path().join("requirements.toml");
|
||||
std::fs::write(&requirements_path, allow).expect("write system requirements");
|
||||
std::fs::write(&requirements_path, deny).expect("write system requirements");
|
||||
std::fs::write(tmp.path().join(CONFIG_TOML_FILE), allow).expect("write user config");
|
||||
let mut loader_overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
loader_overrides.system_requirements_path = Some(requirements_path);
|
||||
@@ -434,10 +434,6 @@ async fn managed_browser_import_denial_survives_user_and_session_config() {
|
||||
ConfigLoadOptions {
|
||||
loader_overrides,
|
||||
strict_config: false,
|
||||
cloud_config_bundle:
|
||||
crate::test_support::CloudConfigBundleFixture::enterprise_requirement(deny)
|
||||
.add_enterprise_requirement("[in_app_browser]")
|
||||
.into_loader(),
|
||||
},
|
||||
&crate::NoopThreadConfigLoader,
|
||||
)
|
||||
@@ -1035,17 +1031,14 @@ fn local_layer_projection_preserves_override_blockers_and_cloud_position() {
|
||||
"[a]\nunrequested=true",
|
||||
),
|
||||
],
|
||||
cloud_insertion_index: 1,
|
||||
},
|
||||
requirements: LocalTomlLayerStack {
|
||||
layers: Vec::<LocalTomlLayer<RequirementSource>>::new(),
|
||||
cloud_insertion_index: 0,
|
||||
},
|
||||
};
|
||||
|
||||
let only_user = layers.clone().project(&[vec!["only_user".into()]], &[]);
|
||||
assert_eq!(only_user.config.layers.len(), 1);
|
||||
assert_eq!(only_user.config.cloud_insertion_index, 0);
|
||||
|
||||
let projected = layers.project(
|
||||
&[
|
||||
@@ -1072,7 +1065,6 @@ fn local_layer_projection_preserves_override_blockers_and_cloud_position() {
|
||||
layer(ConfigLayerSource::SessionFlags, "a=2"),
|
||||
layer(ConfigLayerSource::LegacyManagedConfigTomlFromMdm, "[a]"),
|
||||
],
|
||||
cloud_insertion_index: 1,
|
||||
}
|
||||
);
|
||||
|
||||
@@ -1163,8 +1155,6 @@ async fn local_layers_keep_raw_paths_order_and_legacy_requirements() {
|
||||
managed_dir.clone(),
|
||||
]
|
||||
);
|
||||
assert_eq!(layers.config.cloud_insertion_index, 1);
|
||||
assert_eq!(layers.requirements.cloud_insertion_index, 1);
|
||||
assert_eq!(
|
||||
(
|
||||
layers.config.layers[2].toml.clone(),
|
||||
|
||||
@@ -1,424 +0,0 @@
|
||||
//! 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;
|
||||
@@ -1,84 +0,0 @@
|
||||
//! 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,327 +0,0 @@
|
||||
//! 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)
|
||||
]));
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,6 @@ 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`.
|
||||
@@ -156,7 +154,7 @@ impl AsRef<str> for McpServerEnvVar {
|
||||
}
|
||||
}
|
||||
|
||||
/// Client settings for MCP OAuth login or enterprise token exchange.
|
||||
/// Client settings for MCP OAuth login.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[schemars(deny_unknown_fields)]
|
||||
pub struct McpServerOAuthConfig {
|
||||
@@ -168,10 +166,15 @@ pub struct McpServerOAuthConfig {
|
||||
#[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>,
|
||||
/// Removed: EMA client authentication method. Accepted and ignored.
|
||||
#[serde(
|
||||
default,
|
||||
rename = "token_endpoint_auth_method",
|
||||
deserialize_with = "ignore_removed_oauth_setting",
|
||||
skip_serializing
|
||||
)]
|
||||
#[schemars(skip)]
|
||||
pub removed_token_endpoint_auth_method: (),
|
||||
|
||||
/// Registered callback URL associated with this OAuth client.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -181,18 +184,26 @@ pub struct McpServerOAuthConfig {
|
||||
#[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)]
|
||||
/// Removed: EMA resource authorization server issuer. Accepted and ignored.
|
||||
#[serde(
|
||||
default,
|
||||
rename = "authorization_server_issuer",
|
||||
deserialize_with = "ignore_removed_oauth_setting",
|
||||
skip_serializing
|
||||
)]
|
||||
#[schemars(skip)]
|
||||
pub ema_registration: Option<McpEmaRegistration>,
|
||||
pub removed_authorization_server_issuer: (),
|
||||
}
|
||||
|
||||
fn ignore_removed_oauth_setting<'de, D>(deserializer: D) -> Result<(), D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
serde::de::IgnoredAny::deserialize(deserializer).map(|_| ())
|
||||
}
|
||||
|
||||
/// Authentication flow for an HTTP MCP server. Explicit credentials take
|
||||
/// precedence for OAuth and ChatGPT; EMA rejects alternate credentials and fallback.
|
||||
/// precedence for OAuth and ChatGPT.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq, JsonSchema)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum McpServerAuth {
|
||||
@@ -206,8 +217,8 @@ pub enum McpServerAuth {
|
||||
/// 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.
|
||||
/// Removed: enterprise-managed authorization (EMA) was deleted. Accepted so
|
||||
/// existing configs still parse; servers that select it are never started.
|
||||
#[serde(rename = "ema_auth")]
|
||||
EmaAuth,
|
||||
}
|
||||
@@ -233,7 +244,7 @@ pub struct McpServerConfig {
|
||||
#[serde(flatten)]
|
||||
pub transport: McpServerTransportConfig,
|
||||
|
||||
/// Authentication flow, including an explicit no-fallback EMA mode.
|
||||
/// Authentication flow.
|
||||
#[serde(default, skip_serializing_if = "is_default")]
|
||||
pub auth: McpServerAuth,
|
||||
|
||||
@@ -590,29 +601,6 @@ impl TryFrom<RawMcpServerConfig> for McpServerConfig {
|
||||
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,
|
||||
|
||||
@@ -22,9 +22,9 @@ 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 managed_source = RequirementSource::MdmManagedPreferences {
|
||||
domain: "Gateway".into(),
|
||||
key: "req_1".into(),
|
||||
};
|
||||
let requirements = compose_requirements([
|
||||
RequirementsLayerEntry::from_toml(
|
||||
@@ -43,7 +43,7 @@ X-Managed = "old"
|
||||
name = "Other provider"
|
||||
"#,
|
||||
),
|
||||
RequirementsLayerEntry::from_toml(cloud_source.clone(), REQUIRED),
|
||||
RequirementsLayerEntry::from_toml(managed_source.clone(), REQUIRED),
|
||||
])?
|
||||
.expect("provider requirements must not be discarded");
|
||||
let normalized = ConfigRequirements::try_from(requirements.clone())?;
|
||||
@@ -52,7 +52,7 @@ name = "Other provider"
|
||||
.model_provider
|
||||
.as_ref()
|
||||
.map(|requirement| &requirement.source),
|
||||
Some(&cloud_source)
|
||||
Some(&managed_source)
|
||||
);
|
||||
let requirements = requirements.into_toml();
|
||||
let expected: ConfigRequirementsToml = toml::from_str(
|
||||
|
||||
@@ -10,14 +10,6 @@ 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,
|
||||
@@ -102,19 +94,6 @@ impl ComposableRequirementsLayer {
|
||||
.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.
|
||||
@@ -293,14 +272,6 @@ fn strip_special_fields(layer_toml: &mut TomlValue) {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,5 @@ 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;
|
||||
|
||||
@@ -18,9 +18,9 @@ use tempfile::tempdir;
|
||||
|
||||
fn layer(id: &str, name: &str, contents: &str) -> RequirementsLayerEntry {
|
||||
RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: id.to_string(),
|
||||
name: name.to_string(),
|
||||
RequirementSource::MdmManagedPreferences {
|
||||
domain: name.to_string(),
|
||||
key: id.to_string(),
|
||||
},
|
||||
contents,
|
||||
)
|
||||
@@ -57,40 +57,6 @@ fn empty_layers_compose_to_none() {
|
||||
assert_eq!(composed, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cloud_auth_requirements_do_not_override_local_or_discard_other_policy() {
|
||||
let local = RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::Unknown,
|
||||
r#"allowed_login_methods = ["api"]
|
||||
cli_auth_credentials_store = "keyring"
|
||||
chatgpt_base_url = "https://managed.example/backend-api/""#,
|
||||
);
|
||||
for cloud_auth in [
|
||||
r#"allowed_login_methods = ["api", "chatgpt"]
|
||||
allowed_chatgpt_workspaces = ["other"]"#,
|
||||
r#"allowed_login_methods = ["saml"]
|
||||
allowed_chatgpt_workspaces = "invalid"
|
||||
cli_auth_credentials_store = "invalid"
|
||||
chatgpt_base_url = false"#,
|
||||
] {
|
||||
let cloud = layer(
|
||||
"req_cloud",
|
||||
"Cloud policy",
|
||||
&format!("{cloud_auth}\nallow_login_shell = false"),
|
||||
);
|
||||
assert_eq!(
|
||||
compose(vec![local.clone(), cloud])
|
||||
.expect("cloud auth cannot invalidate enterprise policy"),
|
||||
Some(expected_requirements(
|
||||
r#"allowed_login_methods = ["api"]
|
||||
cli_auth_credentials_store = "keyring"
|
||||
chatgpt_base_url = "https://managed.example/backend-api/"
|
||||
allow_login_shell = false"#
|
||||
))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn top_level_values_use_toml_priority() {
|
||||
let composed = compose(vec![
|
||||
@@ -583,9 +549,9 @@ allow_managed_hooks_only = true
|
||||
composed.allow_managed_hooks_only,
|
||||
Some(Sourced::new(
|
||||
/*value*/ true,
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: "req_1".to_string(),
|
||||
name: "Security baseline".to_string(),
|
||||
RequirementSource::MdmManagedPreferences {
|
||||
domain: "Security baseline".to_string(),
|
||||
key: "req_1".to_string(),
|
||||
},
|
||||
))
|
||||
);
|
||||
@@ -684,13 +650,13 @@ fn feature_aliases_merge_with_layer_precedence() {
|
||||
|
||||
#[test]
|
||||
fn merged_table_source_is_composite_in_priority_order() {
|
||||
let high_source = RequirementSource::EnterpriseManaged {
|
||||
id: "req_high".to_string(),
|
||||
name: "High".to_string(),
|
||||
let high_source = RequirementSource::MdmManagedPreferences {
|
||||
domain: "High".to_string(),
|
||||
key: "req_high".to_string(),
|
||||
};
|
||||
let low_source = RequirementSource::EnterpriseManaged {
|
||||
id: "req_low".to_string(),
|
||||
name: "Low".to_string(),
|
||||
let low_source = RequirementSource::MdmManagedPreferences {
|
||||
domain: "Low".to_string(),
|
||||
key: "req_low".to_string(),
|
||||
};
|
||||
let composed = compose_requirements_for_hostname(
|
||||
vec![
|
||||
@@ -1337,8 +1303,8 @@ managed_dir = "/managed/high"
|
||||
)
|
||||
.expect_err("conflicting managed dirs should fail closed");
|
||||
assert!(err.to_string().contains("hooks.managed_dir"));
|
||||
assert!(err.to_string().contains("High (req_high)"));
|
||||
assert!(err.to_string().contains("Low (req_low)"));
|
||||
assert!(err.to_string().contains("MDM High:req_high"));
|
||||
assert!(err.to_string().contains("MDM Low:req_low"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1367,8 +1333,8 @@ windows_managed_dir = 'C:\managed\high'
|
||||
.expect_err("conflicting windows managed dirs should fail closed");
|
||||
|
||||
assert!(err.to_string().contains("hooks.windows_managed_dir"));
|
||||
assert!(err.to_string().contains("High (req_high)"));
|
||||
assert!(err.to_string().contains("Low (req_low)"));
|
||||
assert!(err.to_string().contains("MDM High:req_high"));
|
||||
assert!(err.to_string().contains("MDM Low:req_low"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1672,7 +1638,7 @@ fn parse_error_names_layer() {
|
||||
)])
|
||||
.expect_err("invalid layer should fail");
|
||||
|
||||
assert!(err.to_string().contains("Bad layer (req_bad)"));
|
||||
assert!(err.to_string().contains("MDM Bad layer:req_bad"));
|
||||
assert!(err.to_string().contains("allowed_approval_policies"));
|
||||
}
|
||||
|
||||
@@ -1785,7 +1751,10 @@ reff = "main"
|
||||
)])
|
||||
.expect_err("invalid marketplace rule should fail");
|
||||
|
||||
assert!(err.to_string().contains("Bad marketplace layer (req_bad)"));
|
||||
assert!(
|
||||
err.to_string()
|
||||
.contains("MDM Bad marketplace layer:req_bad")
|
||||
);
|
||||
assert!(err.to_string().contains("unknown field `reff`"));
|
||||
}
|
||||
|
||||
@@ -1891,20 +1860,3 @@ scopes = ["policy.read"]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetched_policy_cannot_change_config_server() {
|
||||
let result = crate::compose_requirements([RequirementsLayerEntry::from_toml(
|
||||
RequirementSource::EnterpriseManaged {
|
||||
id: "remote".into(),
|
||||
name: "Remote policy".into(),
|
||||
},
|
||||
"[config_server]\nbase_url = 'https://replacement.example/settings'",
|
||||
)]);
|
||||
assert!(
|
||||
result
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("only be configured in local managed requirements")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,6 @@ 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;
|
||||
@@ -25,7 +24,6 @@ use toml::Value as TomlValue;
|
||||
pub struct ConfigLoadOptions {
|
||||
pub loader_overrides: LoaderOverrides,
|
||||
pub strict_config: bool,
|
||||
pub cloud_config_bundle: CloudConfigBundleLoader,
|
||||
}
|
||||
|
||||
impl From<LoaderOverrides> for ConfigLoadOptions {
|
||||
@@ -33,7 +31,6 @@ impl From<LoaderOverrides> for ConfigLoadOptions {
|
||||
Self {
|
||||
loader_overrides,
|
||||
strict_config: false,
|
||||
cloud_config_bundle: CloudConfigBundleLoader::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -224,7 +221,6 @@ impl ConfigLayerEntry {
|
||||
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,
|
||||
@@ -248,12 +244,6 @@ impl ConfigLayerEntry {
|
||||
|
||||
#[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.
|
||||
@@ -287,9 +277,6 @@ pub struct ConfigLayerStack {
|
||||
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,
|
||||
@@ -299,8 +286,7 @@ impl PartialEq for ConfigLayerStack {
|
||||
is_projectless,
|
||||
project_trust,
|
||||
} = self;
|
||||
applied_config_server == &other.applied_config_server
|
||||
&& model_provider_requirements == &other.model_provider_requirements
|
||||
model_provider_requirements == &other.model_provider_requirements
|
||||
&& layers == &other.layers
|
||||
&& requirements == &other.requirements
|
||||
&& requirements_toml == &other.requirements_toml
|
||||
@@ -324,9 +310,6 @@ impl ConfigLayerStack {
|
||||
&requirements_toml,
|
||||
)?);
|
||||
let stack = Self {
|
||||
cloud_config_binding: None,
|
||||
mcp_ema_cancellation: crate::McpEmaCancellation::default(),
|
||||
applied_config_server: None,
|
||||
model_provider_requirements,
|
||||
layers,
|
||||
requirements,
|
||||
@@ -374,45 +357,14 @@ impl ConfigLayerStack {
|
||||
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.
|
||||
/// Fails closed when managed requirements demand configuration from a
|
||||
/// remote configuration server: aKode never fetches remote configuration,
|
||||
/// so such a requirement can never be satisfied.
|
||||
pub fn ensure_config_server_applied(&self) -> std::io::Result<()> {
|
||||
if self.requirements_toml.config_server.as_ref() != self.applied_config_server() {
|
||||
if self.requirements_toml.config_server.is_some() {
|
||||
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",
|
||||
"Managed requirements demand configuration from a remote configuration server, which aKode does not support; refusing to start a session",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
@@ -548,9 +500,6 @@ impl ConfigLayerStack {
|
||||
}
|
||||
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(),
|
||||
@@ -633,9 +582,6 @@ impl ConfigLayerStack {
|
||||
}
|
||||
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(),
|
||||
|
||||
@@ -14,7 +14,6 @@ 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;
|
||||
@@ -262,13 +261,12 @@ pub(crate) fn ignored_config_warning(
|
||||
// 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 {
|
||||
let Ok((source, 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
|
||||
|
||||
@@ -239,9 +239,9 @@ fn layer(source: ConfigLayerSource, contents: &str) -> ConfigLayerEntry {
|
||||
fn checks_merged_config_and_ignores_disabled_layers() {
|
||||
let layers = vec![
|
||||
layer(
|
||||
ConfigLayerSource::EnterpriseManaged {
|
||||
id: "cfg".into(),
|
||||
name: "Defaults".into(),
|
||||
ConfigLayerSource::Mdm {
|
||||
domain: "Defaults".into(),
|
||||
key: "cfg".into(),
|
||||
},
|
||||
r#"
|
||||
[model_providers.custom]
|
||||
@@ -275,7 +275,7 @@ include_view_image_tool = false
|
||||
.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."
|
||||
"Codex is ignoring 3 unrecognized configuration settings. Check for typos or deprecated settings.\n MDM (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."
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -2,76 +2,105 @@
|
||||
//!
|
||||
//! Production code should not depend on this module.
|
||||
|
||||
use crate::CloudConfigBundle;
|
||||
use crate::CloudConfigBundleLoader;
|
||||
use crate::CloudConfigFragment;
|
||||
use crate::CloudRequirementsFragment;
|
||||
use crate::LoaderOverrides;
|
||||
use crate::merge_toml_values;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use toml::Value as TomlValue;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct CloudConfigBundleFixture {
|
||||
bundle: CloudConfigBundle,
|
||||
/// Directory, relative to the caller-provided root, that holds fixture files.
|
||||
const FIXTURE_DIR: &str = "managed-config-fixture";
|
||||
|
||||
/// Local managed configuration used by tests: requirements are written to a
|
||||
/// system `requirements.toml` and configuration to a system `config.toml`,
|
||||
/// which the loader picks up through [`LoaderOverrides`].
|
||||
///
|
||||
/// Fragments are listed from highest to lowest precedence; when more than one
|
||||
/// fragment is added they are merged into a single file so that values from
|
||||
/// earlier fragments win.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct ManagedConfigFixture {
|
||||
requirements: Vec<String>,
|
||||
config: Vec<String>,
|
||||
}
|
||||
|
||||
impl CloudConfigBundleFixture {
|
||||
pub fn enterprise_requirement(contents: impl Into<String>) -> Self {
|
||||
Self::default().add_enterprise_requirement(contents)
|
||||
impl ManagedConfigFixture {
|
||||
pub fn requirements(contents: impl Into<String>) -> Self {
|
||||
Self::default().with_requirements(contents)
|
||||
}
|
||||
|
||||
pub fn enterprise_config(contents: impl Into<String>) -> Self {
|
||||
Self::default().add_enterprise_config(contents)
|
||||
pub fn config(contents: impl Into<String>) -> Self {
|
||||
Self::default().with_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(),
|
||||
});
|
||||
pub fn with_requirements(mut self, contents: impl Into<String>) -> Self {
|
||||
self.requirements.push(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(),
|
||||
});
|
||||
pub fn with_config(mut self, contents: impl Into<String>) -> Self {
|
||||
self.config.push(contents.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn into_bundle(self) -> CloudConfigBundle {
|
||||
self.bundle
|
||||
/// Returns the managed requirements document, if any requirements were added.
|
||||
pub fn requirements_toml(&self) -> io::Result<Option<String>> {
|
||||
merge_fragments(&self.requirements)
|
||||
}
|
||||
|
||||
pub fn into_loader(self) -> CloudConfigBundleLoader {
|
||||
let bundle = self.into_bundle();
|
||||
CloudConfigBundleLoader::new(async move { Ok(Some(bundle)) })
|
||||
/// Returns the managed config document, if any config was added.
|
||||
pub fn config_toml(&self) -> io::Result<Option<String>> {
|
||||
merge_fragments(&self.config)
|
||||
}
|
||||
|
||||
/// Writes the fixture below `root` and returns `base` with the system
|
||||
/// requirements and system config paths pointing at the written files.
|
||||
pub fn loader_overrides(
|
||||
&self,
|
||||
root: &Path,
|
||||
base: LoaderOverrides,
|
||||
) -> io::Result<LoaderOverrides> {
|
||||
let mut overrides = base;
|
||||
if self.requirements.is_empty() && self.config.is_empty() {
|
||||
return Ok(overrides);
|
||||
}
|
||||
let dir = root.join(FIXTURE_DIR);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
if let Some(requirements) = self.requirements_toml()? {
|
||||
let path = dir.join("requirements.toml");
|
||||
std::fs::write(&path, requirements)?;
|
||||
overrides.system_requirements_path = Some(path);
|
||||
}
|
||||
if let Some(config) = self.config_toml()? {
|
||||
let path = dir.join("config.toml");
|
||||
std::fs::write(&path, config)?;
|
||||
overrides.system_config_path = Some(path);
|
||||
}
|
||||
Ok(overrides)
|
||||
}
|
||||
|
||||
/// Like [`Self::loader_overrides`], starting from overrides that ignore
|
||||
/// host-managed configuration.
|
||||
pub fn loader_overrides_for_tests(&self, root: &Path) -> io::Result<LoaderOverrides> {
|
||||
self.loader_overrides(root, LoaderOverrides::without_managed_config_for_tests())
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_fragments(fragments: &[String]) -> io::Result<Option<String>> {
|
||||
match fragments {
|
||||
[] => Ok(None),
|
||||
[single] => Ok(Some(single.clone())),
|
||||
fragments => {
|
||||
let mut merged = TomlValue::Table(toml::map::Map::new());
|
||||
for fragment in fragments.iter().rev() {
|
||||
let value = toml::from_str::<TomlValue>(fragment)
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
|
||||
merge_toml_values(&mut merged, &value);
|
||||
}
|
||||
toml::to_string(&merged)
|
||||
.map(Some)
|
||||
.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,24 +2,44 @@ 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();
|
||||
fn earlier_requirement_fragments_take_precedence() {
|
||||
let fixture = ManagedConfigFixture::requirements("[features]\na = true\n")
|
||||
.with_requirements("[features]\na = false\nb = false\n");
|
||||
|
||||
let merged: TomlValue = toml::from_str(
|
||||
&fixture
|
||||
.requirements_toml()
|
||||
.expect("merge requirements")
|
||||
.expect("requirements present"),
|
||||
)
|
||||
.expect("merged requirements parse");
|
||||
|
||||
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(),
|
||||
},
|
||||
]
|
||||
merged,
|
||||
toml::from_str::<TomlValue>("[features]\na = true\nb = false\n").expect("expected toml"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writes_fixture_files_as_system_layers() {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let fixture = ManagedConfigFixture::requirements("allowed_approval_policies = [\"never\"]\n")
|
||||
.with_config("model = \"managed\"\n");
|
||||
|
||||
let overrides = fixture
|
||||
.loader_overrides_for_tests(dir.path())
|
||||
.expect("write fixture");
|
||||
|
||||
let requirements_path = overrides
|
||||
.system_requirements_path
|
||||
.expect("requirements path");
|
||||
let config_path = overrides.system_config_path.expect("config path");
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(requirements_path).expect("read requirements"),
|
||||
"allowed_approval_policies = [\"never\"]\n"
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(config_path).expect("read config"),
|
||||
"model = \"managed\"\n"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,9 +3,6 @@
|
||||
// Note this file should generally be restricted to simple struct/enum
|
||||
// definitions that do not contain business logic.
|
||||
|
||||
pub use crate::mcp_ema::McpEmaAuthScope;
|
||||
pub use crate::mcp_ema::McpEnterpriseManagedAuthConfig;
|
||||
pub use crate::mcp_ema::McpServerIdpOAuthConfig;
|
||||
pub use crate::mcp_types::AppToolApproval;
|
||||
pub use crate::mcp_types::McpServerAuth;
|
||||
pub use crate::mcp_types::McpServerConfig;
|
||||
@@ -1034,23 +1031,18 @@ pub struct PluginConfig {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub enabled: Option<bool>,
|
||||
|
||||
/// Stable, unique identifier of a ChatGPT-hosted remote plugin.
|
||||
/// Availability to the requesting user is determined by Plugin Service at
|
||||
/// provisioning time.
|
||||
/// Removed: identifier of a ChatGPT-hosted remote plugin. Remote plugins are not
|
||||
/// available in aKode; this key is accepted and ignored.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub remote_plugin_id: Option<String>,
|
||||
|
||||
/// Release identifier used to pin the remote plugin to a specific release.
|
||||
/// Omission leaves release selection unchanged.
|
||||
/// Core stores this metadata without selecting or fetching a release.
|
||||
/// Removed: remote plugin release pin. Remote plugins are not available in aKode;
|
||||
/// this key is accepted and ignored.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub release_id: Option<String>,
|
||||
|
||||
/// Provisioning metadata. Omission does not request provisioning.
|
||||
/// Only applies with `remote_plugin_id` and Plugin Service availability to the
|
||||
/// requesting user at provisioning time. Effective enablement, trusted
|
||||
/// provisioning policy, and authentication and authorization restrictions still apply.
|
||||
/// This value is not trusted authorization and does not trigger provisioning.
|
||||
/// Removed: remote plugin provisioning metadata. Remote plugins are not available in
|
||||
/// aKode; this key is accepted and ignored.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auto_provision: Option<bool>,
|
||||
|
||||
|
||||
Reference in New Issue
Block a user