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:
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user