Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

accept mcp protected resources matching the endpoint or its origin (#3368)

ktaab5020ae3f7
diff --git a/crates/pa-cli/src/codex_subscription_login.rs b/crates/pa-cli/src/codex_subscription_login.rs
index 7a0408c86d..0346d149e8 100644
--- a/crates/pa-cli/src/codex_subscription_login.rs
+++ b/crates/pa-cli/src/codex_subscription_login.rs
@@ -95,6 +95,7 @@ pub(crate) async fn run_codex_subscription_login(
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
},
);
diff --git a/crates/pa-cli/src/mcp_login.rs b/crates/pa-cli/src/mcp_login.rs
index a61bad885d..9c18c1064b 100644
--- a/crates/pa-cli/src/mcp_login.rs
+++ b/crates/pa-cli/src/mcp_login.rs
@@ -463,6 +463,7 @@ mod tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
},
);
diff --git a/crates/pa-cli/src/provider_login/tests.rs b/crates/pa-cli/src/provider_login/tests.rs
index aeecb07bc8..895180d6c5 100644
--- a/crates/pa-cli/src/provider_login/tests.rs
+++ b/crates/pa-cli/src/provider_login/tests.rs
@@ -37,6 +37,7 @@ fn the_status_indicator_maps_the_ts_labels() {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
}),
&AuthStatus::default(),
@@ -210,6 +211,7 @@ async fn the_anthropic_subscription_warning_matches_the_active_credential() {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
account_id: None,
enterprise_url: None,
},
diff --git a/crates/pa-cli/src/subscription_login.rs b/crates/pa-cli/src/subscription_login.rs
index ee2a304276..bac065e418 100644
--- a/crates/pa-cli/src/subscription_login.rs
+++ b/crates/pa-cli/src/subscription_login.rs
@@ -151,6 +151,7 @@ fn store_anthropic_login(
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
},
);
if let Some(error) = auth.drain_errors().pop() {
@@ -197,6 +198,7 @@ pub(crate) async fn run_github_copilot_login(
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
},
);
if let Some(error) = auth.drain_errors().pop() {
@@ -241,6 +243,7 @@ pub(crate) async fn run_xai_login(
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
},
);
if let Some(error) = auth.drain_errors().pop() {
diff --git a/crates/pa-core/src/auth/manager/tests.rs b/crates/pa-core/src/auth/manager/tests.rs
index 3952153b93..4ddebe0ca4 100644
--- a/crates/pa-core/src/auth/manager/tests.rs
+++ b/crates/pa-core/src/auth/manager/tests.rs
@@ -519,6 +519,7 @@ impl CountingOAuth {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
}
}
}
@@ -552,6 +553,7 @@ fn oauth_credential(access: &str, expires: i64) -> AuthCredential {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
}
}
diff --git a/crates/pa-core/src/auth/provider_oauth.rs b/crates/pa-core/src/auth/provider_oauth.rs
index e63c61a05e..bd92a78794 100644
--- a/crates/pa-core/src/auth/provider_oauth.rs
+++ b/crates/pa-core/src/auth/provider_oauth.rs
@@ -101,6 +101,7 @@ impl ProviderOAuth {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
})
}
ANTHROPIC_PROVIDER_ID => {
@@ -121,6 +122,7 @@ impl ProviderOAuth {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
})
}
GITHUB_COPILOT_PROVIDER_ID => {
@@ -144,6 +146,7 @@ impl ProviderOAuth {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
})
}
XAI_PROVIDER_ID => {
@@ -161,6 +164,7 @@ impl ProviderOAuth {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
})
}
// The match arms cover the four subscription ids;
@@ -272,6 +276,7 @@ mod tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
}
}
@@ -289,6 +294,7 @@ mod tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
},
_ => AuthCredential::Oauth {
access: "stale-access".to_string(),
@@ -301,6 +307,7 @@ mod tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
},
}
}
@@ -509,6 +516,7 @@ mod tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
};
let mut auth = storage_with_credential(OPENAI_CODEX_PROVIDER_ID, &unexpired);
assert_eq!(
diff --git a/crates/pa-core/src/auth/types.rs b/crates/pa-core/src/auth/types.rs
index 9ccfbee7ca..72a4a50b77 100644
--- a/crates/pa-core/src/auth/types.rs
+++ b/crates/pa-core/src/auth/types.rs
@@ -101,6 +101,16 @@ pub enum AuthCredential {
/// RFC 8414/OIDC issuer selected by the protected-resource metadata.
#[serde(rename = "issuer", default, skip_serializing_if = "Option::is_none")]
issuer: Option<String>,
+ /// How `resource` associates with the configured endpoint: "exact"
+ /// (component-equal to the endpoint) or "origin" (the endpoint's bare
+ /// origin). `None` on legacy credentials that predate audience
+ /// modes (they were only ever issued under exact matching).
+ #[serde(
+ rename = "audienceMode",
+ default,
+ skip_serializing_if = "Option::is_none"
+ )]
+ audience_mode: Option<String>,
},
}
diff --git a/crates/pa-core/src/mcp/catalog_plugin_views.rs b/crates/pa-core/src/mcp/catalog_plugin_views.rs
index a8904ce3bf..e376bbc95b 100644
--- a/crates/pa-core/src/mcp/catalog_plugin_views.rs
+++ b/crates/pa-core/src/mcp/catalog_plugin_views.rs
@@ -775,6 +775,7 @@ mod connection_view_tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
account_id: None,
enterprise_url: None,
}
diff --git a/crates/pa-core/src/mcp/login.rs b/crates/pa-core/src/mcp/login.rs
index b347783d87..983dd8f2a0 100644
--- a/crates/pa-core/src/mcp/login.rs
+++ b/crates/pa-core/src/mcp/login.rs
@@ -558,6 +558,7 @@ mod tests {
client_id: Some("fixture-client".to_string()),
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
},
);
@@ -608,6 +609,7 @@ mod tests {
client_id: Some("fixture-client".to_string()),
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
},
);
diff --git a/crates/pa-core/src/mcp/manager_catalog/tests.rs b/crates/pa-core/src/mcp/manager_catalog/tests.rs
index f8acf5aba7..afa080c9bc 100644
--- a/crates/pa-core/src/mcp/manager_catalog/tests.rs
+++ b/crates/pa-core/src/mcp/manager_catalog/tests.rs
@@ -244,6 +244,7 @@ fn installed_connections_are_endpoint_pinned_across_catalog_url_changes() {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
},
);
@@ -704,6 +705,7 @@ fn api_key_credential_views_read_the_shared_store() {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
},
);
diff --git a/crates/pa-core/src/mcp/oauth.rs b/crates/pa-core/src/mcp/oauth.rs
index deedeb38b7..5d025c22a9 100644
--- a/crates/pa-core/src/mcp/oauth.rs
+++ b/crates/pa-core/src/mcp/oauth.rs
@@ -16,7 +16,8 @@ use crate::auth::types::AuthCredential;
use super::oauth_callback::{CallbackCode, CallbackServer};
use super::oauth_discovery::{
canonical_resource, discover, exchange_token, generate_pkce, parse_redirect_input,
- random_state, register_client, validated_https_url, TokenResponse, TOKEN_EXPIRY_BUFFER_MS,
+ random_state, register_client, validated_https_url, AudienceMode, TokenResponse,
+ TOKEN_EXPIRY_BUFFER_MS,
};
use super::oauth_http::OAuthHttp;
use url::Url;
@@ -62,6 +63,16 @@ fn now_ms() -> i64 {
.map_or(i64::MAX, |elapsed| elapsed.as_millis() as i64)
}
+/// The audience binding a login persists with the credential (the TS
+/// `Discovery` trio): the declared resource, the PRM-selected issuer, and
+/// how the resource associates with the configured endpoint.
+#[derive(Debug, Clone, Default)]
+struct ResourceBinding {
+ resource: Option<String>,
+ issuer: Option<String>,
+ audience_mode: Option<String>,
+}
+
/// Build the credential the flow persists. A missing `expires_in` defaults to one hour; some
/// servers omit `refresh_token`, so the prior one is kept.
fn to_credentials(
@@ -69,8 +80,7 @@ fn to_credentials(
token_endpoint: &str,
client_id: &str,
endpoint: Option<&str>,
- resource: Option<&str>,
- issuer: Option<&str>,
+ binding: &ResourceBinding,
previous_refresh: Option<&str>,
) -> AuthCredential {
AuthCredential::Oauth {
@@ -87,8 +97,9 @@ fn to_credentials(
endpoint: endpoint.map(str::to_string),
token_endpoint: Some(token_endpoint.to_string()),
client_id: (!client_id.is_empty()).then(|| client_id.to_string()),
- resource: resource.map(str::to_string),
- issuer: issuer.map(str::to_string),
+ resource: binding.resource.clone(),
+ issuer: binding.issuer.clone(),
+ audience_mode: binding.audience_mode.clone(),
enterprise_url: None,
}
}
@@ -133,6 +144,20 @@ pub async fn mcp_login(
.unwrap_or(discovery.metadata.issuer.as_str())
));
+ // SEP-835: configured scopes, then the protected-resource metadata's
+ // scopes; never a blind AS-wide join.
+ let scope = config
+ .scopes
+ .clone()
+ .or_else(|| {
+ discovery
+ .protected_resource
+ .as_ref()
+ .and_then(|protected| protected.scopes_supported.as_ref())
+ .map(|scopes| scopes.join(" "))
+ })
+ .unwrap_or_default();
+
let client_id = if let Some(client_id) = &config.client_id {
client_id.clone()
} else {
@@ -144,7 +169,13 @@ pub async fn mcp_login(
);
};
ui.on_progress("Registering OAuth client…");
- register_client(http, registration_endpoint, &config.label).await?
+ register_client(
+ http,
+ registration_endpoint,
+ &config.label,
+ (!scope.is_empty()).then_some(scope.as_str()),
+ )
+ .await?
};
let (verifier, challenge) = generate_pkce();
@@ -153,18 +184,6 @@ pub async fn mcp_login(
let state = random_state();
let callback = Arc::new(CallbackServer::start(&config.label).await?);
let redirect_uri = callback.redirect_uri();
-
- let scope = config
- .scopes
- .clone()
- .or_else(|| {
- discovery
- .metadata
- .scopes_supported
- .as_ref()
- .map(|scopes| scopes.join(" "))
- })
- .unwrap_or_default();
let mut auth_params: Vec<(String, String)> = vec![
("client_id".to_string(), client_id.clone()),
("response_type".to_string(), "code".to_string()),
@@ -272,8 +291,14 @@ pub async fn mcp_login(
&discovery.metadata.token_endpoint,
&client_id,
Some(&config.url),
- discovery.resource.as_deref(),
- discovery.issuer.as_deref(),
+ &ResourceBinding {
+ resource: discovery.resource.clone(),
+ issuer: discovery.issuer.clone(),
+ audience_mode: discovery
+ .audience_mode
+ .map(AudienceMode::as_str)
+ .map(str::to_string),
+ },
None,
))
}
@@ -283,8 +308,12 @@ pub async fn mcp_login(
///
/// # Errors
///
-/// Returns an error when the stored credential is not OAuth, no longer bound to the same endpoint
-/// or token endpoint, carries no refresh token, or discovery or the token exchange fails.
+/// Returns an error when the stored credential is not OAuth, is no longer
+/// bound to the same endpoint, resource audience (exact grants pin to the
+/// canonical endpoint, origin-mode grants to the endpoint's origin),
+/// issuer, or token endpoint, carries an unknown audience mode, no refresh
+/// token, when discovery fails or changed modes, or when the token exchange
+/// fails.
///
/// # Panics
///
@@ -301,6 +330,7 @@ pub async fn mcp_refresh_token(
client_id,
resource,
issuer,
+ audience_mode,
..
} = credentials
else {
@@ -317,11 +347,26 @@ pub async fn mcp_refresh_token(
config.server
);
}
+ let endpoint_url = validated_https_url(&config.url, "MCP endpoint")?;
+ let configured_resource = canonical_resource(&endpoint_url);
if let Some(stored_resource) = resource {
- let configured = canonical_resource(&validated_https_url(&config.url, "MCP endpoint")?);
- if stored_resource != &configured {
+ // Audience-aware binding (TS parity): exact grants (and legacy
+ // grants, which were only ever issued under exact matching) pin to
+ // the canonical endpoint; origin-mode grants pin to the endpoint's
+ // exact origin. Anything else fails closed.
+ let stored_audience = canonical_resource(&validated_https_url(
+ stored_resource,
+ "Stored resource audience",
+ )?);
+ let allowed_audience = if audience_mode.as_deref() == Some("origin") {
+ endpoint_url.origin().ascii_serialization()
+ } else {
+ configured_resource.clone()
+ };
+ if stored_audience != allowed_audience {
bail!(
- "Stored OAuth credentials are not bound to {configured}; re-run /mcp login {}",
+ "Stored OAuth credentials are not bound to {allowed_audience}; re-run /mcp \
+ login {}",
config.server
);
}
@@ -335,6 +380,24 @@ pub async fn mcp_refresh_token(
config.server
),
}
+ // Stored audience modes are JSON-sourced; unknown values require
+ // re-login.
+ if resource.is_some()
+ && audience_mode.is_some()
+ && audience_mode.as_deref() != Some("exact")
+ && audience_mode.as_deref() != Some("origin")
+ {
+ bail!(
+ "Stored OAuth credentials for {} have an unknown audience mode; re-run /mcp \
+ login {}",
+ config.label,
+ config.server
+ );
+ }
+ // Legacy credentials predate audience modes: they were only ever
+ // issued under exact resource matching, so only "exact" re-discovery
+ // may serve them.
+ let legacy_audience = resource.is_some() && audience_mode.is_none();
if let Some(issuer) = issuer {
validated_https_url(issuer, "Stored authorization server issuer")?;
}
@@ -366,6 +429,23 @@ pub async fn mcp_refresh_token(
config.url
);
}
+ let current_mode = discovery.audience_mode;
+ if legacy_audience && current_mode != Some(AudienceMode::Exact) {
+ bail!(
+ "Stored OAuth credentials for {} predate origin-level resource audiences and \
+ may not be refreshed against them; re-run /mcp login {}",
+ config.label,
+ config.server
+ );
+ }
+ if !legacy_audience && current_mode.map(AudienceMode::as_str) != audience_mode.as_deref() {
+ bail!(
+ "Stored OAuth credentials do not match current resource audience for {}; \
+ re-run /mcp login {}",
+ config.url,
+ config.server
+ );
+ }
}
let stored_token_endpoint = token_endpoint.clone();
let token_endpoint = stored_token_endpoint
@@ -407,8 +487,11 @@ pub async fn mcp_refresh_token(
&token_endpoint,
&client_id,
endpoint.as_deref(),
- resource.as_deref(),
- issuer.as_deref(),
+ &ResourceBinding {
+ resource: resource.clone(),
+ issuer: issuer.clone(),
+ audience_mode: audience_mode.clone(),
+ },
refresh.as_deref(),
))
}
@@ -601,6 +684,7 @@ mod tests {
&json_response(&serde_json::json!({
"resource": RESOURCE,
"authorization_servers": [PLANE_ISSUER],
+ "scopes_supported": ["read", "write"],
})),
),
(PLANE_META_URL, 200, None, &json_response(&plane_meta())),
@@ -634,6 +718,7 @@ mod tests {
client_id,
resource,
issuer,
+ audience_mode,
..
} => {
assert_eq!(access, "access-1");
@@ -643,9 +728,25 @@ mod tests {
assert_eq!(client_id.as_deref(), Some("plane-client"));
assert_eq!(resource.as_deref(), Some(RESOURCE));
assert_eq!(issuer.as_deref(), Some(PLANE_ISSUER));
+ assert_eq!(audience_mode.as_deref(), Some("exact"));
}
other => panic!("oauth credential expected, got {other:?}"),
}
+ // The registration request carried the resolved scope.
+ let registration_request = http
+ .seen
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(url, _)| url == PLANE_REGISTER)
+ .cloned()
+ .unwrap();
+ let registration_body =
+ serde_json::from_str::<serde_json::Value>(&registration_request.1.unwrap()).unwrap();
+ assert_eq!(
+ registration_body.get("scope").and_then(|v| v.as_str()),
+ Some("read write")
+ );
// The authorization URL carries the client, the resource, and the
// server's advertised scopes.
let auth_url = Url::parse(&ui.auth_url.lock().unwrap()).unwrap();
@@ -816,7 +917,10 @@ mod tests {
.await
.unwrap_err()
.to_string();
- assert!(error.contains("resource does not exactly match"), "{error}");
+ assert!(
+ error.contains("resource does not match the configured endpoint"),
+ "{error}"
+ );
}
#[tokio::test]
@@ -945,6 +1049,7 @@ mod tests {
client_id: Some("c".to_string()),
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
};
let origin_prm = "https://srv.test/.well-known/oauth-protected-resource/mcp";
@@ -975,6 +1080,7 @@ mod tests {
client_id: Some("client-xyz".to_string()),
resource: Some(RESOURCE.to_string()),
issuer: Some(PLANE_ISSUER.to_string()),
+ audience_mode: None,
enterprise_url: None,
};
let http = ScriptedHttp::new(vec![
@@ -1048,6 +1154,7 @@ mod tests {
client_id: None,
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
};
let error = mcp_refresh_token(&http, &config("plane", RESOURCE), &retargeted)
@@ -1068,6 +1175,7 @@ mod tests {
client_id: Some("client-xyz".to_string()),
resource: Some(RESOURCE.to_string()),
issuer: Some(PLANE_ISSUER.to_string()),
+ audience_mode: None,
enterprise_url: None,
};
let error = mcp_refresh_token(&http, &config("plane", RESOURCE), &drifted)
@@ -1099,6 +1207,7 @@ mod tests {
client_id: Some("origin-client".to_string()),
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
};
let http = ScriptedHttp::new(vec![
@@ -1199,4 +1308,316 @@ mod tests {
.collect();
assert!(!urls.contains(&ORIGIN_REGISTER.to_string()));
}
+
+ /// The Vercel shape (TS parity): a root endpoint whose declared
+ /// resource keeps the trailing slash is component-equal, never a
+ /// string-equal, match — the declared resource is the stored and sent
+ /// audience.
+ #[tokio::test]
+ async fn root_endpoint_trailing_slash_resource_audience() {
+ const ROOT: &str = "https://root.example";
+ const ROOT_PRM: &str = "https://root.example/.well-known/oauth-protected-resource";
+ const ROOT_AS: &str = "https://root.example/.well-known/oauth-authorization-server";
+ let http = ScriptedHttp::new(vec![
+ (ROOT, 401, None, ""),
+ (
+ ROOT_PRM,
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "resource": "https://root.example/",
+ "authorization_servers": [ROOT],
+ "scopes_supported": ["openid"],
+ })),
+ ),
+ (
+ ROOT_AS,
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "issuer": ROOT,
+ "authorization_endpoint": "https://root.example/authorize",
+ "token_endpoint": "https://root.example/token",
+ "scopes_supported": ["openid"],
+ })),
+ ),
+ (
+ "https://root.example/token",
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "access_token": "root-access",
+ "refresh_token": "root-refresh",
+ })),
+ ),
+ ]);
+ let ui = test_ui();
+ let mut login_config = config("root", ROOT);
+ login_config.client_id = Some("root-client".to_string());
+ let credentials = mcp_login(&http, &login_config, &ui).await.unwrap();
+ match &credentials {
+ AuthCredential::Oauth {
+ access,
+ endpoint,
+ resource,
+ issuer,
+ audience_mode,
+ ..
+ } => {
+ assert_eq!(access, "root-access");
+ assert_eq!(endpoint.as_deref(), Some(ROOT));
+ assert_eq!(resource.as_deref(), Some("https://root.example/"));
+ assert_eq!(issuer.as_deref(), Some(ROOT));
+ assert_eq!(audience_mode.as_deref(), Some("exact"));
+ }
+ other => panic!("oauth credential expected, got {other:?}"),
+ }
+ // The declared resource and the PRM-advertised scope went out on
+ // the authorization URL.
+ let auth_url = Url::parse(&ui.auth_url.lock().unwrap()).unwrap();
+ let param = |name: &str| {
+ auth_url
+ .query_pairs()
+ .find(|(key, _)| key == name)
+ .map(|(_, value)| value.to_string())
+ };
+ assert_eq!(param("resource").as_deref(), Some("https://root.example/"));
+ assert_eq!(param("scope").as_deref(), Some("openid"));
+ // The token request carried the declared resource.
+ let token_request = http
+ .seen
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(url, _)| url == "https://root.example/token")
+ .cloned()
+ .unwrap();
+ let body = token_request.1.unwrap();
+ let encoded_resource = url::form_urlencoded::Serializer::new(String::new())
+ .append_pair("resource", "https://root.example/")
+ .finish();
+ assert!(body.contains(&encoded_resource));
+ }
+
+ /// The Notion/Slack shape (TS parity): an origin-level declared
+ /// resource serves a pathful endpoint as an "origin" audience.
+ #[tokio::test]
+ async fn origin_level_resource_audience_serves_pathful_endpoint() {
+ const NOTION_PRM: &str = "https://srv.test/.well-known/oauth-protected-resource/mcp";
+ let http = ScriptedHttp::new(vec![
+ (ORIGIN_URL, 401, None, ""),
+ (
+ NOTION_PRM,
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "resource": "https://srv.test",
+ "authorization_servers": ["https://srv.test/tenant"],
+ "scopes_supported": ["default"],
+ })),
+ ),
+ (
+ "https://srv.test/.well-known/oauth-authorization-server/tenant",
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "issuer": "https://srv.test/tenant",
+ "authorization_endpoint": ORIGIN_AUTHORIZE,
+ "token_endpoint": ORIGIN_TOKEN,
+ "registration_endpoint": ORIGIN_REGISTER,
+ })),
+ ),
+ (
+ ORIGIN_REGISTER,
+ 200,
+ None,
+ &json_response(&serde_json::json!({ "client_id": "origin-client" })),
+ ),
+ (
+ ORIGIN_TOKEN,
+ 200,
+ None,
+ &json_response(&serde_json::json!({ "access_token": "origin-access" })),
+ ),
+ ]);
+ let ui = test_ui();
+ let credentials = mcp_login(&http, &config("origin", ORIGIN_URL), &ui)
+ .await
+ .unwrap();
+ match &credentials {
+ AuthCredential::Oauth {
+ access,
+ resource,
+ issuer,
+ audience_mode,
+ ..
+ } => {
+ assert_eq!(access, "origin-access");
+ assert_eq!(resource.as_deref(), Some("https://srv.test"));
+ assert_eq!(issuer.as_deref(), Some("https://srv.test/tenant"));
+ assert_eq!(audience_mode.as_deref(), Some("origin"));
+ }
+ other => panic!("oauth credential expected, got {other:?}"),
+ }
+ // The declared origin-level audience went out on the authorization
+ // URL.
+ let auth_url = Url::parse(&ui.auth_url.lock().unwrap()).unwrap();
+ let resource = auth_url
+ .query_pairs()
+ .find(|(key, _)| key == "resource")
+ .map(|(_, value)| value.to_string());
+ assert_eq!(resource.as_deref(), Some("https://srv.test"));
+ }
+
+ /// Origin-mode credentials refresh against the origin-level binding;
+ /// an audience-mode drift against current discovery requires re-login.
+ #[tokio::test]
+ async fn refresh_validates_audience_modes() {
+ const NOTION_PRM: &str = "https://srv.test/.well-known/oauth-protected-resource/mcp";
+ const DECLARED: &str = "https://srv.test";
+ // A credential factory: the enum is not a struct, so variant
+ // rebuilds spell every field.
+ let reissued_oauth =
+ |resource: Option<&str>, audience_mode: Option<&str>| AuthCredential::Oauth {
+ access: "origin-access".to_string(),
+ refresh: Some("origin-refresh".to_string()),
+ expires: 0,
+ account_id: None,
+ endpoint: Some(ORIGIN_URL.to_string()),
+ token_endpoint: Some(ORIGIN_TOKEN.to_string()),
+ client_id: Some("origin-client".to_string()),
+ resource: resource.map(str::to_string),
+ issuer: Some("https://srv.test/tenant".to_string()),
+ audience_mode: audience_mode.map(str::to_string),
+ enterprise_url: None,
+ };
+ let credentials = reissued_oauth(Some(DECLARED), Some("origin"));
+ let http = ScriptedHttp::new(vec![
+ (ORIGIN_URL, 401, None, ""),
+ (
+ NOTION_PRM,
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "resource": DECLARED,
+ "authorization_servers": ["https://srv.test/tenant"],
+ })),
+ ),
+ (
+ "https://srv.test/.well-known/oauth-authorization-server/tenant",
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "issuer": "https://srv.test/tenant",
+ "authorization_endpoint": ORIGIN_AUTHORIZE,
+ "token_endpoint": ORIGIN_TOKEN,
+ })),
+ ),
+ (
+ ORIGIN_TOKEN,
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "access_token": "origin-access-2",
+ "expires_in": 1800,
+ })),
+ ),
+ ]);
+ // The origin-mode grant refreshes through the origin-level binding.
+ let refreshed = mcp_refresh_token(&http, &config("origin", ORIGIN_URL), &credentials)
+ .await
+ .unwrap();
+ match &refreshed {
+ AuthCredential::Oauth {
+ access,
+ resource,
+ audience_mode,
+ ..
+ } => {
+ assert_eq!(access, "origin-access-2");
+ assert_eq!(resource.as_deref(), Some(DECLARED));
+ assert_eq!(audience_mode.as_deref(), Some("origin"));
+ }
+ other => panic!("oauth credential expected, got {other:?}"),
+ }
+ // The refresh request carried the stored origin-level audience.
+ let token_request = http
+ .seen
+ .lock()
+ .unwrap()
+ .iter()
+ .find(|(url, _)| url == ORIGIN_TOKEN)
+ .cloned()
+ .unwrap();
+ assert!(token_request
+ .1
+ .unwrap()
+ .contains("resource=https%3A%2F%2Fsrv.test"));
+
+ // (The TS audience-mode equality fences on re-discovery — legacy
+ // must re-discover as "exact", non-legacy modes must match — are
+ // migration fences: classification is a pure function of the
+ // endpoint and the declared resource, so a well-formed discovery
+ // can never drift modes for the same stored binding. They stay
+ // ported, unreachable by construction.)
+
+ // Legacy credentials (no stored audience mode) pin to the canonical
+ // endpoint: an origin-level stored resource is refused at the
+ // binding check before any request leaves.
+ let legacy = reissued_oauth(Some(DECLARED), None);
+ let error = mcp_refresh_token(&http, &config("origin", ORIGIN_URL), &legacy)
+ .await
+ .unwrap_err()
+ .to_string();
+ assert!(
+ error.contains("not bound to https://srv.test/mcp"),
+ "{error}"
+ );
+
+ // Legacy credentials whose stored resource is the canonical
+ // endpoint refresh under "exact" re-discovery.
+ let http = ScriptedHttp::new(vec![
+ (ORIGIN_URL, 401, None, ""),
+ (
+ NOTION_PRM,
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "resource": ORIGIN_URL,
+ "authorization_servers": ["https://srv.test/tenant"],
+ })),
+ ),
+ (
+ "https://srv.test/.well-known/oauth-authorization-server/tenant",
+ 200,
+ None,
+ &json_response(&serde_json::json!({
+ "issuer": "https://srv.test/tenant",
+ "authorization_endpoint": ORIGIN_AUTHORIZE,
+ "token_endpoint": ORIGIN_TOKEN,
+ })),
+ ),
+ (
+ ORIGIN_TOKEN,
+ 200,
+ None,
+ &json_response(&serde_json::json!({ "access_token": "exact-access" })),
+ ),
+ ]);
+ let legacy_exact = reissued_oauth(Some(ORIGIN_URL), None);
+ let refreshed = mcp_refresh_token(&http, &config("origin", ORIGIN_URL), &legacy_exact)
+ .await
+ .unwrap();
+ match &refreshed {
+ AuthCredential::Oauth {
+ access,
+ audience_mode,
+ ..
+ } => {
+ assert_eq!(access, "exact-access");
+ assert!(audience_mode.is_none());
+ }
+ other => panic!("oauth credential expected, got {other:?}"),
+ }
+ }
}
diff --git a/crates/pa-core/src/mcp/oauth_discovery.rs b/crates/pa-core/src/mcp/oauth_discovery.rs
index 4437878361..8779f5d238 100644
--- a/crates/pa-core/src/mcp/oauth_discovery.rs
+++ b/crates/pa-core/src/mcp/oauth_discovery.rs
@@ -197,23 +197,72 @@ async fn discover_authorization_server(
)
}
-/// Protected-resource metadata (RFC 9728 shape).
-#[derive(Debug)]
-struct ProtectedResourceMetadata {
- resource: String,
- authorization_servers: Vec<String>,
+/// Protected-resource metadata (RFC 9728 shape; schema-validated,
+/// servers non-empty by policy).
+#[derive(Debug, Clone)]
+pub(crate) struct ProtectedResourceMetadata {
+ /// The DECLARED resource audience, sent as the `resource` parameter
+ /// (never the endpoint's own canonical string).
+ pub resource: String,
+ pub authorization_servers: Vec<String>,
+ /// SEP-835: the default scope source when the config has no scopes.
+ pub scopes_supported: Option<Vec<String>>,
+}
+
+/// How the resource declared by protected-resource metadata associates with
+/// the configured endpoint (the TS `AudienceMode`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum AudienceMode {
+ /// Component-equal to the configured endpoint (origin, path, query).
+ Exact,
+ /// The endpoint's bare HTTPS origin.
+ Origin,
+}
+
+impl AudienceMode {
+ /// The TS storage shape ("exact" | "origin").
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ AudienceMode::Exact => "exact",
+ AudienceMode::Origin => "origin",
+ }
+ }
+}
+
+/// Narrow audience policy (the TS `resourceAudienceMode`): the resource
+/// declared by protected-resource metadata must be the exact configured
+/// endpoint or the endpoint's exact HTTPS origin — component-compared,
+/// never a string prefix. Anything else fails closed.
+fn resource_audience_mode(endpoint: &Url, declared: &str) -> Result<AudienceMode> {
+ let resource = validated_https_url(declared, "Protected-resource resource")?;
+ let same_origin = resource.origin() == endpoint.origin();
+ if same_origin && resource.path() == endpoint.path() && resource.query() == endpoint.query() {
+ return Ok(AudienceMode::Exact);
+ }
+ // The TS check also allows an empty pathname; a parsed `Url` always
+ // normalizes the root path to "/".
+ let origin_level = same_origin
+ && (resource.path() == "/" || resource.path().is_empty())
+ && resource.query().is_none();
+ if origin_level {
+ return Ok(AudienceMode::Origin);
+ }
+ bail!(
+ "Protected-resource metadata resource does not match the configured endpoint {} or its origin",
+ canonical_resource(endpoint)
+ );
}
fn resource_metadata(
value: &serde_json::Value,
- resource: &str,
+ endpoint: &Url,
) -> Result<ProtectedResourceMetadata> {
let Some(object) = value.as_object() else {
bail!("Protected-resource metadata is invalid");
};
- if object.get("resource").and_then(|v| v.as_str()) != Some(resource) {
- bail!("Protected-resource metadata resource does not exactly match {resource}");
- }
+ let Some(declared) = object.get("resource").and_then(|v| v.as_str()) else {
+ bail!("Protected-resource metadata is invalid");
+ };
let Some(servers) = object
.get("authorization_servers")
.and_then(|value| value.as_array())
@@ -231,9 +280,20 @@ fn resource_metadata(
validated_https_url(issuer, "Authorization server issuer")?;
issuers.push(issuer.to_string());
}
+ let scopes_supported = object
+ .get("scopes_supported")
+ .and_then(|value| value.as_array())
+ .map(|scopes| {
+ scopes
+ .iter()
+ .filter_map(|scope| scope.as_str().map(str::to_string))
+ .collect::<Vec<String>>()
+ });
+ resource_audience_mode(endpoint, declared)?;
Ok(ProtectedResourceMetadata {
- resource: resource.to_string(),
+ resource: declared.to_string(),
authorization_servers: issuers,
+ scopes_supported,
})
}
@@ -283,10 +343,17 @@ fn header_resource_metadata(value: Option<&str>) -> Option<String> {
/// What discovery resolved for one MCP endpoint.
pub(crate) struct Discovery {
pub metadata: AuthServerMetadata,
- /// The RFC 9728 resource indicator when the login is PRM-based.
+ /// RFC 9728 metadata when present; the source of default scopes
+ /// (SEP-835).
+ pub protected_resource: Option<ProtectedResourceMetadata>,
+ /// The RFC 9728 resource audience declared by the protected resource,
+ /// sent as the `resource` parameter when the login is PRM-based.
pub resource: Option<String>,
/// The RFC 8414/OIDC issuer a PRM-based login selected.
pub issuer: Option<String>,
+ /// How the declared resource associates with the configured endpoint;
+ /// present exactly when `protected_resource` is.
+ pub audience_mode: Option<AudienceMode>,
}
/// Discover RFC 9728 protected-resource metadata before the origin-level
@@ -294,11 +361,15 @@ pub(crate) struct Discovery {
pub(crate) async fn discover(http: &dyn OAuthHttp, url: &str) -> Result<Discovery> {
let resource_url = validated_https_url(url, ENDPOINT_LABEL)?;
let protected = try_protected_resource_metadata(http, &resource_url).await?;
- if let Some((metadata, resource, issuer)) = protected {
+ if let Some(metadata) = protected {
+ let issuer = metadata.authorization_servers[0].clone();
+ let audience_mode = resource_audience_mode(&resource_url, &metadata.resource)?;
return Ok(Discovery {
- metadata,
- resource: Some(resource),
+ metadata: discover_authorization_server(http, &issuer, true).await?,
+ protected_resource: Some(metadata.clone()),
+ resource: Some(metadata.resource),
issuer: Some(issuer),
+ audience_mode: Some(audience_mode),
});
}
Ok(Discovery {
@@ -308,12 +379,14 @@ pub(crate) async fn discover(http: &dyn OAuthHttp, url: &str) -> Result<Discover
false,
)
.await?,
+ protected_resource: None,
resource: None,
issuer: None,
+ audience_mode: None,
})
}
-type ProtectedDiscovery = Option<(AuthServerMetadata, String, String)>;
+type ProtectedDiscovery = Option<ProtectedResourceMetadata>;
/// Probe protected-resource metadata:`resource_metadata` pointer first, then the RFC well-known
/// location. `None` when the server serves no RFC 9728 metadata.
@@ -347,11 +420,8 @@ async fn try_protected_resource_metadata(
if response.status == 404 && header_url.is_none() {
return Ok(None);
}
- let resource = canonical_resource(resource_url);
- let metadata = resource_metadata(&json_metadata(&response, &candidate)?, &resource)?;
- let issuer = metadata.authorization_servers[0].clone();
- let server = discover_authorization_server(http, &issuer, true).await?;
- Ok(Some((server, metadata.resource, issuer)))
+ let metadata = resource_metadata(&json_metadata(&response, &candidate)?, resource_url)?;
+ Ok(Some(metadata))
}
/// RFC 7591 dynamic client registration.
@@ -359,15 +429,19 @@ pub(crate) async fn register_client(
http: &dyn OAuthHttp,
registration_endpoint: &str,
label: &str,
+ scope: Option<&str>,
) -> Result<String> {
validated_https_url(registration_endpoint, "Registration endpoint")?;
- let body = serde_json::json!({
+ let mut body = serde_json::json!({
"client_name": format!("Prime Agent ({label})"),
"redirect_uris": super::oauth_callback::all_redirect_uris(),
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none",
});
+ if let Some(scope) = scope.filter(|scope| !scope.is_empty()) {
+ body["scope"] = serde_json::Value::String(scope.to_string());
+ }
let request = OAuthHttpRequest {
method: OAuthHttpMethod::Post,
url: registration_endpoint.to_string(),
@@ -636,20 +710,41 @@ mod tests {
}
#[test]
- fn protected_resource_metadata_validation() {
+ fn protected_resource_metadata_audience_policy() {
+ let endpoint = Url::parse("https://mcp.example/mcp").unwrap();
+ // A cross-origin declared resource fails closed.
let error = resource_metadata(
- &serde_json::json!({ "resource": "https://other/mcp" }),
- "https://mcp.example/mcp",
+ &serde_json::json!({
+ "resource": "https://other/mcp",
+ "authorization_servers": ["https://issuer.example"],
+ }),
+ &endpoint,
+ )
+ .unwrap_err()
+ .to_string();
+ assert_eq!(
+ error,
+ "Protected-resource metadata resource does not match the configured endpoint \
+ https://mcp.example/mcp or its origin"
+ );
+ // A same-origin resource with a different path fails closed too.
+ let error = resource_metadata(
+ &serde_json::json!({
+ "resource": "https://mcp.example/other",
+ "authorization_servers": ["https://issuer.example"],
+ }),
+ &endpoint,
)
.unwrap_err()
.to_string();
assert_eq!(
error,
- "Protected-resource metadata resource does not exactly match https://mcp.example/mcp"
+ "Protected-resource metadata resource does not match the configured endpoint \
+ https://mcp.example/mcp or its origin"
);
let error = resource_metadata(
&serde_json::json!({ "resource": "https://mcp.example/mcp" }),
- "https://mcp.example/mcp",
+ &endpoint,
)
.unwrap_err()
.to_string();
@@ -657,6 +752,38 @@ mod tests {
error,
"Protected-resource metadata has no authorization_servers"
);
+ // The Vercel shape: a root endpoint whose declared resource keeps
+ // the trailing slash — component-equal, not string-equal.
+ let root = Url::parse("https://mcp.example").unwrap();
+ let metadata = resource_metadata(
+ &serde_json::json!({
+ "resource": "https://mcp.example/",
+ "authorization_servers": ["https://vercel.example"],
+ "scopes_supported": ["openid"],
+ }),
+ &root,
+ )
+ .unwrap();
+ assert_eq!(metadata.resource, "https://mcp.example/");
+ assert_eq!(
+ metadata.authorization_servers,
+ vec!["https://vercel.example".to_string()]
+ );
+ assert_eq!(metadata.scopes_supported, Some(vec!["openid".to_string()]));
+ assert_eq!(
+ resource_audience_mode(&root, "https://mcp.example/").unwrap(),
+ AudienceMode::Exact
+ );
+ // The Notion/Slack shape: an origin-level declared resource serves
+ // a pathful endpoint.
+ assert_eq!(
+ resource_audience_mode(&endpoint, "https://mcp.example").unwrap(),
+ AudienceMode::Origin
+ );
+ assert_eq!(
+ resource_audience_mode(&root, "https://mcp.example").unwrap(),
+ AudienceMode::Exact
+ );
}
#[test]
diff --git a/crates/pa-daemon/src/mcp_login.rs b/crates/pa-daemon/src/mcp_login.rs
index fb020915b7..eb6e5e7990 100644
--- a/crates/pa-daemon/src/mcp_login.rs
+++ b/crates/pa-daemon/src/mcp_login.rs
@@ -444,6 +444,7 @@ mod tests {
client_id: Some("fixture-client".to_string()),
resource: None,
issuer: None,
+ audience_mode: None,
enterprise_url: None,
};
let value = serde_json::to_value(&credential).unwrap();