aKode fase 2b-2: rimosso login ChatGPT e tutti i sottosistemi solo-ChatGPT

- Login: resta solo chiave API (+ header, Bedrock). Rimossi OAuth/browser,
  device code, refresh/revoke su auth.openai.com, PAT, agent/workload identity,
  runtime agent instance, backend-client e openapi-models, workspace routing.
- Rimossi: generazione immagini (ext + skill imagegen), history notes, plugin
  remoti (catalogo, sync, share), cyber access program, daybreak, cloud config
  e requirements (config_server ora fail-closed), attestation, frozen cloud
  skills, EMA MCP auth, Codex Apps/connettori, ricerca ospitata, header/zstd/
  routing/cookie del backend Codex, fallback OPENAI_API_KEY del realtime.
- Messaggi d'errore senza link a chatgpt.com.
- Chiavi di config legacy accettate e ignorate; feature rimosse = Stage::Removed.
- Test: cancellati solo quelli del codice rimosso; test di sicurezza
  (sandbox estensioni, permessi, redazione, auth storage, requirements)
  adattati. Restano solo fallimenti d'ambiente (code-mode-host/V8, ~/.agents).
- Istruzioni di sistema invariate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-10 16:20:15 +01:00
parent 82347a58ed
commit 6089fbde91
1573 changed files with 10289 additions and 177679 deletions

View File

@@ -104,21 +104,21 @@ impl TestToolServer {
Arc::new(sandbox_meta_schema),
);
sandbox_meta_tool.annotations = Some(ToolAnnotations::new().read_only(true));
let entitlement_tools = std::env::var("MCP_TEST_DAYBREAK_READ_ONLY")
let entitlement_tools = std::env::var("MCP_TEST_ENTITLEMENT_READ_ONLY")
.ok()
.into_iter()
.flat_map(|read_only| {
["get_codex_security_daybreak_access", "get_daybreak_access"].map(|name| {
["get_requested_entitlement_access", "get_entitlement_access"].map(|name| {
let mut tool = sandbox_meta_tool.clone();
tool.name = Cow::Borrowed(name);
tool.description =
Some(Cow::Borrowed("Return requested account access metadata."));
tool.annotations = Some(ToolAnnotations::new().read_only(read_only == "true"));
if name == "get_codex_security_daybreak_access" {
if name == "get_requested_entitlement_access" {
let mut meta = MetaObject::new();
meta.insert(
"openai/requestedEntitlements".to_string(),
json!(["cyber_trusted_access"]),
json!(["example_entitlement"]),
);
tool.meta = Some(meta);
}
@@ -815,7 +815,7 @@ impl ServerHandler for TestToolServer {
.supports_openai_form_elicitation
.load(Ordering::Relaxed),
}))),
"sandbox_meta" | "get_codex_security_daybreak_access" | "get_daybreak_access" => Ok(
"sandbox_meta" | "get_requested_entitlement_access" | "get_entitlement_access" => Ok(
Self::structured_result(serde_json::Value::Object(context.meta.0.0)),
),
"cwd" => {

View File

@@ -1,235 +0,0 @@
//! Select the resource authorization server before polling identity or exchanging credentials.
use std::collections::HashMap;
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use codex_exec_server::HttpClient;
use futures::future::BoxFuture;
use http::StatusCode;
use serde::Deserialize;
use serde_json::Value;
use url::Url;
use crate::EmaCredentialLease;
use crate::EmaErrorDetail;
use crate::ema_auth_policy::advertised_capability;
use crate::ema_auth_policy::resolve_ema_client_auth;
use crate::ema_auth_policy::validate_ema_auth_resource;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_exchange::EmaAccessToken;
use crate::ema_exchange::EmaIdJagExchangeRequest;
use crate::ema_exchange::JWT_BEARER_GRANT_TYPE;
use crate::ema_exchange::exchange_id_jag;
use crate::ema_identity::EmaIdpIdentity;
use crate::ema_resource::EmaDiscoveryRequest;
use crate::ema_resource::EmaResource;
use crate::ema_resource::discover_ema_resource;
use crate::ema_resource::validate_ema_metadata_issuer;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
const ID_JAG_GRANT_PROFILE: &str = "urn:ietf:params:oauth:grant-profile:id-jag";
/// Token-only Resource AS metadata must not require an unused authorization endpoint.
#[derive(Deserialize)]
struct EmaAuthorizationMetadata {
issuer: Option<String>,
token_endpoint: String,
#[serde(flatten)]
additional_fields: HashMap<String, Value>,
}
/// Inputs for non-interactive enterprise-managed MCP authorization.
pub struct EmaAuthTokenExchangeRequest<'a, L = EmaCredentialLease> {
pub server_url: &'a str,
pub resource: Option<&'a str>,
pub scopes: &'a [String],
pub mcp_client_id: Option<&'a str>,
pub mcp_client_secret: Option<&'a str>,
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
pub expected_authorization_server_issuer: Option<&'a str>,
pub idp_issuer: &'a str,
pub idp_client_id: &'a str,
pub idp_identity: BoxFuture<'a, Result<EmaIdpIdentity<L>>>,
pub idp_http_client: Arc<dyn HttpClient>,
pub resource_http_client: Arc<dyn HttpClient>,
}
impl<'a, L> From<&EmaAuthTokenExchangeRequest<'a, L>> for EmaDiscoveryRequest<'a> {
fn from(request: &EmaAuthTokenExchangeRequest<'a, L>) -> Self {
Self {
server_url: request.server_url,
resource: request.resource,
expected_issuer: request.expected_authorization_server_issuer,
http_client: Arc::clone(&request.resource_http_client),
}
}
}
/// Discover the resource's authorization server, then perform the ID-JAG flow.
pub async fn exchange_ema_auth_token<L: Send, R: Send>(
request: EmaAuthTokenExchangeRequest<'_, L>,
finish_idp: impl FnOnce(L) -> R + Send,
) -> Result<(EmaAccessToken, R)> {
validate_ema_auth_resource(request.server_url, request.resource)?;
let client_id = request
.mcp_client_id
.filter(|value| !value.trim().is_empty())
.ok_or_else(|| {
anyhow!(
"ema_auth requires the OAuth client ID registered with the MCP authorization server"
)
})?;
if request.mcp_client_secret.is_some()
&& request
.expected_authorization_server_issuer
.is_none_or(|issuer| issuer.trim().is_empty())
{
bail!("confidential ema_auth requires a configured authorization server issuer");
}
let (metadata, resource, resource_client_authentication) = discover_ema_authorization_metadata(
EmaDiscoveryRequest::from(&request),
request.mcp_client_secret,
request.token_endpoint_auth_method,
)
.await
.context(EmaErrorDetail::new(
"enterprise MCP authorization server discovery failed",
))?;
let issuer = metadata
.issuer
.as_deref()
.ok_or_else(|| anyhow!("MCP authorization metadata is missing an issuer"))?;
let EmaIdpIdentity {
token_endpoint,
refresh_token,
credentials,
client_authentication: idp_client_authentication,
} = request.idp_identity.await?;
exchange_id_jag(
EmaIdJagExchangeRequest {
resource: &resource,
scopes: request.scopes,
mcp_client_id: client_id,
authorization_server_issuer: issuer,
authorization_server_token_endpoint: &metadata.token_endpoint,
idp_token_endpoint: &token_endpoint,
idp_issuer: request.idp_issuer,
idp_client_id: request.idp_client_id,
idp_client_authentication,
resource_client_authentication,
refresh_token,
idp_http_client: request.idp_http_client,
resource_http_client: request.resource_http_client,
},
credentials,
finish_idp,
)
.await
}
async fn discover_ema_authorization_metadata(
request: EmaDiscoveryRequest<'_>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(EmaAuthorizationMetadata, String, EmaClientAuthentication)> {
let expected_issuer = request.expected_issuer;
let EmaResource {
server_url: server,
resource,
authorization_servers: issuers,
client,
} = discover_ema_resource(request).await?;
for issuer in issuers {
let issuer_url = match Url::parse(&issuer) {
Ok(url) => url,
Err(error) if expected_issuer.is_some() => {
return Err(error)
.context("configured enterprise authorization server issuer is invalid");
}
Err(_) => continue,
};
if let Err(error) = validate_ema_metadata_issuer(&server, &issuer_url) {
if expected_issuer.is_some() {
return Err(error);
}
continue;
}
let path = issuer_url.path().trim_matches('/');
let suffix = if path.is_empty() {
String::new()
} else {
format!("/{path}")
};
let mut urls = vec![
issuer_url.join(&format!("/.well-known/oauth-authorization-server{suffix}"))?,
issuer_url.join(&format!("/.well-known/openid-configuration{suffix}"))?,
];
if !path.is_empty() {
urls.push(issuer_url.join(&format!("/{path}/.well-known/openid-configuration"))?);
urls.push(issuer_url.join("/.well-known/oauth-authorization-server")?);
}
for url in urls {
let response = client.get(url).await?;
if response.status() != StatusCode::OK {
continue;
}
let Ok(metadata) = serde_json::from_slice::<EmaAuthorizationMetadata>(response.body())
else {
continue;
};
if metadata.issuer.as_deref() != Some(issuer.as_str()) {
bail!(EmaErrorDetail::new(
"enterprise authorization metadata issuer does not match its advertised issuer"
));
}
validate_ema_oauth_endpoint(
&metadata.token_endpoint,
"MCP authorization server token endpoint",
)?;
if expected_issuer.is_some()
&& issuer_url.origin() != Url::parse(&metadata.token_endpoint)?.origin()
{
bail!("enterprise MCP authorization server token endpoint changed origin");
}
let profile = advertised_capability(
metadata
.additional_fields
.get("authorization_grant_profiles_supported"),
ID_JAG_GRANT_PROFILE,
"MCP authorization grant profiles",
)?;
let grant = advertised_capability(
metadata.additional_fields.get("grant_types_supported"),
JWT_BEARER_GRANT_TYPE,
"MCP authorization grant types",
)?;
if profile == Some(false) || grant != Some(true) {
break;
}
match resolve_ema_client_auth(
metadata
.additional_fields
.get("token_endpoint_auth_methods_supported"),
client_secret,
token_endpoint_auth_method,
"MCP authorization server",
) {
Ok(authentication) => return Ok((metadata, resource, authentication)),
Err(error) if expected_issuer.is_some() => return Err(error),
Err(_) => break,
}
}
}
bail!(
"enterprise MCP discovery found no authorization server supporting the configured client authentication and ID-JAG JWT bearer grant"
)
}
#[cfg(test)]
#[path = "ema_auth_tests.rs"]
mod tests;

View File

@@ -1,364 +0,0 @@
//! Credential-destination policy for enterprise MCP OAuth.
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use rmcp::transport::auth::enterprise::EmaError;
use rmcp::transport::auth::enterprise::EmaExchangeStage;
use serde_json::Value;
use url::Host;
use url::Url;
/// A sanitized enterprise-auth failure that callers may handle without parsing text.
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
pub enum EmaAuthFailure {
#[error("invalid_grant")]
InvalidGrant { grant_source: EmaInvalidGrantSource },
#[error("insufficient_user_authentication")]
InsufficientUserAuthentication { grant_source: EmaInvalidGrantSource },
#[error("enterprise identity rejected the OAuth client")]
IdentityClientRejected,
#[error("enterprise identity requires authentication")]
ReauthenticationRequired,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EmaInvalidGrantSource {
EnterpriseIdentity,
ResourceAuthorization,
}
/// The credential source selected for enterprise token acquisition or validation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EmaCredentialKind {
Account,
Keyring,
}
/// A diagnostic containing only static local text or sanitized SDK exchange fields.
/// Never retains an arbitrary error's display text, provider response, or source chain.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct EmaErrorDetail {
message: &'static str,
stage: Option<EmaExchangeStage>,
status: Option<u16>,
}
impl EmaErrorDetail {
pub fn new(message: &'static str) -> Self {
Self {
message,
stage: None,
status: None,
}
}
pub fn from_error(error: &anyhow::Error) -> Self {
// SDK diagnostics are already sanitized, including allowlisted OAuth codes.
// Prefer them to an outer operation label when both are available.
if let Some(error) = error.downcast_ref::<EmaError>() {
let (stage, status, message) = match error {
EmaError::InvalidRequest(message) => (None, None, *message),
EmaError::InvalidResponse { stage, message } => (Some(*stage), None, *message),
EmaError::RequestFailed(stage) => (Some(*stage), None, "request failed"),
EmaError::InvalidGrant(stage) => (Some(*stage), None, "invalid_grant"),
EmaError::InsufficientUserAuthentication(stage) => {
(Some(*stage), None, "insufficient_user_authentication")
}
EmaError::OAuthRejected {
stage,
status,
code,
} => (Some(*stage), Some(*status), *code),
_ => (None, None, "enterprise MCP token exchange failed"),
};
return Self {
message,
stage,
status,
};
}
error
.chain()
.filter_map(|cause| cause.downcast_ref::<Self>())
.last()
.copied()
.or_else(|| error.downcast_ref::<Self>().copied())
.unwrap_or_else(|| Self::new("enterprise MCP token exchange failed"))
}
}
impl std::fmt::Display for EmaErrorDetail {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(stage) = self.stage {
write!(f, "{stage:?}: ")?;
}
if let Some(status) = self.status {
write!(f, "HTTP {status}: ")?;
}
f.write_str(self.message)
}
}
impl std::error::Error for EmaErrorDetail {}
/// Carries a credential kind and sanitized failure to transport, without raw error chains.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum EmaTokenSourceError {
AuthFailure {
credential: EmaCredentialKind,
failure: EmaAuthFailure,
},
Unexpected {
credential: EmaCredentialKind,
detail: EmaErrorDetail,
},
}
impl EmaTokenSourceError {
pub fn new(credential: EmaCredentialKind, failure: EmaAuthFailure) -> Self {
Self::AuthFailure {
credential,
failure,
}
}
pub fn unexpected(credential: EmaCredentialKind) -> Self {
Self::Unexpected {
credential,
detail: EmaErrorDetail::new("enterprise MCP token exchange failed"),
}
}
fn credential(self) -> EmaCredentialKind {
match self {
Self::AuthFailure { credential, .. } | Self::Unexpected { credential, .. } => {
credential
}
}
}
fn failure(self) -> Option<EmaAuthFailure> {
match self {
Self::AuthFailure { failure, .. } => Some(failure),
Self::Unexpected { .. } => None,
}
}
pub fn is_authentication_required(&self) -> bool {
match (self.credential(), self.failure()) {
(
_,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::ReauthenticationRequired,
),
)
| (EmaCredentialKind::Account, Some(EmaAuthFailure::IdentityClientRejected)) => true,
(
_,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
},
)
| None,
)
| (EmaCredentialKind::Keyring, Some(EmaAuthFailure::IdentityClientRejected)) => false,
}
}
}
impl std::fmt::Display for EmaTokenSourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Self::Unexpected { detail, .. } = self {
return std::fmt::Display::fmt(detail, f);
}
let message = match (self.credential(), self.failure()) {
(
_,
Some(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}),
) => {
"The MCP authorization server requires additional user authentication; contact your administrator"
}
(EmaCredentialKind::Keyring, Some(EmaAuthFailure::IdentityClientRejected)) => {
"The enterprise IdP rejected the configured MCP OAuth client; contact your administrator"
}
(
EmaCredentialKind::Account,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::IdentityClientRejected,
),
) => "Complete enterprise sign-in for this MCP server",
(EmaCredentialKind::Account, Some(EmaAuthFailure::ReauthenticationRequired)) => {
"Sign in to your Codex account to restore enterprise MCP access"
}
(
EmaCredentialKind::Keyring,
Some(
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::ReauthenticationRequired,
),
) => "Complete enterprise sign-in to restore MCP access",
(
_,
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}),
) => "The MCP authorization server rejected the enterprise grant: invalid_grant",
(_, None) => "enterprise MCP token exchange failed",
};
f.write_str(message)
}
}
impl std::error::Error for EmaTokenSourceError {}
pub(crate) fn ema_reauthentication_required(message: &'static str) -> anyhow::Error {
anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired).context(message)
}
pub(crate) fn resolve_ema_client_auth(
advertised_methods: Option<&Value>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
issuer_description: &str,
) -> Result<rmcp::transport::auth::enterprise::EmaClientAuthentication> {
use oauth2::ClientSecret;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
if let Some(secret) = client_secret {
if secret.trim().is_empty() {
bail!("{issuer_description} client secret must not be empty");
}
let registered_method = token_endpoint_auth_method.unwrap_or_default();
// RFC 8414 defaults absent server capabilities to Basic. Capabilities
// validate the registration; they do not select its authentication method.
let supported = match advertised_methods {
None => registered_method == McpEmaTokenEndpointAuthMethod::ClientSecretBasic,
Some(methods) => methods.as_array().is_some_and(|methods| {
methods
.iter()
.any(|method| method.as_str() == Some(registered_method.as_str()))
}),
};
if !supported {
bail!(
"{issuer_description} does not support the registered token endpoint authentication method"
);
}
let secret = ClientSecret::new(secret.to_owned());
return Ok(match registered_method {
McpEmaTokenEndpointAuthMethod::ClientSecretBasic => {
EmaClientAuthentication::ClientSecretBasic(secret)
}
McpEmaTokenEndpointAuthMethod::ClientSecretPost => {
EmaClientAuthentication::ClientSecretPost(secret)
}
});
}
if token_endpoint_auth_method.is_some() {
bail!("{issuer_description} token endpoint authentication method requires a client secret");
}
let advertised_methods = advertised_methods.ok_or_else(|| {
anyhow!(
"{issuer_description} does not explicitly advertise public-client token endpoint authentication"
)
})?;
let methods = advertised_methods.as_array().ok_or_else(|| {
anyhow!("{issuer_description} advertised malformed token endpoint authentication methods")
})?;
if !methods.iter().any(|method| method.as_str() == Some("none")) {
bail!("{issuer_description} does not support public-client token endpoint authentication");
}
Ok(EmaClientAuthentication::None)
}
pub(crate) fn validate_ema_oauth_endpoint(endpoint: &str, description: &str) -> Result<()> {
let url = Url::parse(endpoint).with_context(|| format!("{description} is not a valid URL"))?;
validate_credential_destination(&url, description)
}
fn validate_credential_destination(url: &Url, description: &str) -> Result<()> {
let loopback = match url.host() {
Some(Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
Some(Host::Ipv4(address)) => address.is_loopback(),
Some(Host::Ipv6(address)) => address.is_loopback(),
None => false,
};
if url.scheme() != "https" && !(url.scheme() == "http" && loopback) {
bail!("{description} must use HTTPS or an HTTP loopback address");
}
if !url.username().is_empty() || url.password().is_some() || url.fragment().is_some() {
bail!("{description} contains disallowed credentials or a URL fragment");
}
Ok(())
}
pub(crate) fn advertised_capability(
value: Option<&Value>,
expected: &str,
description: &str,
) -> Result<Option<bool>> {
value
.map(|value| {
let values = value
.as_array()
.ok_or_else(|| anyhow!("{description} is malformed"))?;
Ok(values.iter().any(|value| value.as_str() == Some(expected)))
})
.transpose()
}
/// Resource indicators must describe the configured MCP origin, query and path.
pub fn validate_ema_auth_resource(server_url: &str, resource: Option<&str>) -> Result<()> {
let server = Url::parse(server_url).context("enterprise MCP server URL is invalid")?;
validate_credential_destination(&server, "enterprise MCP server URL")?;
let Some(resource) = resource.filter(|resource| !resource.trim().is_empty()) else {
return Ok(());
};
let resource = Url::parse(resource).context("enterprise MCP resource indicator is invalid")?;
validate_credential_destination(&resource, "enterprise MCP resource indicator")?;
if resource.origin() != server.origin() || resource.query() != server.query() {
bail!(
"enterprise MCP resource indicator must match the configured MCP server origin and query"
);
}
let resource_path = resource.path().trim_end_matches('/');
let server_path = server.path().trim_end_matches('/');
if server_path != resource_path
&& !server_path
.strip_prefix(resource_path)
.is_some_and(|suffix| suffix.starts_with('/'))
{
bail!("enterprise MCP resource indicator path must contain the configured MCP server path");
}
Ok(())
}
#[cfg(test)]
#[path = "ema_auth_policy_tests.rs"]
mod tests;

View File

@@ -1,73 +0,0 @@
use pretty_assertions::assert_eq;
use serde_json::json;
use super::*;
#[test]
fn resource_origin_query_and_path_are_bound() {
let server = "https://mcp.example/enterprise/tools?tenant=one";
for (resource, valid) in [
("https://mcp.example/enterprise?tenant=one", true),
("https://other.example/enterprise?tenant=one", false),
("https://mcp.example/enterprise-admin?tenant=one", false),
("https://mcp.example/enterprise?tenant=two", false),
("https://mcp.example/enterprise", false),
("http://localhost:4000/enterprise?tenant=one", false),
] {
assert_eq!(
validate_ema_auth_resource(server, Some(resource)).is_ok(),
valid,
"{resource}"
);
}
for (server, valid) in [
("https://mcp.example/mcp", true),
("http://localhost:4000/mcp", true),
("http://127.0.0.1:4000/mcp", true),
("http://mcp.example/mcp", false),
] {
assert_eq!(
validate_ema_auth_resource(server, /*resource*/ None).is_ok(),
valid,
"{server}"
);
}
}
#[test]
fn public_clients_require_an_explicitly_advertised_auth_method() {
for (advertised, valid) in [
(None, false),
(Some(json!(["none"])), true),
(Some(json!(["client_secret_basic", "none"])), true),
(Some(json!(["private_key_jwt"])), false),
(Some(json!("none")), false),
] {
assert_eq!(
resolve_ema_client_auth(
advertised.as_ref(),
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
"IdP"
)
.is_ok(),
valid
);
}
use McpEmaTokenEndpointAuthMethod::ClientSecretPost;
for (advertised, registered, valid) in [
(None, None, true),
(None, Some(ClientSecretPost), false),
(
Some(json!(["client_secret_basic"])),
Some(ClientSecretPost),
false,
),
(Some(json!(["client_secret_post"])), None, false),
] {
assert_eq!(
resolve_ema_client_auth(advertised.as_ref(), Some("secret"), registered, "IdP").is_ok(),
valid
);
}
}

View File

@@ -1,483 +0,0 @@
//! Bound metadata selection and HTTP confinement run before enterprise credential access.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_config::types::AuthKeyringBackendKind;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaInvalidGrantSource;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::test_support::TempCodexHome;
fn request<'a>(resource: &'a str, issuer: Option<&'a str>) -> EmaAuthTokenExchangeRequest<'a> {
let client: Arc<dyn HttpClient> = Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
)));
EmaAuthTokenExchangeRequest {
mcp_client_secret: None,
token_endpoint_auth_method: None,
server_url: resource,
resource: Some(resource),
scopes: &[],
mcp_client_id: Some("resource-client"),
expected_authorization_server_issuer: issuer,
idp_issuer: "https://idp.example",
idp_client_id: "enterprise-client",
idp_identity: Box::pin(async { bail!("identity resolver reached") }),
idp_http_client: Arc::clone(&client),
resource_http_client: client,
}
}
#[tokio::test]
async fn discovery_pins_resource_issuer_and_public_jwt_bearer_before_identity() -> Result<()> {
let metadata_cases = [
(true, true, json!({}), true),
(false, true, json!({}), false),
(true, false, json!({}), false),
]
.into_iter()
.chain(
[
json!({"issuer": null}),
json!({"issuer": "https://other.example"}),
json!({"token_endpoint": "https://other.example/token"}),
json!({"token_endpoint": "http://as.example/token"}),
json!({"grant_types_supported": null}),
json!({"grant_types_supported": ["authorization_code"]}),
json!({"authorization_grant_profiles_supported": ["other"]}),
json!({"token_endpoint_auth_methods_supported": ["private_key_jwt"]}),
]
.into_iter()
.map(|invalid| (true, true, invalid, false)),
);
let fallback_paths = [
"/.well-known/oauth-protected-resource/enterprise",
"/enterprise/.well-known/oauth-protected-resource",
"/.well-known/oauth-protected-resource",
];
let fallback_cases = fallback_paths.into_iter().flat_map(|path| {
[true, false].map(move |valid| ("GET", path, valid, true, json!({}), valid))
});
for (metadata_method, metadata_path, resource_matches, issuer_matches, additions, valid) in
metadata_cases
.map(|(resource, issuer, additions, valid)| {
(
"POST",
"/enterprise/tools",
resource,
issuer,
additions,
valid,
)
})
.chain(fallback_cases)
{
let server = MockServer::start().await;
let query = "tenant=one%2Ftwo&tenant=three+four&flag=&encoded=%2f";
let resource = format!("{}/enterprise?{query}", server.uri());
let transport = format!("{}/enterprise/tools?{query}", server.uri());
let issuer = format!("{}/as", server.uri());
// A query-only resource change must not be accepted as the same resource.
let advertised_resource = if resource_matches {
resource.clone()
} else {
resource.replace("one", "two")
};
Mock::given(method(metadata_method))
.and(path(metadata_path))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": advertised_resource,
"authorization_servers": [format!("{}/unused", server.uri()), issuer],
})))
.mount(&server)
.await;
let mut metadata = json!({"issuer": issuer, "token_endpoint": format!("{issuer}/token"),
"grant_types_supported": [JWT_BEARER_GRANT_TYPE],
"token_endpoint_auth_methods_supported": ["none"]});
metadata
.as_object_mut()
.expect("metadata")
.extend(additions.as_object().expect("overrides").clone());
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/as"))
.respond_with(ResponseTemplate::new(200).set_body_json(metadata))
.mount(&server)
.await;
let polled = AtomicBool::new(false);
let mut exchange = request(
&resource,
Some(if issuer_matches {
&issuer
} else {
"https://other.example"
}),
);
exchange.server_url = &transport;
exchange.idp_identity = Box::pin(async {
polled.store(true, Ordering::SeqCst);
bail!("identity resolver reached")
});
exchange_ema_auth_token(exchange, std::convert::identity)
.await
.expect_err("stop before token exchange");
assert_eq!(polled.load(Ordering::SeqCst), valid, "{additions}");
let requests = server.received_requests().await.expect("requests");
let resource_requests = requests
.iter()
.filter(|request| request.url.path() != "/.well-known/oauth-authorization-server/as")
.collect::<Vec<_>>();
assert!(
resource_requests
.iter()
.all(|request| request.url.query() == Some(query))
);
assert!(
resource_requests
.iter()
.all(|request| request.url.path() == "/enterprise/tools"
|| (metadata_method == "GET" && fallback_paths.contains(&request.url.path())))
);
assert_eq!(
resource_requests
.last()
.expect("resource metadata request")
.url
.path(),
metadata_path
);
}
Ok(())
}
#[tokio::test]
async fn modern_challenge_confines_metadata_redirects() -> Result<()> {
let server = MockServer::start().await;
let authorization = MockServer::start().await;
let attacker = MockServer::start().await;
let resource = format!("{}/mcp", server.uri());
let issuer = authorization.uri();
let prm = format!("{}/enterprise/resource", server.uri());
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &wiremock::Request| {
assert_eq!(request.headers["mcp-protocol-version"], "2026-07-28");
assert_eq!(
request.body_json::<Value>().expect("discovery")["method"],
"server/discover"
);
ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{prm}\""),
)
})
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/enterprise/resource"))
.respond_with(
ResponseTemplate::new(200)
.set_body_json(json!({"resource": resource, "authorization_servers": [issuer]})),
)
.mount(&server)
.await;
let metadata = json!({"issuer": issuer, "token_endpoint": format!("{issuer}/token"),
"grant_types_supported": [JWT_BEARER_GRANT_TYPE],
"token_endpoint_auth_methods_supported": ["none"]});
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(move |request: &wiremock::Request| {
assert!(!request.headers.contains_key("authorization"));
ResponseTemplate::new(200).set_body_json(metadata.clone())
})
.mount(&authorization)
.await;
let exchange = request(&resource, Some(&issuer));
let (metadata, actual_resource, _) = discover_ema_authorization_metadata(
EmaDiscoveryRequest::from(&exchange),
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
)
.await?;
assert_eq!(
(metadata.issuer, metadata.token_endpoint, actual_resource),
(
Some(issuer.clone()),
format!("{issuer}/token"),
resource.clone()
)
);
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server"))
.respond_with(
ResponseTemplate::new(307)
.insert_header("location", format!("{}/capture", attacker.uri())),
)
.with_priority(1)
.mount(&authorization)
.await;
let error = exchange_ema_auth_token(exchange, std::convert::identity)
.await
.err()
.context("cross-origin redirect must fail")?;
assert!(format!("{error:#}").contains("cross-origin redirect"));
assert_eq!(
EmaErrorDetail::from_error(&error).to_string(),
"enterprise MCP authorization server discovery failed"
);
assert!(
attacker
.received_requests()
.await
.expect("requests")
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn legacy_challenges_require_a_recognized_discovery_rejection() -> Result<()> {
for (status, id, code, message, legacy) in [
(404, json!(null), -1, "", true),
(405, json!(null), -1, "", true),
(
200,
json!("ema-auth-discover"),
-32601,
"Method not found",
true,
),
(
400,
json!("ema-auth-discover"),
-32022,
"Unsupported protocol version: 2026-07-28",
true,
),
(
400,
json!(null),
-32000,
"Bad Request: No valid session ID provided",
true,
),
(200, json!("unrelated"), -32601, "Method not found", false),
(400, json!(null), -32000, "Unrecognized rejection", false),
(503, json!(null), -1, "", false),
] {
for (sse, get_status) in [
(false, 401),
(false, 400),
(false, 404),
(false, 405),
(false, 406),
(true, 401),
(true, 405),
] {
let initialize = get_status != 401;
let server = MockServer::start().await;
let resource = format!("{}/mcp", server.uri());
let prm = format!("{}/custom/metadata", server.uri());
let rejection = if code == -1 {
ResponseTemplate::new(status)
} else {
let body = json!({
"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message},
});
if sse {
ResponseTemplate::new(status).set_body_raw(
format!(": keepalive\n\nevent: message\ndata: {body}\n\n"),
"text/event-stream",
)
} else {
ResponseTemplate::new(status).set_body_json(body)
}
};
let challenge = ResponseTemplate::new(401).insert_header(
"www-authenticate",
format!("Bearer resource_metadata=\"{prm}\""),
);
let post_challenge = challenge.clone();
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(move |request: &wiremock::Request| {
let body = request.body_json::<Value>().expect("probe");
if body["method"] == "server/discover" {
return rejection.clone();
}
assert!(legacy && initialize);
assert_eq!(body["method"], "initialize");
assert_eq!(body["params"]["protocolVersion"], "2025-06-18");
assert!(!request.headers.contains_key("authorization"));
post_challenge.clone()
})
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/mcp"))
.and(wiremock::matchers::header("accept", "text/event-stream"))
.respond_with(if initialize {
ResponseTemplate::new(get_status)
} else {
challenge
})
.expect(u64::from(legacy))
.mount(&server)
.await;
Mock::given(method("GET"))
.and(path("/custom/metadata"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"resource": resource, "authorization_servers": [server.uri()],
})))
.expect(u64::from(legacy))
.mount(&server)
.await;
let exchange = request(&resource, /*issuer*/ None);
let discovered = discover_ema_resource(EmaDiscoveryRequest::from(&exchange)).await;
assert_eq!(
discovered.is_ok(),
legacy,
"{status} {message}, sse={sse}, get_status={get_status}"
);
server.verify().await;
}
}
Ok(())
}
#[test]
fn discovery_rejects_private_or_ambiguous_issuer_destinations() -> Result<()> {
let resource = Url::parse("https://mcp.example/mcp")?;
for issuer in [
"http://issuer.example",
"https://10.0.0.1",
"https://127.0.0.1",
"https://169.254.169.254",
"https://100.64.0.1",
"https://198.19.0.1",
"https://192.0.2.1",
"https://[::ffff:192.0.2.1]",
"https://[fd00::1]",
"https://[::ffff:169.254.169.254]",
"https://metadata.google.internal",
"https://metadata.azure.internal",
"https://test.localhost",
"https://issuer.example?query=1",
"https://issuer.example#fragment",
"https://credentials@issuer.example",
] {
assert!(
validate_ema_metadata_issuer(&resource, &Url::parse(issuer)?).is_err(),
"{issuer}"
);
}
validate_ema_metadata_issuer(&resource, &Url::parse("https://issuer.example/tenant")?)?;
validate_ema_metadata_issuer(
&Url::parse("http://127.0.0.1/mcp")?,
&Url::parse("http://[::1]:1234")?,
)?;
Ok(())
}
#[tokio::test]
async fn rejected_grants_preserve_their_source_and_release_the_credential_lease() -> Result<()> {
let _home = TempCodexHome::new();
for failure_source in [
EmaInvalidGrantSource::EnterpriseIdentity,
EmaInvalidGrantSource::ResourceAuthorization,
] {
let server = MockServer::start().await;
let resource = format!("{}/mcp", server.uri());
let issuer = format!("{}/as", server.uri());
let idp = format!("{}/idp", server.uri());
let assertion = format!(
"{}.{}.{}",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256","typ":"oauth-id-jag+jwt"}"#),
URL_SAFE_NO_PAD.encode(serde_json::to_vec(&json!({"iss": idp, "aud": issuer,
"client_id": "resource-client", "sub": "user", "jti": "one", "iat": 0,
"exp": u64::MAX, "resource": resource}))?),
URL_SAFE_NO_PAD.encode(b"signature")
);
for (endpoint, status, response) in [
(
"/mcp",
200,
json!({"resource": resource, "authorization_servers": [issuer]}),
),
(
"/.well-known/oauth-authorization-server/as",
200,
json!({"issuer": issuer, "token_endpoint": format!("{issuer}/token"),
"grant_types_supported": [JWT_BEARER_GRANT_TYPE], "token_endpoint_auth_methods_supported": ["none"]}),
),
(
"/idp/token",
if failure_source == EmaInvalidGrantSource::EnterpriseIdentity {
400
} else {
200
},
if failure_source == EmaInvalidGrantSource::EnterpriseIdentity {
json!({"error": "invalid_grant"})
} else {
json!({"access_token": assertion, "token_type": "N_A", "issued_token_type": "urn:ietf:params:oauth:token-type:id-jag"})
},
),
("/as/token", 400, json!({"error": "invalid_grant"})),
] {
Mock::given(path(endpoint))
.respond_with(ResponseTemplate::new(status).set_body_json(response))
.mount(&server)
.await;
}
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": "ema-idp:revoked-test", "url": idp, "issuer": idp, "client_id": "enterprise-client",
"token_response": {"access_token": "unused", "token_type": "Bearer", "refresh_token": "old-grant"},
}))?;
let credentials = StoredOAuthCredentialSnapshot::new(tokens.clone(), store);
let mut exchange = request(&resource, Some(&issuer));
exchange.idp_issuer = &idp;
exchange.idp_identity = Box::pin(async {
Ok(EmaIdpIdentity {
client_authentication: EmaClientAuthentication::None,
token_endpoint: format!("{idp}/token"),
refresh_token: "old-grant".to_string(),
credentials: crate::EmaCredentialLease { credentials },
})
});
let error = exchange_ema_auth_token(exchange, std::convert::identity)
.await
.expect_err("invalid grant");
assert_eq!(
error.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::InvalidGrant {
grant_source: failure_source
})
);
let _exclusive = tokio::time::timeout(
std::time::Duration::from_secs(1),
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &idp),
)
.await
.expect("failed exchange must not retain the credential lock")?;
}
Ok(())
}

