mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +00:00
Refresh managed Guardian policy independently of MCP (#62276)
## Why Managed approval requirements can change while an MCP runtime is still in use. Later turns need to honor those changes without restarting MCP, while in-flight MCP actions need to retain the mandatory review requirements of their issuing turn. ## What changed - Add `CodexThread::refresh_guardian_policy` to apply managed policy updates to an existing thread. MCP configuration refreshes preserve the active Guardian policy, including when a policy update lands while MCP configuration is loading. - Resolve MCP tool and elicitation reviewers against the issuing turn's policy. Live requirements can still require Guardian review, and a live policy change cannot waive mandatory review captured by the turn. ## Testing Extend coverage for overlapping Guardian and MCP refreshes and for an existing MCP runtime that must prompt the user on the next turn after a policy update allows only the `user` reviewer. GitOrigin-RevId: 5a1649f917313f6fb152a206bc89986fe6345481
This commit is contained in:
@@ -1474,6 +1474,15 @@ impl CodexThread {
|
||||
self.session.disable_mcp_enterprise_auth().await;
|
||||
}
|
||||
|
||||
/// Refresh managed Guardian policy for future turns without changing MCP state.
|
||||
/// Session and user policy fallbacks remain pinned until their own reload.
|
||||
pub async fn refresh_guardian_policy(
|
||||
&self,
|
||||
snapshot: &codex_config::GuardianPolicySnapshot,
|
||||
) -> ConfigRefreshOutcome {
|
||||
self.session.refresh_guardian_policy(snapshot).await
|
||||
}
|
||||
|
||||
/// Refresh MCP configuration, managed requirements, and session plugin and app overrides.
|
||||
/// An omitted section preserves its current overrides. An empty map restores inheritance.
|
||||
/// A stale owner requires reloading from the current config before retrying.
|
||||
|
||||
@@ -214,6 +214,12 @@ impl Config {
|
||||
}
|
||||
config.config_layer_stack = layers
|
||||
.with_mcp_ema_cancellation(self.config_layer_stack.mcp_ema_cancellation().clone());
|
||||
// Startup and publication assign a revision when Guardian owns the policy.
|
||||
if matches!(scope, RuntimeConfigRefresh::Mcp) && self.guardian_policy_revision != 0 {
|
||||
config
|
||||
.config_layer_stack
|
||||
.retain_guardian_policy_from(&self.config_layer_stack);
|
||||
}
|
||||
config.plugins = cfg.plugins;
|
||||
if enterprise_retired {
|
||||
config.disable_mcp_enterprise_auth();
|
||||
@@ -222,6 +228,18 @@ impl Config {
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
pub(crate) fn retain_guardian_policy_from(&mut self, current: &Self) {
|
||||
self.config_layer_stack
|
||||
.retain_guardian_policy_from(¤t.config_layer_stack);
|
||||
self.guardian_policy_config
|
||||
.clone_from(¤t.guardian_policy_config);
|
||||
self.guardian_extra_policy
|
||||
.clone_from(¤t.guardian_extra_policy);
|
||||
self.guardian_policy_revision = current.guardian_policy_revision;
|
||||
self.requested_approvals_reviewer = current.requested_approvals_reviewer;
|
||||
self.approvals_reviewer = current.approvals_reviewer;
|
||||
}
|
||||
|
||||
/// Disables enterprise MCP authorization while preserving unrelated MCP servers.
|
||||
pub fn disable_mcp_enterprise_auth(&mut self) {
|
||||
self.mcp_enterprise_managed_auth = None;
|
||||
|
||||
@@ -3,9 +3,15 @@
|
||||
use super::*;
|
||||
use crate::config::ConfigBuilder;
|
||||
use codex_config::CONFIG_TOML_FILE;
|
||||
use codex_config::CloudConfigBundleLoader;
|
||||
use codex_config::CloudConfigBundlePolicy;
|
||||
use codex_config::CloudConfigBundleSnapshot;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::loader::load_guardian_policy_snapshot;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_core_plugins::PluginLoadOutcome;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
async fn base_config() -> (tempfile::TempDir, Config) {
|
||||
@@ -170,7 +176,7 @@ async fn ordinary_transport_transitions_use_the_resolved_incoming_map() {
|
||||
#[tokio::test]
|
||||
async fn mcp_refresh_preserves_current_user_and_session_layers_without_reopening_ema() {
|
||||
let (_home, base) = base_config().await;
|
||||
let current = layered_config(
|
||||
let mut current = layered_config(
|
||||
&base,
|
||||
&enterprise_config("https://current-idp.example", "current-resource"),
|
||||
"",
|
||||
@@ -178,14 +184,44 @@ async fn mcp_refresh_preserves_current_user_and_session_layers_without_reopening
|
||||
"[mcp_servers.enterprise]\nenabled = false",
|
||||
)
|
||||
.await;
|
||||
let bundle = CloudConfigBundleFixture::enterprise_config("auto_review.policy = 'published'")
|
||||
.add_enterprise_requirement(
|
||||
"allowed_approvals_reviewers = ['auto_review']\nauto_review.required_on_models = ['protected']",
|
||||
)
|
||||
.into_bundle();
|
||||
let mut cloud = CloudConfigBundleSnapshot {
|
||||
bundle: Ok(Some(bundle)),
|
||||
config_server: None,
|
||||
binding: None,
|
||||
};
|
||||
CloudConfigBundlePolicy::default().publish_snapshot(&mut cloud);
|
||||
let snapshot = load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
base.codex_home.as_path(),
|
||||
&LoaderOverrides::without_managed_config_for_tests(),
|
||||
&CloudConfigBundleLoader::from_snapshot(cloud),
|
||||
/*revision*/ 1,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let next = layered_config(
|
||||
&base,
|
||||
&enterprise_config("https://old-idp.example", "old-resource"),
|
||||
"",
|
||||
"",
|
||||
"mcp_shared_repl_cwd = true\n[auto_review]\nrequired_on_models = ['incoming']",
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let before_publication = current
|
||||
.resolve_runtime_refresh(&next, RuntimeConfigRefresh::Mcp)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
before_publication.config_layer_stack.requirements(),
|
||||
next.config_layer_stack.requirements()
|
||||
);
|
||||
|
||||
current.config_layer_stack.apply_guardian_policy(&snapshot);
|
||||
current.guardian_policy_revision = snapshot.revision;
|
||||
let refreshed = current
|
||||
.resolve_runtime_refresh(&next, RuntimeConfigRefresh::Mcp)
|
||||
.unwrap();
|
||||
@@ -203,6 +239,50 @@ async fn mcp_refresh_preserves_current_user_and_session_layers_without_reopening
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(preserved_layers(&refreshed), preserved_layers(¤t));
|
||||
let layers = &refreshed.config_layer_stack;
|
||||
let reviewer = &layers.requirements().approvals_reviewer;
|
||||
assert!(
|
||||
reviewer
|
||||
.can_set(&codex_config::types::ApprovalsReviewer::User)
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
reviewer
|
||||
.can_set(&codex_config::types::ApprovalsReviewer::AutoReview)
|
||||
.is_ok()
|
||||
);
|
||||
assert_eq!(
|
||||
layers
|
||||
.requirements_toml()
|
||||
.allowed_approvals_reviewers
|
||||
.as_deref(),
|
||||
Some([codex_config::types::ApprovalsReviewer::AutoReview].as_slice())
|
||||
);
|
||||
assert!(
|
||||
layers
|
||||
.requirements()
|
||||
.auto_review_required_for_model("protected")
|
||||
);
|
||||
assert!(
|
||||
!layers
|
||||
.requirements()
|
||||
.auto_review_required_for_model("incoming")
|
||||
);
|
||||
assert_eq!(
|
||||
layers
|
||||
.requirements_toml()
|
||||
.auto_review
|
||||
.as_ref()
|
||||
.and_then(|review| review.required_on_models.as_deref())
|
||||
.unwrap(),
|
||||
["protected"]
|
||||
);
|
||||
assert!(refreshed.features.enabled(Feature::McpSharedReplCwd));
|
||||
assert_eq!(
|
||||
layers.guardian_config().unwrap().policy.as_deref(),
|
||||
Some("published")
|
||||
);
|
||||
assert!(layers.guardian_policy_binding().is_some());
|
||||
let server = &runtime_servers(&refreshed)["enterprise"];
|
||||
assert!(!server.enabled);
|
||||
assert_eq!(
|
||||
|
||||
@@ -24,6 +24,7 @@ use crate::mcp::McpManager;
|
||||
use crate::plugins::list_tool_suggest_discoverable_plugins;
|
||||
use crate::plugins::plugins_manager_for_config_with_runtime;
|
||||
use crate::session::INITIAL_SUBMIT_ID;
|
||||
use codex_config::ConfigRequirements;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use codex_config::types::ToolSuggestDiscoverableType;
|
||||
use codex_core_plugins::PluginsManager;
|
||||
@@ -509,13 +510,13 @@ pub fn with_app_plugin_sources(
|
||||
|
||||
pub(crate) fn mcp_approvals_reviewer_from_layers(
|
||||
config_layer_stack: &codex_config::ConfigLayerStack,
|
||||
requirements: &ConfigRequirements,
|
||||
default_reviewer: ApprovalsReviewer,
|
||||
model: Option<&str>,
|
||||
server_name: &str,
|
||||
connector_id: Option<&str>,
|
||||
link_id: Option<&str>,
|
||||
) -> ApprovalsReviewer {
|
||||
let requirements = config_layer_stack.requirements();
|
||||
if model.is_some_and(|model| requirements.auto_review_required_for_model(model)) {
|
||||
return ApprovalsReviewer::AutoReview;
|
||||
}
|
||||
@@ -543,7 +544,15 @@ pub(crate) fn mcp_approvals_reviewer_from_layers(
|
||||
return reviewer;
|
||||
}
|
||||
|
||||
default_reviewer
|
||||
if requirements
|
||||
.approvals_reviewer
|
||||
.can_set(&default_reviewer)
|
||||
.is_ok()
|
||||
{
|
||||
default_reviewer
|
||||
} else {
|
||||
requirements.approvals_reviewer.value()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -371,6 +371,7 @@ approvals_reviewer = "{app}"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.config_layer_stack.requirements(),
|
||||
config.approvals_reviewer,
|
||||
config.model.as_deref(),
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
@@ -384,6 +385,7 @@ approvals_reviewer = "{app}"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.config_layer_stack.requirements(),
|
||||
config.approvals_reviewer,
|
||||
config.model.as_deref(),
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
@@ -396,6 +398,7 @@ approvals_reviewer = "{app}"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.config_layer_stack.requirements(),
|
||||
config.approvals_reviewer,
|
||||
config.model.as_deref(),
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
@@ -407,6 +410,7 @@ approvals_reviewer = "{app}"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.config_layer_stack.requirements(),
|
||||
config.approvals_reviewer,
|
||||
config.model.as_deref(),
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
@@ -418,6 +422,7 @@ approvals_reviewer = "{app}"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.config_layer_stack.requirements(),
|
||||
config.approvals_reviewer,
|
||||
config.model.as_deref(),
|
||||
"custom_server",
|
||||
@@ -456,7 +461,8 @@ approvals_reviewer = "user"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.approvals_reviewer,
|
||||
config.config_layer_stack.requirements(),
|
||||
ApprovalsReviewer::User,
|
||||
config.model.as_deref(),
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
Some("calendar"),
|
||||
@@ -497,6 +503,7 @@ approvals_reviewer = "user"
|
||||
assert_eq!(
|
||||
mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
config.config_layer_stack.requirements(),
|
||||
config.approvals_reviewer,
|
||||
config.model.as_deref(),
|
||||
CODEX_APPS_MCP_SERVER_NAME,
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! The synchronous service captures one action; no outcome is stored by tool-call ID.
|
||||
|
||||
use codex_async_utils::THREAD_STACK_SIZE_BYTES;
|
||||
use codex_protocol::config_types::ApprovalsReviewer;
|
||||
use codex_protocol::openai_models::GuardianScope;
|
||||
use codex_protocol::protocol::ReviewDecision;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::oneshot;
|
||||
@@ -104,15 +106,32 @@ pub(crate) fn decide_approval(
|
||||
let turn = context.turn();
|
||||
turn.extension_data.insert_arc(Arc::clone(&turn.config));
|
||||
let live_config = session.get_config().await;
|
||||
let requirements = live_config.config_layer_stack.requirements();
|
||||
let model_requires_review =
|
||||
requirements.auto_review_required_for_model(&context.model_info.slug);
|
||||
let mcp_requirements = (matches!(
|
||||
request.request,
|
||||
Ok(GuardianApprovalRequest::McpToolCall { .. })
|
||||
) || (request.request.is_err()
|
||||
&& matches!(
|
||||
request.category,
|
||||
GuardianScope::Mcp | GuardianScope::ComputerUse
|
||||
)))
|
||||
.then(|| turn.config.config_layer_stack.requirements());
|
||||
// Live requirements can harden review. MCP also keeps any mandatory
|
||||
// restrictions from the policy captured for its issuing turn.
|
||||
let requirements = [
|
||||
Some(live_config.config_layer_stack.requirements()),
|
||||
mcp_requirements,
|
||||
];
|
||||
let model_requires_review = requirements.iter().flatten().any(|requirements| {
|
||||
requirements.auto_review_required_for_model(&context.model_info.slug)
|
||||
});
|
||||
let require_guardian = options.require_guardian
|
||||
|| model_requires_review
|
||||
|| requirements
|
||||
.approvals_reviewer
|
||||
.can_set(&codex_protocol::config_types::ApprovalsReviewer::User)
|
||||
.is_err();
|
||||
|| requirements.iter().flatten().any(|requirements| {
|
||||
requirements
|
||||
.approvals_reviewer
|
||||
.can_set(&ApprovalsReviewer::User)
|
||||
.is_err()
|
||||
});
|
||||
let full_access = context.environments().has_full_access(
|
||||
context.approval_policy,
|
||||
&turn.config.permissions.effective_permission_profile(),
|
||||
|
||||
@@ -20,8 +20,6 @@ use codex_config::ConfigLayerStack;
|
||||
use codex_config::NetworkConstraints;
|
||||
use codex_config::NetworkDomainPermissionToml;
|
||||
use codex_config::NetworkDomainPermissionsToml;
|
||||
use codex_config::RequirementSource;
|
||||
use codex_config::Sourced;
|
||||
use codex_config::config_toml::ConfigToml;
|
||||
use codex_config::types::McpServerConfig;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
@@ -2952,25 +2950,22 @@ async fn guardian_review_routes_required_actions(
|
||||
| RequiredGuardianReview::LiveManagedModelWithGuardianV2 => {
|
||||
Arc::make_mut(&mut context.model_info).slug = "required-action-model".to_string();
|
||||
// The admitted turn has neither this model nor the new requirement.
|
||||
let current_config = session.get_config().await;
|
||||
let mut config = current_config.as_ref().clone();
|
||||
let requirements = codex_config::ConfigRequirements {
|
||||
auto_review_required_models: Some(Sourced::new(
|
||||
std::collections::BTreeSet::from([context.model_info.slug.clone()]),
|
||||
RequirementSource::Unknown,
|
||||
)),
|
||||
..Default::default()
|
||||
};
|
||||
config.config_layer_stack = ConfigLayerStack::new(
|
||||
config
|
||||
.config_layer_stack
|
||||
.all_layers_low_to_high()
|
||||
.cloned()
|
||||
.collect(),
|
||||
requirements,
|
||||
config.config_layer_stack.requirements_toml().clone(),
|
||||
)?;
|
||||
let _ = session.refresh_mcp_config(current_config, config).await;
|
||||
let model = &context.model_info.slug;
|
||||
let loader = codex_config::test_support::CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
format!("auto_review.required_on_models = [{model:?}]"),
|
||||
);
|
||||
let snapshot = codex_config::loader::load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
turn.config.codex_home.as_path(),
|
||||
&codex_config::LoaderOverrides::without_managed_config_for_tests(),
|
||||
&loader,
|
||||
/*revision*/ 1,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
session.refresh_guardian_policy(&snapshot).await,
|
||||
crate::ConfigRefreshOutcome::Published
|
||||
);
|
||||
(
|
||||
guardian_exec_command_request("shell-live-managed-model"),
|
||||
ApprovalRequestReasons::default(),
|
||||
|
||||
@@ -35,6 +35,7 @@ use codex_analytics::build_track_events_context;
|
||||
use codex_api::HostedFileUploadContext;
|
||||
use codex_config::ConfigLayerSource;
|
||||
use codex_config::types::AppToolApproval;
|
||||
use codex_config::types::ApprovalsReviewer;
|
||||
use codex_connectors::AppToolPolicy;
|
||||
use codex_connectors::AppToolPolicyEvaluator;
|
||||
use codex_connectors::AppToolPolicyInput;
|
||||
@@ -239,8 +240,6 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
}
|
||||
};
|
||||
let item_metadata = McpToolCallItemMetadata::from_tool_metadata(&server, Some(&metadata));
|
||||
let connector_id = metadata.connector_id.clone();
|
||||
let connector_name = metadata.connector_name.clone();
|
||||
|
||||
let Some(approval_policy) = mcp_tool_approval_policy(&prepared_call, &metadata) else {
|
||||
let result = notify_mcp_tool_call_skip(
|
||||
@@ -260,8 +259,8 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
&outcome,
|
||||
&server,
|
||||
&tool_name,
|
||||
connector_id.as_deref(),
|
||||
connector_name.as_deref(),
|
||||
metadata.connector_id.as_deref(),
|
||||
metadata.connector_name.as_deref(),
|
||||
/*duration*/ None,
|
||||
);
|
||||
return Ok(CompletedMcpToolCall {
|
||||
@@ -270,14 +269,17 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
.unwrap_or_else(|| JsonValue::Object(serde_json::Map::new())),
|
||||
});
|
||||
};
|
||||
let _approval_metadata = sess.register_mcp_tool_approval_metadata(
|
||||
let requested_reviewer = sess.mcp_requested_reviewer(&step_context.settings).await;
|
||||
let approval_context = sess.register_mcp_tool_approval_metadata(
|
||||
&call_id,
|
||||
prepared_call.server_key(),
|
||||
&invocation,
|
||||
metadata.clone(),
|
||||
metadata,
|
||||
GuardianReviewContext::from(step_context),
|
||||
capture_environment_permissions(prepared_call.permission_source()),
|
||||
requested_reviewer,
|
||||
);
|
||||
let metadata = &approval_context.metadata;
|
||||
notify_mcp_tool_call_started(
|
||||
sess.as_ref(),
|
||||
turn_context.as_ref(),
|
||||
@@ -295,12 +297,13 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
&invocation,
|
||||
&invocation_tool_name,
|
||||
&hook_tool_name,
|
||||
&metadata,
|
||||
metadata,
|
||||
prepared_call.config(),
|
||||
prepared_call.permission_source(),
|
||||
prepared_call.server_environment_id(),
|
||||
prepared_call.server_key(),
|
||||
approval_policy,
|
||||
requested_reviewer,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -392,8 +395,8 @@ pub(crate) async fn handle_mcp_tool_call(
|
||||
&outcome,
|
||||
&server,
|
||||
&tool_name,
|
||||
connector_id.as_deref(),
|
||||
connector_name.as_deref(),
|
||||
metadata.connector_id.as_deref(),
|
||||
metadata.connector_name.as_deref(),
|
||||
/*duration*/ None,
|
||||
);
|
||||
|
||||
@@ -482,7 +485,7 @@ async fn handle_approved_mcp_tool_call(
|
||||
originating_call: Option<&ToolCallOrigin>,
|
||||
invocation: McpInvocation,
|
||||
prepared_call: PreparedMcpCall,
|
||||
metadata: McpToolApprovalMetadata,
|
||||
metadata: &McpToolApprovalMetadata,
|
||||
item_metadata: McpToolCallItemMetadata,
|
||||
source: &crate::tools::context::ToolCallSource,
|
||||
approval_application: McpToolApprovalApplication,
|
||||
@@ -556,13 +559,13 @@ async fn handle_approved_mcp_tool_call(
|
||||
let session_approval_key = session_mcp_tool_approval_key(
|
||||
prepared_call.server_key(),
|
||||
&invocation,
|
||||
Some(&metadata),
|
||||
Some(metadata),
|
||||
policy.mode,
|
||||
);
|
||||
let persistent_approval_key = if policy.allow_persistent {
|
||||
persistent_mcp_tool_approval_key(
|
||||
&invocation,
|
||||
Some(&metadata),
|
||||
Some(metadata),
|
||||
policy.mode,
|
||||
)
|
||||
} else {
|
||||
@@ -605,7 +608,7 @@ async fn handle_approved_mcp_tool_call(
|
||||
step_context,
|
||||
&server,
|
||||
call_id,
|
||||
Some(&metadata),
|
||||
Some(metadata),
|
||||
prepared_call.is_host_owned_apps(),
|
||||
);
|
||||
if let Some(recipient) = sess
|
||||
@@ -750,7 +753,7 @@ async fn handle_approved_mcp_tool_call(
|
||||
prepared_call.config().approval_policy.value(),
|
||||
call_id,
|
||||
&invocation.server,
|
||||
Some(&metadata),
|
||||
Some(metadata),
|
||||
result,
|
||||
)
|
||||
.await)
|
||||
@@ -817,7 +820,7 @@ async fn handle_approved_mcp_tool_call(
|
||||
truncate_mcp_tool_result_for_event(&result),
|
||||
)
|
||||
.await;
|
||||
maybe_track_codex_app_used(sess, step_context, &server, &metadata, elicitation_type).await;
|
||||
maybe_track_codex_app_used(sess, step_context, &server, metadata, elicitation_type).await;
|
||||
|
||||
let outcome = mcp_call_metric_outcome(&result).with_request_error_code(request_error_code);
|
||||
emit_mcp_call_metrics(
|
||||
@@ -1367,11 +1370,11 @@ pub(crate) struct McpToolApprovalMetadata {
|
||||
openai_file_input_optional_fields: Option<HashMap<String, Vec<String>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct McpToolApprovalContext {
|
||||
pub(crate) invocation: Option<McpInvocation>,
|
||||
pub(crate) metadata: McpToolApprovalMetadata,
|
||||
pub(crate) review_context: GuardianReviewContext,
|
||||
pub(crate) requested_reviewer: ApprovalsReviewer,
|
||||
/// Rules captured when MCP prepared this call, if the server belongs to an environment.
|
||||
pub(crate) environment_permissions: Option<(String, Arc<FileSystemSandboxContext>)>,
|
||||
}
|
||||
@@ -1389,6 +1392,7 @@ pub(crate) fn capture_environment_permissions(
|
||||
}
|
||||
|
||||
impl Session {
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn register_mcp_tool_approval_metadata(
|
||||
&self,
|
||||
call_id: &str,
|
||||
@@ -1397,6 +1401,7 @@ impl Session {
|
||||
metadata: McpToolApprovalMetadata,
|
||||
review_context: GuardianReviewContext,
|
||||
environment_permissions: Option<(String, Arc<FileSystemSandboxContext>)>,
|
||||
requested_reviewer: ApprovalsReviewer,
|
||||
) -> Arc<McpToolApprovalContext> {
|
||||
let key = (server_key.to_owned(), call_id.to_string());
|
||||
let metadata = Arc::new(McpToolApprovalContext {
|
||||
@@ -1405,6 +1410,7 @@ impl Session {
|
||||
.then(|| invocation.clone()),
|
||||
metadata,
|
||||
review_context,
|
||||
requested_reviewer,
|
||||
environment_permissions,
|
||||
});
|
||||
let mut registry = self
|
||||
@@ -1422,13 +1428,12 @@ impl Session {
|
||||
&self,
|
||||
server: &McpServerKey,
|
||||
call_id: &str,
|
||||
) -> Option<McpToolApprovalContext> {
|
||||
) -> Option<Arc<McpToolApprovalContext>> {
|
||||
self.mcp_tool_approval_metadata
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(&(server.clone(), call_id.to_string()))
|
||||
.and_then(std::sync::Weak::upgrade)
|
||||
.map(|metadata| (*metadata).clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1711,20 +1716,10 @@ async fn prepare_mcp_tool_approval(
|
||||
environment_id: &str,
|
||||
server_key: &McpServerKey,
|
||||
policy: McpToolApprovalPolicy,
|
||||
requested_reviewer: ApprovalsReviewer,
|
||||
) -> McpToolApprovalRequirement {
|
||||
let turn_context = &step_context.turn;
|
||||
let strict_auto_review = turn_context.strict_auto_review_enabled();
|
||||
let approvals_reviewer = connectors::mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
step_context
|
||||
.settings
|
||||
.mcp_approvals_reviewer_override
|
||||
.unwrap_or(config.approvals_reviewer),
|
||||
Some(turn_context.model_info().slug.as_str()),
|
||||
&invocation.server,
|
||||
metadata.connector_id.as_deref(),
|
||||
metadata.link_id.as_deref(),
|
||||
);
|
||||
if !strict_auto_review
|
||||
&& mcp_permission_prompt_is_auto_approved(
|
||||
config.approval_policy.value(),
|
||||
@@ -1756,6 +1751,15 @@ async fn prepare_mcp_tool_approval(
|
||||
return McpToolApprovalRequirement::Remembered;
|
||||
}
|
||||
|
||||
let approvals_reviewer = connectors::mcp_approvals_reviewer_from_layers(
|
||||
&config.config_layer_stack,
|
||||
turn_context.config.config_layer_stack.requirements(),
|
||||
requested_reviewer,
|
||||
Some(step_context.settings.model_info.slug.as_str()),
|
||||
&invocation.server,
|
||||
metadata.connector_id.as_deref(),
|
||||
metadata.link_id.as_deref(),
|
||||
);
|
||||
let action = ApprovalAction::McpToolCall {
|
||||
id: call_id.to_string(),
|
||||
environment_id: environment_id.to_owned(),
|
||||
@@ -1808,6 +1812,7 @@ async fn maybe_request_mcp_tool_approval(
|
||||
environment_id: &str,
|
||||
server_key: &McpServerKey,
|
||||
policy: McpToolApprovalPolicy,
|
||||
requested_reviewer: ApprovalsReviewer,
|
||||
) -> Option<McpToolApproval> {
|
||||
let (action, strict_auto_review) = match prepare_mcp_tool_approval(
|
||||
sess,
|
||||
@@ -1821,6 +1826,7 @@ async fn maybe_request_mcp_tool_approval(
|
||||
environment_id,
|
||||
server_key,
|
||||
policy,
|
||||
requested_reviewer,
|
||||
)
|
||||
.await
|
||||
{
|
||||
@@ -1943,9 +1949,11 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
.push_str(&format!(" Environment: {environment_id}."));
|
||||
}
|
||||
let (decision, cancellation_reason) = if tool_call_mcp_elicitation_enabled {
|
||||
let metadata = approval_context
|
||||
.map(|context| context.metadata)
|
||||
.unwrap_or_else(|| McpToolApprovalMetadata {
|
||||
let fallback_metadata;
|
||||
let metadata = if let Some(context) = approval_context.as_ref() {
|
||||
&context.metadata
|
||||
} else {
|
||||
fallback_metadata = McpToolApprovalMetadata {
|
||||
connector_id: connector_id.clone(),
|
||||
connector_name: connector_name.clone(),
|
||||
connector_description: connector_description.clone(),
|
||||
@@ -1953,13 +1961,15 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
tool_title: tool_title.clone(),
|
||||
tool_description: tool_description.clone(),
|
||||
..Default::default()
|
||||
});
|
||||
};
|
||||
&fallback_metadata
|
||||
};
|
||||
let request_id = rmcp::model::RequestId::String(question_id.clone().into());
|
||||
let request =
|
||||
build_mcp_tool_approval_elicitation_request(McpToolApprovalElicitationRequest {
|
||||
server,
|
||||
tool_name,
|
||||
metadata: Some(&metadata),
|
||||
metadata: Some(metadata),
|
||||
tool_params: rendered_template
|
||||
.as_ref()
|
||||
.and_then(|rendered_template| rendered_template.tool_params.as_ref())
|
||||
@@ -1971,6 +1981,7 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
.map(|rendered_template| rendered_template.elicitation_message.as_str()),
|
||||
prompt_options,
|
||||
});
|
||||
drop(approval_context);
|
||||
let response = sess
|
||||
.request_mcp_server_elicitation(turn_context, server_key.clone(), request_id, request)
|
||||
.await;
|
||||
@@ -1990,6 +2001,7 @@ pub(crate) async fn request_mcp_tool_user_approval(
|
||||
cancellation_reason,
|
||||
)
|
||||
} else {
|
||||
drop(approval_context);
|
||||
if turn_context.root_capabilities_restricted {
|
||||
return ApprovalResolution {
|
||||
decision: ReviewDecision::denied(concat!(
|
||||
|
||||
@@ -48,6 +48,10 @@ pub(crate) async fn prepare_approval_action(
|
||||
let policy = mcp_tool_approval_policy(&call, &metadata).ok_or_else(|| {
|
||||
FunctionCallError::RespondToModel("MCP tool call blocked by app configuration".into())
|
||||
})?;
|
||||
let requested_reviewer = invocation
|
||||
.session
|
||||
.mcp_requested_reviewer(&invocation.step_context.settings)
|
||||
.await;
|
||||
match prepare_mcp_tool_approval(
|
||||
&invocation.session,
|
||||
&invocation.step_context,
|
||||
@@ -60,6 +64,7 @@ pub(crate) async fn prepare_approval_action(
|
||||
call.server_environment_id(),
|
||||
call.server_key(),
|
||||
policy,
|
||||
requested_reviewer,
|
||||
)
|
||||
.await
|
||||
{
|
||||
|
||||
@@ -3068,6 +3068,7 @@ async fn approve_mode_skips_when_annotations_do_not_require_approval() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Approve),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3153,6 +3154,7 @@ async fn guardian_mode_skips_auto_when_annotations_do_not_require_approval() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Auto),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3222,6 +3224,7 @@ async fn permission_request_hook_allows_mcp_tool_call() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Auto),
|
||||
turn_context.config.approvals_reviewer,
|
||||
),
|
||||
)
|
||||
.await
|
||||
@@ -3307,6 +3310,7 @@ async fn permission_request_hook_uses_hook_tool_name_without_metadata() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Auto),
|
||||
turn_context.config.approvals_reviewer,
|
||||
),
|
||||
)
|
||||
.await
|
||||
@@ -3410,6 +3414,7 @@ async fn permission_request_hook_runs_after_remembered_mcp_approval() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Auto),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3528,6 +3533,7 @@ async fn strict_auto_review_forces_guardian_for_mcp_policy_skip(
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(approval_mode),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3615,6 +3621,7 @@ async fn assert_mcp_user_approval_persistence(
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Auto),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await
|
||||
}
|
||||
@@ -3705,6 +3712,7 @@ async fn prompt_mode_waits_for_approval_when_annotations_do_not_require_approval
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Prompt),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await
|
||||
})
|
||||
@@ -3775,6 +3783,7 @@ async fn full_access_mode_skips_mcp_tool_approval_for_all_approval_modes() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(approval_mode),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3873,6 +3882,7 @@ async fn approve_mode_skips_guardian_in_every_permission_mode() {
|
||||
test_environment_id(&turn_context),
|
||||
&McpServerKey::unscoped(&invocation.server),
|
||||
McpToolApprovalPolicy::for_server(AppToolApproval::Approve),
|
||||
turn_context.config.approvals_reviewer,
|
||||
)
|
||||
.await;
|
||||
|
||||
@@ -3905,6 +3915,7 @@ async fn approval_metadata_is_released_when_the_invocation_future_is_dropped() {
|
||||
metadata.clone(),
|
||||
review_context.clone(),
|
||||
/*environment_permissions*/ None,
|
||||
ApprovalsReviewer::User,
|
||||
);
|
||||
std::future::pending::<()>().await;
|
||||
});
|
||||
@@ -3916,12 +3927,17 @@ async fn approval_metadata_is_released_when_the_invocation_future_is_dropped() {
|
||||
metadata.clone(),
|
||||
review_context.clone(),
|
||||
/*environment_permissions*/ None,
|
||||
ApprovalsReviewer::User,
|
||||
);
|
||||
assert_eq!(
|
||||
session
|
||||
.mcp_tool_approval_metadata(&McpServerKey::unscoped(CODEX_APPS_MCP_SERVER_NAME), "call")
|
||||
.map(|context| (context.invocation, context.metadata.connector_id)),
|
||||
Some((Some(invocation.clone()), Some("connector".to_string()))),
|
||||
.as_ref()
|
||||
.map(|context| (
|
||||
context.invocation.as_ref(),
|
||||
context.metadata.connector_id.as_deref()
|
||||
)),
|
||||
Some((Some(&invocation), Some("connector"))),
|
||||
);
|
||||
assert!(
|
||||
session
|
||||
@@ -3941,6 +3957,7 @@ async fn approval_metadata_is_released_when_the_invocation_future_is_dropped() {
|
||||
metadata,
|
||||
review_context,
|
||||
/*environment_permissions*/ None,
|
||||
ApprovalsReviewer::User,
|
||||
);
|
||||
let registry = session.mcp_tool_approval_metadata.lock().unwrap();
|
||||
let mut keys = registry.keys().cloned().collect::<Vec<_>>();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Publishes refreshable configuration while preserving unrelated session settings.
|
||||
//! Publishes independent Guardian policy, MCP configuration, and host rollouts.
|
||||
//! Preserves unrelated session settings.
|
||||
|
||||
use crate::McpRefreshReason;
|
||||
use std::sync::Arc;
|
||||
@@ -32,6 +33,76 @@ impl Session {
|
||||
self.schedule_mcp_prewarm();
|
||||
}
|
||||
|
||||
/// Publishes managed Guardian requirements without validating or restarting MCP.
|
||||
/// User and session fallbacks remain pinned until their own reload.
|
||||
pub(crate) async fn refresh_guardian_policy(
|
||||
&self,
|
||||
snapshot: &codex_config::GuardianPolicySnapshot,
|
||||
) -> ConfigRefreshOutcome {
|
||||
let mut state = self.state.lock().await;
|
||||
let current = &state.session_configuration.original_config_do_not_use;
|
||||
if snapshot.revision <= current.guardian_policy_revision {
|
||||
return ConfigRefreshOutcome::Stale;
|
||||
}
|
||||
let binding = snapshot
|
||||
.binding
|
||||
.as_ref()
|
||||
.map(codex_config::CloudConfigBundleBinding::read);
|
||||
match binding
|
||||
.as_ref()
|
||||
.map(|guard| guard.status)
|
||||
.unwrap_or(CloudConfigBundleBindingStatus::Current)
|
||||
{
|
||||
CloudConfigBundleBindingStatus::Stale => return ConfigRefreshOutcome::Stale,
|
||||
CloudConfigBundleBindingStatus::Suspended => return ConfigRefreshOutcome::Rejected,
|
||||
CloudConfigBundleBindingStatus::Current => {}
|
||||
}
|
||||
let mut config = current.as_ref().clone();
|
||||
config.config_layer_stack.apply_guardian_policy(snapshot);
|
||||
let Ok(fallback) = config.config_layer_stack.guardian_config() else {
|
||||
return ConfigRefreshOutcome::Rejected;
|
||||
};
|
||||
(config.guardian_policy_config, config.guardian_extra_policy) =
|
||||
crate::config::resolve_guardian_policy_text(
|
||||
config.config_layer_stack.requirements_toml(),
|
||||
Some(&fallback),
|
||||
);
|
||||
let configuration = &state.session_configuration;
|
||||
let model = (!configuration.trusted_guardian_reviewer)
|
||||
.then_some(configuration.step_settings.collaboration_mode.model());
|
||||
let requested = config
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or(configuration.step_settings.approvals_reviewer);
|
||||
let Ok(reviewer) = crate::config::resolve_guardian_reviewer(
|
||||
requested,
|
||||
model,
|
||||
config.config_layer_stack.requirements(),
|
||||
) else {
|
||||
return ConfigRefreshOutcome::Rejected;
|
||||
};
|
||||
config.requested_approvals_reviewer = Some(requested);
|
||||
config.approvals_reviewer = reviewer;
|
||||
config.guardian_policy_revision = snapshot.revision;
|
||||
let previous = Arc::downgrade(current);
|
||||
let config = Arc::new(config);
|
||||
let snapshots = &mut state.guardian_config_snapshots;
|
||||
if snapshots
|
||||
.last()
|
||||
.is_none_or(|latest| !latest.ptr_eq(&previous))
|
||||
{
|
||||
snapshots.clear();
|
||||
snapshots.push(previous);
|
||||
}
|
||||
snapshots.retain(|owner| owner.strong_count() != 0);
|
||||
snapshots.push(Arc::downgrade(&config));
|
||||
let settings = &mut state.session_configuration.step_settings;
|
||||
if settings.approvals_reviewer != reviewer {
|
||||
Arc::make_mut(settings).approvals_reviewer = reviewer;
|
||||
}
|
||||
state.session_configuration.original_config_do_not_use = config;
|
||||
ConfigRefreshOutcome::Published
|
||||
}
|
||||
|
||||
pub(crate) async fn refresh_runtime_config(
|
||||
&self,
|
||||
expected_config: Arc<Config>,
|
||||
@@ -127,19 +198,29 @@ impl Session {
|
||||
&& !self.services.extensions.config_contributors().is_empty();
|
||||
let (previous_config, new_config) = {
|
||||
let mut state = self.state.lock().await;
|
||||
// Loaded snapshots can publish only while their captured owner is current.
|
||||
if !Arc::ptr_eq(
|
||||
&state.session_configuration.original_config_do_not_use,
|
||||
&expected_config,
|
||||
) {
|
||||
return ConfigRefreshOutcome::Stale;
|
||||
let current = &state.session_configuration.original_config_do_not_use;
|
||||
if !Arc::ptr_eq(current, &expected_config) {
|
||||
let snapshots = &state.guardian_config_snapshots;
|
||||
if !matches!(scope, RuntimeConfigRefresh::Mcp)
|
||||
|| snapshots
|
||||
.last()
|
||||
.is_none_or(|latest| !std::ptr::eq(latest.as_ptr(), Arc::as_ptr(current)))
|
||||
|| !snapshots
|
||||
.iter()
|
||||
.any(|owner| std::ptr::eq(owner.as_ptr(), Arc::as_ptr(&expected_config)))
|
||||
{
|
||||
return ConfigRefreshOutcome::Stale;
|
||||
}
|
||||
// All MCP inputs still belong to the captured owner. Carry forward
|
||||
// the Guardian policy that was published while we loaded them.
|
||||
Arc::make_mut(&mut config).retain_guardian_policy_from(current);
|
||||
}
|
||||
// User-only refreshes retain the current managed inputs and their
|
||||
// admission binding. Only MCP refreshes can publish a new policy.
|
||||
// admission binding. Guardian policy has a separate publication path.
|
||||
let policy_guard = matches!(scope, RuntimeConfigRefresh::Mcp)
|
||||
.then(|| next_config.config_layer_stack.cloud_config_binding())
|
||||
.flatten()
|
||||
.map(|binding| binding.read());
|
||||
.map(codex_config::CloudConfigBundleBinding::read);
|
||||
let policy_status = policy_guard
|
||||
.as_ref()
|
||||
.map(|guard| guard.status)
|
||||
@@ -193,6 +274,7 @@ impl Session {
|
||||
.with_mcp_ema_cancellation(cancellation);
|
||||
}
|
||||
state.session_configuration.original_config_do_not_use = Arc::clone(&config);
|
||||
state.guardian_config_snapshots.clear();
|
||||
drop(policy_guard);
|
||||
self.mark_mcp_runtime_dirty(match scope {
|
||||
RuntimeConfigRefresh::User => McpRefreshReason::UserConfigReloaded,
|
||||
|
||||
@@ -1,8 +1,57 @@
|
||||
//! Runtime-refresh regressions; pure authority resolution is tested with Config.
|
||||
|
||||
use super::*;
|
||||
use codex_config::loader::load_guardian_policy_snapshot;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_reload_survives_guardian_only_publications() {
|
||||
let (session, _) = make_session_and_context().await;
|
||||
let before = session.get_config().await;
|
||||
let mut incoming = before.as_ref().clone();
|
||||
incoming.config_layer_stack = incoming
|
||||
.config_layer_stack
|
||||
.with_session_plugins(toml::from_str("[_default]\nenabled = false").unwrap())
|
||||
.unwrap();
|
||||
let first_revision = before.guardian_policy_revision + 1;
|
||||
let latest_revision = first_revision + 1;
|
||||
for (revision, policy) in [
|
||||
(first_revision, "first policy"),
|
||||
(latest_revision, "latest policy"),
|
||||
] {
|
||||
let loader = CloudConfigBundleFixture::loader_with_enterprise_requirement(format!(
|
||||
"guardian_policy_config = {policy:?}"
|
||||
));
|
||||
let snapshot = load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
before.codex_home.as_path(),
|
||||
&LoaderOverrides::without_managed_config_for_tests(),
|
||||
&loader,
|
||||
revision,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
session.refresh_guardian_policy(&snapshot).await,
|
||||
crate::ConfigRefreshOutcome::Published
|
||||
);
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
session.refresh_mcp_config(before, incoming).await,
|
||||
crate::ConfigRefreshOutcome::Published
|
||||
);
|
||||
let published = session.get_config().await;
|
||||
assert!(!published.plugins.allows_plugin("browser"));
|
||||
assert_eq!(published.guardian_policy_revision, latest_revision);
|
||||
assert_eq!(
|
||||
published.guardian_policy_config.as_deref(),
|
||||
Some("latest policy")
|
||||
);
|
||||
}
|
||||
|
||||
async fn runtime_servers(session: &Session) -> HashMap<String, McpServerConfig> {
|
||||
let config = session.get_config().await;
|
||||
codex_mcp::configured_mcp_servers(
|
||||
|
||||
@@ -805,6 +805,22 @@ impl Session {
|
||||
)
|
||||
}
|
||||
|
||||
/// Older clients keep using the thread preference until a turn update
|
||||
/// overrides it. That preference is resolved against the issuing turn's rules.
|
||||
pub(crate) async fn mcp_requested_reviewer(
|
||||
&self,
|
||||
settings: &ResolvedStepSettings,
|
||||
) -> ApprovalsReviewer {
|
||||
match settings.mcp_approvals_reviewer_override {
|
||||
Some(reviewer) => reviewer,
|
||||
None => self
|
||||
.get_config()
|
||||
.await
|
||||
.requested_approvals_reviewer
|
||||
.unwrap_or_else(|| settings.approvals_reviewer()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mcp_elicitation_lifecycle(&self) -> codex_mcp::ElicitationLifecycle {
|
||||
self.mcp_elicitation_lifecycle_handle
|
||||
.get_or_init(|| {
|
||||
@@ -1053,7 +1069,6 @@ async fn review_guardian_mcp_elicitation(
|
||||
let Some(mcp_config) = session.services.mcp_runtime.current_config() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let step_settings = turn_context.next_step_settings.load_full();
|
||||
// A callback for a running call keeps the permissions captured by that call.
|
||||
let call_id = request
|
||||
.elicitation
|
||||
@@ -1065,13 +1080,18 @@ async fn review_guardian_mcp_elicitation(
|
||||
.and_then(Value::as_str);
|
||||
let approval_context = call_id
|
||||
.and_then(|call_id| session.mcp_tool_approval_metadata(&request.server_key, call_id));
|
||||
let step_settings = turn_context.next_step_settings.load_full();
|
||||
let reviewer = approval_context.as_ref().map_or_else(
|
||||
|| step_settings.approvals_reviewer(),
|
||||
|context| context.review_context.approvals_reviewer,
|
||||
);
|
||||
|
||||
let is_js_preflight = request.elicitation.meta().is_some_and(|meta| {
|
||||
metadata_str(meta, MCP_ELICITATION_TOOL_NAME_KEY) == Some("js")
|
||||
&& metadata_str(meta, MCP_ELICITATION_CONNECTOR_ID_KEY) == Some("node_repl")
|
||||
});
|
||||
// User approval skips ordinary CUA checks, not separate sensitive requests.
|
||||
let user_cua_execution = step_settings.approvals_reviewer() == ApprovalsReviewer::User
|
||||
let user_cua_execution = reviewer == ApprovalsReviewer::User
|
||||
&& is_node_repl_backed_server(&request.server_name)
|
||||
&& is_js_preflight
|
||||
&& request.elicitation.meta().is_some_and(|meta| {
|
||||
@@ -1148,7 +1168,7 @@ async fn review_guardian_mcp_elicitation(
|
||||
invocation: Some(invocation),
|
||||
metadata,
|
||||
..
|
||||
}) = approval_context.as_ref()
|
||||
}) = approval_context.as_deref()
|
||||
&& invocation.server == request.server_name
|
||||
&& is_node_repl_backed_connector(&invocation.server, metadata.connector_id.as_deref())
|
||||
{
|
||||
@@ -1165,12 +1185,19 @@ async fn review_guardian_mcp_elicitation(
|
||||
Some(Value::Bool(true))
|
||||
);
|
||||
|
||||
// Bind the review to the issuing step, which may include environments that
|
||||
// became ready after the turn started. Do not refresh an in-flight action.
|
||||
// Use the issuing step, or the active turn's captured policy when there is no invocation.
|
||||
let mut review_context = approval_context
|
||||
.as_ref()
|
||||
.map(|context| context.review_context.clone())
|
||||
.unwrap_or_else(|| crate::guardian::GuardianReviewContext::from(&turn_context));
|
||||
.unwrap_or_else(|| {
|
||||
crate::guardian::GuardianReviewContext::from_resolved_settings(
|
||||
Arc::clone(&turn_context),
|
||||
&step_settings,
|
||||
&turn_context.initial_environments,
|
||||
)
|
||||
});
|
||||
let review_config = &review_context.turn().config;
|
||||
let requirements = review_config.config_layer_stack.requirements();
|
||||
let strict_auto_review = matches!(
|
||||
request
|
||||
.elicitation
|
||||
@@ -1192,7 +1219,7 @@ async fn review_guardian_mcp_elicitation(
|
||||
invocation: Some(invocation),
|
||||
metadata,
|
||||
..
|
||||
}) = approval_context.as_ref()
|
||||
}) = approval_context.as_deref()
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
@@ -1216,20 +1243,16 @@ async fn review_guardian_mcp_elicitation(
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if !turn_context
|
||||
.config
|
||||
.features
|
||||
.enabled(Feature::GuardianApproval)
|
||||
|| mcp_config
|
||||
.config_layer_stack
|
||||
.requirements()
|
||||
if !review_config.features.enabled(Feature::GuardianApproval)
|
||||
|| requirements
|
||||
.approvals_reviewer
|
||||
.can_set(&ApprovalsReviewer::AutoReview)
|
||||
.is_err()
|
||||
|| crate::connectors::mcp_approvals_reviewer_from_layers(
|
||||
&mcp_config.config_layer_stack,
|
||||
requirements,
|
||||
ApprovalsReviewer::AutoReview,
|
||||
Some(turn_context.model_info().slug.as_str()),
|
||||
Some(review_context.model_info.slug.as_str()),
|
||||
request.server_name.as_str(),
|
||||
connector_id,
|
||||
/*link_id*/ None,
|
||||
@@ -1294,12 +1317,15 @@ async fn review_guardian_mcp_elicitation(
|
||||
| AskForApproval::Granular(_) => {}
|
||||
}
|
||||
|
||||
let requested_reviewer = match &approval_context {
|
||||
Some(context) => context.requested_reviewer,
|
||||
None => session.mcp_requested_reviewer(&step_settings).await,
|
||||
};
|
||||
let approvals_reviewer = crate::connectors::mcp_approvals_reviewer_from_layers(
|
||||
&mcp_config.config_layer_stack,
|
||||
step_settings
|
||||
.mcp_approvals_reviewer_override
|
||||
.unwrap_or(mcp_config.approvals_reviewer),
|
||||
Some(turn_context.model_info().slug.as_str()),
|
||||
requirements,
|
||||
requested_reviewer,
|
||||
Some(review_context.model_info.slug.as_str()),
|
||||
request.server_name.as_str(),
|
||||
elicitation_connector_id(&request.elicitation),
|
||||
/*link_id*/ None,
|
||||
@@ -1360,6 +1386,8 @@ async fn review_guardian_mcp_elicitation(
|
||||
*prompt_permissions = Some(permissions);
|
||||
}
|
||||
let declined_reason = guardian_request.request.as_ref().err().cloned();
|
||||
// Release the registry entry before awaiting review. The tool owns its lifetime.
|
||||
drop(approval_context);
|
||||
let decision = crate::guardian::decide_approval(
|
||||
session,
|
||||
review_context,
|
||||
|
||||
@@ -41,7 +41,6 @@ impl Session {
|
||||
|| current.runtime_workspace_roots != next.runtime_workspace_roots
|
||||
|| current.step_settings.approval_policy.value()
|
||||
!= next.step_settings.approval_policy.value()
|
||||
|| current.step_settings.approvals_reviewer != next.step_settings.approvals_reviewer
|
||||
|| current.permission_profile() != next.permission_profile()
|
||||
|| current.windows_sandbox_level != next.windows_sandbox_level
|
||||
}
|
||||
|
||||
@@ -434,7 +434,7 @@ impl Session {
|
||||
environments,
|
||||
),
|
||||
};
|
||||
current
|
||||
let settings = current
|
||||
.apply_update(
|
||||
update,
|
||||
&constraints,
|
||||
@@ -443,7 +443,23 @@ impl Session {
|
||||
&self.features,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| error.to_string())
|
||||
.map_err(|error| error.to_string())?;
|
||||
// Changes to the selected model or reviewer must also satisfy the
|
||||
// policy that continues to apply to this turn's MCP actions.
|
||||
if update.approvals_reviewer.is_some() || update.model.is_some() {
|
||||
let requirements = turn_context.config.config_layer_stack.requirements();
|
||||
requirements
|
||||
.approvals_reviewer
|
||||
.can_set(&settings.approvals_reviewer())
|
||||
.and_then(|()| {
|
||||
settings.selected().validate(&StepSettingsConstraints {
|
||||
requirements,
|
||||
..constraints
|
||||
})
|
||||
})
|
||||
.map_err(|error| error.to_string())?;
|
||||
}
|
||||
Ok(settings)
|
||||
}
|
||||
|
||||
/// Rechecks ordinary managed authorization after asynchronous resolution.
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::collections::BTreeSet;
|
||||
use std::collections::HashSet;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Weak;
|
||||
|
||||
use super::AdditionalContextStore;
|
||||
use super::auto_compact_window::AutoCompactWindow;
|
||||
@@ -17,6 +18,7 @@ use super::auto_compact_window::AutoCompactWindowSnapshot;
|
||||
use super::auto_compact_window::ContextWindowIdGenerator;
|
||||
use crate::TurnStartOptions;
|
||||
use crate::agent::host::ServiceTierAcceptance;
|
||||
use crate::config::Config;
|
||||
use crate::context_manager::ContextManager;
|
||||
use crate::context_manager::HistoryReplacement;
|
||||
use crate::session::PreviousTurnSettings;
|
||||
@@ -73,6 +75,9 @@ impl ReasoningEffortPin {
|
||||
/// Persistent, session-scoped state previously stored directly on `Session`.
|
||||
pub(crate) struct SessionState {
|
||||
pub(crate) session_configuration: SessionConfiguration,
|
||||
/// Config identities reachable from the current one through Guardian-only publications.
|
||||
/// A mismatch with the last entry means another kind of update replaced the config.
|
||||
pub(crate) guardian_config_snapshots: Vec<Weak<Config>>,
|
||||
/// Shared root tier publication starts when the runtime wins registration.
|
||||
pub(crate) shared_service_tier_pending: bool,
|
||||
/// Receipt for the current host root tier, retained for callers retrying that commit.
|
||||
@@ -146,6 +151,7 @@ impl SessionState {
|
||||
active_disabled_plugin_ids: Vec::new(),
|
||||
persisted_dynamic_tools: Arc::clone(&session_configuration.dynamic_tools),
|
||||
session_configuration,
|
||||
guardian_config_snapshots: Vec::new(),
|
||||
shared_service_tier_pending: false,
|
||||
service_tier_acceptance: None,
|
||||
base_instructions_provenance: None,
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
#![allow(clippy::unwrap_used)]
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_config::LoaderOverrides;
|
||||
use codex_config::loader::load_guardian_policy_snapshot;
|
||||
use codex_config::test_support::CloudConfigBundleFixture;
|
||||
use codex_config::types::AppToolApproval;
|
||||
use codex_core::ConfigRefreshOutcome;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_core::TurnStartOptions;
|
||||
use codex_core::config::Config;
|
||||
use codex_exec_server::LOCAL_FS;
|
||||
use codex_features::Feature;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_models_manager::bundled_models_response;
|
||||
@@ -989,6 +992,74 @@ approvals_reviewer = "auto_review"
|
||||
Some(&json!("Lunch"))
|
||||
);
|
||||
|
||||
if !protected_model && !work_link_reviewer {
|
||||
let after_policy_refresh = "calendar-after-policy-refresh";
|
||||
mount_sse_sequence(
|
||||
&server,
|
||||
vec![
|
||||
sse(vec![
|
||||
ev_response_created(after_policy_refresh),
|
||||
ev_function_call_with_namespace(
|
||||
after_policy_refresh,
|
||||
SEARCH_CALENDAR_NAMESPACE,
|
||||
SEARCH_CALENDAR_CREATE_TOOL,
|
||||
&calendar_args,
|
||||
),
|
||||
ev_completed(after_policy_refresh),
|
||||
]),
|
||||
sse(vec![ev_response_created("done"), ev_completed("done")]),
|
||||
],
|
||||
)
|
||||
.await;
|
||||
let snapshot = load_guardian_policy_snapshot(
|
||||
LOCAL_FS.as_ref(),
|
||||
test.config.codex_home.as_path(),
|
||||
&LoaderOverrides::without_managed_config_for_tests(),
|
||||
&CloudConfigBundleFixture::loader_with_enterprise_requirement(
|
||||
"allowed_approvals_reviewers = ['user']",
|
||||
),
|
||||
/*revision*/ 1,
|
||||
)
|
||||
.await?;
|
||||
assert_eq!(
|
||||
test.codex.refresh_guardian_policy(&snapshot).await,
|
||||
ConfigRefreshOutcome::Published
|
||||
);
|
||||
submit_user_turn(
|
||||
&test,
|
||||
"Use [$calendar](app://calendar) to create another event.",
|
||||
AskForApproval::OnRequest,
|
||||
PermissionProfile::Disabled,
|
||||
/*collaboration_mode*/ None,
|
||||
)
|
||||
.await?;
|
||||
let EventMsg::ElicitationRequest(request) = wait_for_event(&test.codex, |event| {
|
||||
matches!(
|
||||
event,
|
||||
EventMsg::ElicitationRequest(_) | EventMsg::TurnComplete(_)
|
||||
)
|
||||
})
|
||||
.await
|
||||
else {
|
||||
anyhow::bail!("the existing MCP runtime skipped user approval");
|
||||
};
|
||||
assert_eq!(recorded_apps_tool_calls(&server).await.len(), 1);
|
||||
test.codex
|
||||
.submit(Op::ResolveElicitation {
|
||||
server_name: request.server_name,
|
||||
request_id: request.id,
|
||||
decision: ElicitationAction::Accept,
|
||||
content: None,
|
||||
meta: None,
|
||||
})
|
||||
.await?;
|
||||
wait_for_event(&test.codex, |event| {
|
||||
matches!(event, EventMsg::TurnComplete(_))
|
||||
})
|
||||
.await;
|
||||
recorded_apps_tool_call_by_call_id(&server, after_policy_refresh).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user