Expand enterprise MCP authorization lifecycle test coverage (#55883)

## What changed

- Extend app-server tests for account credential reuse, refresh races, stale bearer rejection, retry exhaustion, and step-up failures at the identity provider and resource authorization server.
- Assert token-exchange request fields and enterprise protocol negotiation while preserving the ordinary MCP handshake.
- Add core scenarios for permission and tool-policy refreshes, policy revocation, and thread removal, including cancellation of in-flight enterprise calls.
- Snapshot conversation history after revocation to verify that prior calls remain visible and ordinary tools continue working.
- Allow the existing startup-failure test to wait through the MCP startup deadline.

GitOrigin-RevId: 31cf71a28f91bd30746b74df8fa669edb6bc23a1
This commit is contained in:
jif
2026-10-21 12:39:12 +00:00
committed by copyberry
parent c419fd01a7
commit d138398cef
3 changed files with 1106 additions and 17 deletions
@@ -210,6 +210,7 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
keyring::set_default_credential_builder(Box::new(keyring));
let server = MockServer::builder().start().await;
let idp_server = MockServer::start().await;
app_test_support::mount_workspace_routing(&server).await;
let origin = server.uri();
let issuer = format!("{}/idp", idp_server.uri());
let resource = format!("{origin}/api/codex/ps/mcp");
@@ -250,6 +251,7 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": format!("{origin}/as"), "token_endpoint": format!("{origin}/as/token"),
"grant_types_supported": ["urn:ietf:params:oauth:grant-type:jwt-bearer"],
"authorization_grant_profiles_supported": ["urn:ietf:params:oauth:grant-profile:id-jag"],
"token_endpoint_auth_methods_supported": ["none"],
})))
.mount(&server)
@@ -272,10 +274,25 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
let expected_jag = jag.clone();
let resource_exchanges = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let exchanges = Arc::clone(&resource_exchanges);
let pending_account_refresh = Arc::new(Mutex::new(std::collections::VecDeque::<(
std::path::PathBuf,
Vec<u8>,
)>::new()));
let account_refresh = Arc::clone(&pending_account_refresh);
Mock::given(method("POST")).and(path("/as/token"))
.respond_with(move |request: &wiremock::Request| {
let fields = url::form_urlencoded::parse(&request.body).into_owned().collect::<HashMap<_, _>>();
assert_eq!(fields.get("assertion"), Some(&expected_jag));
// EMA section 5: the resource AS gets the ID-JAG, never the IdP credential.
assert!(request.headers.get("authorization").is_none());
assert_eq!(serde_json::to_value(fields).unwrap(), json!({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": expected_jag,
"client_id": "mcp-client",
}));
if let Some((path, auth)) = account_refresh.lock().unwrap().pop_front() {
// Another process refreshes the account while the resource exchange runs.
std::fs::write(path, auth).expect("publish account refresh");
}
ResponseTemplate::new(200).set_body_json(json!({
"access_token": format!("enterprise-resource-{}", exchanges.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1),
"token_type": "Bearer", "expires_in": 3600,
@@ -291,6 +308,7 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
.mount(&server)
.await;
let token_resource = resource.clone();
let token_audience = format!("{origin}/as");
let pending_exchange = Arc::new(Mutex::new(
None::<(
tokio::sync::oneshot::Sender<()>,
@@ -307,10 +325,29 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
let fields = url::form_urlencoded::parse(&request.body)
.into_owned()
.collect::<HashMap<_, _>>();
assert_eq!(
fields.get("subject_token").map(String::as_str),
Some("enterprise-refresh")
);
let subject = fields.get("subject_token").map(String::as_str);
assert!(matches!(
subject,
Some(
"enterprise-refresh"
| "discovered-account-refresh"
| "rotated-account-refresh"
| "exchanged-account-refresh"
| "retried-account-refresh"
)
));
// EMA section 4: audience is the authorization server; resource is the MCP server.
assert!(request.headers.get("authorization").is_none());
assert_eq!(serde_json::to_value(&fields).unwrap(), json!({
"grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
"requested_token_type": "urn:ietf:params:oauth:token-type:id-jag",
"subject_token_type": "urn:ietf:params:oauth:token-type:refresh_token",
"subject_token": subject,
"client_id": if subject == Some("enterprise-refresh") { "idp-client" } else { "account-client" },
"audience": token_audience,
"resource": token_resource,
"scope": "files.read",
}));
if let Some((arrived, release)) = exchange_gate.lock().unwrap().take() {
let _ = arrived.send(());
let _ = release.recv();
@@ -331,14 +368,28 @@ async fn enterprise_login_attempt_lifecycle() -> Result<()> {
)
.mount(&server)
.await;
let pending_discovery = Arc::new(Mutex::new(
None::<(
tokio::sync::oneshot::Sender<()>,
std::sync::mpsc::Receiver<()>,
)>,
));
let discovery_gate = Arc::clone(&pending_discovery);
let idp_metadata = json!({
"issuer": issuer,
"authorization_endpoint": format!("{issuer}/authorize"),
"token_endpoint": format!("{issuer}/token"),
"token_endpoint_auth_methods_supported": ["none"],
});
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/idp"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"issuer": issuer,
"authorization_endpoint": format!("{issuer}/authorize"),
"token_endpoint": format!("{issuer}/token"),
"token_endpoint_auth_methods_supported": ["none"],
})))
.respond_with(move |_: &wiremock::Request| {
if let Some((arrived, release)) = discovery_gate.lock().unwrap().take() {
let _ = arrived.send(());
let _ = release.recv();
}
ResponseTemplate::new(200).set_body_json(idp_metadata.clone())
})
.mount(&idp_server)
.await;
let assertion = format!(
@@ -727,6 +778,44 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
);
}
std::fs::write(config_path, saved_config)?;
let handshakes = server.received_requests().await.context("MCP handshakes")?;
let enterprise_discovery = handshakes
.iter()
.find_map(|request| {
let body: Value = serde_json::from_slice(&request.body).ok()?;
(request.headers.get("authorization")?.to_str().ok()? == "Bearer enterprise-resource-1"
&& body["method"] == "server/discover")
.then_some(body)
})
.context("authenticated EMA connection negotiates modern MCP")?;
let metadata = &enterprise_discovery["params"]["_meta"];
assert_eq!(
metadata["io.modelcontextprotocol/protocolVersion"],
"2026-07-28"
);
assert_eq!(
metadata["io.modelcontextprotocol/clientCapabilities"]["extensions"]
[codex_protocol::mcp::ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID],
json!({})
);
let ordinary_initialize = handshakes
.iter()
.find_map(|request| {
let body: Value = serde_json::from_slice(&request.body).ok()?;
(request.headers.get("authorization")?.to_str().ok()? == "Bearer ordinary-access"
&& body["method"] == "initialize")
.then_some(body)
})
.context("ordinary MCP keeps its legacy handshake")?;
assert_eq!(
ordinary_initialize["params"]["protocolVersion"],
"2025-06-18"
);
assert!(
ordinary_initialize["params"]["capabilities"]["extensions"]
.get(codex_protocol::mcp::ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID)
.is_none()
);
let authorization = server
.received_requests()
.await
@@ -912,6 +1001,312 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
json!({"name":"enterprise","threadId":thread_id,"loginId":recovery["loginId"],"success":true})
);
// An eligible account login uses its own OAuth client, without a second sign-in.
let auth_path = home.path().join("auth.json");
let mut account_auth: Value = serde_json::from_slice(&std::fs::read(&auth_path)?)?;
account_auth["tokens"]["oauth_provenance"] =
json!({"issuer": issuer, "client_id": "account-client"});
account_auth["tokens"]["login_owner_id"] = json!("completed-account-login");
account_auth["tokens"]["refresh_token"] = json!("account-refresh");
account_auth["tokens"]["id_token"] = json!(format!("{}.{}.c2lnbmF0dXJl",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(json!({
"iss": issuer, "sub": "enterprise-user", "aud": "account-client", "exp": now + 3600,
"https://api.openai.com/auth": {"chatgpt_user_id": "enterprise-user", "chatgpt_account_id": WORKSPACE_ID_REFRESHED, "chatgpt_plan_type": "business"}
}).to_string())));
std::fs::write(&auth_path, serde_json::to_vec(&account_auth)?)?;
// Startup does not adopt a different login. Explicitly reload the account
// before starting a thread under the new completed login.
enterprise_rpc(&client, "account/read", json!({"refreshToken":true})).await?;
let (discovery_arrived, discovery_wait) = tokio::sync::oneshot::channel();
let (release_discovery, discovery_release) = std::sync::mpsc::channel();
*pending_discovery.lock().unwrap() = Some((discovery_arrived, discovery_release));
let account_thread = enterprise_rpc(&client, "thread/start", json!({})).await?;
let account_id = account_thread["thread"]["id"]
.as_str()
.context("account thread ID")?;
let account_call = json!({"threadId":account_id,"server":"enterprise","tool":"calendar_list_events","arguments":{"query":"hello"}});
let mut initial_call = Box::pin(enterprise_rpc(
&client,
"mcpServer/tool/call",
account_call.clone(),
));
tokio::select! {
arrived = discovery_wait => arrived?,
result = &mut initial_call => anyhow::bail!(
"fresh EMA startup failed before IdP discovery: {result:?}"
),
}
// Account refresh can publish a newer grant while IdP metadata is still pending.
// EMA must acquire that newer credential before sending anything to the IdP.
account_auth["tokens"]["access_token"] = json!("account-after-discovery");
account_auth["tokens"]["refresh_token"] = json!("discovered-account-refresh");
std::fs::write(&auth_path, serde_json::to_vec(&account_auth)?)?;
let refreshed = enterprise_rpc(&client, "account/read", json!({"refreshToken":true})).await;
account_auth["tokens"]["access_token"] = json!("account-after-resource-exchange");
account_auth["tokens"]["id_token"] = json!(format!("{}.{}.c2lnbmF0dXJl",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(json!({
"iss": issuer, "sub": "enterprise-user", "aud": "account-client", "iat": now, "exp": now + 7200,
"https://api.openai.com/auth": {"chatgpt_user_id": "enterprise-user", "chatgpt_account_id": WORKSPACE_ID_REFRESHED, "chatgpt_plan_type": "business"}
}).to_string())));
pending_account_refresh
.lock()
.unwrap()
.push_back((auth_path.clone(), serde_json::to_vec(&account_auth)?));
release_discovery.send(()).expect("release IdP discovery");
refreshed.context("IdP discovery must not block account refresh")?;
assert_eq!(initial_call.await?, ordinary_result);
assert_eq!(
resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
4
);
// A no-op refresh keeps the established connection and its cached bearer.
enterprise_rpc(&client, "config/mcpServer/reload", json!({})).await?;
assert_eq!(
enterprise_rpc(&client, "mcpServer/tool/call", account_call.clone()).await?,
ordinary_result
);
assert_eq!(
resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
4
);
let request_count = server
.received_requests()
.await
.context("MCP requests")?
.len();
account_auth["tokens"]["refresh_token"] = json!("rotated-account-refresh");
std::fs::write(&auth_path, serde_json::to_vec(&account_auth)?)?;
Mock::given(method("POST"))
.and(path("/api/codex/ps/mcp"))
.and(header("authorization", "Bearer enterprise-resource-4"))
.and(body_partial_json(json!({"method":"tools/call"})))
.respond_with(ResponseTemplate::new(401))
.with_priority(1)
.expect(1)
.up_to_n_times(1)
.mount(&server)
.await;
assert_eq!(
enterprise_rpc(&client, "mcpServer/tool/call", account_call.clone()).await?["isError"],
true
);
assert_eq!(
resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
4
);
// Rotate during both resource exchanges; discard stale bearers without revoking the owner.
for refresh_token in ["exchanged-account-refresh", "retried-account-refresh"] {
account_auth["tokens"]["refresh_token"] = json!(refresh_token);
pending_account_refresh
.lock()
.unwrap()
.push_back((auth_path.clone(), serde_json::to_vec(&account_auth)?));
}
assert!(
enterprise_rpc(&client, "mcpServer/tool/call", account_call.clone())
.await
.is_err()
);
assert_eq!(
resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
6
);
// Retry exhaustion fails only this call. The next explicit call can still renew.
assert_eq!(
enterprise_rpc(&client, "mcpServer/tool/call", account_call.clone()).await?,
ordinary_result
);
let account_subjects = idp_server
.received_requests()
.await
.context("IdP requests")?
.iter()
.filter_map(|request| {
url::form_urlencoded::parse(&request.body)
.find(|(name, _)| name == "subject_token")
.map(|(_, token)| token.into_owned())
})
.filter(|token| token != "enterprise-refresh")
.collect::<Vec<_>>();
assert_eq!(
account_subjects,
[
"discovered-account-refresh",
"rotated-account-refresh",
"exchanged-account-refresh",
"retried-account-refresh"
]
);
let renewed_calls = server
.received_requests()
.await
.context("MCP requests")?
.into_iter()
.skip(request_count)
.filter_map(|request| {
let body: Value = serde_json::from_slice(&request.body).ok()?;
(body["method"] == "tools/call").then(|| {
request.headers["authorization"]
.to_str()
.expect("valid bearer header")
.to_owned()
})
})
.collect::<Vec<_>>();
assert_eq!(
renewed_calls,
[
"Bearer enterprise-resource-4",
"Bearer enterprise-resource-7"
],
"failed calls are not replayed and stale exchange bearers never reach MCP"
);
// One-shot responses avoid scoped-mock IDs being reordered by wiremock priorities.
// Resource-AS step-up is an administrator error, not an account sign-in failure.
Mock::given(method("POST"))
.and(path("/as/token"))
.respond_with(
ResponseTemplate::new(400)
.set_body_json(json!({"error":"insufficient_user_authentication"})),
)
.with_priority(1)
.expect(1)
.up_to_n_times(1)
.mount(&server)
.await;
let rejected_thread = enterprise_rpc(&client, "thread/start", json!({})).await?;
let rejected_id = &rejected_thread["thread"]["id"];
let status = enterprise_rpc(
&client,
"mcpServerStatus/list",
json!({"threadId":rejected_id,"serverName":"enterprise"}),
)
.await?;
assert_eq!(status["data"][0]["authStatus"], "bearerToken");
let error = enterprise_rpc(&client, "mcpServer/tool/call", json!({"threadId":rejected_id,"server":"enterprise","tool":"calendar_list_events","arguments":{}})).await.unwrap_err();
assert!(
error.to_string().contains("contact your administrator"),
"{error}"
);
assert_eq!(
serde_json::from_slice::<Value>(&std::fs::read(&auth_path)?)?,
account_auth
);
// IdP step-up preserves the account grant and affects this registration across threads.
Mock::given(method("POST"))
.and(path("/idp/token"))
.and(wiremock::matchers::body_string_contains(
"subject_token=retried-account-refresh",
))
.respond_with(
ResponseTemplate::new(400)
.set_body_json(json!({"error":"insufficient_user_authentication"})),
)
.with_priority(1)
.expect(1)
.up_to_n_times(1)
.mount(&idp_server)
.await;
Mock::given(method("POST"))
.and(path("/api/codex/ps/mcp"))
.and(header("authorization", "Bearer enterprise-resource-7"))
.and(body_partial_json(json!({"method":"tools/call"})))
.respond_with(ResponseTemplate::new(401))
.with_priority(1)
.expect(1)
.up_to_n_times(1)
.mount(&server)
.await;
assert_eq!(
enterprise_rpc(&client, "mcpServer/tool/call", account_call.clone()).await?["isError"],
true
);
assert_eq!(
enterprise_rpc(&client, "mcpServer/tool/call", account_call).await?["isError"],
true
);
assert_eq!(
serde_json::from_slice::<Value>(&std::fs::read(&auth_path)?)?,
account_auth
);
// Access-token rotation must not forget the unchanged grant's sign-in requirement.
account_auth["tokens"]["access_token"] = json!("account-after-step-up");
std::fs::write(&auth_path, serde_json::to_vec(&account_auth)?)?;
enterprise_rpc(&client, "account/read", json!({"refreshToken":true})).await?;
let recovered = enterprise_rpc(&client, "thread/start", json!({})).await?;
let recovered_call = json!({"threadId":recovered["thread"]["id"],"server":"enterprise","tool":"calendar_list_events","arguments":{"query":"hello"}});
assert_eq!(
enterprise_rpc(&client, "mcpServer/tool/call", recovered_call).await?,
ordinary_result
);
assert_eq!(
resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
8
);
let recovered_subject = idp_server
.received_requests()
.await
.context("IdP requests")?
.iter()
.filter_map(|request| {
url::form_urlencoded::parse(&request.body)
.find(|(name, _)| name == "subject_token")
.map(|(_, token)| token.into_owned())
})
.next_back();
assert_eq!(recovered_subject.as_deref(), Some("enterprise-refresh"));
// Both failure stages preserve a dedicated grant. Status must finish startup first.
for (endpoint, identity_provider) in [("/idp/token", true), ("/as/token", false)] {
let target = if identity_provider {
&idp_server
} else {
&server
};
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(
ResponseTemplate::new(400)
.set_body_json(json!({"error":"insufficient_user_authentication"})),
)
.with_priority(1)
.expect(1)
.up_to_n_times(1)
.mount(target)
.await;
let rejected = enterprise_rpc(&client, "thread/start", json!({})).await?;
let rejected_id = &rejected["thread"]["id"];
let status = enterprise_rpc(
&client,
"mcpServerStatus/list",
json!({"threadId":rejected_id,"serverName":"enterprise"}),
)
.await?;
assert_eq!(
status["data"][0]["authStatus"],
if identity_provider {
"notLoggedIn"
} else {
"oAuth"
}
);
let error = enterprise_rpc(&client, "mcpServer/tool/call", json!({"threadId":rejected_id,"server":"enterprise","tool":"calendar_list_events","arguments":{}})).await.unwrap_err();
assert!(
error.to_string().contains(if identity_provider {
"Complete enterprise sign-in"
} else {
"contact your administrator"
}),
"{error}"
);
}
let stalled = enterprise_rpc(
&client,
"mcpServer/oauth/login",
@@ -973,7 +1368,7 @@ oauth = {{ client_id = "mcp-client", authorization_server_issuer = "{origin}/as"
);
assert_eq!(
resource_exchanges.load(std::sync::atomic::Ordering::SeqCst),
3
8
);
assert!(
enterprise_rpc(