View File

@@ -1,105 +0,0 @@
//! Validate OIDC identity assertion bindings before storing enterprise credentials.
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::Deserialize;
use serde::de::DeserializeOwned;
pub(crate) const ID_JAG_TOKEN_TYPE: &str = "urn:ietf:params:oauth:token-type:id-jag";
#[derive(Deserialize)]
struct JwtHeader {
alg: String,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum OAuthResource {
Single(String),
Multiple(Vec<String>),
}
fn signed_jwt<T: DeserializeOwned>(token: &str) -> Result<T> {
let mut parts = token.split('.');
let (Some(header), Some(payload), Some(signature), None) =
(parts.next(), parts.next(), parts.next(), parts.next())
else {
bail!("identity assertion is not a compact signed JWT");
};
if header.is_empty() || payload.is_empty() || signature.is_empty() {
bail!("identity assertion contains an empty JWT segment");
}
let header: JwtHeader = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(header)?)
.map_err(|_| anyhow!("invalid identity assertion JWT header"))?;
if header.alg.trim().is_empty() || header.alg.eq_ignore_ascii_case("none") {
bail!("identity assertion is unsigned");
}
let claims = serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload)?)
.map_err(|_| anyhow!("invalid identity assertion JWT claims"))?;
Ok(claims)
}
#[derive(Deserialize)]
pub(crate) struct OidcClaims {
iss: String,
sub: String,
aud: OAuthResource,
azp: Option<String>,
exp: u64,
}
pub(crate) fn oidc_identity(
assertion: &str,
expected_issuer: &str,
expected_audience: &str,
) -> Result<OidcClaims> {
if expected_issuer.trim().is_empty() || expected_audience.trim().is_empty() {
bail!("OIDC identity assertion requires a non-empty expected issuer and client");
}
let claims: OidcClaims = signed_jwt(assertion)?;
if claims.iss != expected_issuer || claims.sub.trim().is_empty() {
bail!("OIDC identity assertion issuer or subject does not match the enterprise IdP");
}
let (audience_matches, multiple_audiences) = match &claims.aud {
OAuthResource::Single(value) => (value == expected_audience, false),
OAuthResource::Multiple(values) => (
values.iter().any(|value| value == expected_audience),
values.len() > 1,
),
};
if !audience_matches
|| claims
.azp
.as_deref()
.is_some_and(|party| party != expected_audience)
|| multiple_audiences && claims.azp.as_deref() != Some(expected_audience)
{
bail!("OIDC identity assertion audience or authorized party does not match the IdP client");
}
Ok(claims)
}
/// Unverified issuer claim used only to explain a legacy login migration.
/// Never use this hint to choose where a refresh token is sent.
pub(crate) fn oidc_issuer_hint(assertion: &str, expected_issuer: &str) -> bool {
signed_jwt::<OidcClaims>(assertion).is_ok_and(|claims| claims.iss == expected_issuer)
}
pub(crate) fn validate_oidc_identity_assertion(
assertion: &str,
expected_issuer: &str,
expected_audience: &str,
) -> Result<()> {
let claims = oidc_identity(assertion, expected_issuer, expected_audience)?;
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
if claims.exp <= now {
bail!("OIDC identity assertion is expired");
}
Ok(())
}

View File

@@ -1,161 +0,0 @@
//! Adapt the SDK enterprise exchange to Codex HTTP routing and credential lifecycle errors.
use std::sync::Arc;
use std::time::Duration;
use anyhow::Result;
use codex_exec_server::HttpClient;
use oauth2::RefreshToken;
use rmcp::transport::auth::enterprise::EmaAuthorizationServer;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
use rmcp::transport::auth::enterprise::EmaError;
use rmcp::transport::auth::enterprise::EmaExchangeRequest;
use rmcp::transport::auth::enterprise::EmaExchangeStage;
use tokio::time::Instant;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaInvalidGrantSource;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::build_default_headers;
pub(crate) const TOKEN_EXCHANGE_GRANT_TYPE: &str =
"urn:ietf:params:oauth:grant-type:token-exchange";
pub(crate) const JWT_BEARER_GRANT_TYPE: &str = "urn:ietf:params:oauth:grant-type:jwt-bearer";
/// A resource-bound bearer and its server-reported lifetime, with redacted diagnostics.
#[derive(Clone, PartialEq, Eq)]
pub struct EmaAccessToken {
pub access_token: String,
pub expires_in: Option<Duration>,
/// Exchange completion time, before any asynchronous credential validation.
pub received_at: Instant,
}
impl std::fmt::Debug for EmaAccessToken {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("EmaAccessToken")
.field("access_token", &"[REDACTED]")
.field("expires_in", &self.expires_in)
.finish()
}
}
/// The caller supplies trusted authorization-server metadata and an IdP credential.
/// This primitive does not perform resource discovery or interactive login.
pub(crate) struct EmaIdJagExchangeRequest<'a> {
pub resource: &'a str,
pub scopes: &'a [String],
pub mcp_client_id: &'a str,
pub authorization_server_issuer: &'a str,
pub authorization_server_token_endpoint: &'a str,
pub idp_token_endpoint: &'a str,
pub idp_issuer: &'a str,
pub idp_client_id: &'a str,
pub idp_client_authentication: EmaClientAuthentication,
pub resource_client_authentication: EmaClientAuthentication,
pub refresh_token: String,
pub idp_http_client: Arc<dyn HttpClient>,
pub resource_http_client: Arc<dyn HttpClient>,
}
/// Exchanges an enterprise IdP credential for a resource-bound MCP bearer token.
pub(crate) async fn exchange_id_jag<L: Send, R: Send>(
request: EmaIdJagExchangeRequest<'_>,
credentials: L,
finish_idp: impl FnOnce(L) -> R + Send,
) -> Result<(EmaAccessToken, R)> {
let idp_http = OAuthHttpClientAdapter::new_with_redirect_mode(
request.idp_http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
request.idp_token_endpoint,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?;
let resource_http = OAuthHttpClientAdapter::new_with_redirect_mode(
request.resource_http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
request.authorization_server_token_endpoint,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?;
let refresh_token = RefreshToken::new(request.refresh_token);
// Discovery has already verified each registration's authentication method. The SDK owns
// token validation and the two exchanges; Codex retains routing and credential policy.
let assertion = EmaExchangeRequest::new(
EmaAuthorizationServer::new(
request.idp_issuer,
request.idp_token_endpoint,
request.idp_client_id,
)
.with_client_authentication(request.idp_client_authentication),
EmaAuthorizationServer::new(
request.authorization_server_issuer,
request.authorization_server_token_endpoint,
request.mcp_client_id,
)
.with_client_authentication(request.resource_client_authentication),
request.resource,
&refresh_token,
)
.with_scopes(request.scopes.iter().cloned())
.exchange_id_jag(&idp_http)
.await
.map_err(exchange_error)?;
drop(refresh_token);
// Only the IdP uses the refresh token. Release its lease before resource-AS I/O.
let receipt = finish_idp(credentials);
let token = assertion
.exchange(&resource_http)
.await
.map_err(exchange_error)?;
Ok((
EmaAccessToken {
access_token: token.access_token.secret().to_owned(),
expires_in: token.expires_in,
received_at: Instant::now(),
},
receipt,
))
}
fn exchange_error(error: EmaError) -> anyhow::Error {
let failure = match &error {
EmaError::InvalidGrant(EmaExchangeStage::IdentityProvider) => {
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
})
}
EmaError::InvalidGrant(EmaExchangeStage::ResourceAuthorizationServer) => {
Some(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
})
}
EmaError::InsufficientUserAuthentication(EmaExchangeStage::IdentityProvider) => {
Some(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
})
}
EmaError::InsufficientUserAuthentication(EmaExchangeStage::ResourceAuthorizationServer) => {
Some(EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
})
}
EmaError::OAuthRejected {
stage: EmaExchangeStage::IdentityProvider,
code: "unauthorized_client" | "invalid_client",
..
} => Some(EmaAuthFailure::IdentityClientRejected),
// Future SDK stages must not invalidate the shared enterprise credential.
_ => None,
};
match failure {
Some(failure) => anyhow::Error::new(failure).context(error),
None => anyhow::Error::new(error),
}
}
#[cfg(test)]
#[path = "ema_exchange_tests.rs"]
mod tests;

View File

@@ -1,468 +0,0 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use serde_json::Value;
use serde_json::json;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::EmaCredentialKind;
use crate::EmaErrorDetail;
use crate::EmaTokenSourceError;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_claims::ID_JAG_TOKEN_TYPE;
use crate::ema_claims::validate_oidc_identity_assertion;
fn http_client() -> Arc<dyn HttpClient> {
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
)))
}
fn unique_form_fields(body: &[u8]) -> HashMap<String, String> {
let pairs = url::form_urlencoded::parse(body)
.into_owned()
.collect::<Vec<_>>();
let fields = pairs.iter().cloned().collect::<HashMap<_, _>>();
assert_eq!(
pairs.len(),
fields.len(),
"OAuth form must not contain duplicate fields"
);
fields
}
fn jwt(claims: &Value) -> String {
format!(
"{}.{}.c2lnbmF0dXJl",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256","typ":"oauth-id-jag+jwt"}"#),
URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).expect("serialize claims"))
)
}
fn claims(issuer: &str, audience: &str, resource: &str) -> Value {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("current time")
.as_secs();
json!({"iss":issuer,"aud":audience,"sub":"user","client_id":"mcp-client",
"jti":"unique-jag","iat":now,"exp":now + 3600,"resource":resource,"scope":"files.read"})
}
fn jag_response(claims: &Value) -> Value {
let mut response = json!({"access_token":jwt(claims),"issued_token_type":ID_JAG_TOKEN_TYPE,
"token_type":"N_A","resource":claims["resource"]});
if let Some(scope) = claims.get("scope") {
response["scope"] = scope.clone();
}
response
}
fn token_response() -> Value {
json!({"access_token":"resource-token","token_type":"Bearer","expires_in":300})
}
async fn exchange(server: &MockServer, refresh_token: &str) -> Result<EmaAccessToken> {
let issuer = format!("{}/idp", server.uri());
let audience = format!("{}/as", server.uri());
exchange_id_jag(
EmaIdJagExchangeRequest {
idp_client_authentication: EmaClientAuthentication::None,
resource_client_authentication: EmaClientAuthentication::None,
resource: &format!("{}/mcp", server.uri()),
scopes: &[],
mcp_client_id: "mcp-client",
authorization_server_issuer: &audience,
authorization_server_token_endpoint: &format!("{audience}/token"),
idp_token_endpoint: &format!("{issuer}/token"),
idp_issuer: &issuer,
idp_client_id: "idp-client",
refresh_token: refresh_token.to_string(),
idp_http_client: http_client(),
resource_http_client: http_client(),
},
(),
std::convert::identity,
)
.await
.map(|(token, ())| token)
}
#[tokio::test]
async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
let requested_scopes = ["files.read".to_string(), "files.write".to_string()];
let client = http_client();
use codex_config::McpEmaTokenEndpointAuthMethod::ClientSecretBasic;
use codex_config::McpEmaTokenEndpointAuthMethod::ClientSecretPost;
for (scopes, echo_scope, refresh_token, idp_method) in [
(
requested_scopes.as_slice(),
true,
"opaque-refresh-token",
None,
),
(&[], true, "opaque-refresh-token", Some(ClientSecretBasic)),
(&[], false, "opaque-refresh-token", Some(ClientSecretPost)),
(requested_scopes.as_slice(), true, "", None),
(requested_scopes.as_slice(), true, " \t", None),
] {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
let audience = format!("{}/as", server.uri());
let resource = format!("{}/mcp", server.uri());
let mut jag = jag_response(&claims(&issuer, &audience, &resource));
if !echo_scope {
jag.as_object_mut()
.expect("ID-JAG response")
.remove("scope");
}
let valid = !refresh_token.trim().is_empty();
for (endpoint, response) in [("/idp/token", jag.clone()), ("/as/token", token_response())] {
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(u64::from(valid))
.mount(&server)
.await;
}
let expected_subject = refresh_token.to_string();
let resource_method = idp_method.map(|method| match method {
ClientSecretBasic => ClientSecretPost,
ClientSecretPost => ClientSecretBasic,
});
let authentication = |method: Option<_>, secret| {
crate::ema_auth_policy::resolve_ema_client_auth(
Some(&json!([
"none",
"client_secret_basic",
"client_secret_post"
])),
method.map(|_| secret),
method,
"test issuer",
)
};
let idp_secret = "idp:+ /%secret";
let resource_secret = "resource:+ /%secret";
let result = exchange_id_jag(
EmaIdJagExchangeRequest {
idp_client_authentication: authentication(idp_method, idp_secret)?,
resource_client_authentication: authentication(resource_method, resource_secret)?,
resource: &resource,
scopes,
mcp_client_id: "mcp-client",
authorization_server_issuer: &audience,
authorization_server_token_endpoint: &format!("{audience}/token"),
idp_token_endpoint: &format!("{issuer}/token"),
idp_issuer: &issuer,
idp_client_id: "idp-client",
refresh_token: refresh_token.to_string(),
idp_http_client: Arc::clone(&client),
resource_http_client: Arc::clone(&client),
},
(),
std::convert::identity,
)
.boxed()
.await
.map(|(token, ())| token);
if !valid {
assert!(result.is_err(), "invalid subject must fail before HTTP");
assert!(
server
.received_requests()
.await
.expect("requests")
.is_empty()
);
continue;
}
let token = result?;
assert_eq!(
token,
EmaAccessToken {
access_token: "resource-token".to_string(),
expires_in: Some(Duration::from_secs(300)),
received_at: token.received_at,
}
);
let requests = server.received_requests().await.expect("requests");
assert_eq!(requests.len(), 2);
let mut forms = requests
.iter()
.map(|request| unique_form_fields(&request.body))
.collect::<Vec<_>>();
for (index, (method, client_id, secret)) in [
(idp_method, "idp-client", idp_secret),
(resource_method, "mcp-client", resource_secret),
]
.into_iter()
.enumerate()
{
let authorization = requests[index]
.headers
.get("authorization")
.map(|value| value.to_str().unwrap());
let encoded = url::form_urlencoded::byte_serialize(secret.as_bytes())
.collect::<String>()
.replace("%20", "+");
let basic = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!("{client_id}:{encoded}"))
);
assert_eq!(
authorization,
(method == Some(ClientSecretBasic)).then_some(basic.as_str())
);
assert_eq!(
forms[index].remove("client_secret").as_deref(),
(method == Some(ClientSecretPost)).then_some(secret)
);
assert_eq!(
forms[index].remove("client_id").as_deref(),
(method != Some(ClientSecretBasic)).then_some(client_id)
);
}
assert_eq!(
forms[0].remove("scope"),
(!scopes.is_empty()).then(|| scopes.join(" "))
);
assert_eq!(
forms[0],
HashMap::from([
(
"grant_type".to_string(),
TOKEN_EXCHANGE_GRANT_TYPE.to_string()
),
(
"requested_token_type".to_string(),
ID_JAG_TOKEN_TYPE.to_string(),
),
("subject_token".to_string(), expected_subject),
(
"subject_token_type".to_string(),
"urn:ietf:params:oauth:token-type:refresh_token".to_string(),
),
("audience".to_string(), audience.clone()),
("resource".to_string(), resource.clone()),
])
);
assert_eq!(
forms[1],
HashMap::from([
("grant_type".to_string(), JWT_BEARER_GRANT_TYPE.to_string()),
(
"assertion".to_string(),
jag["access_token"].as_str().expect("JAG").to_string()
),
])
);
}
Ok(())
}
#[tokio::test]
async fn sdk_validation_rejects_unsupported_authorization_before_returning_a_bearer() {
for location in [
"signed claims",
"IdP response",
"resource response",
"signed scope",
] {
let server = MockServer::builder().start().await;
let original = claims(
&format!("{}/idp", server.uri()),
&format!("{}/as", server.uri()),
&format!("{}/mcp", server.uri()),
);
let mut jag = jag_response(&original);
let mut bearer = token_response();
let details = json!([{"type": "payment_initiation"}]);
match location {
"signed claims" | "signed scope" => {
let mut changed = original;
if location == "signed claims" {
changed["authorization_details"] = details;
} else {
changed["scope"] = json!("files.read\tfiles.write");
}
jag = jag_response(&changed);
}
"IdP response" => jag["authorization_details"] = details,
"resource response" => bearer["authorization_details"] = details,
_ => unreachable!(),
}
let resource_requested = location == "resource response";
for (endpoint, response, count) in [
("/idp/token", jag, 1),
("/as/token", bearer, u64::from(resource_requested)),
] {
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(ResponseTemplate::new(200).set_body_json(response))
.expect(count)
.mount(&server)
.await;
}
let error = exchange(&server, "refresh-token")
.await
.expect_err("SDK must reject unsupported authorization");
assert_eq!(
error.downcast_ref::<EmaError>(),
Some(&EmaError::InvalidResponse {
stage: if resource_requested {
EmaExchangeStage::ResourceAuthorizationServer
} else {
EmaExchangeStage::IdentityProvider
},
message: if location == "signed scope" {
"malformed or duplicate scopes"
} else {
"authorization_details is not supported"
},
}),
"{location}"
);
assert_eq!(
server.received_requests().await.expect("requests").len(),
if resource_requested { 2 } else { 1 }
);
}
}
#[test]
fn identity_and_credential_destinations_are_bound() {
for endpoint in [
"http://idp.example/token",
"https://user:pass@idp.example/token",
"https://idp.example/token#fragment",
] {
assert!(
validate_ema_oauth_endpoint(endpoint, "IdP").is_err(),
"accepted {endpoint}"
);
}
let original = claims("https://idp.example", "idp-client", "https://mcp.example");
assert!(
validate_oidc_identity_assertion(&jwt(&original), "https://idp.example", "idp-client")
.is_ok()
);
for (field, value) in [
("iss", json!("https://other.example")),
("aud", json!(["idp-client", "other"])),
("azp", json!("other")),
("exp", json!(0)),
("sub", json!("")),
] {
let mut changed = original.clone();
changed[field] = value;
assert!(
validate_oidc_identity_assertion(&jwt(&changed), "https://idp.example", "idp-client")
.is_err(),
"accepted changed {field}"
);
}
}
#[tokio::test]
async fn provider_errors_preserve_credential_policy_without_reflecting_credentials() {
const SENTINEL: &str = "secret-assertion-sentinel";
for (endpoint, grant_source) in [
("/idp/token", EmaInvalidGrantSource::EnterpriseIdentity),
("/as/token", EmaInvalidGrantSource::ResourceAuthorization),
] {
for code in [
SENTINEL,
"invalid_grant",
"insufficient_user_authentication",
"unauthorized_client",
"invalid_client",
"invalid_scope",
"malformed",
] {
let server = MockServer::builder().start().await;
if endpoint == "/as/token" {
let jag = jag_response(&claims(
&format!("{}/idp", server.uri()),
&format!("{}/as", server.uri()),
&format!("{}/mcp", server.uri()),
));
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(jag))
.expect(1)
.mount(&server)
.await;
}
let response = if code == "malformed" {
ResponseTemplate::new(200).set_body_json(json!({"expires_in": SENTINEL}))
} else {
ResponseTemplate::new(400).set_body_json(json!({
"error":code,"error_description":SENTINEL,
}))
};
Mock::given(method("POST"))
.and(path(endpoint))
.respond_with(response)
.expect(1)
.mount(&server)
.await;
let error = exchange(&server, SENTINEL)
.await
.expect_err("provider error should fail");
let expected = match code {
"invalid_grant" => Some(EmaAuthFailure::InvalidGrant { grant_source }),
"insufficient_user_authentication" => {
Some(EmaAuthFailure::InsufficientUserAuthentication { grant_source })
}
"unauthorized_client" | "invalid_client"
if grant_source == EmaInvalidGrantSource::EnterpriseIdentity =>
{
Some(EmaAuthFailure::IdentityClientRejected)
}
_ => None,
};
assert_eq!(error.downcast_ref::<EmaAuthFailure>(), expected.as_ref());
assert!(
!format!("{error:#?}").contains(SENTINEL),
"provider reflected a credential"
);
// Even an unsafe outer context must not reach the transport diagnostic.
let detail = EmaErrorDetail::from_error(&error.context(SENTINEL));
let transport_error = EmaTokenSourceError::Unexpected {
credential: EmaCredentialKind::Keyring,
detail,
};
assert!(!format!("{transport_error:#?} {transport_error}").contains(SENTINEL));
if code == "invalid_scope" {
let stage = if endpoint == "/idp/token" {
"IdentityProvider"
} else {
"ResourceAuthorizationServer"
};
assert_eq!(
transport_error.to_string(),
format!("{stage}: HTTP 400: invalid_scope")
);
}
assert_eq!(
server.received_requests().await.expect("requests").len(),
if endpoint == "/as/token" { 2 } else { 1 },
"exchange must not retry a rejected grant"
);
}
}
}

