mirror of
https://github.com/openai/codex.git
synced 2026-11-18 22:20:48 +00:00
Support enterprise MCP sign-in without refresh tokens (#62129)
## Why An enterprise identity provider can return an OpenID Connect ID token without issuing a refresh token, even when Codex requests `offline_access`. The refresh-token requirement blocked those sign-ins. ## What changed For `ema_auth`, keep requesting `offline_access` and prefer a refresh token when available. Otherwise, use the stored ID token for the ID-JAG exchange after checking its issuer, audience, and expiry. Require reauthentication when the ID token is expired or invalid and no refresh token is available. Update `rmcp` to 3.6.0 for ID token exchange support. ## Testing Add regression coverage for sign-in with and without a refresh token, ID token expiry and issuer binding, and the subject token type sent to the identity provider. GitOrigin-RevId: ee7e253627c8274f9b3096e3b87e92e2f99885ea
This commit is contained in:
Generated
+3
-3
File diff suppressed because one or more lines are too long
Generated
+4
-4
@@ -13566,8 +13566,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcp"
|
||||
version = "3.5.1"
|
||||
source = "git+https://github.com/modelcontextprotocol/rust-sdk?rev=98a54789b80110ad210495c4ad845c89e1980471#98a54789b80110ad210495c4ad845c89e1980471"
|
||||
version = "3.6.0"
|
||||
source = "git+https://github.com/modelcontextprotocol/rust-sdk?rev=b11a40d889e022087d7f2b8cd23aa28e19ceaf5b#b11a40d889e022087d7f2b8cd23aa28e19ceaf5b"
|
||||
dependencies = [
|
||||
"async-trait",
|
||||
"base64 0.23.0",
|
||||
@@ -13602,8 +13602,8 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rmcp-macros"
|
||||
version = "3.5.1"
|
||||
source = "git+https://github.com/modelcontextprotocol/rust-sdk?rev=98a54789b80110ad210495c4ad845c89e1980471#98a54789b80110ad210495c4ad845c89e1980471"
|
||||
version = "3.6.0"
|
||||
source = "git+https://github.com/modelcontextprotocol/rust-sdk?rev=b11a40d889e022087d7f2b8cd23aa28e19ceaf5b#b11a40d889e022087d7f2b8cd23aa28e19ceaf5b"
|
||||
dependencies = [
|
||||
"darling 0.24.0",
|
||||
"proc-macro2",
|
||||
|
||||
+1
-1
@@ -477,7 +477,7 @@ regex-automata = { version = "0.4.13", default-features = false, features = ["st
|
||||
regex-lite = "0.1.8"
|
||||
regex-syntax = "0.8.8"
|
||||
reqwest = { version = "0.12", features = ["cookies"] }
|
||||
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", rev = "98a54789b80110ad210495c4ad845c89e1980471", version = "=3.5.1", default-features = false }
|
||||
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", rev = "b11a40d889e022087d7f2b8cd23aa28e19ceaf5b", version = "=3.6.0", default-features = false }
|
||||
runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" }
|
||||
rustix = { version = "1.1.4", features = ["net"] }
|
||||
rustls = { version = "0.23.46", default-features = false, features = [
|
||||
|
||||
@@ -206,7 +206,7 @@ pub enum McpServerAuth {
|
||||
/// still fall back to stored OAuth credentials.
|
||||
#[serde(rename = "chatgpt")]
|
||||
ChatGpt,
|
||||
/// Exchange an enterprise IdP refresh token for resource-specific authorization.
|
||||
/// Exchange an enterprise IdP refresh token or, if none was issued, a current ID token for resource-specific authorization.
|
||||
/// Alternate credentials and ordinary OAuth fallback are not permitted.
|
||||
#[serde(rename = "ema_auth")]
|
||||
EmaAuth,
|
||||
|
||||
@@ -2903,7 +2903,7 @@
|
||||
"type": "string"
|
||||
},
|
||||
{
|
||||
"description": "Exchange an enterprise IdP refresh token for resource-specific authorization. Alternate credentials and ordinary OAuth fallback are not permitted.",
|
||||
"description": "Exchange an enterprise IdP refresh token or, if none was issued, a current ID token for resource-specific authorization. Alternate credentials and ordinary OAuth fallback are not permitted.",
|
||||
"enum": [
|
||||
"ema_auth"
|
||||
],
|
||||
|
||||
@@ -106,7 +106,7 @@ pub async fn exchange_ema_auth_token<L: Send, R: Send>(
|
||||
.ok_or_else(|| anyhow!("MCP authorization metadata is missing an issuer"))?;
|
||||
let EmaIdpIdentity {
|
||||
token_endpoint,
|
||||
refresh_token,
|
||||
subject_token,
|
||||
credentials,
|
||||
client_authentication: idp_client_authentication,
|
||||
} = request.idp_identity.await?;
|
||||
@@ -122,7 +122,7 @@ pub async fn exchange_ema_auth_token<L: Send, R: Send>(
|
||||
idp_client_id: request.idp_client_id,
|
||||
idp_client_authentication,
|
||||
resource_client_authentication,
|
||||
refresh_token,
|
||||
subject_token,
|
||||
idp_http_client: request.idp_http_client,
|
||||
resource_http_client: request.resource_http_client,
|
||||
},
|
||||
|
||||
@@ -459,7 +459,9 @@ async fn rejected_grants_preserve_their_source_and_release_the_credential_lease(
|
||||
Ok(EmaIdpIdentity {
|
||||
client_authentication: EmaClientAuthentication::None,
|
||||
token_endpoint: format!("{idp}/token"),
|
||||
refresh_token: "old-grant".to_string(),
|
||||
subject_token: crate::ema_exchange::EmaSubjectToken::RefreshToken(
|
||||
oauth2::RefreshToken::new("old-grant".to_string()),
|
||||
),
|
||||
credentials: crate::EmaCredentialLease { credentials },
|
||||
})
|
||||
});
|
||||
|
||||
@@ -42,6 +42,12 @@ impl std::fmt::Debug for EmaAccessToken {
|
||||
}
|
||||
}
|
||||
|
||||
/// An issuer-bound exchange subject. The IdP verifies the credential during exchange.
|
||||
pub(crate) enum EmaSubjectToken {
|
||||
RefreshToken(RefreshToken),
|
||||
IdToken(String),
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
@@ -55,7 +61,7 @@ pub(crate) struct EmaIdJagExchangeRequest<'a> {
|
||||
pub idp_client_id: &'a str,
|
||||
pub idp_client_authentication: EmaClientAuthentication,
|
||||
pub resource_client_authentication: EmaClientAuthentication,
|
||||
pub refresh_token: String,
|
||||
pub subject_token: EmaSubjectToken,
|
||||
pub idp_http_client: Arc<dyn HttpClient>,
|
||||
pub resource_http_client: Arc<dyn HttpClient>,
|
||||
}
|
||||
@@ -80,31 +86,35 @@ pub(crate) async fn exchange_id_jag<L: Send, R: Send>(
|
||||
/*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,
|
||||
let idp = EmaAuthorizationServer::new(
|
||||
request.idp_issuer,
|
||||
request.idp_token_endpoint,
|
||||
request.idp_client_id,
|
||||
)
|
||||
.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.
|
||||
.with_client_authentication(request.idp_client_authentication);
|
||||
let resource_as = EmaAuthorizationServer::new(
|
||||
request.authorization_server_issuer,
|
||||
request.authorization_server_token_endpoint,
|
||||
request.mcp_client_id,
|
||||
)
|
||||
.with_client_authentication(request.resource_client_authentication);
|
||||
let exchange = match &request.subject_token {
|
||||
EmaSubjectToken::RefreshToken(token) => {
|
||||
EmaExchangeRequest::new(idp, resource_as, request.resource, token)
|
||||
}
|
||||
EmaSubjectToken::IdToken(token) => {
|
||||
EmaExchangeRequest::new_with_id_token(idp, resource_as, request.resource, token)
|
||||
}
|
||||
};
|
||||
let assertion = exchange
|
||||
.with_scopes(request.scopes.iter().cloned())
|
||||
.exchange_id_jag(&idp_http)
|
||||
.await
|
||||
.map_err(exchange_error)?;
|
||||
drop(request.subject_token);
|
||||
// Only the IdP uses the subject token. Release its lease before resource-AS I/O.
|
||||
let receipt = finish_idp(credentials);
|
||||
let token = assertion
|
||||
.exchange(&resource_http)
|
||||
|
||||
@@ -90,7 +90,9 @@ async fn exchange(server: &MockServer, refresh_token: &str) -> Result<EmaAccessT
|
||||
idp_token_endpoint: &format!("{issuer}/token"),
|
||||
idp_issuer: &issuer,
|
||||
idp_client_id: "idp-client",
|
||||
refresh_token: refresh_token.to_string(),
|
||||
subject_token: EmaSubjectToken::RefreshToken(RefreshToken::new(
|
||||
refresh_token.to_string(),
|
||||
)),
|
||||
idp_http_client: http_client(),
|
||||
resource_http_client: http_client(),
|
||||
},
|
||||
@@ -107,17 +109,37 @@ async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
|
||||
let client = http_client();
|
||||
use codex_config::McpEmaTokenEndpointAuthMethod::ClientSecretBasic;
|
||||
use codex_config::McpEmaTokenEndpointAuthMethod::ClientSecretPost;
|
||||
for (scopes, echo_scope, refresh_token, idp_method) in [
|
||||
for (scopes, echo_scope, subject_token, subject_type, idp_method) in [
|
||||
(
|
||||
requested_scopes.as_slice(),
|
||||
true,
|
||||
"opaque-refresh-token",
|
||||
"refresh_token",
|
||||
None,
|
||||
),
|
||||
(
|
||||
&[],
|
||||
true,
|
||||
"opaque-refresh-token",
|
||||
"refresh_token",
|
||||
Some(ClientSecretBasic),
|
||||
),
|
||||
(
|
||||
&[],
|
||||
false,
|
||||
"opaque-refresh-token",
|
||||
"refresh_token",
|
||||
Some(ClientSecretPost),
|
||||
),
|
||||
(&[], true, "test-id-token", "id_token", None),
|
||||
(requested_scopes.as_slice(), true, "", "refresh_token", None),
|
||||
(
|
||||
requested_scopes.as_slice(),
|
||||
true,
|
||||
" \t",
|
||||
"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());
|
||||
@@ -129,7 +151,7 @@ async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
|
||||
.expect("ID-JAG response")
|
||||
.remove("scope");
|
||||
}
|
||||
let valid = !refresh_token.trim().is_empty();
|
||||
let valid = !subject_token.trim().is_empty();
|
||||
for (endpoint, response) in [("/idp/token", jag.clone()), ("/as/token", token_response())] {
|
||||
Mock::given(method("POST"))
|
||||
.and(path(endpoint))
|
||||
@@ -138,7 +160,7 @@ async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
|
||||
.mount(&server)
|
||||
.await;
|
||||
}
|
||||
let expected_subject = refresh_token.to_string();
|
||||
let expected_subject = subject_token.to_string();
|
||||
let resource_method = idp_method.map(|method| match method {
|
||||
ClientSecretBasic => ClientSecretPost,
|
||||
ClientSecretPost => ClientSecretBasic,
|
||||
@@ -169,7 +191,11 @@ async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
|
||||
idp_token_endpoint: &format!("{issuer}/token"),
|
||||
idp_issuer: &issuer,
|
||||
idp_client_id: "idp-client",
|
||||
refresh_token: refresh_token.to_string(),
|
||||
subject_token: if subject_type == "id_token" {
|
||||
EmaSubjectToken::IdToken(subject_token.to_owned())
|
||||
} else {
|
||||
EmaSubjectToken::RefreshToken(RefreshToken::new(subject_token.to_owned()))
|
||||
},
|
||||
idp_http_client: Arc::clone(&client),
|
||||
resource_http_client: Arc::clone(&client),
|
||||
},
|
||||
@@ -254,7 +280,7 @@ async fn client_round_trip_preserves_signed_narrowing() -> Result<()> {
|
||||
("subject_token".to_string(), expected_subject),
|
||||
(
|
||||
"subject_token_type".to_string(),
|
||||
"urn:ietf:params:oauth:token-type:refresh_token".to_string(),
|
||||
format!("urn:ietf:params:oauth:token-type:{subject_type}"),
|
||||
),
|
||||
("audience".to_string(), audience.clone()),
|
||||
("resource".to_string(), resource.clone()),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Shared enterprise IdP discovery and stored refresh-token resolution.
|
||||
//! Shared enterprise IdP discovery and stored exchange-subject resolution.
|
||||
//! Login and token exchange require published metadata bound to the configured issuer.
|
||||
|
||||
use std::sync::Arc;
|
||||
@@ -11,7 +11,6 @@ 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;
|
||||
@@ -24,11 +23,12 @@ 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::EmaSubjectToken;
|
||||
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::stored_ema_subject;
|
||||
use crate::oauth_http_client::OAuthHttpClientAdapter;
|
||||
use crate::utils::build_default_headers;
|
||||
use rmcp::transport::auth::enterprise::EmaClientAuthentication;
|
||||
@@ -43,10 +43,10 @@ pub struct EmaIdpIdentityRequest<'a> {
|
||||
pub redirect_mode: StreamableHttpRedirectMode,
|
||||
}
|
||||
|
||||
/// An opaque IdP refresh token paired with the credentials admitted for its exchange.
|
||||
/// An opaque IdP exchange subject 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) subject_token: EmaSubjectToken,
|
||||
pub(crate) credentials: L,
|
||||
pub(crate) client_authentication: EmaClientAuthentication,
|
||||
}
|
||||
@@ -57,7 +57,7 @@ impl<L> EmaIdpIdentity<L> {
|
||||
pub fn map_credentials<U>(self, map: impl FnOnce(L) -> U) -> EmaIdpIdentity<U> {
|
||||
EmaIdpIdentity {
|
||||
token_endpoint: self.token_endpoint,
|
||||
refresh_token: self.refresh_token,
|
||||
subject_token: self.subject_token,
|
||||
credentials: map(self.credentials),
|
||||
client_authentication: self.client_authentication,
|
||||
}
|
||||
@@ -103,7 +103,7 @@ pub async fn resolve_ema_account_idp_identity<L: Send>(
|
||||
))?;
|
||||
Ok(EmaIdpIdentity {
|
||||
token_endpoint,
|
||||
refresh_token,
|
||||
subject_token: EmaSubjectToken::RefreshToken(oauth2::RefreshToken::new(refresh_token)),
|
||||
credentials,
|
||||
client_authentication,
|
||||
})
|
||||
@@ -119,7 +119,7 @@ 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.
|
||||
/// Returns whether stored credentials contain an exchange subject bound to the configured login.
|
||||
pub fn stored_ema_identity_is_usable(
|
||||
tokens: &StoredOAuthTokens,
|
||||
issuer: &str,
|
||||
@@ -128,8 +128,7 @@ pub fn stored_ema_identity_is_usable(
|
||||
tokens.url == issuer
|
||||
&& tokens.bound_issuer() == Some(issuer)
|
||||
&& tokens.client_id == client_id
|
||||
&& tokens.has_refresh_token()
|
||||
&& stored_oidc_identity(tokens).is_ok()
|
||||
&& stored_ema_subject(tokens).is_ok()
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_ema_idp_authorization_manager(
|
||||
@@ -177,7 +176,7 @@ pub(crate) async fn resolve_ema_idp_authorization_manager(
|
||||
Ok((manager, metadata, authentication))
|
||||
}
|
||||
|
||||
/// Resolve a stored refresh-token subject against the configured enterprise IdP metadata.
|
||||
/// Resolve a stored exchange subject against the configured enterprise IdP metadata.
|
||||
pub async fn resolve_ema_idp_identity(
|
||||
request: EmaIdpIdentityRequest<'_>,
|
||||
) -> Result<EmaIdpIdentity> {
|
||||
@@ -198,7 +197,7 @@ async fn resolve_ema_idp_identity_in<K: KeyringStore + Clone + 'static>(
|
||||
{
|
||||
bail!("stored enterprise IdP credentials do not match the configured issuer and client");
|
||||
}
|
||||
stored_oidc_identity(credentials)?;
|
||||
stored_ema_subject(credentials)?;
|
||||
let (token_endpoint, client_authentication) = resolve_ema_idp_token_endpoint(
|
||||
request.issuer,
|
||||
request.client_secret,
|
||||
@@ -225,19 +224,9 @@ async fn resolve_ema_idp_identity_in<K: KeyringStore + Clone + 'static>(
|
||||
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(),
|
||||
subject_token: stored_ema_subject(&latest)?,
|
||||
credentials,
|
||||
client_authentication,
|
||||
})
|
||||
|
||||
@@ -259,14 +259,59 @@ async fn refresh_subject_rereads_pinned_credentials_after_id_token_expiry() -> R
|
||||
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")
|
||||
);
|
||||
assert_eq!(identity.token_endpoint, format!("{issuer}/token"));
|
||||
let EmaSubjectToken::RefreshToken(token) = identity.subject_token else {
|
||||
panic!("expected the refresh token to take precedence");
|
||||
};
|
||||
assert_eq!(token.secret(), "stored-refresh");
|
||||
let _released = RefreshCredentialLock::acquire_for_server(&stored.server_name, &issuer).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn id_token_subject_requires_a_current_bound_assertion() -> Result<()> {
|
||||
let _home = TempCodexHome::new();
|
||||
let (_server, issuer) = discovery().await;
|
||||
let store = ResolvedOAuthCredentialStore::keyring(AuthKeyringBackendKind::Direct);
|
||||
let keyring = MockKeyringStore::default();
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
|
||||
for (asserted_issuer, expires_at) in [
|
||||
(issuer.as_str(), now + 300),
|
||||
(issuer.as_str(), 0),
|
||||
("https://other.example", now + 300),
|
||||
] {
|
||||
let mut stored = credentials(asserted_issuer, "user", expires_at);
|
||||
stored.url = issuer.clone();
|
||||
stored.issuer = Some(issuer.clone());
|
||||
stored.token_response.0.set_refresh_token(None);
|
||||
store.save(&keyring, &stored.server_name, &stored)?;
|
||||
let snapshot = StoredOAuthCredentialSnapshot::new(stored.clone(), store);
|
||||
let identity = resolve_ema_idp_identity_in(request(&issuer, &snapshot), &keyring).await;
|
||||
let valid = asserted_issuer == issuer && expires_at > now;
|
||||
assert_eq!(
|
||||
stored_ema_identity_is_usable(&stored, &issuer, "idp-client"),
|
||||
valid
|
||||
);
|
||||
if valid {
|
||||
let EmaSubjectToken::IdToken(token) = identity?.subject_token else {
|
||||
panic!("expected the login's ID token");
|
||||
};
|
||||
assert_eq!(
|
||||
Some(token.as_str()),
|
||||
stored.token_response.0.extra_fields().0["id_token"].as_str()
|
||||
);
|
||||
} else {
|
||||
assert!(matches!(
|
||||
identity
|
||||
.err()
|
||||
.and_then(|error| error.downcast::<EmaAuthFailure>().ok()),
|
||||
Some(EmaAuthFailure::ReauthenticationRequired)
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refresh_subject_rejects_removed_replaced_or_missing_credentials() -> Result<()> {
|
||||
let _home = TempCodexHome::new();
|
||||
|
||||
@@ -330,9 +330,6 @@ pub(crate) fn enterprise_callback_settings(
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -256,6 +256,91 @@ fn enterprise_callback_requires_loopback() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn enterprise_login_keeps_offline_access_with_incomplete_metadata() -> Result<()> {
|
||||
if isolated_process(
|
||||
"enterprise_oauth_login::tests::enterprise_login_keeps_offline_access_with_incomplete_metadata",
|
||||
)
|
||||
.await?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
let keyring = TestKeyring::default();
|
||||
keyring::set_default_credential_builder(Box::new(keyring));
|
||||
// RFC 8414 permits metadata to omit supported scopes. Both issuers
|
||||
// accept offline_access, but only one issues a refresh token.
|
||||
for refresh_token in [None, Some(SECRET)] {
|
||||
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"),
|
||||
"token_endpoint_auth_methods_supported": ["none"],
|
||||
"scopes_supported": ["openid"],
|
||||
})))
|
||||
.mount(&server)
|
||||
.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()
|
||||
)
|
||||
);
|
||||
let mut token_response = json!({
|
||||
"access_token":SECRET,"id_token":assertion,"token_type":"Bearer",
|
||||
});
|
||||
if let Some(refresh_token) = refresh_token {
|
||||
token_response["refresh_token"] = json!(refresh_token);
|
||||
}
|
||||
Mock::given(method("POST"))
|
||||
.and(path("/idp/token"))
|
||||
.respond_with(ResponseTemplate::new(200).set_body_json(token_response))
|
||||
.expect(1)
|
||||
.mount(&server)
|
||||
.await;
|
||||
|
||||
let login = login(
|
||||
&issuer, /*callback_url*/ None, /*auth_method*/ None,
|
||||
)
|
||||
.await?;
|
||||
let authorization_url = login.authorization_url();
|
||||
let url = Url::parse(&authorization_url)?;
|
||||
let scopes = url
|
||||
.query_pairs()
|
||||
.find(|(key, _)| key == "scope")
|
||||
.expect("authorization scope")
|
||||
.1;
|
||||
assert_eq!(
|
||||
scopes.split_ascii_whitespace().collect::<Vec<_>>(),
|
||||
vec!["openid", "offline_access"]
|
||||
);
|
||||
callback(&authorization_url, &issuer, /*provider_error*/ false).await?;
|
||||
login.wait().await?.commit_if(|| async { Some(()) }).await?;
|
||||
|
||||
let stored = crate::stored_oauth_credentials(
|
||||
CREDENTIAL_NAME,
|
||||
&issuer,
|
||||
OAuthCredentialsStoreMode::Keyring,
|
||||
AuthKeyringBackendKind::Direct,
|
||||
)?
|
||||
.expect("stored grant");
|
||||
use crate::ema_exchange::EmaSubjectToken;
|
||||
match (refresh_token, crate::oauth::stored_ema_subject(&stored)?) {
|
||||
(None, EmaSubjectToken::IdToken(token)) => assert_eq!(token, assertion),
|
||||
(Some(expected), EmaSubjectToken::RefreshToken(token)) => {
|
||||
assert_eq!(token.secret(), expected);
|
||||
}
|
||||
_ => panic!("selected the wrong enterprise exchange subject"),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[traced_test]
|
||||
#[tokio::test]
|
||||
async fn enterprise_public_api_storage_and_privacy() -> Result<()> {
|
||||
|
||||
@@ -86,7 +86,7 @@ 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::ema_identity::stored_ema_subject;
|
||||
pub(crate) use self::enterprise_generation::EnterpriseOAuthGeneration;
|
||||
pub(crate) use self::enterprise_generation::EnterpriseOAuthGenerationFile;
|
||||
pub(crate) use self::enterprise_generation::EnterpriseOAuthGenerationKind;
|
||||
|
||||
@@ -8,13 +8,15 @@ use anyhow::anyhow;
|
||||
use anyhow::bail;
|
||||
use codex_keyring_store::DefaultKeyringStore;
|
||||
use codex_keyring_store::KeyringStore;
|
||||
use oauth2::TokenResponse;
|
||||
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::ema_claims::validate_oidc_identity_assertion;
|
||||
use crate::ema_exchange::EmaSubjectToken;
|
||||
use crate::oauth::EnterpriseOAuthGeneration;
|
||||
use crate::oauth::EnterpriseOAuthGenerationFile;
|
||||
use crate::oauth::EnterpriseOAuthGenerationKind;
|
||||
@@ -52,7 +54,7 @@ impl std::fmt::Debug for EmaCredentialLease {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn stored_oidc_identity(tokens: &StoredOAuthTokens) -> Result<OidcClaims> {
|
||||
pub(crate) fn stored_ema_subject(tokens: &StoredOAuthTokens) -> Result<EmaSubjectToken> {
|
||||
let assertion = tokens
|
||||
.token_response
|
||||
.0
|
||||
@@ -65,12 +67,26 @@ pub(crate) fn stored_oidc_identity(tokens: &StoredOAuthTokens) -> Result<OidcCla
|
||||
"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| {
|
||||
let invalid_identity = || {
|
||||
ema_reauthentication_required("stored enterprise IdP identity is invalid; sign in again")
|
||||
.context(error.to_string())
|
||||
})
|
||||
};
|
||||
if let Some(refresh_token) = tokens
|
||||
.token_response
|
||||
.0
|
||||
.refresh_token()
|
||||
.filter(|token| !token.secret().trim().is_empty())
|
||||
{
|
||||
// An expired ID token still corroborates the binding of a separate refresh token.
|
||||
oidc_identity(assertion, &tokens.url, &tokens.client_id).map_err(|_| invalid_identity())?;
|
||||
return Ok(EmaSubjectToken::RefreshToken(refresh_token.clone()));
|
||||
}
|
||||
// When the assertion itself is the exchange credential, it must still be live.
|
||||
validate_oidc_identity_assertion(assertion, &tokens.url, &tokens.client_id).map_err(|_| {
|
||||
ema_reauthentication_required(
|
||||
"enterprise IdP ID token is expired or invalid; sign in again",
|
||||
)
|
||||
})?;
|
||||
Ok(EmaSubjectToken::IdToken(assertion.to_owned()))
|
||||
}
|
||||
|
||||
impl StoredOAuthCredentialSnapshot {
|
||||
@@ -261,15 +277,12 @@ impl StoredOAuthCredentialSnapshot {
|
||||
// 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()
|
||||
{
|
||||
if latest != *previous || previous.bound_issuer() != Some(previous.url.as_str()) {
|
||||
return Err(ema_reauthentication_required(
|
||||
"enterprise IdP identity changed; sign in again and reconnect",
|
||||
));
|
||||
}
|
||||
stored_oidc_identity(&latest)?;
|
||||
stored_ema_subject(&latest)?;
|
||||
Ok(latest)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user