mirror of
https://github.com/openai/codex.git
synced 2026-11-25 23:30:49 +00:00
Add attributed MCP OAuth credential storage telemetry (#49392)
## What changed - Instrument MCP OAuth loads, saves, deletes, fallback cleanup, and refresh persistence with credential-free storage metrics, distinguishing configured policy from operations on a pinned store. - Retain the originating client across background tasks, blocking storage operations, and session recovery, including recovery after startup found no credentials. - Preserve typed keyring and lock error categories for metrics and remove raw error details from storage warnings. ## Testing Add tests for policy and pinned-store outcomes, best-effort cleanup failures, wrapped lock errors, and successful or failed refresh persistence without duplicate observations. Add recovery tests that verify client attribution after anonymous startup and across threads with different originators. GitOrigin-RevId: 5ea4528bcdcf500c8ffdf1d9c7008ea52112c726
This commit is contained in:
@@ -11,6 +11,7 @@ use codex_mcp::ElicitationReviewRequest;
|
||||
use codex_mcp::ElicitationReviewer;
|
||||
use codex_mcp::ElicitationReviewerHandle;
|
||||
use codex_mcp::MCP_TOOL_CODEX_APPS_META_KEY;
|
||||
use codex_otel::auth_storage::AuthStorageOriginator;
|
||||
use codex_prompts::ResolvedModelMessages;
|
||||
use codex_protocol::capabilities::CapabilityRootLocation;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
@@ -343,7 +344,9 @@ impl Session {
|
||||
input.mcp_servers.contains_key(CODEX_APPS_MCP_SERVER_NAME),
|
||||
"unknown MCP server '{CODEX_APPS_MCP_SERVER_NAME}'"
|
||||
);
|
||||
let refreshed = self.services.mcp_runtime.replace_fresh(input).await;
|
||||
let refreshed = AuthStorageOriginator::from_client_name(&desired.originator)
|
||||
.scope(self.services.mcp_runtime.replace_fresh(input))
|
||||
.await;
|
||||
self.services.thread_extension_data.insert(selected_plugins);
|
||||
refreshed
|
||||
}
|
||||
@@ -375,11 +378,14 @@ impl Session {
|
||||
self.mark_mcp_runtime_dirty();
|
||||
}
|
||||
|
||||
let recovered_oauth_servers = self
|
||||
.services
|
||||
.mcp_runtime
|
||||
.updated_oauth_credentials_after_auth_failure()
|
||||
.await;
|
||||
let recovered_oauth_servers =
|
||||
AuthStorageOriginator::from_client_name(&turn_context.originator)
|
||||
.scope(
|
||||
self.services
|
||||
.mcp_runtime
|
||||
.updated_oauth_credentials_after_auth_failure(),
|
||||
)
|
||||
.await;
|
||||
if !recovered_oauth_servers.is_empty()
|
||||
&& let Ok(_refresh) = self.mcp_refresh.acquire().await
|
||||
&& self
|
||||
|
||||
@@ -16,6 +16,7 @@ use codex_mcp::McpServerSource;
|
||||
use codex_mcp::McpStartupPolicy;
|
||||
use codex_mcp::PreparedMcpCall;
|
||||
use codex_mcp::ToolInfo;
|
||||
use codex_otel::auth_storage::AuthStorageOriginator;
|
||||
use codex_protocol::capabilities::SelectedCapabilityRoot;
|
||||
use std::collections::HashSet;
|
||||
|
||||
@@ -300,7 +301,9 @@ impl Session {
|
||||
ready_selected_capability_roots,
|
||||
elicitation_reviewer,
|
||||
);
|
||||
self.services.mcp_runtime.replace(input).await;
|
||||
AuthStorageOriginator::from_client_name(&desired.originator)
|
||||
.scope(self.services.mcp_runtime.replace(input))
|
||||
.await;
|
||||
self.services.thread_extension_data.insert(selected_plugins);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
//! Exercises thread-owned storage attribution through turn-time MCP authentication recovery.
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_config::McpServerConfig;
|
||||
use codex_config::types::OAuthCredentialsStoreMode;
|
||||
use codex_core::StartThreadOptions;
|
||||
use codex_core::TurnInputRequest;
|
||||
use codex_history::InitialHistory;
|
||||
use codex_history::RolloutItem;
|
||||
use codex_otel::MetricsClient;
|
||||
use codex_otel::MetricsConfig;
|
||||
use codex_protocol::protocol::EventMsg;
|
||||
use codex_protocol::protocol::SessionMeta;
|
||||
use codex_protocol::protocol::SessionMetaLine;
|
||||
use codex_protocol::user_input::UserInput;
|
||||
use core_test_support::responses;
|
||||
use core_test_support::skip_if_no_network;
|
||||
use core_test_support::test_codex::test_codex;
|
||||
use core_test_support::wait_for_event;
|
||||
use opentelemetry_sdk::metrics::data::AggregatedMetrics;
|
||||
use opentelemetry_sdk::metrics::data::MetricData;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use wiremock::Mock;
|
||||
use wiremock::ResponseTemplate;
|
||||
use wiremock::matchers::method;
|
||||
use wiremock::matchers::path;
|
||||
|
||||
fn storage_loads(metrics: &MetricsClient) -> Result<BTreeMap<String, u64>> {
|
||||
let mut counts = BTreeMap::new();
|
||||
for metric in metrics
|
||||
.snapshot()?
|
||||
.scope_metrics()
|
||||
.flat_map(opentelemetry_sdk::metrics::data::ScopeMetrics::metrics)
|
||||
{
|
||||
if metric.name() == "codex.auth_storage.operation"
|
||||
&& let AggregatedMetrics::U64(MetricData::Sum(sum)) = metric.data()
|
||||
{
|
||||
for point in sum.data_points() {
|
||||
let tags: BTreeMap<_, _> = point
|
||||
.attributes()
|
||||
.map(|tag| (tag.key.to_string(), tag.value.to_string()))
|
||||
.collect();
|
||||
if tags.get("credential_kind").map(String::as_str) == Some("mcp")
|
||||
&& tags.get("operation").map(String::as_str) == Some("load")
|
||||
{
|
||||
*counts.entry(tags["originator"].clone()).or_default() += point.value();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(counts)
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn recovery_without_a_snapshot_keeps_each_threads_originator() -> Result<()> {
|
||||
skip_if_no_network!(Ok(()));
|
||||
// Isolate global metrics and CODEX_HOME from other integration tests.
|
||||
if std::env::var_os("CODEX_MCP_TELEMETRY_TEST_CHILD").is_none() {
|
||||
let home = tempfile::tempdir()?;
|
||||
let output = tokio::process::Command::new(std::env::current_exe()?)
|
||||
.args(["--exact", "suite::rmcp_client::storage_telemetry_tests::recovery_without_a_snapshot_keeps_each_threads_originator", "--nocapture"])
|
||||
.env("CODEX_MCP_TELEMETRY_TEST_CHILD", "1")
|
||||
.env("CODEX_HOME", home.path())
|
||||
.output().await?;
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let server = responses::start_mock_server().await;
|
||||
let mcp = responses::start_mock_server().await;
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/mcp"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 401).append_header("www-authenticate", "Bearer"))
|
||||
.mount(&mcp)
|
||||
.await;
|
||||
Mock::given(method("GET"))
|
||||
.and(path("/.well-known/oauth-authorization-server/mcp"))
|
||||
.respond_with(ResponseTemplate::new(/*s*/ 200).set_body_json(json!({
|
||||
"authorization_endpoint": format!("{}/authorize", mcp.uri()),
|
||||
"token_endpoint": format!("{}/token", mcp.uri()),
|
||||
})))
|
||||
.mount(&mcp)
|
||||
.await;
|
||||
let home = Arc::new(tempfile::tempdir()?);
|
||||
// The OAuth endpoint remains on the host when the test uses a remote executor.
|
||||
let fixture = test_codex()
|
||||
.with_home(home)
|
||||
.build_with_remote_and_local_env(&server)
|
||||
.await?;
|
||||
let server_config: McpServerConfig =
|
||||
serde_json::from_value(json!({"url": format!("{}/mcp", mcp.uri())}))?;
|
||||
let mut config = fixture.config.clone();
|
||||
config.mcp_oauth_credentials_store_mode = OAuthCredentialsStoreMode::File;
|
||||
config
|
||||
.mcp_servers
|
||||
.set([("reauth".into(), server_config)].into())?;
|
||||
let metrics = codex_otel::install_global_metrics(MetricsClient::new(
|
||||
MetricsConfig::in_memory("test", "test", "1", Default::default()).with_runtime_reader(),
|
||||
)?);
|
||||
let originators = ["codex_desktop", "codex_vscode"];
|
||||
let mut threads = Vec::new();
|
||||
for originator in originators {
|
||||
let thread = fixture
|
||||
.thread_manager
|
||||
.start_thread(StartThreadOptions {
|
||||
initial_history: InitialHistory::Forked(vec![RolloutItem::SessionMeta(
|
||||
SessionMetaLine {
|
||||
meta: SessionMeta {
|
||||
originator: originator.into(),
|
||||
..Default::default()
|
||||
},
|
||||
git: None,
|
||||
},
|
||||
)]),
|
||||
environments: Some(fixture.codex.environment_selections().await),
|
||||
..StartThreadOptions::new(config.clone())
|
||||
})
|
||||
.await?
|
||||
.thread;
|
||||
let EventMsg::McpStartupComplete(startup) = wait_for_event(&thread, |event| {
|
||||
matches!(event, EventMsg::McpStartupComplete(_))
|
||||
})
|
||||
.await
|
||||
else {
|
||||
unreachable!();
|
||||
};
|
||||
assert_eq!(
|
||||
startup
|
||||
.failed
|
||||
.iter()
|
||||
.map(|failure| failure.server.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["reauth"]
|
||||
);
|
||||
threads.push(thread);
|
||||
responses::mount_sse_once(
|
||||
&server,
|
||||
responses::sse(vec![
|
||||
responses::ev_assistant_message("msg", "Sign in to continue."),
|
||||
responses::ev_completed("resp"),
|
||||
]),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
// The runtime reader exports deltas; drain startup observations before recovery.
|
||||
let _ = storage_loads(&metrics)?;
|
||||
futures::future::try_join_all(threads.iter().map(|thread| async {
|
||||
thread
|
||||
.start_or_steer_turn(TurnInputRequest::user_input(vec![UserInput::Text {
|
||||
text: "Continue".into(),
|
||||
text_elements: Vec::new(),
|
||||
}]))
|
||||
.await?;
|
||||
wait_for_event(thread, |event| matches!(event, EventMsg::TurnComplete(_))).await;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}))
|
||||
.await?;
|
||||
let mut after = storage_loads(&metrics)?;
|
||||
after.retain(|_, count| *count > 0);
|
||||
assert_eq!(
|
||||
after.keys().map(String::as_str).collect::<Vec<_>>(),
|
||||
originators
|
||||
);
|
||||
for thread in threads {
|
||||
thread.shutdown_and_wait().await?;
|
||||
}
|
||||
fixture.codex.shutdown_and_wait().await?;
|
||||
metrics.shutdown()?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -132,6 +132,8 @@ use wiremock::MockServer;
|
||||
|
||||
#[path = "mcp_oauth_refresh_tests.rs"]
|
||||
mod oauth_refresh_tests;
|
||||
#[path = "mcp_storage_telemetry_tests.rs"]
|
||||
mod storage_telemetry_tests;
|
||||
|
||||
static OPENAI_PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAD0AAAA9CAYAAAAeYmHpAAAE6klEQVR4Aeyau44UVxCGx1fZsmRLlm3Zoe0XcGQ5cUiCCIgJeS9CHgAhMkISQnIuGQgJEkBcxLW+nqnZ6uqqc+nuWRC7q/P3qetf9e+MtOwyX25O4Nep6JPyop++0qev9HrfgZ+F6r2DuB/vHOrt/UIkqdDHYvujOW6fO7h/CNEI+a5jc+pBR8uy0jVFsziYu5HtfSUk+Io34q921hLNctFSX0gwww+S8wce8K1LfCU+cYW4888aov8NxqvQILUPPReLOrm6zyLxa4i+6VZuFbJo8d1MOHZm+7VUtB/aIvhPWc/3SWg49JcwFLlHxuXKjtyloo+YNhuW3VS+WPBuUEMvCFKjEDVgFBQHXrnazpqiSxNZCkQ1kYiozsbm9Oz7l4i2Il7vGccGNWAc3XosDrZe/9P3ZnMmzHNEQw4smf8RQ87XEAMsC7Az0Au+dgXerfH4+sHvEc0SYGic8WBBUGqFH2gN7yDrazy7m2pbRTeRmU3+MjZmr1h6LJgPbGy23SI6GlYT0brQ71IY8Us4PNQCm+zepSbaD2BY9xCaAsD9IIj/IzFmKMSdHHonwdZATbTnYREf6/VZGER98N9yCWIvXQwXDoDdhZJoT8jwLnJXDB9w4Sb3e6nK5ndzlkTLnP3JBu4LKkbrYrU69gCVceV0JvpyuW1xlsUVngzhwMetn/XamtTORF9IO5YnWNiyeF9zCAfqR3fUW+vZZKLtgP+ts8BmQRBREAdRDhH3o8QuRh/YucNFz2BEjxbRN6LGzphfKmvP6v6QhqIQyZ8XNJ0W0X83MR1PEcJBNO2KC2Z1TW/v244scp9FwRViZxIOBF0Lctk7ZVSavdLvRlV1hz/ysUi9sr8CIcB3nvWBwA93ykTz18eAYxQ6N/K2DkPA1lv3iXCwmDUT7Ykj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