View File

@@ -1,387 +0,0 @@
//! Renewable, endpoint-confined EMA bearers. An unauthorized MCP operation is never replayed.
//! Authentication shares the request deadline, and a rejected bearer cannot evict a newer one.
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::MutexGuard;
use std::sync::PoisonError;
use std::time::Duration;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpClient;
use codex_exec_server::HttpHeader;
use codex_exec_server::HttpRedirectPolicy;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::future::BoxFuture;
use tokio::sync::OwnedRwLockReadGuard;
use tokio::sync::RwLock;
use tokio::sync::Semaphore;
use tokio::time::Instant;
use tokio_util::sync::CancellationToken;
use url::Url;
use crate::EmaAccessToken;
use crate::is_authentication_required_error;
use crate::validate_ema_auth_resource;
/// Supplies resource tokens for one immutable endpoint and pinned enterprise login.
/// Credential ownership is checked when renewing a token, not for cached bearer requests.
pub trait EmaTokenSource: Send + Sync {
fn endpoint(&self) -> &Url;
/// Acquires and validates credentials for renewal. Implementations recheck ownership
/// and a saved grant's generation after exchange before publishing the bearer.
fn access_token(&self) -> impl Future<Output = anyhow::Result<EmaAccessToken>> + Send;
}
/// Revocable authority held while one EMA connection awaits HTTP responses.
#[derive(Clone)]
pub struct EmaRequestAuthority {
revoked: CancellationToken,
is_current: Arc<dyn Fn() -> bool + Send + Sync>,
responses: Arc<RwLock<()>>,
policy: Option<codex_config::CloudConfigBundleBinding>,
}
impl Default for EmaRequestAuthority {
fn default() -> Self {
Self::new(CancellationToken::new(), || true)
}
}
impl EmaRequestAuthority {
/// Couples prompt cancellation with a synchronous check at each HTTP boundary.
/// The check must be cheap and must not perform credential or network I/O.
pub fn new(
revoked: CancellationToken,
is_current: impl Fn() -> bool + Send + Sync + 'static,
) -> Self {
Self {
revoked,
is_current: Arc::new(is_current),
responses: Arc::default(),
policy: None,
}
}
/// Policy changes stop new dispatches without cancelling already admitted responses.
pub fn with_policy(mut self, policy: Option<codex_config::CloudConfigBundleBinding>) -> Self {
self.policy = policy;
self
}
/// Isolate one connection's credential failure while sharing the owner's response drain.
pub fn child(&self) -> Self {
let owner = self.clone();
Self {
revoked: self.revoked.child_token(),
is_current: Arc::new(move || !owner.is_revoked()),
responses: Arc::clone(&self.responses),
policy: self.policy.clone(),
}
}
pub fn revoke(&self) {
self.revoked.cancel();
}
pub fn is_revoked(&self) -> bool {
if !self.revoked.is_cancelled() && !(self.is_current)() {
self.revoke();
}
self.revoked.is_cancelled()
}
pub fn check(&self) -> Result<(), ExecServerError> {
if self.is_revoked() {
return Err(revoked_authority_error());
}
Ok(())
}
pub fn check_new_request(&self) -> Result<(), ExecServerError> {
self.check()?;
if self.policy.as_ref().is_some_and(|binding| {
binding.read().status != codex_config::CloudConfigBundleBindingStatus::Current
}) {
return Err(ExecServerError::RequestNotSent(
"enterprise MCP policy is updating or unavailable; retry after it is applied"
.into(),
));
}
Ok(())
}
/// Wait until response futures admitted before revocation complete or are cancelled.
pub async fn quiesce(&self) {
let _responses = self.responses.clone().write_owned().await;
}
async fn acquire(&self) -> Result<OwnedRwLockReadGuard<()>, ExecServerError> {
let response = self.responses.clone().read_owned().await;
self.check_new_request()?;
Ok(response)
}
async fn cancelled(&self) {
self.revoked.cancelled().await;
}
}
/// Adds a renewable resource bearer to the existing runtime-selected HTTP capability.
pub struct EmaAuthenticatedHttpClient<S> {
inner: Arc<dyn HttpClient>,
source: S,
authority: EmaRequestAuthority,
token: Mutex<Option<CachedToken>>,
renewal: Semaphore,
}
struct CachedToken {
value: String,
refresh_at: Instant,
}
impl CachedToken {
fn new(token: EmaAccessToken) -> Self {
// Bound reuse even when the authorization server omits an expiry.
let lifetime = token
.expires_in
.unwrap_or(Duration::from_secs(300))
.min(Duration::from_secs(300));
let skew = Duration::from_secs(30).min(lifetime / 2);
Self {
value: token.access_token,
refresh_at: token.received_at + lifetime.saturating_sub(skew),
}
}
}
impl<S: EmaTokenSource> EmaAuthenticatedHttpClient<S> {
pub fn new(
inner: Arc<dyn HttpClient>,
source: S,
access_token: EmaAccessToken,
authority: EmaRequestAuthority,
) -> Self {
Self {
inner,
source,
authority,
token: Mutex::new(Some(CachedToken::new(access_token))),
renewal: Semaphore::new(/*permits*/ 1),
}
}
fn cached_token(&self) -> MutexGuard<'_, Option<CachedToken>> {
self.token.lock().unwrap_or_else(PoisonError::into_inner)
}
async fn authenticate(
&self,
params: &mut HttpRequestParams,
) -> Result<String, ExecServerError> {
let expected = self.source.endpoint();
let target = Url::parse(&params.url).map_err(|_| {
ExecServerError::HttpRequest("invalid enterprise MCP destination".to_string())
})?;
if expected.origin() != target.origin()
|| expected.path() != target.path()
|| expected.query() != target.query()
|| validate_ema_auth_resource(&params.url, /*resource*/ None).is_err()
{
return Err(ExecServerError::HttpRequest(
"refusing to send enterprise bearer outside the configured MCP endpoint"
.to_string(),
));
}
let current_token = || {
self.cached_token()
.as_ref()
.filter(|token| Instant::now() < token.refresh_at)
.map(|token| token.value.clone())
};
let value = if let Some(value) = current_token() {
value
} else {
let _renewal = self.renewal.acquire().await.map_err(|_| {
ExecServerError::HttpRequest("enterprise token renewal gate closed".to_string())
})?;
if let Some(value) = current_token() {
value
} else {
let renewed = self.source.access_token().await.map_err(|error| {
if let Err(refusal) = self.authority.check_new_request() {
return refusal;
}
if is_authentication_required_error(&error) {
self.authority.revoke();
}
auth_error(error)
})?;
let token = CachedToken::new(renewed);
if Instant::now() >= token.refresh_at {
return Err(ExecServerError::HttpRequest(
"enterprise MCP bearer expired during credential validation".to_string(),
));
}
let value = token.value.clone();
*self.cached_token() = Some(token);
value
}
};
params.redirect_policy = HttpRedirectPolicy::Stop;
params
.headers
.retain(|header| !header.name.eq_ignore_ascii_case("authorization"));
params.headers.push(HttpHeader {
name: "authorization".to_string(),
value: format!("Bearer {value}"),
value_env_var: None,
});
Ok(value)
}
fn clear_rejected_token(&self, rejected: &str) {
let mut token = self.cached_token();
if token.as_ref().is_some_and(|token| token.value == rejected) {
*token = None;
}
}
fn validate_response(
&self,
response: &HttpRequestResponse,
token: &str,
) -> Result<(), ExecServerError> {
if response.status == 401 {
self.clear_rejected_token(token);
return Err(ExecServerError::AuthenticationRequired(
"enterprise MCP bearer was rejected; reconnect to renew authorization".to_string(),
));
}
// An outer redirect wrapper may still follow a response even though the
// inner HTTP capability received Stop. Do not let it replay this operation.
if (300..400).contains(&response.status) {
return Err(ExecServerError::HttpRequest(
"enterprise MCP redirects are not allowed".to_string(),
));
}
Ok(())
}
}
fn auth_error(error: anyhow::Error) -> ExecServerError {
if let Some(error) = error.downcast_ref::<crate::EmaTokenSourceError>() {
return if error.is_authentication_required() {
ExecServerError::AuthenticationRequired(error.to_string())
} else {
ExecServerError::HttpRequest(error.to_string())
};
}
if is_authentication_required_error(&error) {
ExecServerError::AuthenticationRequired(
"enterprise MCP authentication is required".to_string(),
)
} else {
ExecServerError::HttpRequest(
"enterprise MCP token acquisition or credential validation failed".to_string(),
)
}
}
impl<S: EmaTokenSource> HttpClient for EmaAuthenticatedHttpClient<S> {
fn http_request(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async move {
let deadline = params
.timeout_ms
.map(|timeout_ms| Instant::now() + Duration::from_millis(timeout_ms));
let request = async {
let _authority = self.authority.acquire().await?;
let token = self.authenticate(&mut params).await?;
self.authority.check_new_request()?;
if let Some(deadline) = deadline {
params.timeout_ms = Some(remaining_timeout(deadline)?);
}
let response = self.inner.http_request(params).await?;
self.authority.check()?;
self.validate_response(&response, &token)?;
Ok(response)
};
tokio::select! {
biased;
() = self.authority.cancelled() => Err(revoked_authority_error()),
() = deadline_elapsed(deadline) => Err(request_timeout_error()),
result = request => result,
}
})
}
fn http_request_stream(
&self,
mut params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
Box::pin(async move {
let deadline = params
.timeout_ms
.map(|timeout_ms| Instant::now() + Duration::from_millis(timeout_ms));
let request = async {
let _authority = self.authority.acquire().await?;
let token = self.authenticate(&mut params).await?;
self.authority.check_new_request()?;
if let Some(deadline) = deadline {
params.timeout_ms = Some(remaining_timeout(deadline)?);
}
let response = self.inner.http_request_stream(params).await?;
self.authority.check()?;
self.validate_response(&response.0, &token)?;
Ok((
response.0,
response.1.cancel_on(self.authority.revoked.clone()),
))
};
tokio::select! {
biased;
() = self.authority.cancelled() => Err(revoked_authority_error()),
() = deadline_elapsed(deadline) => Err(request_timeout_error()),
result = request => result,
}
})
}
}
async fn deadline_elapsed(deadline: Option<Instant>) {
match deadline {
Some(deadline) => tokio::time::sleep_until(deadline).await,
None => std::future::pending().await,
}
}
fn remaining_timeout(deadline: Instant) -> Result<u64, ExecServerError> {
let remaining = deadline
.checked_duration_since(Instant::now())
.filter(|remaining| !remaining.is_zero())
.ok_or_else(request_timeout_error)?;
Ok(u64::try_from(remaining.as_millis())
.unwrap_or(u64::MAX)
.max(1))
}
fn request_timeout_error() -> ExecServerError {
ExecServerError::HttpRequest("enterprise MCP request timed out".to_string())
}
fn revoked_authority_error() -> ExecServerError {
ExecServerError::AuthenticationRequired(
"enterprise MCP authorization changed; reconnect before using this server".to_string(),
)
}
#[cfg(test)]
#[path = "ema_http_client_tests.rs"]
mod tests;

View File

@@ -1,470 +0,0 @@
//! Authentication, deadlines, and concurrent responses share the same request invariants.
use codex_config::CloudConfigBundlePolicy;
use codex_config::CloudConfigBundleSnapshot;
use codex_config::test_support::CloudConfigBundleFixture;
use pretty_assertions::assert_eq;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
use super::*;
use crate::ema_auth_policy::EmaInvalidGrantSource;
type Client = EmaAuthenticatedHttpClient<Arc<Source>>;
#[derive(Clone, Copy)]
enum RequestMode {
Buffered,
Streaming,
}
impl RequestMode {
fn start(
self,
client: Arc<Client>,
mut params: HttpRequestParams,
) -> tokio::task::JoinHandle<Result<HttpRequestResponse, ExecServerError>> {
tokio::spawn(async move {
params.stream_response = matches!(self, Self::Streaming);
match self {
Self::Buffered => client.http_request(params).await,
Self::Streaming => client
.http_request_stream(params)
.await
.map(|(response, _body)| response),
}
})
}
}
#[derive(Debug)]
struct PendingRequest {
params: HttpRequestParams,
response: oneshot::Sender<u16>,
}
struct ControlledHttpClient(mpsc::UnboundedSender<PendingRequest>);
impl HttpClient for ControlledHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
Box::pin(async move {
let (response, receiver) = oneshot::channel();
self.0
.send(PendingRequest { params, response })
.expect("capture HTTP request");
Ok(HttpRequestResponse {
status: receiver.await.expect("provide HTTP response"),
headers: Vec::new(),
body: Vec::new().into(),
})
})
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
Box::pin(async move {
Ok((
self.http_request(params).await?,
HttpResponseBodyStream::from_chunks(Vec::new()),
))
})
}
}
fn controlled_fixture() -> (
Arc<Client>,
Arc<Source>,
HttpRequestParams,
mpsc::UnboundedReceiver<PendingRequest>,
) {
controlled_fixture_for_endpoint("https://mcp.example/mcp")
}
fn controlled_fixture_for_endpoint(
endpoint: &str,
) -> (
Arc<Client>,
Arc<Source>,
HttpRequestParams,
mpsc::UnboundedReceiver<PendingRequest>,
) {
let (mut client, source, params) = fixture(endpoint);
let (sender, receiver) = mpsc::unbounded_channel();
client.inner = Arc::new(ControlledHttpClient(sender));
(Arc::new(client), source, params, receiver)
}
#[tokio::test]
async fn exact_endpoint_and_renewal_credentials_are_checked_before_network_use()
-> anyhow::Result<()> {
let endpoint = "https://mcp.example/mcp?tenant=one";
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
let (client, source, params, mut requests) = controlled_fixture_for_endpoint(endpoint);
for target in [
endpoint.replace("one", "two"),
endpoint.replace("/mcp", "/other"),
"https://other.example/mcp?tenant=one".to_string(),
format!("{endpoint}#fragment"),
] {
let mut request = params.clone();
request.url = target;
assert!(matches!(
mode.start(Arc::clone(&client), request).await?,
Err(ExecServerError::HttpRequest(message))
if message == "refusing to send enterprise bearer outside the configured MCP endpoint"
));
}
source.valid.store(false, Ordering::SeqCst);
*client.cached_token() = None;
assert!(matches!(
mode.start(Arc::clone(&client), params.clone()).await?,
Err(ExecServerError::AuthenticationRequired(_))
));
source.valid.store(true, Ordering::SeqCst);
source.invalidate_on_refresh.store(true, Ordering::SeqCst);
*client.cached_token() = None;
assert!(matches!(
mode.start(client, params).await?,
Err(ExecServerError::AuthenticationRequired(_))
));
assert!(requests.try_recv().is_err());
}
Ok(())
}
#[tokio::test]
async fn outgoing_requests_replace_all_authorization_headers_and_stop_redirects()
-> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
let (client, _source, mut params, mut requests) = controlled_fixture();
params
.headers
.extend(["authorization", "aUtHoRiZaTiOn"].map(|name| HttpHeader {
name: name.to_string(),
value: "another-stale-credential".to_string(),
value_env_var: None,
}));
let response = mode.start(client, params);
let request = requests.recv().await.expect("authenticated request");
assert_eq!(request.params.redirect_policy, HttpRedirectPolicy::Stop);
assert_eq!(
request.params.headers,
vec![HttpHeader {
name: "authorization".to_string(),
value: "Bearer initial".to_string(),
value_env_var: None,
}],
"replace every case variant with exactly one bearer"
);
request.response.send(/*t*/ 200).expect("complete request");
assert_eq!(response.await??.status, 200);
}
Ok(())
}
#[tokio::test]
async fn resource_bearers_never_follow_redirects() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(307).insert_header("location", "/mcp"))
.expect(2)
.mount(&server)
.await;
let (client, _source, params) = fixture(&format!("{}/mcp", server.uri()));
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
let client = crate::http_client_redirect::SameOriginRedirectHttpClient::new(Arc::new(client));
for result in [
client.http_request(params.clone()).await.map(|_| ()),
client.http_request_stream(params).await.map(|_| ()),
] {
assert!(matches!(
result,
Err(ExecServerError::HttpRequest(message))
if message == "enterprise MCP redirects are not allowed"
));
}
Ok(())
}
fn bearer(request: &PendingRequest) -> &str {
&request
.params
.headers
.iter()
.find(|header| header.name == "authorization")
.expect("bearer header")
.value
}
#[tokio::test]
async fn credential_failures_are_classified_before_dispatch() -> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
for failure in [
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
},
EmaAuthFailure::InsufficientUserAuthentication {
grant_source: crate::EmaInvalidGrantSource::EnterpriseIdentity,
},
EmaAuthFailure::ReauthenticationRequired,
] {
let (client, source, params, mut requests) = controlled_fixture();
*client.cached_token() = None;
match failure {
EmaAuthFailure::ReauthenticationRequired => {
source.valid.store(/*val*/ false, Ordering::SeqCst);
}
failure => {
*source.renewal_error.lock().unwrap() =
Some(anyhow::Error::new(failure).context("token exchange failed"));
}
}
assert!(matches!(
mode.start(client, params).await?,
Err(ExecServerError::AuthenticationRequired(_))
));
assert!(requests.try_recv().is_err());
}
for error in [
anyhow::Error::new(EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
})
.context("resource authorization failed without invalidating the enterprise identity"),
anyhow::anyhow!("temporary network failure"),
anyhow::Error::new(crate::EmaTokenSourceError::unexpected(
crate::EmaCredentialKind::Account,
)),
] {
let (client, source, params, mut requests) = controlled_fixture();
*client.cached_token() = None;
*source.renewal_error.lock().unwrap() = Some(error);
assert!(matches!(
mode.start(Arc::clone(&client), params.clone()).await?,
Err(ExecServerError::HttpRequest(_))
));
assert!(requests.try_recv().is_err());
let retry = mode.start(client, params);
let request = requests
.recv()
.await
.expect("retry after transient failure");
assert_eq!(bearer(&request), "Bearer renewed-2");
request.response.send(/*t*/ 200).expect("complete retry");
assert_eq!(retry.await??.status, 200);
}
}
Ok(())
}
#[tokio::test]
async fn delayed_unauthorized_response_preserves_the_renewed_bearer() -> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
let (client, source, params, mut requests) = controlled_fixture();
let first = mode.start(Arc::clone(&client), params.clone());
let first_request = requests.recv().await.expect("first request");
let delayed = mode.start(Arc::clone(&client), params.clone());
let delayed_request = requests.recv().await.expect("delayed request");
assert_eq!(
(bearer(&first_request), bearer(&delayed_request)),
("Bearer initial", "Bearer initial")
);
first_request.response.send(/*t*/ 401).expect("first 401");
assert!(matches!(
first.await?,
Err(ExecServerError::AuthenticationRequired(_))
));
let renewed = mode.start(Arc::clone(&client), params.clone());
let renewed_request = requests.recv().await.expect("renewed request");
assert_eq!(bearer(&renewed_request), "Bearer renewed-1");
renewed_request
.response
.send(/*t*/ 200)
.expect("renewed response");
assert_eq!(renewed.await??.status, 200);
delayed_request
.response
.send(/*t*/ 401)
.expect("delayed 401");
assert!(matches!(
delayed.await?,
Err(ExecServerError::AuthenticationRequired(_))
));
let next = mode.start(Arc::clone(&client), params);
let next_request = requests.recv().await.expect("next request");
assert_eq!(bearer(&next_request), "Bearer renewed-1");
next_request
.response
.send(/*t*/ 200)
.expect("next response");
assert_eq!(next.await??.status, 200);
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
assert!(requests.try_recv().is_err(), "no operation was replayed");
}
Ok(())
}
#[tokio::test]
async fn authentication_waits_share_the_request_deadline() -> anyhow::Result<()> {
#[derive(Clone, Copy)]
enum Wait {
Authority,
Renewal,
Credentials,
Exchange,
}
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
for wait in [
Wait::Authority,
Wait::Renewal,
Wait::Credentials,
Wait::Exchange,
] {
let (client, source, mut params, mut requests) = controlled_fixture();
let (gate, _entered, _release) = CredentialGate::new();
let mut authority = None;
let mut renewal = None;
match wait {
Wait::Authority => authority = Some(client.authority.responses.write().await),
Wait::Renewal => {
*client.cached_token() = None;
renewal = Some(client.renewal.acquire().await?);
}
Wait::Credentials => {
*client.cached_token() = None;
*source.credential_gate.lock().unwrap() = Some(gate);
}
Wait::Exchange => {
*client.cached_token() = None;
*source.renewal_gate.lock().unwrap() = Some(gate);
}
}
params.timeout_ms = Some(20);
let response = tokio::time::timeout(
Duration::from_secs(/*secs*/ 1),
mode.start(Arc::clone(&client), params),
)
.await??;
assert!(
matches!(response, Err(ExecServerError::HttpRequest(message))
if message == "enterprise MCP request timed out")
);
assert!(requests.try_recv().is_err());
drop((authority, renewal));
assert_eq!(source.active_leases.load(Ordering::SeqCst), 0);
}
let (client, source, mut params, mut requests) = controlled_fixture();
params.timeout_ms = Some(0);
assert!(matches!(
mode.start(client, params).await?,
Err(ExecServerError::HttpRequest(_))
));
assert_eq!(source.renewals.load(Ordering::SeqCst), 0);
assert!(requests.try_recv().is_err());
}
Ok(())
}
#[tokio::test]
async fn authentication_time_is_removed_from_the_inner_timeout() -> anyhow::Result<()> {
for mode in [RequestMode::Buffered, RequestMode::Streaming] {
for timeout in [Some(1000), None] {
let (client, source, mut params, mut requests) = controlled_fixture();
let (gate, entered, release) = CredentialGate::new();
*client.cached_token() = None;
*source.credential_gate.lock().unwrap() = Some(gate);
params.timeout_ms = timeout;
let response = mode.start(client, params);
entered.await?;
tokio::time::sleep(Duration::from_millis(/*millis*/ 30)).await;
release.send(()).expect("release credentials");
let request = requests.recv().await.expect("authenticated request");
match timeout {
Some(timeout) => assert!(
request
.params
.timeout_ms
.is_some_and(|remaining| remaining > 0 && remaining <= timeout - 30)
),
None => assert_eq!(request.params.timeout_ms, None),
}
request.response.send(/*t*/ 200).expect("complete request");
assert_eq!(response.await??.status, 200);
}
}
Ok(())
}
#[tokio::test]
async fn policy_suspension_requires_fresh_authority_without_cancelling_admitted_request()
-> anyhow::Result<()> {
let (mut client, source, params, mut requests) = controlled_fixture();
let policy = CloudConfigBundlePolicy::default();
let mut snapshot = CloudConfigBundleSnapshot {
bundle: Ok(None),
binding: None,
config_server: None,
};
policy.publish_snapshot(&mut snapshot);
Arc::get_mut(&mut client)
.expect("single client owner")
.authority = EmaRequestAuthority::default().with_policy(snapshot.binding.take());
let pending = RequestMode::Buffered.start(Arc::clone(&client), params.clone());
let dispatched = requests.recv().await.expect("admitted request");
*client.cached_token() = None;
let (gate, waiting, release) = CredentialGate::new();
*source.credential_gate.lock().unwrap() = Some(gate);
let renewal = RequestMode::Streaming.start(Arc::clone(&client), params.clone());
waiting.await?;
let next = CloudConfigBundleFixture::enterprise_config("model = 'managed'").into_bundle();
policy.observe_remote_bundle(&next);
*source.renewal_error.lock().unwrap() =
Some(anyhow::anyhow!("exchange refused after policy changed"));
release.send(()).expect("release renewal");
assert!(matches!(
renewal.await?,
Err(ExecServerError::RequestNotSent(_))
));
assert!(matches!(
client.http_request(params.clone()).await,
Err(ExecServerError::RequestNotSent(message)) if message.contains("retry")
));
assert!(matches!(
requests.try_recv(),
Err(mpsc::error::TryRecvError::Empty)
));
dispatched
.response
.send(200)
.expect("complete admitted request");
assert_eq!(pending.await??.status, 200);
snapshot.bundle = Ok(Some(next));
policy.publish_snapshot(&mut snapshot);
assert!(matches!(
client.http_request(params).await,
Err(ExecServerError::RequestNotSent(_))
));
let (mut fresh_client, _source, fresh_params, mut fresh_requests) = controlled_fixture();
Arc::get_mut(&mut fresh_client)
.expect("single client owner")
.authority = EmaRequestAuthority::default().with_policy(snapshot.binding);
let pending = RequestMode::Buffered.start(fresh_client, fresh_params);
fresh_requests
.recv()
.await
.expect("request after recovery")
.response
.send(200)
.expect("complete recovered request");
assert_eq!(pending.await??.status, 200);
Ok(())
}

View File

@@ -1,450 +0,0 @@
//! Renewable sessions use cached bearers without credential reads and never replay operations.
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use pretty_assertions::assert_eq;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::oauth::RefreshCredentialLock;
struct Source {
endpoint: Url,
renewals: AtomicUsize,
valid: AtomicBool,
invalidate_on_refresh: AtomicBool,
credential_gate: Mutex<Option<CredentialGate>>,
renewal_gate: Mutex<Option<CredentialGate>>,
renewal_error: Mutex<Option<anyhow::Error>>,
active_leases: AtomicUsize,
renewal_with_lease: AtomicBool,
lock_identity: Mutex<Option<(String, String)>>,
}
struct CredentialGate {
entered: tokio::sync::oneshot::Sender<()>,
release: tokio::sync::oneshot::Receiver<()>,
}
impl CredentialGate {
fn new() -> (
Self,
tokio::sync::oneshot::Receiver<()>,
tokio::sync::oneshot::Sender<()>,
) {
let (entered, waiting) = tokio::sync::oneshot::channel();
let (release, released) = tokio::sync::oneshot::channel();
(
Self {
entered,
release: released,
},
waiting,
release,
)
}
async fn wait(self) {
let _ = self.entered.send(());
let _ = self.release.await;
}
}
struct CredentialLease {
source: Arc<Source>,
_lock: Option<RefreshCredentialLock>,
}
impl Drop for CredentialLease {
fn drop(&mut self) {
self.source
.active_leases
.fetch_sub(/*val*/ 1, Ordering::SeqCst);
}
}
impl EmaTokenSource for Arc<Source> {
fn endpoint(&self) -> &Url {
&self.endpoint
}
async fn access_token(&self) -> anyhow::Result<EmaAccessToken> {
if !self.valid.load(Ordering::SeqCst) {
return Err(anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired)
.context("credentials were removed"));
}
let identity = self.lock_identity.lock().unwrap().clone();
let lock = match identity {
Some((name, issuer)) => {
Some(RefreshCredentialLock::acquire_for_server(&name, &issuer).await?)
}
None => None,
};
self.active_leases.fetch_add(/*val*/ 1, Ordering::SeqCst);
let _lease = CredentialLease {
source: Arc::clone(self),
_lock: lock,
};
let gate = self.credential_gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.wait().await;
}
let renewal = self.renewals.fetch_add(/*val*/ 1, Ordering::SeqCst) + 1;
self.renewal_with_lease.fetch_or(
self.active_leases.load(Ordering::SeqCst) != 0,
Ordering::SeqCst,
);
if let Some(error) = self.renewal_error.lock().unwrap().take() {
return Err(error);
}
let received_at = Instant::now();
let gate = self.renewal_gate.lock().unwrap().take();
if let Some(gate) = gate {
gate.wait().await;
}
tokio::task::yield_now().await;
if self.invalidate_on_refresh.load(Ordering::SeqCst) {
self.valid.store(false, Ordering::SeqCst);
return Err(anyhow::Error::new(EmaAuthFailure::ReauthenticationRequired));
}
Ok(EmaAccessToken {
access_token: format!("renewed-{renewal}"),
expires_in: Some(Duration::from_secs(/*secs*/ 300)),
received_at,
})
}
}
fn fixture(
endpoint: &str,
) -> (
EmaAuthenticatedHttpClient<Arc<Source>>,
Arc<Source>,
HttpRequestParams,
) {
let source = Arc::new(Source {
endpoint: Url::parse(endpoint).expect("endpoint"),
renewals: AtomicUsize::new(0),
valid: AtomicBool::new(true),
invalidate_on_refresh: AtomicBool::new(false),
credential_gate: Mutex::new(/*t*/ None),
renewal_gate: Mutex::new(/*t*/ None),
renewal_error: Mutex::new(/*t*/ None),
active_leases: AtomicUsize::new(/*v*/ 0),
renewal_with_lease: AtomicBool::new(/*v*/ false),
lock_identity: Mutex::new(None),
});
let client = EmaAuthenticatedHttpClient::new(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
Arc::clone(&source),
EmaAccessToken {
access_token: "initial".to_string(),
expires_in: Some(Duration::from_secs(300)),
received_at: Instant::now(),
},
EmaRequestAuthority::default(),
);
let params = HttpRequestParams {
method: "POST".to_string(),
url: endpoint.to_string(),
headers: vec![HttpHeader {
name: "Authorization".to_string(),
value: "discard-me".to_string(),
value_env_var: None,
}],
body: Some(br#"{"method":"tools/call"}"#.to_vec().into()),
timeout_ms: Some(5000),
redirect_policy: HttpRedirectPolicy::Follow,
request_id: "operation".to_string(),
stream_response: false,
};
(client, source, params)
}
#[tokio::test]
async fn cached_bearer_does_not_read_credentials_until_renewal() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(200))
.mount(&server)
.await;
let (client, source, params) = fixture(&format!("{}/mcp", server.uri()));
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
assert_eq!(client.http_request(params.clone()).await?.status, 200);
source.valid.store(false, Ordering::SeqCst);
assert_eq!(client.http_request(params.clone()).await?.status, 200);
*client.cached_token() = None;
assert!(matches!(
client.http_request(params).await,
Err(ExecServerError::AuthenticationRequired(_))
));
assert_eq!(source.renewals.load(Ordering::SeqCst), 0);
let requests = server.received_requests().await.expect("recorded requests");
let bearers = requests
.iter()
.map(|request| {
request.headers["authorization"]
.to_str()
.expect("bearer header")
.to_string()
})
.collect::<Vec<_>>();
assert_eq!(bearers, ["Bearer initial", "Bearer initial"]);
Ok(())
}
#[tokio::test]
async fn revocation_during_renewal_prevents_dispatch() -> anyhow::Result<()> {
let server = MockServer::start().await;
let endpoint = format!("{}/mcp", server.uri());
let (gate, validated_rx, release_tx) = CredentialGate::new();
let (mut client, source, params) = fixture(&endpoint);
let current = Arc::new(AtomicBool::new(true));
client.authority = EmaRequestAuthority::new(CancellationToken::new(), {
let current = Arc::clone(&current);
move || current.load(Ordering::SeqCst)
});
*client.cached_token() = None;
*source.credential_gate.lock().unwrap() = Some(gate);
let authority = client.authority.clone();
let request = tokio::spawn(async move { client.http_request(params).await });
validated_rx.await?;
// A watcher need not have run: dispatch must check the current owner itself.
current.store(false, Ordering::SeqCst);
let _ = release_tx.send(());
tokio::time::timeout(Duration::from_secs(1), authority.quiesce()).await?;
assert!(matches!(
request.await?,
Err(ExecServerError::AuthenticationRequired(_))
));
assert!(
server
.received_requests()
.await
.expect("requests")
.is_empty()
);
Ok(())
}
#[tokio::test]
async fn revocation_ends_an_existing_response_stream() -> anyhow::Result<()> {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(ResponseTemplate::new(200).set_body_string("account-a-data"))
.mount(&server)
.await;
let (mut client, _source, params) = fixture(&format!("{}/mcp", server.uri()));
let cancellation = CancellationToken::new();
client.authority = EmaRequestAuthority::new(cancellation.child_token(), || true);
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
let (_response, mut body) = client.http_request_stream(params).await?;
cancellation.cancel();
assert_eq!(body.recv().await?, None);
Ok(())
}
#[tokio::test]
async fn revocation_interrupts_an_active_multichunk_response() -> anyhow::Result<()> {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
let endpoint = format!("http://{}/mcp", listener.local_addr()?);
let (chunks, receiver) = tokio::sync::mpsc::channel::<Result<bytes::Bytes, std::io::Error>>(2);
let receiver = Arc::new(Mutex::new(Some(receiver)));
let app = axum::Router::new().route(
"/mcp",
axum::routing::post(move || {
let receiver = receiver.lock().unwrap().take().expect("one request");
async move {
let stream = futures::stream::unfold(receiver, |mut receiver| async {
receiver.recv().await.map(|chunk| (chunk, receiver))
});
(
[("content-type", "text/event-stream")],
axum::body::Body::from_stream(stream),
)
}
}),
);
let server = tokio_util::task::AbortOnDropHandle::new(tokio::spawn(async move {
axum::serve(listener, app).await
}));
let (client, _source, params) = fixture(&endpoint);
chunks
.send(Ok(bytes::Bytes::from_static(b"data: first\n\n")))
.await?;
let (_, mut body) = client.http_request_stream(params).await?;
assert_eq!(body.recv().await?, Some(b"data: first\n\n".to_vec()));
let mut next = Box::pin(body.recv());
assert!(futures::poll!(&mut next).is_pending());
client.authority.revoke();
tokio::time::timeout(Duration::from_secs(1), client.authority.quiesce()).await?;
assert_eq!(
tokio::time::timeout(Duration::from_secs(1), next).await??,
None
);
// Even a later chunk cannot revive a stream whose authority was revoked.
let _ = chunks
.send(Ok(bytes::Bytes::from_static(b"data: second\n\n")))
.await;
assert_eq!(body.recv().await?, None);
server.abort();
let _ = server.await;
Ok(())
}
#[tokio::test]
async fn unauthorized_requests_are_not_replayed_and_later_requests_renew() -> anyhow::Result<()> {
for streaming in [false, true] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.and(path("/mcp"))
.respond_with(|request: &wiremock::Request| {
ResponseTemplate::new(if request.headers["authorization"] == "Bearer initial" {
401
} else {
200
})
})
.mount(&server)
.await;
let (client, source, params) = fixture(&format!("{}/mcp", server.uri()));
crate::oauth::test_support::warm_http_client(client.inner.as_ref()).await?;
for (status, count) in [(401, 1), (200, 2), (200, 3)] {
let result = if streaming {
client
.http_request_stream(params.clone())
.await
.map(|response| response.0.status)
} else {
client
.http_request(params.clone())
.await
.map(|response| response.status)
};
if status == 401 {
let error = result.expect_err("unauthorized operation fails without replay");
assert!(is_authentication_required_error(&anyhow::Error::new(error)));
} else {
assert_eq!(result?, status);
}
assert_eq!(
server.received_requests().await.expect("requests").len(),
count
);
}
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
// Concurrent callers of an expiring token share one renewal.
client
.cached_token()
.as_mut()
.expect("cached token")
.refresh_at = Instant::now();
let results =
futures::future::join_all((0..8).map(|_| client.http_request(params.clone()))).await;
assert!(results.iter().all(Result::is_ok));
assert_eq!(source.renewals.load(Ordering::SeqCst), 2);
}
Ok(())
}
#[path = "ema_http_client_regression_tests.rs"]
mod regressions;
#[tokio::test]
async fn initial_bearer_aged_during_validation_is_renewed_before_dispatch() -> anyhow::Result<()> {
for streaming in [false, true] {
let server = MockServer::start().await;
Mock::given(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&server)
.await;
let (client, source, params) = fixture(&format!("{}/mcp", server.uri()));
// Age the token by advancing time: backdating an Instant can underflow
// on a Windows runner that has only recently booted.
tokio::time::pause();
let received_at = Instant::now();
tokio::time::advance(Duration::from_secs(301)).await;
let client = EmaAuthenticatedHttpClient::new(
client.inner,
Arc::clone(&source),
EmaAccessToken {
access_token: "aged-in-validation".to_string(),
expires_in: Some(Duration::from_secs(300)),
received_at,
},
client.authority,
);
tokio::time::resume();
if streaming {
client.http_request_stream(params).await?;
} else {
client.http_request(params).await?;
}
let requests = server.received_requests().await.expect("requests");
assert_eq!(requests.len(), 1);
assert_eq!(requests[0].headers["authorization"], "Bearer renewed-1");
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
}
Ok(())
}
#[tokio::test]
async fn renewal_aged_during_validation_is_not_dispatched_or_cached() -> anyhow::Result<()> {
for streaming in [false, true] {
let server = MockServer::start().await;
let (client, source, mut params) = fixture(&format!("{}/mcp", server.uri()));
params.timeout_ms = None;
*client.cached_token() = None;
let client = Arc::new(client);
let (gate, waiting, release) = CredentialGate::new();
*source.renewal_gate.lock().unwrap() = Some(gate);
tokio::time::pause();
let request = {
let client = Arc::clone(&client);
tokio::spawn(async move {
if streaming {
client
.http_request_stream(params)
.await
.map(|(response, _)| response)
} else {
client.http_request(params).await
}
})
};
waiting.await?;
tokio::time::advance(Duration::from_secs(301)).await;
release.send(()).expect("release validation");
let result = request.await?;
tokio::time::resume();
assert!(matches!(result, Err(ExecServerError::HttpRequest(message))
if message == "enterprise MCP bearer expired during credential validation"));
assert!(client.cached_token().is_none());
assert!(
server
.received_requests()
.await
.expect("requests")
.is_empty()
);
assert_eq!(source.renewals.load(Ordering::SeqCst), 1);
}
Ok(())
}

View File

@@ -1,294 +0,0 @@
//! Shared enterprise IdP discovery and stored refresh-token resolution.
//! Login and token exchange require published metadata bound to the configured issuer.
use std::sync::Arc;
use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use codex_exec_server::HttpClient;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use oauth2::TokenResponse;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthHttpClient;
use tracing::instrument::WithSubscriber;
use crate::EmaCredentialLease;
use crate::EmaErrorDetail;
use crate::ema_auth_policy::advertised_capability;
use crate::ema_auth_policy::ema_reauthentication_required;
use crate::ema_auth_policy::resolve_ema_client_auth;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_claims::ID_JAG_TOKEN_TYPE;
use crate::ema_exchange::TOKEN_EXCHANGE_GRANT_TYPE;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::stored_oidc_identity;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::build_default_headers;
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
pub struct EmaIdpIdentityRequest<'a> {
pub issuer: &'a str,
pub client_id: &'a str,
pub client_secret: Option<&'a str>,
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
pub credentials: EmaCredentialLease,
pub http_client: Arc<dyn HttpClient>,
pub redirect_mode: StreamableHttpRedirectMode,
}
/// An opaque IdP refresh token paired with the credentials admitted for its exchange.
pub struct EmaIdpIdentity<L = EmaCredentialLease> {
pub(crate) token_endpoint: String,
pub(crate) refresh_token: String,
pub(crate) credentials: L,
pub(crate) client_authentication: EmaClientAuthentication,
}
impl<L> EmaIdpIdentity<L> {
/// Preserve an opaque credential lease when selecting an EMA credential source.
/// The mapping must retain its owned refresh guard until the IdP exchange finishes.
pub fn map_credentials<U>(self, map: impl FnOnce(L) -> U) -> EmaIdpIdentity<U> {
EmaIdpIdentity {
token_endpoint: self.token_endpoint,
refresh_token: self.refresh_token,
credentials: map(self.credentials),
client_authentication: self.client_authentication,
}
}
}
/// Resolve a refresh token issued by the account's validated OAuth authority.
/// The caller supplies trusted persisted issuer/client provenance and an ID/refresh-token
/// pair from one admitted account record. Discovery may run before acquiring a refresh
/// guard; before exchange, attach a lease that still matches that record with map_credentials.
/// ID-token claims corroborate that record; this does not verify a JWT signature or
/// authenticate an expired ID token. Only the refresh token is exchanged with the IdP.
pub async fn resolve_ema_account_idp_identity<L: Send>(
idp: &codex_config::McpServerIdpOAuthConfig,
client_id: &str,
id_token: &str,
refresh_token: String,
credentials: L,
http_client: Arc<dyn HttpClient>,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<EmaIdpIdentity<L>> {
if refresh_token.trim().is_empty() {
return Err(ema_reauthentication_required(
"Codex account has no refresh token; sign in again",
));
}
if idp.client_secret.is_some() && client_id != idp.client_id {
bail!("enterprise IdP client secret does not belong to the account OAuth client");
}
let issuer = &idp.issuer;
let client_secret = idp.client_secret.as_ref().map(|secret| secret.as_str());
crate::ema_claims::oidc_identity(id_token, issuer, client_id)?;
let (token_endpoint, client_authentication) = resolve_ema_idp_token_endpoint(
issuer,
client_secret,
idp.token_endpoint_auth_method,
http_client,
redirect_mode,
)
.await
.context(EmaErrorDetail::new(
"enterprise IdP discovery or validation failed",
))?;
Ok(EmaIdpIdentity {
token_endpoint,
refresh_token,
credentials,
client_authentication,
})
}
/// Validate account ID-token bindings without treating an expired ID token as an expired grant.
pub fn account_oidc_identity_is_usable(id_token: &str, issuer: &str, client_id: &str) -> bool {
crate::ema_claims::oidc_identity(id_token, issuer, client_id).is_ok()
}
/// Only an explanatory legacy-login hint, never authority for RT exchange.
pub fn account_oidc_issuer_hint(id_token: &str, issuer: &str) -> bool {
crate::ema_claims::oidc_issuer_hint(id_token, issuer)
}
/// Returns whether stored credentials contain a refresh token bound to the configured login.
pub fn stored_ema_identity_is_usable(
tokens: &StoredOAuthTokens,
issuer: &str,
client_id: &str,
) -> bool {
tokens.url == issuer
&& tokens.bound_issuer() == Some(issuer)
&& tokens.client_id == client_id
&& tokens.has_refresh_token()
&& stored_oidc_identity(tokens).is_ok()
}
pub(crate) async fn resolve_ema_idp_authorization_manager(
issuer: &str,
http_client: Arc<dyn OAuthHttpClient>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(
AuthorizationManager,
AuthorizationMetadata,
EmaClientAuthentication,
)> {
validate_ema_oauth_endpoint(issuer, "enterprise IdP issuer")?;
let mut manager = AuthorizationManager::new_with_oauth_http_client(issuer, http_client)
.await
.context("failed to create enterprise IdP metadata discovery client")?;
manager.set_allow_missing_issuer(false);
let resolution = manager
.resolve_metadata()
.await
.context(EmaErrorDetail::new(
"failed to discover enterprise IdP authorization metadata",
))?;
if !resolution.source.is_discovered() {
bail!(EmaErrorDetail::new(
"enterprise IdP must publish authorization metadata"
));
}
let metadata = resolution.metadata;
if metadata.issuer.as_deref() != Some(issuer) {
bail!(EmaErrorDetail::new(
"enterprise IdP authorization metadata issuer does not match configuration"
));
}
validate_ema_oauth_endpoint(&metadata.token_endpoint, "enterprise IdP token endpoint")?;
let authentication = resolve_ema_client_auth(
metadata
.additional_fields
.get("token_endpoint_auth_methods_supported"),
client_secret,
token_endpoint_auth_method,
"enterprise IdP",
)?;
Ok((manager, metadata, authentication))
}
/// Resolve a stored refresh-token subject against the configured enterprise IdP metadata.
pub async fn resolve_ema_idp_identity(
request: EmaIdpIdentityRequest<'_>,
) -> Result<EmaIdpIdentity> {
resolve_ema_idp_identity_in(request, &DefaultKeyringStore).await
}
async fn resolve_ema_idp_identity_in<K: KeyringStore + Clone + 'static>(
request: EmaIdpIdentityRequest<'_>,
keyring_store: &K,
) -> Result<EmaIdpIdentity> {
if request.issuer.trim().is_empty() || request.client_id.trim().is_empty() {
bail!("ema_auth requires a non-empty enterprise IdP issuer and client ID");
}
let credentials = request.credentials.credentials.credentials();
if credentials.url != request.issuer
|| credentials.bound_issuer() != Some(request.issuer)
|| credentials.client_id != request.client_id
{
bail!("stored enterprise IdP credentials do not match the configured issuer and client");
}
stored_oidc_identity(credentials)?;
let (token_endpoint, client_authentication) = resolve_ema_idp_token_endpoint(
request.issuer,
request.client_secret,
request.token_endpoint_auth_method,
request.http_client,
request.redirect_mode,
)
.await
.context(EmaErrorDetail::new(
"enterprise IdP discovery or validation failed",
))?;
let credentials = request.credentials;
let credential_lock = RefreshCredentialLock::acquire_for_server(
&credentials.credentials.credentials().server_name,
request.issuer,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
let keyring_store = keyring_store.clone();
// The worker retains the short read lock if its caller stops waiting for the reread.
tokio::task::spawn_blocking(move || {
let _credential_lock = credential_lock;
let latest = credentials
.credentials
.load_ema_credentials(&keyring_store)?;
let refresh_token = latest
.token_response
.0
.refresh_token()
.filter(|token| !token.secret().trim().is_empty())
.ok_or_else(|| {
ema_reauthentication_required(
"enterprise IdP session has no refresh token; sign in again",
)
})?;
Ok(EmaIdpIdentity {
token_endpoint,
refresh_token: refresh_token.secret().to_string(),
credentials,
client_authentication,
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise IdP credential reread task failed"
))
})?
}
async fn resolve_ema_idp_token_endpoint(
issuer: &str,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
http_client: Arc<dyn HttpClient>,
redirect_mode: StreamableHttpRedirectMode,
) -> Result<(String, EmaClientAuthentication)> {
let client = OAuthHttpClientAdapter::new_with_redirect_mode(
http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
issuer,
/*has_configured_headers*/ false,
redirect_mode,
)?;
let (_, metadata, authentication) = resolve_ema_idp_authorization_manager(
issuer,
Arc::new(client),
client_secret,
token_endpoint_auth_method,
)
.await?;
for (name, expected) in [
(
"identity_chaining_requested_token_types_supported",
ID_JAG_TOKEN_TYPE,
),
("grant_types_supported", TOKEN_EXCHANGE_GRANT_TYPE),
] {
if advertised_capability(metadata.additional_fields.get(name), expected, name)?
== Some(false)
{
bail!(
"enterprise IdP does not advertise the required ID-JAG token exchange capability"
);
}
}
Ok((metadata.token_endpoint, authentication))
}
#[cfg(test)]
#[path = "ema_identity_tests.rs"]
mod tests;

View File

@@ -1,439 +0,0 @@
use std::io;
use std::sync::Mutex;
use std::sync::PoisonError;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_config::types::AuthKeyringBackendKind;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_keyring_store::CredentialStoreError;
use codex_keyring_store::tests::MockKeyringStore;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use pretty_assertions::assert_ne;
use serde_json::json;
use tokio::sync::oneshot;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
use crate::EmaAuthFailure;
use crate::WrappedOAuthTokenResponse;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::test_support::TempCodexHome;
fn credentials(issuer: &str, subject: &str, expires_at: u64) -> StoredOAuthTokens {
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
serde_json::to_vec(&json!({
"iss":issuer,"aud":"idp-client","sub":subject,"exp":expires_at,
}))
.expect("claims")
)
);
StoredOAuthTokens {
server_name: "ema-idp:enterprise-test".to_string(),
url: issuer.to_string(),
issuer: Some(issuer.to_string()),
client_id: "idp-client".to_string(),
token_response: WrappedOAuthTokenResponse(
serde_json::from_value(json!({
"access_token":"unused","token_type":"Bearer","id_token":assertion,
"refresh_token":"stored-refresh","scope":"openid offline_access",
}))
.expect("credentials"),
),
expires_at: None,
}
}
fn request<'a>(
issuer: &'a str,
credentials: &'a StoredOAuthCredentialSnapshot,
) -> EmaIdpIdentityRequest<'a> {
EmaIdpIdentityRequest {
client_secret: None,
token_endpoint_auth_method: None,
issuer,
client_id: "idp-client",
credentials: EmaCredentialLease {
credentials: credentials.clone(),
},
http_client: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
redirect_mode: StreamableHttpRedirectMode::Legacy,
}
}
async fn discovery() -> (MockServer, String) {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
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"),
"identity_chaining_requested_token_types_supported":[ID_JAG_TOKEN_TYPE],
"grant_types_supported":[TOKEN_EXCHANGE_GRANT_TYPE],
"token_endpoint_auth_methods_supported":["none"],
})))
.mount(&server)
.await;
(server, issuer)
}
#[tokio::test]
async fn enterprise_discovery_shares_idp_checks_but_keeps_login_endpoint_policy() -> Result<()> {
for case in [
"valid",
"missing-discovery",
"issuer",
"missing-issuer",
"token-endpoint",
"public-client",
"authorization-endpoint",
] {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
// Login need not advertise ID-JAG exchange capabilities.
let mut metadata = json!({
"issuer": issuer, "authorization_endpoint": format!("{issuer}/authorize"),
"token_endpoint": format!("{issuer}/token"),
"token_endpoint_auth_methods_supported": ["none"],
"grant_types_supported": ["authorization_code"],
});
match case {
"issuer" => metadata["issuer"] = json!("https://other.example"),
"missing-issuer" => {
metadata.as_object_mut().expect("metadata").remove("issuer");
}
"token-endpoint" => metadata["token_endpoint"] = json!("http://unsafe.example/token"),
"public-client" => {
metadata["token_endpoint_auth_methods_supported"] = json!(["client_secret_basic"])
}
"authorization-endpoint" => {
metadata["authorization_endpoint"] = json!("http://unsafe.example/authorize")
}
"valid" | "missing-discovery" => {}
_ => unreachable!(),
}
if case != "missing-discovery" {
Mock::given(method("GET"))
.and(path("/.well-known/oauth-authorization-server/idp"))
.respond_with(ResponseTemplate::new(200).set_body_json(metadata))
.mount(&server)
.await;
}
let client = Arc::new(OAuthHttpClientAdapter::new_with_redirect_mode(
Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
&issuer,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?);
let shared = resolve_ema_idp_authorization_manager(
&issuer,
client.clone(),
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
)
.await;
let login = crate::enterprise_oauth_login::resolve_enterprise_authorization_manager(
&issuer, client, /*client_secret*/ None, /*token_endpoint_auth_method*/ None,
)
.await;
assert_eq!(
(shared.is_ok(), login.is_ok()),
(
matches!(case, "valid" | "authorization-endpoint"),
case == "valid"
),
"{case}",
);
if case == "missing-discovery" {
assert_eq!(
shared
.err()
.expect("reject synthesized metadata")
.to_string(),
"enterprise IdP must publish authorization metadata",
);
}
}
Ok(())
}
const REREAD_TEST_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5);
const REREAD_PANIC_SENTINEL: &str = "credential-panic-payload-sentinel";
#[derive(Clone, Copy, Debug)]
enum ReadOutcome {
Stored,
BackendError,
Panic,
}
#[derive(Clone, Debug)]
struct GatedKeyringStore {
inner: MockKeyringStore,
executor_thread: thread::ThreadId,
entered: Arc<Mutex<Option<oneshot::Sender<()>>>>,
release: Arc<Mutex<mpsc::Receiver<ReadOutcome>>>,
}
impl KeyringStore for GatedKeyringStore {
fn load(&self, service: &str, account: &str) -> Result<Option<String>, CredentialStoreError> {
// Fail before blocking if a regression puts this read on the current-thread executor.
assert_ne!(thread::current().id(), self.executor_thread);
if let Some(entered) = self
.entered
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
{
let _ = entered.send(());
}
let outcome = match self
.release
.lock()
.unwrap_or_else(PoisonError::into_inner)
.recv_timeout(REREAD_TEST_TIMEOUT)
{
Ok(outcome) => outcome,
Err(mpsc::RecvTimeoutError::Disconnected) => ReadOutcome::Stored,
Err(mpsc::RecvTimeoutError::Timeout) => panic!("credential reread gate timed out"),
};
match outcome {
ReadOutcome::Stored => self.inner.load(service, account),
ReadOutcome::BackendError => Err(CredentialStoreError::new(
keyring::Error::PlatformFailure(Box::new(io::Error::new(
io::ErrorKind::PermissionDenied,
"credential backend unavailable",
))),
)),
ReadOutcome::Panic => panic!("{REREAD_PANIC_SENTINEL}"),
}
}
fn save(&self, service: &str, account: &str, value: &str) -> Result<(), CredentialStoreError> {
self.inner.save(service, account, value)
}
fn delete(&self, service: &str, account: &str) -> Result<bool, CredentialStoreError> {
self.inner.delete(service, account)
}
}
#[tokio::test(flavor = "current_thread")]
async fn refresh_subject_reread_is_cancellable_and_releases_guard_on_failure() -> Result<()> {
let _home = TempCodexHome::new();
let (_server, issuer) = discovery().await;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let stored = credentials(&issuer, "user", /*expires_at*/ 0);
let snapshot = StoredOAuthCredentialSnapshot::new(stored.clone(), store);
for outcome in [
ReadOutcome::Stored,
ReadOutcome::BackendError,
ReadOutcome::Panic,
] {
let inner = MockKeyringStore::default();
store.save(&inner, &stored.server_name, &stored)?;
let (entered_tx, entered_rx) = oneshot::channel();
// Dropping the sole sender releases the worker on any early return or panic.
let (release_tx, release_rx) = mpsc::channel();
let keyring = GatedKeyringStore {
inner,
executor_thread: thread::current().id(),
entered: Arc::new(Mutex::new(Some(entered_tx))),
release: Arc::new(Mutex::new(release_rx)),
};
let request = request(&issuer, &snapshot);
crate::oauth::test_support::warm_http_client(request.http_client.as_ref()).await?;
let mut identity = Box::pin(resolve_ema_idp_identity_in(request, &keyring));
tokio::select! {
result = &mut identity => {
result?;
bail!("credential reread completed before its gate was released");
}
entered = tokio::time::timeout(REREAD_TEST_TIMEOUT, entered_rx) => { entered??; }
}
if matches!(outcome, ReadOutcome::Stored) {
// The caller times out while the already-started blocking read remains gated.
assert!(
tokio::time::timeout(Duration::ZERO, identity)
.await
.is_err()
);
assert!(
RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer)
.now_or_never()
.is_none()
);
release_tx.send(outcome)?;
} else {
release_tx.send(outcome)?;
let error = tokio::time::timeout(REREAD_TEST_TIMEOUT, identity)
.await?
.err()
.context("credential reread should fail")?;
if matches!(outcome, ReadOutcome::Panic) {
assert_eq!(
format!("{error:#}"),
"enterprise IdP credential reread task failed"
);
} else {
assert_eq!(
format!("{error:#}"),
"failed to read enterprise IdP credentials from keyring"
);
assert!(
!error
.chain()
.any(<dyn std::error::Error + 'static>::is::<io::Error>)
);
}
}
// Drain the detached read before TempCodexHome changes the process environment.
let _released = tokio::time::timeout(
REREAD_TEST_TIMEOUT,
RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer),
)
.await??;
}
Ok(())
}
#[tokio::test]
async fn refresh_subject_rereads_pinned_credentials_after_id_token_expiry() -> Result<()> {
let _home = TempCodexHome::new();
let (_server, issuer) = discovery().await;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let stored = credentials(&issuer, "user", /*expires_at*/ 0);
let snapshot = StoredOAuthCredentialSnapshot::new(stored.clone(), store);
let keyring = MockKeyringStore::default();
store.save(&keyring, &stored.server_name, &stored)?;
let identity = resolve_ema_idp_identity_in(request(&issuer, &snapshot), &keyring).await?;
assert_eq!(
(&identity.token_endpoint, identity.refresh_token.as_str()),
(&format!("{issuer}/token"), "stored-refresh")
);
let _released = RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer).await?;
Ok(())
}
#[tokio::test]
async fn refresh_subject_rejects_removed_replaced_or_missing_credentials() -> Result<()> {
let _home = TempCodexHome::new();
let (server, issuer) = discovery().await;
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let original = credentials(&issuer, "user", /*expires_at*/ 0);
for change in [
"deleted",
"subject",
"issuer",
"client",
"refresh",
"login",
"missing-refresh",
"file",
] {
let keyring = MockKeyringStore::default();
let snapshot = StoredOAuthCredentialSnapshot::new(
original.clone(),
if change == "file" {
ResolvedOAuthCredentialStore::file()
} else {
store
},
);
let mut latest = original.clone();
match change {
"subject" => latest = credentials(&issuer, "other-user", /*expires_at*/ 0),
"issuer" => latest.issuer = Some("https://other.example".to_string()),
"client" => latest.client_id = "other-client".to_string(),
"refresh" => {
latest
.token_response
.0
.set_refresh_token(Some(oauth2::RefreshToken::new(
"other-users-refresh".to_string(),
)))
}
"login" => latest = credentials(&issuer, "user", now + 3600),
"missing-refresh" => latest.token_response.0.set_refresh_token(None),
"deleted" | "file" => {}
_ => panic!("unexpected change"),
}
if change != "deleted" {
store.save(&keyring, &original.server_name, &latest)?;
}
let error = resolve_ema_idp_identity_in(request(&issuer, &snapshot), &keyring)
.await
.err()
.expect("must not reuse the stale snapshot or fall back to its ID token");
if change == "file" {
assert!(error.to_string().contains("require keyring storage"));
} else {
assert_eq!(
error.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::ReauthenticationRequired),
"{change}"
);
}
}
assert!(
server
.received_requests()
.await
.expect("requests")
.iter()
.all(|request| request.method.as_str() == "GET")
);
Ok(())
}
#[test]
fn stored_identity_usability_requires_a_bound_refresh_token_not_a_current_id_token() {
let issuer = "https://idp.example";
let expired = credentials(issuer, "user", /*expires_at*/ 0);
assert!(stored_ema_identity_is_usable(
&expired,
issuer,
"idp-client"
));
for change in ["url", "issuer", "client", "refresh"] {
let mut changed = expired.clone();
match change {
"url" => changed.url = "https://other.example".to_string(),
"issuer" => changed.issuer = Some("https://other.example".to_string()),
"client" => changed.client_id = "other-client".to_string(),
"refresh" => changed.token_response.0.set_refresh_token(None),
_ => panic!("unexpected change"),
}
assert!(!stored_ema_identity_is_usable(
&changed,
issuer,
"idp-client"
));
}
}

View File

@@ -1,411 +0,0 @@
//! Bound resource discovery and its HTTP safety policy before enterprise credential use.
//! The returned client keeps one deadline across resource and authorization-server discovery.
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_exec_server::HttpClient;
use codex_network_proxy::is_non_public_ip;
use codex_protocol::mcp::ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID;
use futures::StreamExt;
use http::Method;
use http::StatusCode;
use http::header::ACCEPT;
use http::header::CONTENT_TYPE;
use http::header::LOCATION;
use http::header::WWW_AUTHENTICATE;
use rmcp::model::ClientCapabilities;
use rmcp::model::ClientJsonRpcMessage;
use rmcp::model::ClientRequest;
use rmcp::model::DiscoverRequest;
use rmcp::model::DiscoverRequestParams;
use rmcp::model::ErrorCode;
use rmcp::model::Implementation;
use rmcp::model::InitializeRequest;
use rmcp::model::InitializeRequestParams;
use rmcp::model::JsonRpcMessage;
use rmcp::model::JsonRpcRequest;
use rmcp::model::ProtocolVersion;
use rmcp::model::RequestId;
use rmcp::model::RequestMetaObject;
use rmcp::model::ServerJsonRpcMessage;
use rmcp::transport::auth::OAuthHttpRedirectPolicy;
use rmcp::transport::auth::WWWAuthenticateParams;
use rmcp::transport::common::http_header::HEADER_MCP_METHOD;
use rmcp::transport::common::http_header::HEADER_MCP_PROTOCOL_VERSION;
use serde::Deserialize;
use sse_stream::SseStream;
use url::Host;
use url::Url;
use crate::ema_auth_policy::validate_ema_auth_resource;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::http_client_adapter::legacy_discovery_fallback_response;
use crate::oauth_http_client::OAuthHttpClientAdapter;
use crate::utils::build_default_headers;
const MAX_EMA_AUTHORIZATION_SERVERS: usize = 16;
const MAX_EMA_DISCOVERY_REDIRECTS: usize = 10;
const EMA_DISCOVERY_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Deserialize)]
struct EmaResourceMetadata {
resource: String,
authorization_server: Option<String>,
#[serde(default)]
authorization_servers: Vec<String>,
}
/// EMA discovery retains its own resource/issuer context while sharing the HTTP safety policy.
pub(super) struct EmaDiscoveryClient {
inner: OAuthHttpClientAdapter,
deadline: Instant,
}
impl EmaDiscoveryClient {
pub(super) async fn get(&self, url: Url) -> Result<oauth2::HttpResponse> {
self.execute(
oauth2::http::Request::builder()
.uri(url.as_str())
.body(Vec::new())?,
)
.await
}
async fn post(
&self,
url: &Url,
request: &JsonRpcRequest<ClientRequest>,
version: ProtocolVersion,
) -> Result<oauth2::HttpResponse> {
self.execute(
oauth2::http::Request::builder()
.method(Method::POST)
.uri(url.as_str())
.header(ACCEPT, "application/json, text/event-stream")
.header(CONTENT_TYPE, "application/json")
.header(HEADER_MCP_PROTOCOL_VERSION, version.as_str())
.header(HEADER_MCP_METHOD, request.request.method())
.body(serde_json::to_vec(request)?)?,
)
.await
}
async fn execute(&self, request: oauth2::HttpRequest) -> Result<oauth2::HttpResponse> {
let (parts, body) = request.into_parts();
let mut url = Url::parse(&parts.uri.to_string())?;
for _ in 0..MAX_EMA_DISCOVERY_REDIRECTS {
validate_ema_oauth_endpoint(url.as_str(), "enterprise metadata URL")?;
let remaining = self
.deadline
.checked_duration_since(Instant::now())
.ok_or_else(|| anyhow!("enterprise metadata discovery timed out"))?;
let mut request = oauth2::http::Request::builder()
.method(parts.method.clone())
.uri(url.as_str())
.body(body.clone())?;
*request.headers_mut() = parts.headers.clone();
let response = self
.inner
.execute_request(request, OAuthHttpRedirectPolicy::Stop, Some(remaining))
.await
.map_err(|error| {
anyhow!("enterprise metadata discovery request failed: {error}")
})?;
if response.status().is_server_error()
|| matches!(
response.status(),
StatusCode::REQUEST_TIMEOUT
| StatusCode::TOO_EARLY
| StatusCode::TOO_MANY_REQUESTS
)
{
bail!(
"enterprise metadata discovery returned HTTP {}",
response.status()
);
}
if !response.status().is_redirection() || parts.method != Method::GET {
return Ok(response);
}
let Some(location) = response.headers().get(LOCATION) else {
return Ok(response);
};
let next = url.join(location.to_str()?)?;
if next.origin() != url.origin() {
bail!("enterprise metadata discovery refused a cross-origin redirect");
}
url = next;
}
bail!("enterprise metadata discovery exceeded its redirect limit")
}
}
// Discovery responses use the same JSON or SSE framing as ordinary MCP requests.
// The HTTP adapter has already bounded this body; only a terminal RPC message matters.
async fn discovery_response_message(
response: &oauth2::HttpResponse,
) -> Option<ServerJsonRpcMessage> {
if !response
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| value.starts_with("text/event-stream"))
{
return serde_json::from_slice(response.body()).ok();
}
let mut events =
SseStream::from_bytes_stream(futures::stream::iter([Ok::<_, std::convert::Infallible>(
response.body().as_slice(),
)]));
while let Some(event) = events.next().await {
let event = event.ok()?;
if !matches!(event.event.as_deref(), None | Some("") | Some("message")) {
continue;
}
let Some(data) = event.data.filter(|data| !data.trim().is_empty()) else {
continue;
};
let message = serde_json::from_str(&data).ok()?;
if matches!(
message,
JsonRpcMessage::Response(_) | JsonRpcMessage::Error(_)
) {
return Some(message);
}
}
None
}
/// Retain rmcp's denial of metadata endpoints on private addresses and cloud-metadata hosts.
pub(super) fn validate_ema_metadata_issuer(resource: &Url, issuer: &Url) -> Result<()> {
validate_ema_oauth_endpoint(issuer.as_str(), "enterprise authorization server issuer")?;
if issuer.query().is_some() {
bail!("enterprise authorization server issuer must not contain a query");
}
let loopback = |url: &Url| match url.host() {
Some(Host::Domain(host)) => {
let host = host.trim_end_matches('.');
host == "localhost" || host.ends_with(".localhost")
}
Some(Host::Ipv4(ip)) => ip.is_loopback(),
Some(Host::Ipv6(ip)) => ip.is_loopback(),
None => false,
};
if loopback(resource) && loopback(issuer) {
return Ok(());
}
let disallowed = match issuer.host() {
Some(Host::Domain(host)) => {
let host = host.trim_end_matches('.').to_ascii_lowercase();
matches!(
host.as_str(),
"localhost" | "metadata" | "metadata.google.internal" | "metadata.azure.internal"
) || host.ends_with(".localhost")
}
Some(Host::Ipv4(ip)) => is_non_public_ip(IpAddr::V4(ip)),
Some(Host::Ipv6(ip)) => is_non_public_ip(IpAddr::V6(ip)),
None => true,
};
if disallowed {
bail!("enterprise discovery refused a private authorization-server metadata destination");
}
Ok(())
}
pub(super) struct EmaDiscoveryRequest<'a> {
pub(super) server_url: &'a str,
pub(super) resource: Option<&'a str>,
pub(super) expected_issuer: Option<&'a str>,
pub(super) http_client: Arc<dyn HttpClient>,
}
/// A validated resource and candidate list, with the discovery deadline still in force.
pub(super) struct EmaResource {
pub(super) server_url: Url,
pub(super) resource: String,
pub(super) authorization_servers: Vec<String>,
pub(super) client: EmaDiscoveryClient,
}
pub(super) async fn discover_ema_resource(request: EmaDiscoveryRequest<'_>) -> Result<EmaResource> {
let client = EmaDiscoveryClient {
inner: OAuthHttpClientAdapter::new_with_redirect_mode(
request.http_client,
build_default_headers(/*http_headers*/ None, /*env_http_headers*/ None)?,
request.server_url,
/*has_configured_headers*/ false,
StreamableHttpRedirectMode::Legacy,
)?,
deadline: Instant::now() + EMA_DISCOVERY_TIMEOUT,
};
let server = Url::parse(request.server_url)?;
let resource = Url::parse(request.resource.unwrap_or(request.server_url))?;
let path = resource.path().trim_matches('/');
let mut resource_urls = vec![server.clone()];
let metadata_url = |path: &str| {
let mut url = resource.clone();
url.set_path(path);
url
};
if !path.is_empty() {
resource_urls.push(metadata_url(&format!(
"/.well-known/oauth-protected-resource/{path}"
)));
resource_urls.push(metadata_url(&format!(
"/{path}/.well-known/oauth-protected-resource"
)));
}
resource_urls.push(metadata_url("/.well-known/oauth-protected-resource"));
let mut resource_metadata = None;
for url in resource_urls {
let mut response = if url == server {
// Modern MCP servers need not serve GET. Probe a read-only RPC to receive
// their authentication challenge before resolving enterprise credentials.
let mut discover = DiscoverRequest::new(DiscoverRequestParams {});
discover
.extensions
.insert(RequestMetaObject::with_client_context(
ProtocolVersion::V_2026_07_28,
Implementation::new("codex", env!("CARGO_PKG_VERSION")),
ClientCapabilities::builder()
.enable_extensions_with(
[(
ENTERPRISE_MANAGED_AUTHORIZATION_EXTENSION_ID.to_string(),
Default::default(),
)]
.into(),
)
.build(),
));
let discover = JsonRpcRequest::new(
RequestId::String("ema-auth-discover".into()),
discover.into(),
);
let mut response = client
.post(&server, &discover, ProtocolVersion::V_2026_07_28)
.await?;
let legacy = response.status() != StatusCode::UNAUTHORIZED
&& match discovery_response_message(&response).await {
Some(message) => matches!(
legacy_discovery_fallback_response(
&ClientJsonRpcMessage::Request(discover),
message,
response.status() == StatusCode::BAD_REQUEST,
),
JsonRpcMessage::Error(error) if error.error.code == ErrorCode::METHOD_NOT_FOUND
),
None => matches!(
response.status(),
StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED
),
};
if legacy {
// Preserve legacy custom metadata challenges without exchanging credentials
// or retrying application operations. All probes share the same deadline.
response = client
.execute(
oauth2::http::Request::builder()
.uri(server.as_str())
.header(ACCEPT, "text/event-stream")
.body(Vec::new())?,
)
.await?;
if matches!(
response.status(),
StatusCode::BAD_REQUEST
| StatusCode::NOT_FOUND
| StatusCode::METHOD_NOT_ALLOWED
| StatusCode::NOT_ACCEPTABLE
) {
response = client
.post(
&server,
&JsonRpcRequest::new(
RequestId::String("ema-auth-initialize".into()),
InitializeRequest::new(
InitializeRequestParams::new(
ClientCapabilities::default(),
Implementation::new("codex", env!("CARGO_PKG_VERSION")),
)
.with_protocol_version(ProtocolVersion::V_2025_06_18),
)
.into(),
),
ProtocolVersion::V_2025_06_18,
)
.await?;
}
}
response
} else {
client.get(url).await?
};
if response.status() == StatusCode::UNAUTHORIZED {
let challenge_url = response
.headers()
.get_all(WWW_AUTHENTICATE)
.iter()
.filter_map(|value| value.to_str().ok())
.find_map(|value| {
WWWAuthenticateParams::parse(value, &server).resource_metadata_url
});
if let Some(url) = challenge_url {
response = client.get(url).await?;
}
}
if response.status() == StatusCode::OK
&& let Ok(metadata) = serde_json::from_slice::<EmaResourceMetadata>(response.body())
{
resource_metadata = Some(metadata);
break;
}
}
let Some(EmaResourceMetadata {
resource,
authorization_server,
authorization_servers,
}) = resource_metadata
else {
bail!("enterprise MCP protected-resource metadata is missing or invalid");
};
if resource.trim().is_empty() {
bail!("enterprise MCP protected-resource identifier is empty");
}
validate_ema_auth_resource(request.server_url, Some(&resource))?;
if request
.resource
.is_some_and(|expected| expected != resource)
{
bail!(
"configured enterprise MCP resource does not match the RFC 9728 protected-resource metadata"
);
}
let mut issuers = authorization_server
.into_iter()
.chain(authorization_servers)
.collect::<Vec<_>>();
if issuers.len() > MAX_EMA_AUTHORIZATION_SERVERS {
bail!(
"enterprise MCP protected-resource metadata advertises too many authorization servers"
);
}
if let Some(expected) = request.expected_issuer {
issuers.retain(|issuer| issuer == expected);
if issuers.is_empty() {
bail!("enterprise MCP authorization server issuer does not match configured issuer");
}
}
Ok(EmaResource {
server_url: server,
resource,
authorization_servers: issuers,
client,
})
}

View File

@@ -1,446 +0,0 @@
//! Enterprise OIDC policy and staged, keyring-only credential commits.
//! Browser completion never persists a grant; its owner revalidates authority under the commit lock.
use std::future::Future;
use std::net::IpAddr;
use std::net::Ipv4Addr;
use std::sync::Arc;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use codex_config::types::AuthKeyringBackendKind;
use codex_config::types::OAuthCredentialsStoreMode;
use codex_exec_server::HttpClient;
use http::Method;
use http::header::CONTENT_LENGTH;
use http::header::CONTENT_TYPE;
use rmcp::transport::AuthorizationManager;
use rmcp::transport::auth::AuthorizationMetadata;
use rmcp::transport::auth::OAuthHttpClient;
use rmcp::transport::auth::OAuthHttpClientFuture;
use rmcp::transport::auth::OAuthHttpRequest;
use tracing::instrument::WithSubscriber;
use url::Host;
use url::Url;
use crate::EmaErrorDetail;
use crate::StoredOAuthTokens;
use crate::ema_auth_policy::validate_ema_oauth_endpoint;
use crate::ema_claims::validate_oidc_identity_assertion;
use crate::ema_identity::resolve_ema_idp_authorization_manager;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::EnterpriseOAuthGeneration;
use crate::oauth::EnterpriseOAuthGenerationFile;
use crate::oauth::EnterpriseOAuthGenerationKind;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::delete_oauth_tokens_with_lock_held;
use crate::oauth::save_oauth_tokens_with_lock_held;
use crate::oauth::validate_authorization_server_endpoints;
use crate::oauth_client_registration::McpOAuthClientRegistration;
use crate::perform_oauth_login::OAuthHttpContext;
use crate::perform_oauth_login::OAuthLoginPurpose;
use crate::perform_oauth_login::OauthLoginFlow;
/// An exclusive credential mutation guard. Hold it through primary account logout
/// so a competing process cannot commit between deleting the grant and signing out.
/// Coordination, like ordinary OAuth refresh, is scoped to the same CODEX_HOME.
pub struct EnterpriseOAuthCredentialGuard {
credential_name: String,
issuer: String,
keyring_backend: AuthKeyringBackendKind,
generation_file: EnterpriseOAuthGenerationFile,
_lock: RefreshCredentialLock,
}
impl EnterpriseOAuthCredentialGuard {
pub async fn acquire(
credential_name: &str,
issuer: &str,
keyring_backend: AuthKeyringBackendKind,
) -> Result<Self> {
let lock = RefreshCredentialLock::acquire_for_server(credential_name, issuer)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!("failed to lock enterprise credentials"))?;
let generation_file = EnterpriseOAuthGenerationFile::open(
credential_name,
issuer,
EnterpriseOAuthGenerationKind::LoginAttempt,
&lock,
)
.map_err(|_| anyhow!("failed to open enterprise login generation"))?;
Ok(Self {
credential_name: credential_name.to_owned(),
issuer: issuer.to_owned(),
keyring_backend,
generation_file,
_lock: lock,
})
}
/// Invalidate pending logins and delete the grant, if present. A false return
/// means no grant was stored; earlier login attempts are still invalidated.
pub fn delete_tokens(&self) -> Result<bool> {
// Invalidate attempts that have not stored a grant yet, including other processes.
// Persist before deletion so no successful logout can admit an earlier login.
self.generation_file
.replace()
.map_err(|_| anyhow!("failed to invalidate pending enterprise sign-ins"))?;
// Underlying keyring diagnostics include the account-scoped key. Suppress
// them and discard their error chain, not merely the outer error message.
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
delete_oauth_tokens_with_lock_held(
&self._lock,
&self.credential_name,
&self.issuer,
OAuthCredentialsStoreMode::Keyring,
self.keyring_backend,
)
})
.map_err(|_| anyhow!("failed to delete enterprise credentials"))
}
}
/// Invalidate earlier enterprise logins across processes, then delete any stored grant.
pub async fn delete_enterprise_oauth_tokens(
credential_name: &str,
issuer: &str,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<bool> {
EnterpriseOAuthCredentialGuard::acquire(credential_name, issuer, keyring_backend_kind)
.await?
.delete_tokens()
}
/// A browser login with no detached persistence worker. Dropping this handle or
/// its wait future unblocks the callback listener and cannot write credentials.
pub struct EnterpriseOAuthLoginHandle {
flow: OauthLoginFlow,
keyring_backend: AuthKeyringBackendKind,
generation: EnterpriseOAuthGeneration,
}
impl EnterpriseOAuthLoginHandle {
pub fn authorization_url(&self) -> String {
self.flow.authorization_url()
}
/// Capture before waiting; after the handle or wait future is dropped, await
/// this to ensure the callback worker released its listener before rebinding.
pub fn callback_closed(&self) -> impl Future<Output = ()> + Send + 'static {
self.flow.callback_closed()
}
pub async fn wait(self) -> Result<EnterpriseOAuthCredentials> {
let stored = self
.flow
.complete(/*emit_browser_url*/ false)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("enterprise IdP authorization failed")))?;
validate_enterprise_credentials(&stored)?;
Ok(EnterpriseOAuthCredentials {
stored,
keyring_backend: self.keyring_backend,
generation: self.generation,
})
}
}
/// A validated grant that is not yet stored. It intentionally does not expose tokens.
pub struct EnterpriseOAuthCredentials {
stored: StoredOAuthTokens,
keyring_backend: AuthKeyringBackendKind,
generation: EnterpriseOAuthGeneration,
}
impl EnterpriseOAuthCredentials {
/// Revalidate the current attempt, account and configuration under the same
/// exclusive lock used by logout, then persist without an intervening await.
/// Return the authority proof so the caller can retire its attempt while still
/// holding the commit gate, before notifying clients or refreshing runtimes.
pub async fn commit_if<F, Fut, T>(self, is_current: F) -> Result<T>
where
F: FnOnce() -> Fut,
Fut: Future<Output = Option<T>>,
{
let guard = EnterpriseOAuthCredentialGuard::acquire(
&self.stored.server_name,
&self.stored.url,
self.keyring_backend,
)
.await?;
let generation = guard.generation_file.current().map_err(|_| {
anyhow!(EmaErrorDetail::new(
"failed to read enterprise login generation"
))
})?;
if generation.as_ref() != Some(&self.generation) {
bail!(EmaErrorDetail::new(
"enterprise sign-in was invalidated by logout"
));
}
let Some(authority) = is_current().await else {
bail!(EmaErrorDetail::new(
"enterprise sign-in no longer matches the active account or configuration"
));
};
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
save_oauth_tokens_with_lock_held(
&guard._lock,
&self.stored.server_name,
&self.stored,
OAuthCredentialsStoreMode::Keyring,
self.keyring_backend,
)
})
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"failed to store enterprise credentials"
))
})?;
Ok(authority)
}
}
/// Start a host-registered enterprise login without launching the browser or
/// persisting a credential. The caller owns both the attempt and its later commit.
pub async fn perform_enterprise_oauth_login_return_url(
request: EnterpriseOAuthLoginRequest<'_>,
) -> Result<EnterpriseOAuthLoginHandle> {
let observed_generation = {
let guard = EnterpriseOAuthCredentialGuard::acquire(
request.credential_name,
request.issuer,
request.keyring_backend_kind,
)
.await?;
guard
.generation_file
.current()
.map_err(|_| anyhow!("failed to read enterprise login generation"))?
};
let flow = OauthLoginFlow::new(
request.credential_name,
request.issuer,
OAuthCredentialsStoreMode::Keyring,
request.keyring_backend_kind,
OAuthHttpContext {
http_headers: None,
env_http_headers: None,
http_client: request.http_client,
redirect_mode: request.redirect_mode,
},
&["openid".to_string(), "offline_access".to_string()],
Some(&codex_config::McpServerOAuthConfig {
client_id: Some(request.client_id.to_string()),
client_secret: request.client_secret.map(Into::into),
token_endpoint_auth_method: request.token_endpoint_auth_method,
..Default::default()
}),
OAuthLoginPurpose::EnterpriseIdp,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
/*launch_browser*/ false,
request.callback_port,
request.callback_url,
/*global_callback_url*/ None,
request.timeout_secs,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|error| {
if error.downcast_ref::<EmaErrorDetail>().is_some() {
return EmaErrorDetail::from_error(&error);
}
EmaErrorDetail::from_error(&error.context(EmaErrorDetail::new(
"failed to start enterprise IdP authorization",
)))
})?;
// Keep the current attempt valid until replacement setup succeeds. A logout
// or another completed setup during this work must still invalidate this start.
let generation = async {
let guard = EnterpriseOAuthCredentialGuard::acquire(
request.credential_name,
request.issuer,
request.keyring_backend_kind,
)
.await?;
let current_generation = guard
.generation_file
.current()
.map_err(|_| anyhow!("failed to read enterprise login generation"))?;
if current_generation != observed_generation {
bail!("enterprise login changed during replacement setup");
}
guard
.generation_file
.replace()
.map_err(|_| anyhow!("failed to start enterprise login generation"))
}
.await;
let generation = match generation {
Ok(generation) => generation,
Err(error) => {
let callback_closed = flow.callback_closed();
drop(flow);
callback_closed.await;
return Err(error);
}
};
Ok(EnterpriseOAuthLoginHandle {
flow,
keyring_backend: request.keyring_backend_kind,
generation,
})
}
pub(crate) fn enterprise_callback_settings(
issuer: &str,
client_id: Option<&str>,
callback_url: Option<&str>,
callback_port: Option<u16>,
) -> Result<(IpAddr, Option<u16>)> {
validate_ema_oauth_endpoint(issuer, "enterprise IdP issuer")?;
if client_id.is_none_or(|client_id| client_id.trim().is_empty()) {
bail!("enterprise IdP login requires its registered client ID");
}
let (ip, registered_port) = if let Some(callback_url) = callback_url {
validate_ema_oauth_endpoint(callback_url, "enterprise IdP callback URL")?;
let callback = Url::parse(callback_url)?;
let ip = match (callback.scheme(), callback.host()) {
("http", Some(Host::Domain("localhost"))) => Ipv4Addr::LOCALHOST.into(),
("http", Some(Host::Ipv4(ip))) if ip.is_loopback() => ip.into(),
("http", Some(Host::Ipv6(ip))) if ip.is_loopback() => ip.into(),
_ => bail!("enterprise IdP callback URL must use an HTTP loopback address"),
};
(ip, callback.port())
} else {
(Ipv4Addr::LOCALHOST.into(), None)
};
if callback_port
.zip(registered_port)
.is_some_and(|(configured, registered)| configured != registered)
{
bail!("enterprise IdP callback URL and listener specify different ports");
}
Ok((ip, callback_port.or(registered_port)))
}
fn validate_enterprise_credentials(stored: &StoredOAuthTokens) -> Result<()> {
if !stored.has_refresh_token() {
bail!("enterprise IdP login did not return a refresh token");
}
let assertion = stored
.token_response
.0
.extra_fields()
.0
.get("id_token")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| anyhow!("enterprise IdP login did not return an OIDC identity assertion"))?;
validate_oidc_identity_assertion(
assertion,
stored.issuer.as_deref().unwrap_or(&stored.url),
&stored.client_id,
)
.map_err(|_| anyhow!("enterprise IdP returned an invalid OIDC identity assertion"))
}
pub(crate) async fn resolve_enterprise_authorization_manager(
issuer: &str,
http_client: Arc<dyn OAuthHttpClient>,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(AuthorizationManager, AuthorizationMetadata)> {
let (manager, mut metadata, _) = resolve_ema_idp_authorization_manager(
issuer,
Arc::new(EnterpriseOAuthHttpClient(http_client)),
client_secret,
token_endpoint_auth_method,
)
.await?;
if client_secret.is_some() {
// The SDK chooses Basic when both methods are advertised. Its login client
// must use the validated registration method, just like the EMA exchanges.
metadata.additional_fields.insert(
"token_endpoint_auth_methods_supported".to_owned(),
serde_json::json!([token_endpoint_auth_method.unwrap_or_default().as_str()]),
);
}
validate_authorization_server_endpoints(&metadata)?;
validate_ema_oauth_endpoint(
&metadata.authorization_endpoint,
"enterprise IdP authorization endpoint",
)?;
Ok((manager, metadata))
}
pub(crate) fn enterprise_authorization_url(auth_url: &str) -> Result<String> {
let mut url = Url::parse(auth_url)?;
let query = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(
url.query_pairs()
.filter(|(key, _)| key != "resource" && key != "prompt"),
)
.append_pair("prompt", "consent")
.finish();
url.set_query(Some(&query));
Ok(url.to_string())
}
/// rmcp supplies a resource indicator for MCP OAuth, but the independent OIDC
/// login must not request the IdP issuer as a protected-resource audience.
struct EnterpriseOAuthHttpClient(Arc<dyn OAuthHttpClient>);
impl OAuthHttpClient for EnterpriseOAuthHttpClient {
fn execute(&self, mut request: OAuthHttpRequest) -> OAuthHttpClientFuture<'_> {
if request.request.method() == Method::POST
&& request
.request
.headers()
.get(CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.is_some_and(|value| {
value.split(';').next().is_some_and(|mime| {
mime.trim()
.eq_ignore_ascii_case("application/x-www-form-urlencoded")
})
})
&& url::form_urlencoded::parse(request.request.body())
.any(|(key, value)| key == "grant_type" && value == "authorization_code")
{
let body = url::form_urlencoded::Serializer::new(String::new())
.extend_pairs(
url::form_urlencoded::parse(request.request.body())
.filter(|(key, _)| key != "resource"),
)
.finish();
*request.request.body_mut() = body.into_bytes();
request.request.headers_mut().remove(CONTENT_LENGTH);
}
self.0.execute(request)
}
}
/// Enterprise registration and host-owned login settings. The flow always uses
/// OpenID Connect, strict issuer validation, and keyring-only credential storage.
pub struct EnterpriseOAuthLoginRequest<'a> {
pub credential_name: &'a str,
pub issuer: &'a str,
pub client_id: &'a str,
pub client_secret: Option<&'a str>,
pub token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
pub keyring_backend_kind: AuthKeyringBackendKind,
pub callback_port: Option<u16>,
pub callback_url: Option<&'a str>,
pub timeout_secs: Option<i64>,
pub http_client: Arc<dyn HttpClient>,
pub redirect_mode: StreamableHttpRedirectMode,
}
#[cfg(test)]
#[path = "enterprise_oauth_login_tests.rs"]
mod tests;

View File

@@ -1,617 +0,0 @@
//! Enterprise login exercises the real callback and keyring adapter in an isolated process.
use std::any::Any;
use std::collections::HashMap;
use std::sync::Mutex;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_exec_server::RouteAwareHttpClient;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use keyring::credential::Credential;
use keyring::credential::CredentialApi;
use keyring::credential::CredentialBuilderApi;
use keyring::credential::CredentialPersistence;
use keyring::mock::MockCredential;
use oauth2::TokenResponse;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::io::AsyncReadExt;
use tokio::io::AsyncWriteExt;
use tracing_test::traced_test;
use wiremock::Mock;
use wiremock::MockServer;
use wiremock::ResponseTemplate;
use wiremock::matchers::method;
use wiremock::matchers::path;
use super::*;
const SECRET: &str = "enterprise-secret-sentinel";
const CLIENT_SECRET: &str = "client-secret-sentinel";
const CREDENTIAL_NAME: &str = "ema-idp:enterprise-secret-sentinel";
#[path = "enterprise_oauth_logout_tests.rs"]
mod logout;
async fn isolated_process(test_name: &str) -> Result<bool> {
const CHILD: &str = "CODEX_ENTERPRISE_LOGIN_TEST_CHILD";
if std::env::var_os(CHILD).is_some() {
return Ok(false);
}
let home = tempfile::tempdir()?;
let output = tokio::process::Command::new(std::env::current_exe()?)
.args(["--exact", test_name, "--nocapture"])
.env(CHILD, "1")
.env("CODEX_HOME", home.path())
.current_dir(home.path())
.output()
.await?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
Ok(true)
}
async fn login(
issuer: &str,
callback_url: Option<&str>,
auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<EnterpriseOAuthLoginHandle> {
perform_enterprise_oauth_login_return_url(EnterpriseOAuthLoginRequest {
client_secret: auth_method.map(|_| CLIENT_SECRET),
token_endpoint_auth_method: auth_method,
credential_name: CREDENTIAL_NAME,
issuer,
client_id: "enterprise-client",
keyring_backend_kind: AuthKeyringBackendKind::Direct,
callback_port: None,
callback_url,
timeout_secs: Some(5),
http_client: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
redirect_mode: StreamableHttpRedirectMode::Legacy,
})
.await
}
async fn complete_login(issuer: &str) -> Result<EnterpriseOAuthCredentials> {
let handle = login(
issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await?;
callback(
&handle.authorization_url(),
issuer,
/*provider_error*/ false,
)
.await?;
handle.wait().await
}
async fn metadata(server: &MockServer, issuer: &str) {
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?prompt=none"),
"token_endpoint": format!("{issuer}/token"), "token_endpoint_auth_methods_supported": ["none", "client_secret_basic", "client_secret_post"],
}))).mount(server).await;
}
async fn callback(authorization_url: &str, issuer: &str, provider_error: bool) -> Result<()> {
let query = Url::parse(authorization_url)?
.query_pairs()
.into_owned()
.collect::<HashMap<_, _>>();
assert_eq!(query.get("prompt").map(String::as_str), Some("consent"));
assert!(!query.contains_key("resource"));
let mut callback = Url::parse(&query["redirect_uri"])?;
let mut pairs = callback.query_pairs_mut();
if provider_error {
pairs
.append_pair("error", SECRET)
.append_pair("error_description", SECRET);
} else {
pairs
.append_pair("code", SECRET)
.append_pair("state", &query["state"])
.append_pair("iss", issuer);
}
drop(pairs);
let port = callback.port().expect("actual listener port");
let mut stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await?;
stream
.write_all(
format!(
"GET {}?{} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nConnection: close\r\n\r\n",
callback.path(),
callback.query().expect("query")
)
.as_bytes(),
)
.await?;
stream.read_to_end(&mut Vec::new()).await?;
Ok(())
}
#[traced_test]
#[tokio::test]
async fn enterprise_callback_errors_and_sdk_logs_exclude_credentials() -> Result<()> {
if isolated_process(
"enterprise_oauth_login::tests::enterprise_callback_errors_and_sdk_logs_exclude_credentials",
)
.await?
{
return Ok(());
}
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &format!("https://{SECRET}.example/idp")).await;
let error = login(
&issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await
.err()
.expect("reject mismatched discovery issuer");
assert_eq!(
error.downcast_ref::<EmaErrorDetail>(),
Some(&EmaErrorDetail::new(
"failed to discover enterprise IdP authorization metadata"
))
);
assert!(!format!("{error} {error:?} {error:#}").contains(SECRET));
for (callback_error, token_success) in [(true, false), (false, false), (false, true)] {
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &issuer).await;
let response = if token_success {
ResponseTemplate::new(200).set_body_json(json!({
"access_token": SECRET, "refresh_token": SECRET, "id_token": SECRET, "token_type": "Bearer",
}))
} else {
ResponseTemplate::new(400)
.set_body_json(json!({"error": "invalid_grant", "error_description": SECRET}))
};
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(response)
.expect(u64::from(!callback_error))
.mount(&server)
.await;
let login = login(
&issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await?;
callback(&login.authorization_url(), &issuer, callback_error).await?;
tracing::trace!(target: "rmcp::transport::auth", "SDK trace capture enabled");
let error = login.wait().await.err().expect("reject provider response");
assert!(!format!("{error} {error:?} {error:#}").contains(SECRET));
assert!(logs_contain("SDK trace capture enabled"));
assert!(!logs_contain(SECRET));
}
Ok(())
}
#[test]
fn enterprise_callback_requires_loopback() -> Result<()> {
let issuer = "https://idp.example";
let client_id = Some("enterprise-client");
for (callback, port, expected_ip, expected_port) in [
(None, None, "127.0.0.1", None),
(None, Some(8080), "127.0.0.1", Some(8080)),
(Some("http://localhost/callback"), None, "127.0.0.1", None),
(Some("http://127.0.0.2/callback"), None, "127.0.0.2", None),
(Some("http://[::1]/callback"), None, "::1", None),
(
Some("http://localhost:8080/callback"),
None,
"127.0.0.1",
Some(8080),
),
(
Some("http://localhost:8080/callback"),
Some(8080),
"127.0.0.1",
Some(8080),
),
] {
assert_eq!(
enterprise_callback_settings(issuer, client_id, callback, port)?,
(expected_ip.parse::<IpAddr>()?, expected_port),
);
}
for callback in [
"http://0.0.0.0/callback",
"http://[::]/callback",
"https://127.0.0.1/callback",
"http://remote.example/callback",
] {
assert!(
enterprise_callback_settings(
issuer,
client_id,
Some(callback),
/*callback_port*/ None
)
.is_err()
);
}
assert!(
enterprise_callback_settings(
issuer,
client_id,
Some("http://localhost:8080/callback"),
Some(9090),
)
.is_err()
);
Ok(())
}
#[traced_test]
#[tokio::test]
async fn enterprise_public_api_storage_and_privacy() -> Result<()> {
if isolated_process("enterprise_oauth_login::tests::enterprise_public_api_storage_and_privacy")
.await?
{
return Ok(());
}
let keyring = TestKeyring::default();
keyring::set_default_credential_builder(Box::new(keyring.clone()));
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &issuer).await;
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({"iss":issuer,"sub":"user","aud":"enterprise-client","exp":4102444800_u64})
.to_string()
)
);
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token":SECRET,"refresh_token":SECRET,"id_token":assertion,"token_type":"Bearer",
})))
.mount(&server)
.await;
// Callback, exchange and DefaultKeyringStore all run through public entrypoints.
use McpEmaTokenEndpointAuthMethod::ClientSecretBasic;
use McpEmaTokenEndpointAuthMethod::ClientSecretPost;
for (login_index, (callback_url, auth_method)) in [
("http://localhost/callback", None),
("http://127.0.0.1/callback", None),
("http://localhost/callback", Some(ClientSecretBasic)),
("http://127.0.0.1/callback", Some(ClientSecretPost)),
]
.into_iter()
.enumerate()
{
let login = login(&issuer, Some(callback_url), auth_method).await?;
let authorization_url = login.authorization_url();
assert!(!authorization_url.contains(CLIENT_SECRET));
let authorization_query = Url::parse(&authorization_url)?
.query_pairs()
.into_owned()
.collect::<HashMap<_, _>>();
callback(&authorization_url, &issuer, /*provider_error*/ false).await?;
let credentials = login.wait().await?;
let token_requests = server
.received_requests()
.await
.expect("recorded OAuth requests")
.into_iter()
.filter(|request| {
request.method == http::Method::POST && request.url.path() == "/idp/token"
})
.collect::<Vec<_>>();
assert_eq!(token_requests.len(), login_index + 1);
let token_request = &token_requests[login_index];
let mut token_form = url::form_urlencoded::parse(&token_request.body)
.into_owned()
.collect::<HashMap<_, _>>();
let authorization = token_request
.headers
.get("authorization")
.map(|value| value.to_str().unwrap());
let expected_basic = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD
.encode(format!("enterprise-client:{CLIENT_SECRET}"))
);
assert_eq!(
authorization,
(auth_method == Some(ClientSecretBasic)).then_some(expected_basic.as_str())
);
assert_eq!(
token_form.remove("client_secret").as_deref(),
(auth_method == Some(ClientSecretPost)).then_some(CLIENT_SECRET)
);
assert_eq!(
token_form.remove("client_id").as_deref(),
(auth_method != Some(ClientSecretBasic)).then_some("enterprise-client")
);
let verifier = oauth2::PkceCodeVerifier::new(
token_form.remove("code_verifier").expect("PKCE verifier"),
);
assert_eq!(
oauth2::PkceCodeChallenge::from_code_verifier_sha256(&verifier).as_str(),
authorization_query["code_challenge"],
);
assert_eq!(authorization_query["code_challenge_method"], "S256");
assert_eq!(
token_form,
HashMap::from([
("grant_type".to_string(), "authorization_code".to_string()),
("code".to_string(), SECRET.to_string()),
(
"redirect_uri".to_string(),
authorization_query["redirect_uri"].clone()
),
])
);
assert!(
keyring
.values
.lock()
.unwrap()
.values()
.all(|value| value.get_secret().is_err())
);
let attempt = tokio::sync::Mutex::new(Some("active"));
{
let mut authority = credentials
.commit_if(|| async { Some(attempt.lock().await) })
.await?;
assert!(
attempt.try_lock().is_err(),
"commit retains the attempt gate until the caller retires it"
);
*authority = None;
}
assert_eq!(*attempt.lock().await, None);
let stored = tracing::subscriber::with_default(
tracing::subscriber::NoSubscriber::default(),
|| {
crate::stored_oauth_credentials(
CREDENTIAL_NAME,
&issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
},
)?
.expect("stored grant");
assert!(!serde_json::to_string(&stored)?.contains(CLIENT_SECRET));
assert!(!logs_contain(CLIENT_SECRET));
assert_eq!(
stored
.token_response
.0
.refresh_token()
.map(|token| token.secret().as_str()),
Some(SECRET)
);
// Exercise the production lease and keyring snapshot without installing another
// test backend. Use a non-sensitive name so routine keyring-read traces are safe.
let mut lease_tokens = stored.clone();
lease_tokens.server_name = "ema-idp:lease-snapshot".to_string();
crate::save_oauth_tokens(
&lease_tokens.server_name,
&lease_tokens,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
.await?;
let snapshot = crate::stored_oauth_credential_snapshot(
&lease_tokens.server_name,
&issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?
.expect("keyring-backed snapshot");
let pinned = snapshot.clone().pin_ema_credentials().await?;
let accesses = keyring.accesses.load(Ordering::SeqCst);
keyring.fail.store(true, Ordering::SeqCst);
let leases = futures::future::try_join_all(
(0..32).map(|_| pinned.acquire_current_ema_credentials()),
)
.await?;
assert_eq!(keyring.accesses.load(Ordering::SeqCst), accesses);
drop(leases);
keyring.fail.store(false, Ordering::SeqCst);
// Even an identical replacement, or a failed write, revokes the old version.
for fail in [false, true] {
let pinned = snapshot.clone().pin_ema_credentials().await?;
keyring.fail.store(fail, Ordering::SeqCst);
let saved = crate::save_oauth_tokens(
&lease_tokens.server_name,
&lease_tokens,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
.await;
keyring.fail.store(false, Ordering::SeqCst);
assert_eq!(saved.is_err(), fail);
assert!(pinned.acquire_current_ema_credentials().await.is_err());
}
let pinned = snapshot.pin_ema_credentials().await?;
let first = pinned.acquire_current_ema_credentials().await?;
let second = pinned.acquire_current_ema_credentials().await?;
assert!(
tokio::time::timeout(
Duration::from_secs(5),
delete_enterprise_oauth_tokens(
&lease_tokens.server_name,
&issuer,
AuthKeyringBackendKind::Direct,
),
)
.await??
);
drop(first);
drop(second);
assert!(pinned.acquire_current_ema_credentials().await.is_err());
assert!(
delete_enterprise_oauth_tokens(
CREDENTIAL_NAME,
&issuer,
AuthKeyringBackendKind::Direct
)
.await?
);
}
// Cancellation while blocked on the actual credential lock cannot leave a
// detached persistence worker that writes after the other process releases it.
let canceled = complete_login(&issuer).await?;
let guard = EnterpriseOAuthCredentialGuard::acquire(
CREDENTIAL_NAME,
&issuer,
AuthKeyringBackendKind::Direct,
)
.await?;
let mut commit = Box::pin(canceled.commit_if(|| async { Some(()) }));
assert!(futures::poll!(&mut commit).is_pending());
drop(commit);
drop(guard);
assert!(
keyring
.values
.lock()
.unwrap()
.values()
.all(|value| value.get_secret().is_err())
);
// Failed replacement setup leaves the existing attempt valid.
let retained = complete_login(&issuer).await?;
assert!(
login(
&issuer,
Some(&format!("{}/callback", server.uri())),
/*auth_method*/ None
)
.await
.is_err(),
"an occupied registered callback port must not silently move"
);
retained.commit_if(|| async { Some(()) }).await?;
// A newer start fences a delayed callback even across Codex processes.
let old = complete_login(&issuer).await?;
complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await?;
assert!(old.commit_if(|| async { Some(()) }).await.is_err());
assert!(
keyring
.values
.lock()
.unwrap()
.values()
.any(|value| value.get_secret().is_ok())
);
// Inject raw account identifiers into the actual keyring adapter's error chain.
keyring.fail.store(true, Ordering::SeqCst);
let save_error = complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await
.unwrap_err();
let delete_error =
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await
.unwrap_err();
let save_error = save_error.context(EmaErrorDetail::new(
"enterprise sign-in credential commit failed",
));
assert_eq!(
EmaErrorDetail::from_error(&save_error).to_string(),
"failed to store enterprise credentials"
);
for error in [save_error, delete_error] {
assert!(!format!("{error} {error:?} {error:#}").contains(SECRET));
}
keyring.fail.store(false, Ordering::SeqCst);
let home = std::path::PathBuf::from(std::env::var("CODEX_HOME")?);
assert!(
!home.join(".credentials.json").exists(),
"enterprise storage never falls back to plaintext"
);
let locks = home.join("mcp-oauth-locks");
std::fs::rename(&locks, home.join("held-locks"))?;
std::fs::write(&locks, b"not a directory")?;
let lock_error =
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await
.unwrap_err();
assert!(!format!("{lock_error} {lock_error:?} {lock_error:#}").contains(SECRET));
assert!(!logs_contain(SECRET));
Ok(())
}
#[derive(Clone, Default)]
struct TestKeyring {
values: Arc<Mutex<HashMap<String, Arc<MockCredential>>>>,
fail: Arc<AtomicBool>,
accesses: Arc<AtomicUsize>,
}
struct TestCredential(Arc<MockCredential>);
impl CredentialApi for TestCredential {
fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
self.0.set_secret(secret)
}
fn get_secret(&self) -> keyring::Result<Vec<u8>> {
self.0.get_secret()
}
fn delete_credential(&self) -> keyring::Result<()> {
self.0.delete_credential()
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl CredentialBuilderApi for TestKeyring {
fn build(
&self,
_target: Option<&str>,
_service: &str,
user: &str,
) -> keyring::Result<Box<Credential>> {
self.accesses.fetch_add(1, Ordering::SeqCst);
if self.fail.load(Ordering::SeqCst) {
return Err(keyring::Error::Invalid("account".into(), user.into()));
}
Ok(Box::new(TestCredential(
self.values
.lock()
.unwrap()
.entry(user.into())
.or_default()
.clone(),
)))
}
fn as_any(&self) -> &dyn Any {
self
}
fn persistence(&self) -> CredentialPersistence {
CredentialPersistence::ProcessOnly
}
}

View File

@@ -1,422 +0,0 @@
//! Cross-process credential changes invalidate staged logins and cached EMA leases.
use std::fs;
use std::path::PathBuf;
use codex_exec_server::ExecServerError;
use codex_exec_server::HttpRequestParams;
use codex_exec_server::HttpRequestResponse;
use codex_exec_server::HttpResponseBodyStream;
use futures::FutureExt;
use futures::future::BoxFuture;
use pretty_assertions::assert_eq;
use sha2::Digest;
use sha2::Sha256;
use tokio::sync::Notify;
use super::*;
#[tokio::test]
async fn failed_persistence_fences_old_snapshots_but_allows_fresh_pins() -> Result<()> {
if isolated_process("enterprise_oauth_login::tests::logout::failed_persistence_fences_old_snapshots_but_allows_fresh_pins").await? {
return Ok(());
}
let keyring = TestKeyring::default();
keyring::set_default_credential_builder(Box::new(keyring.clone()));
let issuer = "https://idp.example";
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({"iss":issuer,"sub":"user","aud":"enterprise-client","exp":4102444800_u64})
.to_string()
)
);
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": CREDENTIAL_NAME, "url": issuer, "issuer": issuer,
"client_id": "enterprise-client", "token_response": {
"access_token": SECRET, "refresh_token": SECRET, "id_token": assertion, "token_type": "Bearer"
}
}))?;
let mode = OAuthCredentialsStoreMode::Keyring;
let backend = AuthKeyringBackendKind::Direct;
crate::save_oauth_tokens(CREDENTIAL_NAME, &tokens, mode, backend).await?;
for operation in ["save", "delete"] {
let snapshot =
crate::stored_oauth_credential_snapshot(CREDENTIAL_NAME, issuer, mode, backend)?
.expect("stored grant")
.pin_ema_credentials()
.await?;
drop(snapshot.acquire_current_ema_credentials().await?);
// Fail the actual keyring mutation, after the public API advances the generation.
keyring
.values
.lock()
.unwrap()
.values()
.next()
.expect("credential")
.set_error(keyring::Error::PlatformFailure(Box::new(
std::io::Error::other("injected persistence failure"),
)));
let result = match operation {
"save" => crate::save_oauth_tokens(CREDENTIAL_NAME, &tokens, mode, backend).await,
"delete" => crate::delete_oauth_tokens(CREDENTIAL_NAME, issuer, mode, backend)
.await
.map(|_| ()),
_ => unreachable!(),
};
assert!(
result.is_err(),
"{operation} must report the storage failure"
);
assert!(
snapshot.acquire_current_ema_credentials().await.is_err(),
"{operation} must fence the old snapshot"
);
assert_eq!(stored(issuer)?, Some(tokens.clone()));
// A generation is not a deletion tombstone: a fresh connection may use the surviving grant.
let fresh =
crate::stored_oauth_credential_snapshot(CREDENTIAL_NAME, issuer, mode, backend)?
.expect("surviving grant")
.pin_ema_credentials()
.await?;
drop(fresh.acquire_current_ema_credentials().await?);
}
Ok(())
}
const TEST: &str =
"enterprise_oauth_login::tests::logout::logout_invalidates_pending_login_across_processes";
const LOGOUT_ISSUER: &str = "CODEX_ENTERPRISE_LOGOUT_TEST_ISSUER";
const REPLACE_CREDENTIAL: &str = "CODEX_ENTERPRISE_LOGOUT_TEST_REPLACE";
#[tokio::test]
async fn logout_invalidates_pending_login_across_processes() -> Result<()> {
if isolated_process(TEST).await? {
return Ok(());
}
let home = PathBuf::from(std::env::var("CODEX_HOME")?);
let keyring = FileKeyring(home.join("test-keyring"));
fs::create_dir_all(&keyring.0)?;
keyring::set_default_credential_builder(Box::new(keyring));
if let Ok(issuer) = std::env::var(LOGOUT_ISSUER) {
if std::env::var_os(REPLACE_CREDENTIAL).is_some() {
crate::save_oauth_tokens(
CREDENTIAL_NAME,
&stored(&issuer)?.expect("stored grant"),
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
.await?;
} else {
delete_enterprise_oauth_tokens(
CREDENTIAL_NAME,
&issuer,
AuthKeyringBackendKind::Direct,
)
.await?;
}
return Ok(());
}
let server = MockServer::start().await;
let issuer = format!("{}/idp", server.uri());
metadata(&server, &issuer).await;
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(r#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({"iss":issuer,"sub":"user","aud":"enterprise-client","exp":4102444800_u64})
.to_string()
)
);
Mock::given(method("POST"))
.and(path("/idp/token"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({
"access_token":SECRET,"refresh_token":SECRET,"id_token":assertion,"token_type":"Bearer",
})))
.mount(&server)
.await;
// A logout during provider setup must invalidate the in-flight start.
let paused_client = Arc::new(PausedSetupHttpClient {
inner: Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new(
OutboundProxyPolicy::ReqwestDefault,
))),
should_pause: AtomicBool::new(true),
entered: Notify::new(),
release: Notify::new(),
});
let starting_client = Arc::clone(&paused_client);
let starting_issuer = issuer.clone();
let starting = tokio::spawn(async move {
perform_enterprise_oauth_login_return_url(EnterpriseOAuthLoginRequest {
client_secret: None,
token_endpoint_auth_method: None,
credential_name: CREDENTIAL_NAME,
issuer: &starting_issuer,
client_id: "enterprise-client",
keyring_backend_kind: AuthKeyringBackendKind::Direct,
callback_port: None,
callback_url: None,
timeout_secs: Some(5),
http_client: starting_client,
redirect_mode: StreamableHttpRedirectMode::Legacy,
})
.await
});
tokio::time::timeout(
std::time::Duration::from_secs(5),
paused_client.entered.notified(),
)
.await?;
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await?;
paused_client.release.notify_one();
let error = tokio::time::timeout(std::time::Duration::from_secs(5), starting)
.await??
.err()
.expect("logout must invalidate a start during provider setup");
assert_eq!(
error.to_string(),
"enterprise login changed during replacement setup"
);
// The first logout has no grant to delete. The second deletes the fresh grant
// from the previous iteration. Both must invalidate pending callbacks and staged grants.
for _ in 0..2 {
let pending = login(
&issuer, /*callback_url*/ None, /*auth_method*/ None,
)
.await?;
let staged = complete_login(&issuer).await?;
let output = tokio::process::Command::new(std::env::current_exe()?)
.args(["--exact", TEST, "--nocapture"])
.env(LOGOUT_ISSUER, &issuer)
.output()
.await?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(stored(&issuer)?.is_none());
// The logout process has exited; its invalidation must survive that exit.
assert!(staged.commit_if(|| async { Some(()) }).await.is_err());
assert!(stored(&issuer)?.is_none());
// A fresh login after logout remains usable, including for the same account.
complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await?;
let fresh = stored(&issuer)?.expect("fresh grant");
callback(
&pending.authorization_url(),
&issuer,
/*provider_error*/ false,
)
.await?;
assert!(
pending
.wait()
.await?
.commit_if(|| async { Some(()) })
.await
.is_err()
);
assert_eq!(stored(&issuer)?, Some(fresh));
}
// Even a byte-identical replacement in another process retires the cached
// version. Its next lease must fail after that process exits, as must logout.
for operation in ["replace", "delete"] {
let before = stored(&issuer)?;
let cached = crate::stored_oauth_credential_snapshot(
CREDENTIAL_NAME,
&issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)?
.expect("keyring-backed snapshot")
.pin_ema_credentials()
.await?;
drop(cached.acquire_current_ema_credentials().await?);
let mut child = tokio::process::Command::new(std::env::current_exe()?);
child
.args(["--exact", TEST, "--nocapture"])
.env(LOGOUT_ISSUER, &issuer);
if operation == "replace" {
child.env(REPLACE_CREDENTIAL, "1");
}
let output = child.output().await?;
assert!(
output.status.success(),
"{}\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
assert!(cached.acquire_current_ema_credentials().await.is_err());
assert_eq!(
stored(&issuer)?,
if operation == "replace" { before } else { None }
);
}
let stale = complete_login(&issuer).await?;
let generation_path = fs::read_dir(home.join("mcp-oauth-locks"))?
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.find(|path| {
path.extension()
.is_some_and(|ext| ext == "enterprise-generation")
})
.expect("persistent generation");
fs::write(&generation_path, b"incomplete write")?;
assert!(stale.commit_if(|| async { Some(()) }).await.is_err());
assert!(
login(
&issuer, /*callback_url*/ None, /*auth_method*/ None
)
.await
.is_err()
);
// A lost marker never revives a pre-logout attempt or a pre-reset generation.
fs::remove_file(&generation_path)?;
let stale = complete_login(&issuer).await?;
fs::remove_file(&generation_path)?;
complete_login(&issuer)
.await?
.commit_if(|| async { Some(()) })
.await?;
assert!(stale.commit_if(|| async { Some(()) }).await.is_err());
// Metadata failures are logout errors and must leave the stored grant intact.
let before = stored(&issuer)?;
let version_path = generation_path.with_extension("enterprise-credential-version");
let version = fs::read(&version_path)?;
fs::remove_file(&version_path)?;
fs::create_dir(&version_path)?;
let mode = OAuthCredentialsStoreMode::Keyring;
let backend = AuthKeyringBackendKind::Direct;
let mut replacement = before.clone().expect("stored grant");
replacement.client_id.push_str("-replacement");
let saved = crate::save_oauth_tokens(CREDENTIAL_NAME, &replacement, mode, backend).await;
assert!(saved.is_err());
assert_eq!(stored(&issuer)?, before);
let deleted = crate::delete_oauth_tokens(CREDENTIAL_NAME, &issuer, mode, backend).await;
assert!(deleted.is_err());
assert_eq!(stored(&issuer)?, before);
fs::remove_dir(&version_path)?;
fs::write(&version_path, version)?;
fs::remove_file(&generation_path)?;
fs::create_dir(&generation_path)?;
assert!(
delete_enterprise_oauth_tokens(CREDENTIAL_NAME, &issuer, AuthKeyringBackendKind::Direct)
.await
.is_err()
);
assert_eq!(stored(&issuer)?, before);
assert!(!home.join(".credentials.json").exists());
Ok(())
}
struct PausedSetupHttpClient {
inner: Arc<dyn HttpClient>,
should_pause: AtomicBool,
entered: Notify,
release: Notify,
}
impl PausedSetupHttpClient {
async fn pause_once(&self) {
if self.should_pause.swap(false, Ordering::SeqCst) {
self.entered.notify_one();
self.release.notified().await;
}
}
}
impl HttpClient for PausedSetupHttpClient {
fn http_request(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<HttpRequestResponse, ExecServerError>> {
async move {
self.pause_once().await;
self.inner.http_request(params).await
}
.boxed()
}
fn http_request_stream(
&self,
params: HttpRequestParams,
) -> BoxFuture<'_, Result<(HttpRequestResponse, HttpResponseBodyStream), ExecServerError>> {
async move {
self.pause_once().await;
self.inner.http_request_stream(params).await
}
.boxed()
}
}
fn stored(issuer: &str) -> Result<Option<StoredOAuthTokens>> {
crate::stored_oauth_credentials(
CREDENTIAL_NAME,
issuer,
OAuthCredentialsStoreMode::Keyring,
AuthKeyringBackendKind::Direct,
)
}
// Only synthetic fixture credentials are persisted here. Every process still uses
// DefaultKeyringStore and the production credential lock, serializer and logout API.
struct FileKeyring(PathBuf);
struct FileCredential(PathBuf);
impl CredentialBuilderApi for FileKeyring {
fn build(
&self,
_target: Option<&str>,
_service: &str,
user: &str,
) -> keyring::Result<Box<Credential>> {
let name = format!("{:x}", Sha256::digest(user.as_bytes()));
Ok(Box::new(FileCredential(self.0.join(name))))
}
fn as_any(&self) -> &dyn Any {
self
}
}
impl CredentialApi for FileCredential {
fn set_secret(&self, secret: &[u8]) -> keyring::Result<()> {
fs::write(&self.0, secret).map_err(keyring_error)
}
fn get_secret(&self) -> keyring::Result<Vec<u8>> {
fs::read(&self.0).map_err(keyring_error)
}
fn delete_credential(&self) -> keyring::Result<()> {
fs::remove_file(&self.0).map_err(keyring_error)
}
fn as_any(&self) -> &dyn Any {
self
}
}
fn keyring_error(error: std::io::Error) -> keyring::Error {
if error.kind() == std::io::ErrorKind::NotFound {
keyring::Error::NoEntry
} else {
keyring::Error::PlatformFailure(Box::new(error))
}
}

View File

@@ -1,14 +1,6 @@
mod auth_status;
mod bounded_stdio_transport;
mod elicitation_client_service;
mod ema_auth;
mod ema_auth_policy;
mod ema_claims;
mod ema_exchange;
mod ema_http_client;
mod ema_identity;
mod ema_resource;
mod enterprise_oauth_login;
mod event_notification_transport;
mod executor_process_transport;
mod http_client_adapter;
@@ -49,38 +41,11 @@ pub use auth_status::determine_streamable_http_auth_status;
pub use auth_status::determine_streamable_http_auth_status_from_credentials;
pub use auth_status::discover_streamable_http_oauth;
pub use codex_protocol::protocol::McpAuthStatus;
pub use ema_auth::EmaAuthTokenExchangeRequest;
pub use ema_auth::exchange_ema_auth_token;
pub use ema_auth_policy::EmaAuthFailure;
pub use ema_auth_policy::EmaCredentialKind;
pub use ema_auth_policy::EmaErrorDetail;
pub use ema_auth_policy::EmaInvalidGrantSource;
pub use ema_auth_policy::EmaTokenSourceError;
pub use ema_auth_policy::validate_ema_auth_resource;
pub use ema_exchange::EmaAccessToken;
pub use ema_http_client::EmaAuthenticatedHttpClient;
pub use ema_http_client::EmaRequestAuthority;
pub use ema_http_client::EmaTokenSource;
pub use ema_identity::EmaIdpIdentity;
pub use ema_identity::EmaIdpIdentityRequest;
pub use ema_identity::account_oidc_identity_is_usable;
pub use ema_identity::account_oidc_issuer_hint;
pub use ema_identity::resolve_ema_account_idp_identity;
pub use ema_identity::resolve_ema_idp_identity;
pub use ema_identity::stored_ema_identity_is_usable;
pub use enterprise_oauth_login::EnterpriseOAuthCredentialGuard;
pub use enterprise_oauth_login::EnterpriseOAuthCredentials;
pub use enterprise_oauth_login::EnterpriseOAuthLoginHandle;
pub use enterprise_oauth_login::EnterpriseOAuthLoginRequest;
pub use enterprise_oauth_login::delete_enterprise_oauth_tokens;
pub use enterprise_oauth_login::perform_enterprise_oauth_login_return_url;
pub use event_notification_transport::EventNotificationReceiver;
pub use http_client_adapter::StreamableHttpRedirectMode;
pub use http_headers::with_http_headers_helper;
pub use http_request_auth::AuthProviderResolver;
pub use in_process_transport::InProcessTransportFactory;
pub use oauth::EmaCredentialLease;
pub use oauth::EmaCredentialSnapshot;
pub use oauth::StoredOAuthCredentialSnapshot;
pub use oauth::StoredOAuthTokens;
pub use oauth::WrappedOAuthTokenResponse;

View File

@@ -17,8 +17,6 @@
//! If the keyring is not available or fails, we fall back to CODEX_HOME/.credentials.json which is consistent with other coding CLI agents.
mod credential_store;
mod ema_identity;
mod enterprise_generation;
mod issuer_binding;
mod refresh_lock;
mod refresh_transaction;
@@ -80,13 +78,6 @@ use tokio::sync::Mutex;
use codex_utils_home_dir::find_codex_home;
pub(crate) use self::credential_store::OAuthCredentialStore;
pub use self::ema_identity::EmaCredentialLease;
pub use self::ema_identity::EmaCredentialSnapshot;
pub(crate) use self::ema_identity::stored_oidc_identity;
pub(crate) use self::enterprise_generation::EnterpriseOAuthGeneration;
pub(crate) use self::enterprise_generation::EnterpriseOAuthGenerationFile;
pub(crate) use self::enterprise_generation::EnterpriseOAuthGenerationKind;
use self::enterprise_generation::invalidate_enterprise_credential_version;
pub(crate) use self::issuer_binding::validate_authorization_server_endpoints;
pub(crate) use self::issuer_binding::validate_refresh_token_issuer;
pub(crate) use self::refresh_lock::RefreshCredentialLock;
@@ -471,13 +462,12 @@ pub async fn save_oauth_tokens(
/// Save while retaining the matching credential lock acquired by the caller.
pub(crate) fn save_oauth_tokens_with_lock_held(
lock: &RefreshCredentialLock,
_lock: &RefreshCredentialLock,
server_name: &str,
tokens: &StoredOAuthTokens,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<()> {
invalidate_enterprise_credential_version(server_name, &tokens.url, lock)?;
let keyring_store = DefaultKeyringStore;
let mut observation = telemetry::policy(store_mode, keyring_backend_kind, Operation::Save);
match store_mode {
@@ -647,13 +637,12 @@ pub async fn delete_oauth_tokens(
/// Delete while retaining the matching credential lock acquired by the caller.
pub(crate) fn delete_oauth_tokens_with_lock_held(
lock: &RefreshCredentialLock,
_lock: &RefreshCredentialLock,
server_name: &str,
url: &str,
store_mode: OAuthCredentialsStoreMode,
keyring_backend_kind: AuthKeyringBackendKind,
) -> Result<bool> {
invalidate_enterprise_credential_version(server_name, url, lock)?;
let keyring_store = DefaultKeyringStore;
delete_oauth_tokens_from_keyring_and_file(
&keyring_store,
@@ -1055,7 +1044,6 @@ fn token_needs_refresh(expires_at: Option<u64>) -> bool {
fn compute_store_key(server_name: &str, server_url: &str) -> Result<String> {
let executor_owned = server_name.starts_with("executor:");
let enterprise_owned = server_name.starts_with("ema-idp:");
let server_name = server_name.strip_prefix("local:").unwrap_or(server_name);
let mut payload = JsonMap::new();
payload.insert(
@@ -1064,20 +1052,7 @@ fn compute_store_key(server_name: &str, server_url: &str) -> Result<String> {
);
payload.insert("url".to_string(), Value::String(server_url.to_string()));
payload.insert("headers".to_string(), Value::Object(JsonMap::new()));
let payload = if enterprise_owned {
// The OS keyring is shared across homes. Keep enterprise sessions
// isolated by Codex profile as well as authenticated user and workspace.
let codex_home = find_codex_home()?;
fs::create_dir_all(&codex_home)?;
payload.insert(
"codex_home".to_string(),
serde_json::to_value(codex_home.as_path().canonicalize()?)?,
);
// Different binaries can enable different serde_json ordering features.
serde_json::to_value(payload.into_iter().collect::<BTreeMap<_, _>>())?
} else {
Value::Object(payload)
};
let payload = Value::Object(payload);
let truncated = sha_256_prefix(&payload)?;
let separator = if executor_owned { ':' } else { '|' };
Ok(format!("{server_name}{separator}{truncated}"))

View File

@@ -342,12 +342,9 @@ impl<K: KeyringStore + Clone + 'static> CredentialStore for OAuthCredentialStore
let mut retired = expected.clone();
retired.token_response.0.set_refresh_token(None);
*inner.last_credentials.lock().await = Some(retired.clone());
if inner.store.backend == Backend::Keyring(AuthKeyringBackendKind::Direct)
&& !inner.server_name.starts_with("ema-idp:")
{
// Ordinary direct-keyring entries are shared across CODEX_HOMEs, but their
if inner.store.backend == Backend::Keyring(AuthKeyringBackendKind::Direct) {
// Direct-keyring entries are shared across CODEX_HOMEs, but their
// refresh locks are not. Do not risk overwriting another home's newer login.
// Enterprise entries include the home in their key and remain protected.
warn!(
server_name = %inner.server_name,
"rejected MCP OAuth refresh token retired only in this connection; shared direct-keyring storage lacks cross-home coordination"

View File

@@ -1,279 +0,0 @@
//! Pin enterprise credentials to a non-secret version advanced by cooperating writers.
//! Exchanges reread the pinned keyring record and reject changes made outside this protocol.
use std::future::Future;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_keyring_store::DefaultKeyringStore;
use codex_keyring_store::KeyringStore;
use tracing::instrument::WithSubscriber;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaErrorDetail;
use crate::ema_auth_policy::ema_reauthentication_required;
use crate::ema_claims::OidcClaims;
use crate::ema_claims::oidc_identity;
use crate::oauth::EnterpriseOAuthGeneration;
use crate::oauth::EnterpriseOAuthGenerationFile;
use crate::oauth::EnterpriseOAuthGenerationKind;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::ResolvedOAuthCredentialStore;
use crate::oauth::StoredOAuthCredentialSnapshot;
use crate::oauth::StoredOAuthTokens;
use crate::oauth::invalidate_enterprise_credential_version;
/// One validated keyring record and its cross-process credential version.
#[derive(Clone)]
pub struct EmaCredentialSnapshot {
snapshot: StoredOAuthCredentialSnapshot,
version: EnterpriseOAuthGeneration,
}
/// A credential snapshot admitted by a short generation check.
/// Logout may replace the grant while an admitted exchange finishes.
pub struct EmaCredentialLease {
pub(crate) credentials: StoredOAuthCredentialSnapshot,
}
// Discard storage and lock error chains: keyring backends can include the stable
// account/workspace key. Keep only the sanitized authentication classification.
fn sanitize_ema_credential_error(error: anyhow::Error, message: &'static str) -> anyhow::Error {
match error.downcast::<EmaAuthFailure>() {
Ok(failure) => anyhow::Error::new(failure).context(message),
Err(_) => EmaErrorDetail::new(message).into(),
}
}
impl std::fmt::Debug for EmaCredentialLease {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EmaCredentialLease").finish_non_exhaustive()
}
}
pub(crate) fn stored_oidc_identity(tokens: &StoredOAuthTokens) -> Result<OidcClaims> {
let assertion = tokens
.token_response
.0
.extra_fields()
.0
.get("id_token")
.and_then(serde_json::Value::as_str)
.ok_or_else(|| {
ema_reauthentication_required(
"enterprise IdP session has no OIDC ID token; sign in again",
)
})?;
// The ID token binds the login identity. Its expiry does not determine
// whether the IdP will accept the independently valid refresh token.
oidc_identity(assertion, &tokens.url, &tokens.client_id).map_err(|error| {
ema_reauthentication_required("stored enterprise IdP identity is invalid; sign in again")
.context(error.to_string())
})
}
impl StoredOAuthCredentialSnapshot {
/// Bind the record and its version under one lease, validating any earlier snapshot read.
pub async fn pin_ema_credentials(self) -> Result<EmaCredentialSnapshot> {
self.pin_ema_credentials_in(&DefaultKeyringStore).await
}
async fn pin_ema_credentials_in<K: KeyringStore + Clone + 'static>(
self,
keyring_store: &K,
) -> Result<EmaCredentialSnapshot> {
if !self.credentials.server_name.starts_with("ema-idp:") {
bail!("enterprise credentials require the enterprise namespace");
}
let lock = RefreshCredentialLock::acquire_for_server(
&self.credentials.server_name,
&self.credentials.url,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
let keyring_store = keyring_store.clone();
tokio::task::spawn_blocking(move || {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
self.load_ema_credentials(&keyring_store)?;
let versions = EnterpriseOAuthGenerationFile::open(
&self.credentials.server_name,
&self.credentials.url,
EnterpriseOAuthGenerationKind::Credential,
&lock,
)?;
let version = match versions.current()? {
Some(version) => version,
None => versions.replace()?,
};
Ok(EmaCredentialSnapshot {
snapshot: self,
version,
})
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise credential pinning task failed"
))
})?
.map_err(|error: anyhow::Error| {
sanitize_ema_credential_error(error, "failed to pin enterprise credentials")
})
}
}
impl EmaCredentialSnapshot {
/// Validate the pinned version under the credential lock without reading the keyring.
pub async fn acquire_current_ema_credentials(&self) -> Result<EmaCredentialLease> {
let credential_lock = RefreshCredentialLock::acquire_for_server(
&self.snapshot.credentials.server_name,
&self.snapshot.credentials.url,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
let pinned = self.clone();
tokio::task::spawn_blocking(move || {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
let credentials = pinned.snapshot.credentials();
let versions = EnterpriseOAuthGenerationFile::open(
&credentials.server_name,
&credentials.url,
EnterpriseOAuthGenerationKind::Credential,
&credential_lock,
)?;
if versions.current()?.as_ref() != Some(&pinned.version) {
return Err(ema_reauthentication_required(
"enterprise credentials changed; reconnect",
));
}
Ok(EmaCredentialLease {
credentials: pinned.snapshot,
})
})
})
.await
.map_err(|_| {
anyhow!(EmaErrorDetail::new(
"enterprise credential validation task failed"
))
})?
.map_err(|error: anyhow::Error| {
sanitize_ema_credential_error(error, "failed to validate enterprise credentials")
})
}
/// Exclusively lock and delete a rejected grant only if its pinned record is still current.
pub async fn invalidate_ema_credentials_if_current(
&self,
is_current: impl Future<Output = bool> + Send,
) -> Result<()> {
self.invalidate_ema_credentials_if_current_in(&DefaultKeyringStore, is_current)
.await
}
async fn invalidate_ema_credentials_if_current_in<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
is_current: impl Future<Output = bool> + Send,
) -> Result<()> {
let credential_lock = RefreshCredentialLock::acquire_for_server(
&self.snapshot.credentials.server_name,
&self.snapshot.credentials.url,
)
.with_subscriber(tracing::subscriber::NoSubscriber::default())
.await
.map_err(|_| anyhow!(EmaErrorDetail::new("failed to lock enterprise credentials")))?;
if !is_current.await {
return Ok(());
}
let cancelled = tokio_util::sync::CancellationToken::new();
let _cancel_on_drop = cancelled.clone().drop_guard();
let pinned = self.clone();
let keyring_store = keyring_store.clone();
tokio::task::spawn_blocking(move || {
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
let snapshot = &pinned.snapshot;
let previous = snapshot.credentials();
let versions = EnterpriseOAuthGenerationFile::open(
&previous.server_name,
&previous.url,
EnterpriseOAuthGenerationKind::Credential,
&credential_lock,
)?;
if versions.current()?.as_ref() != Some(&pinned.version) {
return Ok(());
}
if let Some(mut latest) =
snapshot
.store
.load(&keyring_store, &previous.server_name, &previous.url)?
{
latest.token_response.0.set_expires_in(None);
if latest == *previous && !cancelled.is_cancelled() {
invalidate_enterprise_credential_version(
&previous.server_name,
&previous.url,
&credential_lock,
)?;
snapshot.store.delete(
&keyring_store,
&previous.server_name,
&previous.url,
)?;
}
}
Ok(())
})
})
.await
.map_err(|_| anyhow!("enterprise credential invalidation task failed"))?
.map_err(|error: anyhow::Error| {
sanitize_ema_credential_error(error, "failed to invalidate enterprise credentials")
})
}
}
impl StoredOAuthCredentialSnapshot {
/// Reread only the pinned keyring authority; a changed record rejects the exchange.
pub(crate) fn load_ema_credentials<K: KeyringStore + Clone + 'static>(
&self,
keyring_store: &K,
) -> Result<StoredOAuthTokens> {
if self.store == ResolvedOAuthCredentialStore::file() {
bail!("enterprise IdP credentials require keyring storage");
}
let previous = &self.credentials;
let mut latest =
tracing::subscriber::with_default(tracing::subscriber::NoSubscriber::default(), || {
self.store
.load(keyring_store, &previous.server_name, &previous.url)
})
.map_err(|_| anyhow!("failed to read enterprise IdP credentials from keyring"))?
.ok_or_else(|| {
ema_reauthentication_required(
"enterprise IdP credentials were removed; sign in again",
)
})?;
// There is no refresh-token rotation writer in the supported EMA profile.
// Pin the whole atomic login record, not just the claims of its ID token.
latest.token_response.0.set_expires_in(None);
if latest != *previous
|| previous.bound_issuer() != Some(previous.url.as_str())
|| !latest.has_refresh_token()
{
return Err(ema_reauthentication_required(
"enterprise IdP identity changed; sign in again and reconnect",
));
}
stored_oidc_identity(&latest)?;
Ok(latest)
}
}
#[cfg(test)]
#[path = "ema_identity_tests.rs"]
mod tests;

View File

@@ -1,414 +0,0 @@
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use codex_config::types::AuthKeyringBackendKind;
use codex_keyring_store::CredentialStoreError;
use codex_keyring_store::KeyringStore;
use codex_keyring_store::tests::MockKeyringStore;
use futures::FutureExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use tracing_test::traced_test;
use super::*;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::oauth::RefreshCredentialLock;
use crate::oauth::compute_store_key;
use crate::oauth::test_support::TempCodexHome;
#[derive(Clone, Debug, Default)]
struct TracingKeyringStore(MockKeyringStore);
impl KeyringStore for TracingKeyringStore {
fn load(
&self,
service: &str,
account: &str,
) -> std::result::Result<Option<String>, CredentialStoreError> {
tracing::trace!(account, "reading enterprise keyring entry");
self.0.load(service, account)
}
fn save(
&self,
service: &str,
account: &str,
value: &str,
) -> std::result::Result<(), CredentialStoreError> {
self.0.save(service, account, value)
}
fn delete(
&self,
service: &str,
account: &str,
) -> std::result::Result<bool, CredentialStoreError> {
tracing::trace!(account, "deleting enterprise keyring entry");
self.0.delete(service, account)
}
}
#[tokio::test]
async fn invalidation_rereads_under_exclusive_lock_and_preserves_newer_grants() -> Result<()> {
let _home = TempCodexHome::new();
for replacement in [
None,
Some("refresh_token"),
Some("client_id"),
Some("version"),
] {
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": "ema-idp:rejected-grant", "url": "https://idp.example",
"issuer": "https://idp.example", "client_id": "client",
"token_response": {
"access_token": "unused", "token_type": "Bearer", "refresh_token": "old-grant"
},
}))?;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let keyring = MockKeyringStore::default();
let writer =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let versions = EnterpriseOAuthGenerationFile::open(
&tokens.server_name,
&tokens.url,
EnterpriseOAuthGenerationKind::Credential,
&writer,
)?;
let snapshot = EmaCredentialSnapshot {
snapshot: StoredOAuthCredentialSnapshot::new(tokens.clone(), store),
version: versions.replace()?,
};
store.save(&keyring, &tokens.server_name, &tokens)?;
let mut invalidation = Box::pin(
snapshot.invalidate_ema_credentials_if_current_in(&keyring, std::future::ready(true)),
);
assert!(invalidation.as_mut().now_or_never().is_none());
assert_eq!(
store.load(&keyring, &tokens.server_name, &tokens.url)?,
Some(tokens.clone())
);
// A login that wins the lock may change any part of the atomic credential record.
let mut latest = tokens.clone();
match replacement {
Some("refresh_token") => latest
.token_response
.0
.set_refresh_token(Some(oauth2::RefreshToken::new("new-grant".to_string()))),
Some("client_id") => latest.client_id = "new-client".to_string(),
// An identical token response can still belong to a newer login.
Some("version") => {
invalidate_enterprise_credential_version(&tokens.server_name, &tokens.url, &writer)?
}
None => {}
Some(_) => unreachable!(),
}
store.save(&keyring, &tokens.server_name, &latest)?;
drop(writer);
invalidation.await?;
assert_eq!(
store.load(&keyring, &tokens.server_name, &tokens.url)?,
replacement.map(|_| latest),
);
let _reader =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
assert_eq!(
versions.current()?.as_ref() != Some(&snapshot.version),
replacement.is_none() || replacement == Some("version"),
"invalidation advances the version only when deleting its own grant",
);
}
Ok(())
}
fn versioned_tokens() -> Result<StoredOAuthTokens> {
let assertion = format!(
"{}.{}.signature",
URL_SAFE_NO_PAD.encode(br#"{"alg":"ES256"}"#),
URL_SAFE_NO_PAD.encode(
json!({
"iss":"https://idp.example", "aud":"client", "sub":"user", "exp":4102444800_u64,
})
.to_string()
),
);
Ok(serde_json::from_value(json!({
"server_name":"ema-idp:versioned", "url":"https://idp.example",
"issuer":"https://idp.example", "client_id":"client",
"token_response": {
"access_token":"unused", "token_type":"Bearer",
"refresh_token":"enterprise-refresh", "id_token":assertion,
},
}))?)
}
#[tokio::test]
async fn cached_credentials_require_the_current_version_after_waiting_for_a_writer() -> Result<()> {
let home = TempCodexHome::new();
for change in ["replacement", "missing", "corrupt"] {
let tokens = versioned_tokens()?;
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
store.save(&keyring, &tokens.server_name, &tokens)?;
let snapshot = StoredOAuthCredentialSnapshot::new(tokens.clone(), store)
.pin_ema_credentials_in(&keyring)
.await?;
let version_path = std::fs::read_dir(home.path().join("mcp-oauth-locks"))?
.filter_map(std::result::Result::ok)
.map(|entry| entry.path())
.find(|path| {
path.extension()
.is_some_and(|ext| ext == "enterprise-credential-version")
})
.expect("credential version");
let writer =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let mut acquisition = Box::pin(snapshot.acquire_current_ema_credentials());
assert!(acquisition.as_mut().now_or_never().is_none());
match change {
"replacement" => {
invalidate_enterprise_credential_version(&tokens.server_name, &tokens.url, &writer)?
}
"missing" => std::fs::remove_file(&version_path)?,
"corrupt" => std::fs::write(&version_path, b"incomplete write")?,
_ => unreachable!(),
}
drop(writer);
let error = acquisition
.await
.expect_err("cached grant must not survive a change");
if change != "corrupt" {
assert_eq!(
error.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::ReauthenticationRequired),
"{change}"
);
}
assert_eq!(
store.load(&keyring, &tokens.server_name, &tokens.url)?,
Some(tokens)
);
std::fs::remove_file(version_path)?;
}
Ok(())
}
#[tokio::test]
async fn pinning_does_not_bind_a_stale_record_to_a_new_credential_version() -> Result<()> {
let _home = TempCodexHome::new();
let tokens = versioned_tokens()?;
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
store.save(&keyring, &tokens.server_name, &tokens)?;
let snapshot = StoredOAuthCredentialSnapshot::new(tokens.clone(), store);
let writer =
RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let mut pinning = Box::pin(snapshot.pin_ema_credentials_in(&keyring));
assert!(pinning.as_mut().now_or_never().is_none());
let mut replacement = tokens;
replacement
.token_response
.0
.set_refresh_token(Some(oauth2::RefreshToken::new(
"replacement-grant".to_string(),
)));
invalidate_enterprise_credential_version(&replacement.server_name, &replacement.url, &writer)?;
store.save(&keyring, &replacement.server_name, &replacement)?;
drop(writer);
assert!(pinning.await.is_err());
let current = StoredOAuthCredentialSnapshot::new(replacement, store)
.pin_ema_credentials_in(&keyring)
.await?;
current.acquire_current_ema_credentials().await?;
Ok(())
}
#[tokio::test]
async fn admitted_credentials_do_not_block_a_new_pin() -> Result<()> {
let _home = TempCodexHome::new();
let tokens = versioned_tokens()?;
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
store.save(&keyring, &tokens.server_name, &tokens)?;
let snapshot = StoredOAuthCredentialSnapshot::new(tokens, store);
let pinned = snapshot.clone().pin_ema_credentials_in(&keyring).await?;
let _active_request = pinned.acquire_current_ema_credentials().await?;
let concurrent = tokio::time::timeout(
std::time::Duration::from_secs(1),
snapshot.pin_ema_credentials_in(&keyring),
)
.await??;
assert!(concurrent.version == pinned.version);
Ok(())
}
#[tokio::test]
async fn keyring_failure_does_not_reuse_the_pinned_refresh_token() -> Result<()> {
let _home = TempCodexHome::new();
let tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": "ema-idp:keyring-failure",
"url": "https://idp.example",
"issuer": "https://idp.example",
"client_id": "client",
"token_response": {
"access_token": "unused",
"token_type": "Bearer",
"refresh_token": "stale-refresh",
},
}))?;
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
let _lock = RefreshCredentialLock::acquire_for_server(&tokens.server_name, &tokens.url).await?;
let snapshot = StoredOAuthCredentialSnapshot::new(
tokens,
ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct),
);
let keyring = MockKeyringStore::default();
keyring.set_error(
&key,
keyring::Error::Invalid("backend".into(), "unavailable".into()),
);
let error = snapshot
.load_ema_credentials(&keyring)
.expect_err("keyring failure must be terminal");
assert!(
error
.to_string()
.contains("failed to read enterprise IdP credentials from keyring")
);
Ok(())
}
#[traced_test]
#[tokio::test]
async fn enterprise_credential_errors_and_keyring_traces_hide_account_key() -> Result<()> {
let home = TempCodexHome::new();
let sentinel = "private-workspace-sentinel";
let mut tokens = versioned_tokens()?;
tokens.server_name = format!("ema-idp:{sentinel}");
let key = compute_store_key(&tokens.server_name, &tokens.url)?;
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let keyring = TracingKeyringStore::default();
let snapshot = StoredOAuthCredentialSnapshot::new(tokens.clone(), store);
tracing::trace!("enterprise keyring privacy test capture enabled");
assert!(logs_contain(
"enterprise keyring privacy test capture enabled"
));
keyring
.0
.set_error(&key, keyring::Error::Invalid("account".into(), key.clone()));
let error = snapshot
.load_ema_credentials(&keyring)
.expect_err("backend read must fail");
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
keyring
.0
.set_error(&key, keyring::Error::Invalid("account".into(), key.clone()));
let error = snapshot
.clone()
.pin_ema_credentials_in(&keyring)
.await
.err()
.expect("backend pin must fail");
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
assert_eq!(error.downcast_ref::<EmaAuthFailure>(), None);
let keyring = TracingKeyringStore::default();
let removed = snapshot
.clone()
.pin_ema_credentials_in(&keyring)
.await
.err()
.expect("removed grant must fail");
assert_eq!(
removed.downcast_ref::<EmaAuthFailure>(),
Some(&EmaAuthFailure::ReauthenticationRequired),
);
assert!(!format!("{removed} {removed:?} {removed:#}").contains(sentinel));
store.save(&keyring, &tokens.server_name, &tokens)?;
let pinned = snapshot.clone().pin_ema_credentials_in(&keyring).await?;
keyring
.0
.set_error(&key, keyring::Error::Invalid("account".into(), key.clone()));
let error = pinned
.invalidate_ema_credentials_if_current_in(&keyring, std::future::ready(true))
.await
.unwrap_err();
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
let successful_keyring = TracingKeyringStore::default();
store.save(&successful_keyring, &tokens.server_name, &tokens)?;
snapshot
.clone()
.pin_ema_credentials_in(&successful_keyring)
.await?
.invalidate_ema_credentials_if_current_in(&successful_keyring, std::future::ready(true))
.await?;
assert_eq!(successful_keyring.0.saved_value(&key), None);
let lock_dir = home.path().join("mcp-oauth-locks");
std::fs::rename(&lock_dir, home.path().join("held-locks"))?;
std::fs::write(&lock_dir, b"not a directory")?;
for error in [
snapshot
.pin_ema_credentials_in(&keyring)
.await
.err()
.expect("lock must fail"),
pinned.acquire_current_ema_credentials().await.unwrap_err(),
pinned
.invalidate_ema_credentials_if_current_in(&keyring, std::future::ready(true))
.await
.unwrap_err(),
] {
assert!(!format!("{error} {error:?} {error:#}").contains(sentinel));
}
assert!(!logs_contain(sentinel));
Ok(())
}
#[test]
fn ordinary_oauth_names_cannot_alias_enterprise_credential_keys() -> Result<()> {
let _home = TempCodexHome::new();
let issuer = "https://idp.example";
let enterprise_name = "ema-idp:synthetic-identity";
let ordinary: codex_config::McpServerConfig = serde_json::from_value(json!({
"url": issuer,
"oauth": {"client_id": "idp-client"},
}))?;
let ordinary_name = ordinary.oauth_credential_name(enterprise_name);
pretty_assertions::assert_ne!(
compute_store_key(&ordinary_name, issuer)?,
compute_store_key(enterprise_name, issuer)?,
"an ordinary server name must not select the enterprise credential namespace"
);
let legacy_key = compute_store_key("ordinary-server", issuer)?;
let legacy_hash = legacy_key.split_once('|').expect("legacy key separator").1;
pretty_assertions::assert_eq!(
compute_store_key(&ordinary_name, issuer)?,
format!("{enterprise_name}|{legacy_hash}"),
"escaping the reserved prefix preserves the pre-EMA ordinary credential key"
);
let keyring = MockKeyringStore::default();
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
let enterprise_tokens: StoredOAuthTokens = serde_json::from_value(json!({
"server_name": enterprise_name, "url": issuer, "issuer": issuer,
"client_id": "idp-client", "token_response": {
"access_token": "unused", "token_type": "Bearer", "refresh_token": "enterprise-refresh"
}
}))?;
store.save(&keyring, enterprise_name, &enterprise_tokens)?;
let mut ordinary_tokens = enterprise_tokens.clone();
ordinary_tokens.server_name = ordinary_name.to_string();
store.save(&keyring, &ordinary_name, &ordinary_tokens)?;
assert!(store.delete(&keyring, &ordinary_name, issuer)?);
pretty_assertions::assert_eq!(
store.load(&keyring, enterprise_name, issuer)?,
Some(enterprise_tokens),
"ordinary OAuth save/logout must not overwrite or remove the enterprise entry"
);
Ok(())
}

View File

@@ -1,114 +0,0 @@
//! Persistent, non-secret fences for login attempts and cached enterprise credentials.
//! Separate generations preserve pending-login semantics when a stored grant changes.
//! All reads and writes require the credential lock; missing state never admits old authority.
use std::fs::File;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::Seek;
use std::io::Write;
use anyhow::Result;
use anyhow::ensure;
use codex_utils_home_dir::find_codex_home;
use oauth2::CsrfToken;
use sha2::Digest;
use sha2::Sha256;
use super::RefreshCredentialLock;
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct EnterpriseOAuthGeneration([u8; 32]);
pub(crate) enum EnterpriseOAuthGenerationKind {
LoginAttempt,
Credential,
}
pub(crate) struct EnterpriseOAuthGenerationFile {
file: File,
}
impl EnterpriseOAuthGenerationFile {
pub(crate) fn open(
credential_name: &str,
issuer: &str,
kind: EnterpriseOAuthGenerationKind,
_lock: &RefreshCredentialLock,
) -> Result<Self> {
let key = super::compute_store_key(credential_name, issuer)?;
let suffix = match kind {
EnterpriseOAuthGenerationKind::LoginAttempt => "enterprise-generation",
EnterpriseOAuthGenerationKind::Credential => "enterprise-credential-version",
};
let name = format!("{:x}.{suffix}", Sha256::digest(key.as_bytes()));
let path = find_codex_home()?.join("mcp-oauth-locks").join(name);
let mut options = OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
#[cfg(windows)]
{
use std::os::windows::fs::OpenOptionsExt;
use windows_sys::Win32::Storage::FileSystem::FILE_FLAG_OPEN_REPARSE_POINT;
options.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT);
}
let file = options.open(path)?;
ensure!(
file.metadata()?.is_file(),
"invalid enterprise generation file"
);
Ok(Self { file })
}
pub(crate) fn current(&self) -> Result<Option<EnterpriseOAuthGeneration>> {
let mut file = &self.file;
file.rewind()?;
match file.metadata()?.len() {
0 => Ok(None),
32 => {
let mut generation = [0; 32];
file.read_exact(&mut generation)?;
Ok(Some(EnterpriseOAuthGeneration(generation)))
}
_ => anyhow::bail!("invalid enterprise generation file"),
}
}
pub(crate) fn replace(&self) -> Result<EnterpriseOAuthGeneration> {
// Reuse OAuth's randomness without storing any credential. Random initialization
// also prevents an old attempt becoming valid if metadata is removed or truncated.
let random = CsrfToken::new_random_len(/*num_bytes*/ 32);
let generation =
EnterpriseOAuthGeneration(Sha256::digest(random.secret().as_bytes()).into());
let mut file = &self.file;
file.set_len(/*size*/ 0)?;
file.rewind()?;
file.write_all(&generation.0)?;
file.sync_all()?;
Ok(generation)
}
}
/// Invalidate cached grants before mutation, including when the following store write fails.
pub(crate) fn invalidate_enterprise_credential_version(
credential_name: &str,
issuer: &str,
lock: &RefreshCredentialLock,
) -> Result<()> {
if credential_name.starts_with("ema-idp:") {
EnterpriseOAuthGenerationFile::open(
credential_name,
issuer,
EnterpriseOAuthGenerationKind::Credential,
lock,
)?
.replace()?;
}
Ok(())
}

View File

@@ -3,7 +3,6 @@
use super::CallbackResult;
use super::OAuthHttpContext;
use super::OAuthLoginPurpose;
use super::OAuthProviderError;
use super::OauthCallbackResult;
use super::OauthLoginFlow;
@@ -61,7 +60,6 @@ where
},
scopes,
oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
/*launch_browser*/ false,

View File

@@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::future::Future;
use std::net::SocketAddr;
use std::string::String;
use std::sync::Arc;
@@ -9,7 +8,6 @@ use anyhow::Context;
use anyhow::Result;
use anyhow::anyhow;
use anyhow::bail;
use codex_config::McpEmaTokenEndpointAuthMethod;
use codex_config::McpServerOAuthConfig;
use codex_exec_server::HttpClient;
use codex_otel::auth_storage::AuthStorageOriginator;
@@ -28,9 +26,6 @@ use urlencoding::decode;
use crate::StoredOAuthTokens;
use crate::WrappedOAuthTokenResponse;
use crate::enterprise_oauth_login::enterprise_authorization_url;
use crate::enterprise_oauth_login::enterprise_callback_settings;
use crate::enterprise_oauth_login::resolve_enterprise_authorization_manager;
use crate::http_client_adapter::StreamableHttpRedirectMode;
use crate::oauth::compute_expires_at_millis;
use crate::oauth::validate_authorization_server_endpoints;
@@ -38,7 +33,6 @@ use crate::oauth_callback::McpOAuthCallbackMode;
use crate::oauth_callback::append_callback_id_to_redirect_uri;
use crate::oauth_callback::callback_id_from_server_url;
use crate::oauth_callback::callback_mode;
use crate::oauth_callback::resolve_mcp_oauth_callback_url;
use crate::oauth_callback::validate_callback_redirect;
use crate::oauth_client_credentials::OAuthClientCredentials;
use crate::oauth_client_registration::McpOAuthClientRegistration;
@@ -54,12 +48,6 @@ use codex_config::types::OAuthCredentialsStoreMode;
mod callback_input;
pub use callback_input::perform_oauth_login_with_callback_input;
#[derive(Clone, Copy)]
pub(crate) enum OAuthLoginPurpose {
Mcp,
EnterpriseIdp,
}
pub(crate) struct OAuthHttpContext {
pub(crate) http_headers: Option<HashMap<String, String>>,
pub(crate) env_http_headers: Option<HashMap<String, String>>,
@@ -217,7 +205,6 @@ async fn perform_oauth_login_with_browser_output(
http_context,
scopes,
oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
/*launch_browser*/ true,
@@ -264,7 +251,6 @@ pub async fn perform_oauth_login_return_url(
http_context,
scopes,
oauth_config,
OAuthLoginPurpose::Mcp,
client_registration,
oauth_resource,
/*launch_browser*/ false,
@@ -285,11 +271,8 @@ fn spawn_callback_server(
server: Arc<Server>,
tx: oneshot::Sender<CallbackResult>,
expected_callback_path: String,
closed: tokio_util::sync::CancellationToken,
) {
tokio::task::spawn_blocking(move || {
// Drop the listener before publishing closure, including if this task unwinds.
let _closed = closed.drop_guard();
let listener = server;
while let Ok(request) = listener.recv() {
let path = request.url().to_string();
@@ -449,7 +432,6 @@ pub(crate) struct OauthLoginFlow {
authorization_server_issuer: Option<String>,
rx: oneshot::Receiver<CallbackResult>,
guard: CallbackServerGuard,
callback_closed: tokio_util::sync::CancellationToken,
server_name: String,
server_url: String,
store_mode: OAuthCredentialsStoreMode,
@@ -549,7 +531,6 @@ impl OauthLoginFlow {
http_context: OAuthHttpContext,
scopes: &[String],
oauth_config: Option<&McpServerOAuthConfig>,
purpose: OAuthLoginPurpose,
client_registration: McpOAuthClientRegistration,
oauth_resource: Option<&str>,
launch_browser: bool,
@@ -563,18 +544,6 @@ impl OauthLoginFlow {
let credentials = OAuthClientCredentials::resolve(oauth_config)?;
let oauth_client_id = credentials.client_id.as_deref();
let callback_port = resolve_callback_port(callback_port)?;
let is_enterprise_idp = matches!(purpose, OAuthLoginPurpose::EnterpriseIdp);
let (enterprise_bind_ip, callback_port) = if is_enterprise_idp {
let (ip, port) = enterprise_callback_settings(
server_url,
oauth_client_id,
callback_url,
callback_port,
)?;
(Some(ip), port)
} else {
(None, callback_port)
};
let callback_id = callback_id_from_server_url(server_url)?;
let configured_callback = if oauth_client_id.is_some() {
callback_url
@@ -610,17 +579,8 @@ impl OauthLoginFlow {
)?);
let registered_authorization = if oauth_client_id.is_some() {
Some(
resolve_authorization_manager(
server_url,
Arc::clone(&oauth_http_client),
purpose,
credentials
.client_secret
.as_ref()
.map(|secret| secret.secret().as_str()),
oauth_config.and_then(|config| config.token_endpoint_auth_method),
)
.await?,
resolve_authorization_manager(server_url, Arc::clone(&oauth_http_client))
.await?,
)
} else {
None
@@ -629,8 +589,7 @@ impl OauthLoginFlow {
.as_ref()
.map(|(_, metadata)| callback_mode(metadata))
.transpose()?;
let use_legacy_fallback = !is_enterprise_idp
&& registered_callback_mode == Some(McpOAuthCallbackMode::CallbackSpecific)
let use_legacy_fallback = registered_callback_mode == Some(McpOAuthCallbackMode::CallbackSpecific)
&& configured_callback.as_ref().is_some_and(|callback_url| {
callback_url
.path_segments()
@@ -649,50 +608,15 @@ impl OauthLoginFlow {
callback_url
};
let bind_ip = match enterprise_bind_ip {
Some(ip) => ip,
None => callback_bind_host(callback_url).parse()?,
};
let bind_ip: std::net::IpAddr = callback_bind_host(callback_url).parse()?;
// Port zero asks the OS for a free ephemeral port; the resolved
// redirect receives that port after the listener has been bound.
let bind_addr = SocketAddr::new(bind_ip, callback_port.unwrap_or(0));
let bind_deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 1);
let server = loop {
match Server::http(bind_addr) {
Ok(server) => break Arc::new(server),
Err(err)
if is_enterprise_idp
&& callback_port.is_some()
&& err
.downcast_ref::<std::io::Error>()
.is_some_and(|err| err.kind() == std::io::ErrorKind::AddrInUse)
&& tokio::time::Instant::now() < bind_deadline =>
{
// tiny_http drops its accept loop asynchronously after Server::drop.
// Only retry the fixed listener bind, never OAuth requests or callbacks.
tokio::time::sleep(Duration::from_millis(/*millis*/ 10)).await;
}
Err(err) => return Err(anyhow!(err)),
}
};
let server = Arc::new(Server::http(bind_addr).map_err(|err| anyhow!(err))?);
let guard = CallbackServerGuard {
server: Arc::clone(&server),
};
let redirect_uri = resolve_redirect_uri(&server, callback_url)?;
let redirect_uri = if is_enterprise_idp {
let listener_port = server
.server_addr()
.to_ip()
.ok_or_else(|| anyhow!("unable to determine enterprise callback listener port"))?
.port();
let mut redirect = Url::parse(&redirect_uri)?;
redirect
.set_port(Some(listener_port))
.map_err(|()| anyhow!("invalid enterprise callback port"))?;
redirect.to_string()
} else {
redirect_uri
};
let scope_refs: Vec<&str> = scopes.iter().map(String::as_str).collect();
let PreparedOAuthLogin {
@@ -702,13 +626,7 @@ impl OauthLoginFlow {
} = if let Some((oauth_client_id, (auth_manager, metadata))) =
oauth_client_id.zip(registered_authorization)
{
let redirect_uri = if is_enterprise_idp {
resolve_mcp_oauth_callback_url(
server_url,
Some(&redirect_uri),
callback_mode(&metadata)?,
)?
} else if callback_url.is_some() && !use_legacy_fallback {
let redirect_uri = if callback_url.is_some() && !use_legacy_fallback {
redirect_uri
} else {
append_callback_id_to_redirect_uri(&redirect_uri, &callback_id)?
@@ -721,7 +639,6 @@ impl OauthLoginFlow {
&callback_id,
oauth_client_id,
credentials.client_secret.as_ref(),
purpose,
)
.await?
} else {
@@ -746,8 +663,7 @@ impl OauthLoginFlow {
// No fallible work or suspension after spawning: every callback worker
// must be owned by a returned flow, including during constructor cancellation.
let (tx, rx) = oneshot::channel();
let callback_closed = tokio_util::sync::CancellationToken::new();
spawn_callback_server(server, tx, callback_path, callback_closed.clone());
spawn_callback_server(server, tx, callback_path);
Ok(Self {
auth_url,
@@ -756,7 +672,6 @@ impl OauthLoginFlow {
authorization_server_issuer,
rx,
guard,
callback_closed,
server_name: server_name.to_string(),
server_url: server_url.to_string(),
store_mode,
@@ -770,10 +685,6 @@ impl OauthLoginFlow {
self.auth_url.clone()
}
pub(crate) fn callback_closed(&self) -> impl Future<Output = ()> + Send + 'static {
self.callback_closed.clone().cancelled_owned()
}
async fn finish(self, emit_browser_url: bool) -> Result<()> {
let store_mode = self.store_mode;
let keyring_backend_kind = self.keyring_backend_kind;
@@ -874,19 +785,7 @@ impl OauthLoginFlow {
async fn resolve_authorization_manager(
server_url: &str,
http_client: Arc<dyn OAuthHttpClient>,
purpose: OAuthLoginPurpose,
client_secret: Option<&str>,
token_endpoint_auth_method: Option<McpEmaTokenEndpointAuthMethod>,
) -> Result<(AuthorizationManager, AuthorizationMetadata)> {
if matches!(purpose, OAuthLoginPurpose::EnterpriseIdp) {
return resolve_enterprise_authorization_manager(
server_url,
http_client,
client_secret,
token_endpoint_auth_method,
)
.await;
}
let mut auth_manager =
AuthorizationManager::new_with_oauth_http_client(server_url, http_client).await?;
auth_manager.set_allow_missing_issuer(true);
@@ -904,9 +803,7 @@ async fn start_authorization(
callback_id: &str,
oauth_client_id: &str,
client_secret: Option<&oauth2::ClientSecret>,
purpose: OAuthLoginPurpose,
) -> Result<PreparedOAuthLogin> {
let strict_enterprise_idp = matches!(purpose, OAuthLoginPurpose::EnterpriseIdp);
let authorization_server_issuer = metadata.issuer.clone();
validate_callback_redirect(redirect_uri, callback_id, callback_mode(&metadata)?)?;
auth_manager.set_metadata(metadata);
@@ -917,11 +814,6 @@ async fn start_authorization(
}
auth_manager.configure_client(client_config)?;
let auth_url = auth_manager.get_authorization_url(scopes).await?;
let auth_url = if strict_enterprise_idp {
enterprise_authorization_url(&auth_url)?
} else {
auth_url
};
Ok(PreparedOAuthLogin {
oauth_state: OAuthState::Session(AuthorizationSession::for_scope_upgrade(
@@ -988,7 +880,6 @@ mod tests {
use super::McpOAuthClientRegistration;
use super::OAuthHttpClientAdapter;
use super::OAuthHttpContext;
use super::OAuthLoginPurpose;
use super::OAuthProviderError;
use super::OauthLoginFlow;
use super::StreamableHttpRedirectMode;
@@ -1147,7 +1038,6 @@ mod tests {
client_id: Some("test-client".to_string()),
..Default::default()
}),
OAuthLoginPurpose::Mcp,
McpOAuthClientRegistration::Auto,
/*oauth_resource*/ None,
/*launch_browser*/ false,
@@ -1199,9 +1089,6 @@ mod tests {
HeaderMap::new(),
&format!("{base_url}/mcp"),
)),
OAuthLoginPurpose::Mcp,
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
)
.await
.expect("resolve pre-registered OAuth metadata");
@@ -1213,7 +1100,6 @@ mod tests {
"configured-client",
"eci-prd-pub-codex-123",
/*client_secret*/ None,
OAuthLoginPurpose::Mcp,
)
.await
.expect("start pre-registered OAuth authorization");
@@ -1311,9 +1197,6 @@ mod tests {
HeaderMap::new(),
&format!("{issuer}/mcp"),
)),
OAuthLoginPurpose::Mcp,
/*client_secret*/ None,
/*token_endpoint_auth_method*/ None,
)
.await
.expect("resolve issuer-aware authorization metadata");
@@ -1325,7 +1208,6 @@ mod tests {
"test-callback",
"test-client",
/*client_secret*/ None,
OAuthLoginPurpose::Mcp,
)
.await
.expect("start issuer-aware authorization");

View File

@@ -6,8 +6,6 @@ use rmcp::transport::DynamicTransportError;
use rmcp::transport::auth::AuthError;
use rmcp::transport::streamable_http_client::StreamableHttpError;
use crate::ema_auth_policy::EmaAuthFailure;
use crate::ema_auth_policy::EmaInvalidGrantSource;
use crate::http_client_adapter::StreamableHttpClientAdapterError;
use crate::rmcp_client::ClientOperationError;
@@ -18,31 +16,9 @@ use crate::rmcp_client::ClientOperationError;
/// transport error, which is not part of the standard error source chain.
pub fn is_authentication_required_error(error: &Error) -> bool {
error.chain().any(|source| {
if let Some(error) = source.downcast_ref::<crate::EmaTokenSourceError>() {
return error.is_authentication_required();
}
source
.downcast_ref::<AuthError>()
.is_some_and(auth_error_requires_authentication)
|| source
.downcast_ref::<EmaAuthFailure>()
.is_some_and(|error| match error {
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::EnterpriseIdentity,
}
| EmaAuthFailure::IdentityClientRejected
| EmaAuthFailure::ReauthenticationRequired => true,
// Rejecting an ID-JAG does not invalidate the enterprise login itself.
EmaAuthFailure::InvalidGrant {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
}
| EmaAuthFailure::InsufficientUserAuthentication {
grant_source: EmaInvalidGrantSource::ResourceAuthorization,
} => false,
})
|| source
.downcast_ref::<ExecServerError>()
.is_some_and(exec_server_error_requires_authentication)