From 5c7d2de363aff23ed0a22c23d782f32690eb6a49 Mon Sep 17 00:00:00 2001 From: oxoxDev Date: Wed, 4 Nov 2026 14:37:53 +0530 Subject: [PATCH 1/3] Read the token endpoint auth methods an authorization server lists AuthorizationServerMetadata gains the optional token_endpoint_auth_methods_supported (RFC 8414), omitted from the wire when absent. Contract 1.29. The OpenID document does not fill it in when the OAuth one omits it, matching how grant types are merged. OriginLookup boxes its metadata to stay within clippy's variant-size limit. --- crates/tinymcp-bus/README.md | 5 +++ crates/tinymcp-bus/src/transport/mod_tests.rs | 37 ++++++++++++++++++- crates/tinymcp-bus/src/transport/types.rs | 5 +++ crates/tinymcp-bus/src/version/mod.rs | 4 +- crates/tinymcp-bus/src/version/mod_tests.rs | 2 +- .../tinymcp/src/transport/http/discovery.rs | 6 +-- .../tinymcp/src/transport/http/mod_tests.rs | 19 ++++++++++ crates/tinymcp/src/transport/payload_tests.rs | 2 + 8 files changed, 74 insertions(+), 6 deletions(-) diff --git a/crates/tinymcp-bus/README.md b/crates/tinymcp-bus/README.md index 02b713d3..d5f1c4dd 100644 --- a/crates/tinymcp-bus/README.md +++ b/crates/tinymcp-bus/README.md @@ -90,6 +90,11 @@ so a host can tell a tool that only reads from one that changes something before it calls it. The field is optional and omitted when absent, and `StaticScrubTools` scrubs it like the rest of a tool's metadata. +Contract 1.29 adds the optional `token_endpoint_auth_methods_supported` on +`AuthorizationServerMetadata`, so a client can register as a public client +(`none`) with an authorization server that accepts nothing else. The field is +omitted when absent. + Library consumers bring implementation extension traits into scope for moved DTO methods. Contract-only hosts call the compiled module. See [the relocation specification](../../docs/specs/pure-vocabulary.md) for public diff --git a/crates/tinymcp-bus/src/transport/mod_tests.rs b/crates/tinymcp-bus/src/transport/mod_tests.rs index a16f9bbd..aac938e1 100644 --- a/crates/tinymcp-bus/src/transport/mod_tests.rs +++ b/crates/tinymcp-bus/src/transport/mod_tests.rs @@ -1,4 +1,5 @@ -//! The remote tool's wire form, annotations included. +//! The transport wire forms: remote tool annotations and authorization-server +//! metadata. use serde_json::json; @@ -51,3 +52,37 @@ fn absent_annotations_stay_off_the_wire() -> TestResult { assert_eq!(serde_json::from_value::(wire)?, annotated); Ok(()) } + +#[test] +fn an_authorization_servers_token_endpoint_auth_methods_are_kept() -> TestResult { + let metadata: AuthorizationServerMetadata = serde_json::from_value(json!({ + "issuer": "https://auth.test", + "token_endpoint_auth_methods_supported": ["none"], + }))?; + + assert_eq!( + metadata.token_endpoint_auth_methods_supported, + Some(vec!["none".to_string()]) + ); + let wire = serde_json::to_value(&metadata)?; + assert_eq!( + wire["token_endpoint_auth_methods_supported"], + json!(["none"]) + ); + assert_eq!( + serde_json::from_value::(wire)?, + metadata + ); + Ok(()) +} + +#[test] +fn absent_token_endpoint_auth_methods_stay_off_the_wire() -> TestResult { + let metadata: AuthorizationServerMetadata = + serde_json::from_value(json!({ "issuer": "https://auth.test" }))?; + + assert_eq!(metadata.token_endpoint_auth_methods_supported, None); + let wire = serde_json::to_value(&metadata)?; + assert!(wire.get("token_endpoint_auth_methods_supported").is_none()); + Ok(()) +} diff --git a/crates/tinymcp-bus/src/transport/types.rs b/crates/tinymcp-bus/src/transport/types.rs index a1078070..c9323c95 100644 --- a/crates/tinymcp-bus/src/transport/types.rs +++ b/crates/tinymcp-bus/src/transport/types.rs @@ -427,6 +427,11 @@ pub struct AuthorizationServerMetadata { /// The PKCE code-challenge methods the server supports. #[serde(default)] pub code_challenge_methods_supported: Vec, + /// How clients may authenticate at the token endpoint, for example + /// `client_secret_post` or `none` for a public client. `None` when the + /// server does not say. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub token_endpoint_auth_methods_supported: Option>, } /// A parsed `WWW-Authenticate` challenge from a 401. diff --git a/crates/tinymcp-bus/src/version/mod.rs b/crates/tinymcp-bus/src/version/mod.rs index 200713df..ee7be8e5 100644 --- a/crates/tinymcp-bus/src/version/mod.rs +++ b/crates/tinymcp-bus/src/version/mod.rs @@ -44,7 +44,9 @@ /// `StdioSandboxConfig::enforcement` (`StdioSandboxEnforcement`), letting the /// host choose `Declared` for a backend with partial enforcement; the default /// stays `Enforced`. 1.28 adds the optional `annotations` on `McpRemoteTool`. -pub const CONTRACT_VERSION: (u32, u32) = (1, 28); +/// 1.29 adds the optional `token_endpoint_auth_methods_supported` on +/// `AuthorizationServerMetadata`. +pub const CONTRACT_VERSION: (u32, u32) = (1, 29); /// Returns whether a host holding [`CONTRACT_VERSION`] can bind to a module /// reporting `module`. diff --git a/crates/tinymcp-bus/src/version/mod_tests.rs b/crates/tinymcp-bus/src/version/mod_tests.rs index 33c85162..80f4c1f2 100644 --- a/crates/tinymcp-bus/src/version/mod_tests.rs +++ b/crates/tinymcp-bus/src/version/mod_tests.rs @@ -4,7 +4,7 @@ use super::{CONTRACT_VERSION, binds, is_compatible}; #[test] fn the_shipped_contract_version_is_pinned() { - assert_eq!(CONTRACT_VERSION, (1, 28)); + assert_eq!(CONTRACT_VERSION, (1, 29)); } #[test] diff --git a/crates/tinymcp/src/transport/http/discovery.rs b/crates/tinymcp/src/transport/http/discovery.rs index 25de05b0..27c00394 100644 --- a/crates/tinymcp/src/transport/http/discovery.rs +++ b/crates/tinymcp/src/transport/http/discovery.rs @@ -78,7 +78,7 @@ enum Fetched { /// What the origin's own authorization-server metadata lookup found. #[derive(Debug)] enum OriginLookup { - Found(String, AuthorizationServerMetadata), + Found(String, Box), Missing, Transient, } @@ -160,7 +160,7 @@ impl McpHttpClient { WellKnownOutcome::Found(WellKnownAuthorization { metadata_url, protected_resource_metadata, - authorization_servers: vec![metadata], + authorization_servers: vec![*metadata], }) } OriginLookup::Transient => WellKnownOutcome::Transient, @@ -225,7 +225,7 @@ impl McpHttpClient { } match found { - Some((url, metadata)) => OriginLookup::Found(url, metadata), + Some((url, metadata)) => OriginLookup::Found(url, Box::new(metadata)), None if transient => OriginLookup::Transient, None => OriginLookup::Missing, } diff --git a/crates/tinymcp/src/transport/http/mod_tests.rs b/crates/tinymcp/src/transport/http/mod_tests.rs index 58cd8201..d9696c76 100644 --- a/crates/tinymcp/src/transport/http/mod_tests.rs +++ b/crates/tinymcp/src/transport/http/mod_tests.rs @@ -70,6 +70,7 @@ fn metadata_issuer_matching_preserves_trailing_slash_identity() { response_types_supported: Vec::new(), grant_types_supported: Vec::new(), code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, }; assert!(!metadata_matches_issuer( @@ -91,6 +92,7 @@ fn metadata_issued_by(issuer: &str) -> AuthorizationServerMetadata { response_types_supported: Vec::new(), grant_types_supported: Vec::new(), code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, } } @@ -129,6 +131,7 @@ fn mismatched_metadata_issuers_are_not_merged() { response_types_supported: Vec::new(), grant_types_supported: Vec::new(), code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, }; let secondary = AuthorizationServerMetadata { issuer: "https://example.com/tenant/".into(), @@ -138,6 +141,7 @@ fn mismatched_metadata_issuers_are_not_merged() { response_types_supported: Vec::new(), grant_types_supported: Vec::new(), code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, }; assert_eq!( @@ -156,6 +160,7 @@ fn metadata_merge_preserves_rfc_default_for_omitted_grant_types() { response_types_supported: Vec::new(), grant_types_supported: Vec::new(), code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, }; let secondary = AuthorizationServerMetadata { issuer: "https://example.com".into(), @@ -165,6 +170,7 @@ fn metadata_merge_preserves_rfc_default_for_omitted_grant_types() { response_types_supported: Vec::new(), grant_types_supported: vec!["client_credentials".into()], code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, }; let merged = fill_missing_metadata(primary, secondary); @@ -172,6 +178,19 @@ fn metadata_merge_preserves_rfc_default_for_omitted_grant_types() { assert_eq!(merged.grant_types_supported.len(), 0); } +#[test] +fn metadata_merge_preserves_omitted_token_endpoint_auth_methods() { + let primary = metadata_issued_by("https://example.com"); + let secondary = AuthorizationServerMetadata { + token_endpoint_auth_methods_supported: Some(vec!["client_secret_basic".into()]), + ..metadata_issued_by("https://example.com") + }; + + let merged = fill_missing_metadata(primary, secondary); + + assert_eq!(merged.token_endpoint_auth_methods_supported, None); +} + // --------------------------------------------------------------------------- // Test server // --------------------------------------------------------------------------- diff --git a/crates/tinymcp/src/transport/payload_tests.rs b/crates/tinymcp/src/transport/payload_tests.rs index 5569d98b..a3742e47 100644 --- a/crates/tinymcp/src/transport/payload_tests.rs +++ b/crates/tinymcp/src/transport/payload_tests.rs @@ -432,6 +432,7 @@ fn an_authorization_context_round_trips_with_several_servers() { response_types_supported: vec!["code".into()], grant_types_supported: vec!["authorization_code".into()], code_challenge_methods_supported: vec!["S256".into()], + token_endpoint_auth_methods_supported: None, }, AuthorizationServerMetadata { issuer: "https://b.test".into(), @@ -441,6 +442,7 @@ fn an_authorization_context_round_trips_with_several_servers() { response_types_supported: Vec::new(), grant_types_supported: Vec::new(), code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: None, }, ], }; From eb91b766608788c316ad18779fc6de0826b09412 Mon Sep 17 00:00:00 2001 From: oxoxDev Date: Wed, 4 Nov 2026 14:37:53 +0530 Subject: [PATCH 2/3] Register as a public client when the server accepts only none Dynamic registration asks for client_secret_post when the server lists it or lists nothing, and for none when it lists only that. A public client keeps no secret, so the code exchange and refresh send none. A server accepting neither is detected as wanting a static token and refused by begin before registering. Closes #163 --- README.md | 7 + crates/tinymcp/src/registry/oauth/flow.rs | 109 +++++- .../registry/oauth/mod_public_client_tests.rs | 312 ++++++++++++++++++ .../tinymcp/src/registry/oauth/mod_tests.rs | 7 + 4 files changed, 417 insertions(+), 18 deletions(-) create mode 100644 crates/tinymcp/src/registry/oauth/mod_public_client_tests.rs diff --git a/README.md b/README.md index 0a6e15cb..69149d9e 100644 --- a/README.md +++ b/README.md @@ -310,6 +310,13 @@ check. `registry::OAuthBundle` is the stored refresh bundle's shape. the authorization server shows on its consent screen; it defaults to `DEFAULT_CLIENT_NAME` (`TinyMCP`). +Dynamic registration asks for a confidential client (`client_secret_post`) +when the authorization server's `token_endpoint_auth_methods_supported` lists +it or lists nothing, and for a public client (`none`) when it lists only that. +A public client stores no secret, and neither the code exchange nor a refresh +sends one. A server that accepts neither is not offered a sign-in: `detect` +reports a static token and `begin` refuses before registering. + OAuth discovery starts from the 401. When its challenge names `resource_metadata`, that protected-resource metadata is followed. When a Bearer challenge names none, the server's origin is checked in this order: diff --git a/crates/tinymcp/src/registry/oauth/flow.rs b/crates/tinymcp/src/registry/oauth/flow.rs index 44340e87..c8582314 100644 --- a/crates/tinymcp/src/registry/oauth/flow.rs +++ b/crates/tinymcp/src/registry/oauth/flow.rs @@ -232,18 +232,13 @@ impl OAuthFlow { // Chosen by capability rather than by position: the first advertised // authorization server may be incomplete while a later one is usable. - let metadata = context + let (metadata, auth_method) = context .authorization_server_metadata .iter() .find(|metadata| can_drive_sign_in(metadata)) + .and_then(|metadata| client_auth_method(metadata).map(|method| (metadata, method))) .ok_or_else(|| Error::AuthDiscovery { - detail: if context.authorization_server_metadata.is_empty() { - "the server advertises no authorization server".to_string() - } else { - "no authorization server offers an authorize endpoint, a token endpoint, and \ - dynamic client registration together" - .to_string() - }, + detail: no_drivable_server_reason(&context.authorization_server_metadata), challenge: Box::new(context.challenge.clone()), })?; @@ -270,6 +265,7 @@ impl OAuthFlow { registration_http.as_ref().unwrap_or(&self.http), ®istration_endpoint, redirect_uri, + auth_method, ) .await?; @@ -469,22 +465,28 @@ impl OAuthFlow { /// Registers a client dynamically, per RFC 7591. /// - /// A confidential client is requested, and the secret is kept when one is - /// issued: some servers issue one regardless of what was asked for, and the - /// token exchange then fails without it. + /// A confidential client keeps the secret when one is issued: some servers + /// issue one regardless of what was asked for, and the token exchange then + /// fails without it. A public client keeps none, so neither the exchange + /// nor a refresh sends one. async fn register_client( &self, http: &reqwest::Client, registration_endpoint: &str, redirect_uri: &str, + auth_method: ClientAuthMethod, ) -> Result<(String, Option)> { let body = json!({ "client_name": self.client_name, "redirect_uris": [redirect_uri], "grant_types": ["authorization_code", "refresh_token"], "response_types": ["code"], - "token_endpoint_auth_method": "client_secret_post", + "token_endpoint_auth_method": auth_method.as_str(), }); + tracing::debug!( + auth_method = auth_method.as_str(), + "registering an oauth client" + ); let response = http .post(registration_endpoint) @@ -519,28 +521,99 @@ impl OAuthFlow { .ok_or_else(|| Error::malformed("client registration returned no client_id"))? .to_string(); - let client_secret = registered - .get("client_secret") - .and_then(Value::as_str) - .map(ToString::to_string); + let client_secret = match auth_method { + ClientAuthMethod::SecretPost => registered + .get("client_secret") + .and_then(Value::as_str) + .map(ToString::to_string), + ClientAuthMethod::None => None, + }; Ok((client_id, client_secret)) } } +/// How a registered client authenticates at the token endpoint. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ClientAuthMethod { + /// A confidential client sending its secret in the form body. + SecretPost, + /// A public client sending no secret. + None, +} + +impl ClientAuthMethod { + /// The RFC 7591 `token_endpoint_auth_method` value. + fn as_str(self) -> &'static str { + match self { + Self::SecretPost => "client_secret_post", + Self::None => "none", + } + } +} + +/// The method to register with: `client_secret_post` when the server lists it +/// or lists nothing, `none` when it lists that instead, and `None` when it +/// accepts neither. +fn client_auth_method( + metadata: &tinymcp_bus::AuthorizationServerMetadata, +) -> Option { + let Some(methods) = metadata + .token_endpoint_auth_methods_supported + .as_deref() + .filter(|methods| !methods.is_empty()) + else { + return Some(ClientAuthMethod::SecretPost); + }; + let lists = |method: ClientAuthMethod| methods.iter().any(|listed| listed == method.as_str()); + [ClientAuthMethod::SecretPost, ClientAuthMethod::None] + .into_iter() + .find(|method| lists(*method)) +} + +/// Why no advertised authorization server can drive a sign-in. +pub(super) fn no_drivable_server_reason( + metadata: &[tinymcp_bus::AuthorizationServerMetadata], +) -> String { + if metadata.is_empty() { + return "the server advertises no authorization server".to_string(); + } + let refused_only_for_auth_method = metadata.iter().any(|server| { + has_sign_in_endpoints(server) + && supports_authorization_code(server) + && client_auth_method(server).is_none() + }); + if refused_only_for_auth_method { + "no authorization server accepts client_secret_post or none at its token endpoint" + .to_string() + } else { + "no authorization server offers an authorize endpoint, a token endpoint, and dynamic \ + client registration together" + .to_string() + } +} + /// Whether this flow can run a sign-in against an authorization server: it /// advertises an authorize endpoint, a token endpoint and dynamic client -/// registration, and accepts an authorization code. +/// registration, accepts an authorization code, and accepts a client that +/// authenticates with `client_secret_post` or `none`. /// /// [`OAuthFlow::detect`] and [`OAuthFlow::begin`] both ask this one question, /// so detection never offers a sign-in that `begin` would then refuse — a /// server with no registration endpoint (Slack's, for one) reads as wanting a /// static token, not as a Sign in button that leads nowhere. fn can_drive_sign_in(metadata: &tinymcp_bus::AuthorizationServerMetadata) -> bool { + has_sign_in_endpoints(metadata) + && supports_authorization_code(metadata) + && client_auth_method(metadata).is_some() +} + +/// Whether an authorization server advertises the authorize, token and +/// registration endpoints the flow posts to. +fn has_sign_in_endpoints(metadata: &tinymcp_bus::AuthorizationServerMetadata) -> bool { metadata.authorization_endpoint.is_some() && metadata.token_endpoint.is_some() && metadata.registration_endpoint.is_some() - && supports_authorization_code(metadata) } /// Whether an authorization server will accept an authorization code. diff --git a/crates/tinymcp/src/registry/oauth/mod_public_client_tests.rs b/crates/tinymcp/src/registry/oauth/mod_public_client_tests.rs new file mode 100644 index 00000000..b1ae7b7c --- /dev/null +++ b/crates/tinymcp/src/registry/oauth/mod_public_client_tests.rs @@ -0,0 +1,312 @@ +//! Choosing how a client authenticates at the token endpoint: a confidential +//! client with `client_secret_post`, or a public one with `none` when that is +//! all the authorization server accepts. + +use super::*; +use crate::registry::OAuthBundle; + +/// What the authorization server advertised and was sent. +#[derive(Debug, Default)] +struct Methods { + advertised: Option, + registrations: parking_lot::Mutex>, + token_forms: parking_lot::Mutex>>, +} + +impl Methods { + fn last_registration(&self) -> Value { + self.registrations + .lock() + .last() + .cloned() + .expect("a registration") + } + + fn token_form(&self, index: usize) -> BTreeMap { + self.token_forms.lock()[index].clone() + } +} + +/// Accepts a registration the way the advertised list says it would: a +/// method a non-empty list leaves out is refused with +/// `invalid_client_metadata`, as `OnArrival` refuses `client_secret_post`. +async fn register(State(state): State>, Json(body): Json) -> impl IntoResponse { + state.registrations.lock().push(body.clone()); + let requested = body["token_endpoint_auth_method"] + .as_str() + .unwrap_or_default() + .to_string(); + let accepted = state.advertised.as_ref().is_none_or(|advertised| { + advertised.as_array().is_some_and(|methods| { + methods.is_empty() || methods.iter().any(|method| method == &json!(requested)) + }) + }); + if !accepted { + return ( + AxumStatus::BAD_REQUEST, + Json(json!({ + "error": "invalid_client_metadata", + "error_description": "Only public clients (token_endpoint_auth_method \"none\") are supported.", + })), + ) + .into_response(); + } + Json(json!({ + "client_id": "client-1", + "client_secret": "client-secret-1", + "token_endpoint_auth_method": requested, + })) + .into_response() +} + +/// Records each token request and mints a token that is already due for a +/// refresh, so one sign-in exercises both the exchange and the refresh. +async fn token( + State(state): State>, + Form(form): Form>, +) -> impl IntoResponse { + state.token_forms.lock().push(form); + Json(json!({ + "access_token": "at-1", + "refresh_token": "rt-1", + "token_type": "Bearer", + "expires_in": 0, + })) +} + +/// An MCP endpoint demanding OAuth from an authorization server on the same +/// origin that advertises `advertised` as its token endpoint auth methods, or +/// nothing when it is `None`. +async fn authority_advertising(advertised: Option) -> (String, Arc) { + let state = Arc::new(Methods { + advertised, + ..Methods::default() + }); + let origin: Arc> = Arc::new(parking_lot::Mutex::new(String::new())); + + let app = Router::new() + .route( + "/.well-known/oauth-protected-resource", + get({ + let origin = Arc::clone(&origin); + move || { + let origin = origin.lock().clone(); + async move { + Json(json!({ + "resource": format!("{origin}/mcp"), + "authorization_servers": [origin], + })) + } + } + }), + ) + .route( + "/.well-known/oauth-authorization-server", + get({ + let origin = Arc::clone(&origin); + let state = Arc::clone(&state); + move || { + let origin = origin.lock().clone(); + let state = Arc::clone(&state); + async move { + let mut metadata = json!({ + "issuer": origin, + "authorization_endpoint": format!("{origin}/authorize"), + "token_endpoint": format!("{origin}/token"), + "registration_endpoint": format!("{origin}/register"), + "grant_types_supported": ["authorization_code", "refresh_token"], + }); + if let Some(advertised) = &state.advertised { + metadata["token_endpoint_auth_methods_supported"] = advertised.clone(); + } + Json(metadata) + } + } + }), + ) + .route("/register", post(register)) + .route("/token", post(token)) + .fallback({ + let origin = Arc::clone(&origin); + move || { + let origin = origin.lock().clone(); + async move { + let challenge = format!( + "Bearer resource_metadata=\"{origin}/.well-known/oauth-protected-resource\"" + ); + ( + AxumStatus::UNAUTHORIZED, + [("WWW-Authenticate", challenge)], + "unauthorized", + ) + .into_response() + } + } + }) + .with_state(Arc::clone(&state)); + + let base = serve(app).await; + *origin.lock() = base.clone(); + (format!("{base}/mcp"), state) +} + +/// Signs in and refreshes once against `advertised`, returning what the +/// authorization server saw and the bundle left in the store. +async fn sign_in_and_refresh(advertised: Option) -> (Arc, OAuthBundle) { + let (endpoint, state) = authority_advertising(advertised).await; + let store = store_with_remote(&endpoint); + let flow = flow(); + + let url = flow + .begin(&store, "srv-1", "http://127.0.0.1:7788/callback") + .await + .expect("begin"); + let returned_state = authorize_param(&url, "state").unwrap(); + flow.complete(&store, &returned_state, "the-code") + .await + .expect("complete"); + assert!(flow.refresh(&store, "srv-1").await.expect("refresh")); + + let env = store.load_env_values("srv-1").unwrap(); + let bundle = serde_json::from_str(&env[OAUTH_BUNDLE_KEY]).unwrap(); + (state, bundle) +} + +#[tokio::test] +async fn a_server_accepting_only_public_clients_gets_one_that_sends_no_secret() { + let (state, bundle) = sign_in_and_refresh(Some(json!(["none"]))).await; + + assert_eq!( + state.last_registration()["token_endpoint_auth_method"], + json!("none") + ); + assert_eq!(bundle.client_id, "client-1"); + assert_eq!(bundle.client_secret, None); + + let exchange = state.token_form(0); + assert_eq!( + exchange.get("grant_type").map(String::as_str), + Some("authorization_code") + ); + assert_eq!( + exchange.get("client_id").map(String::as_str), + Some("client-1") + ); + assert!(!exchange.contains_key("client_secret"), "{exchange:?}"); + + let refresh = state.token_form(1); + assert_eq!( + refresh.get("grant_type").map(String::as_str), + Some("refresh_token") + ); + assert_eq!( + refresh.get("client_id").map(String::as_str), + Some("client-1") + ); + assert!(!refresh.contains_key("client_secret"), "{refresh:?}"); +} + +#[tokio::test] +async fn a_server_accepting_both_gets_a_confidential_client() { + let (state, bundle) = sign_in_and_refresh(Some(json!(["client_secret_post", "none"]))).await; + + assert_eq!( + state.last_registration()["token_endpoint_auth_method"], + json!("client_secret_post") + ); + assert_eq!(bundle.client_secret.as_deref(), Some("client-secret-1")); + for index in 0..2 { + assert_eq!( + state + .token_form(index) + .get("client_secret") + .map(String::as_str), + Some("client-secret-1") + ); + } +} + +#[tokio::test] +async fn a_server_that_lists_no_methods_gets_a_confidential_client() { + let (state, bundle) = sign_in_and_refresh(None).await; + + assert_eq!( + state.last_registration()["token_endpoint_auth_method"], + json!("client_secret_post") + ); + assert_eq!(bundle.client_secret.as_deref(), Some("client-secret-1")); +} + +#[tokio::test] +async fn an_empty_method_list_is_read_as_listing_none() { + let (state, _bundle) = sign_in_and_refresh(Some(json!([]))).await; + + assert_eq!( + state.last_registration()["token_endpoint_auth_method"], + json!("client_secret_post") + ); +} + +#[tokio::test] +async fn a_server_accepting_neither_method_is_refused_before_registering() { + let (endpoint, state) = + authority_advertising(Some(json!(["client_secret_basic", "private_key_jwt"]))).await; + let store = store_with_remote(&endpoint); + + let error = flow() + .begin(&store, "srv-1", "http://127.0.0.1:7788/callback") + .await + .expect_err("no usable auth method"); + + match error { + Error::AuthDiscovery { detail, .. } => assert_eq!( + detail, + "no authorization server accepts client_secret_post or none at its token endpoint" + ), + other => panic!("expected an auth discovery error, got {other:?}"), + } + assert!(state.registrations.lock().is_empty()); +} + +#[tokio::test] +async fn a_server_accepting_neither_method_is_detected_as_wanting_a_static_token() { + let (endpoint, _state) = authority_advertising(Some(json!(["client_secret_basic"]))).await; + let store = store_with_remote(&endpoint); + + let detection = flow().detect(&store, "srv-1").await.unwrap(); + + assert_eq!(detection.kind, AuthKind::Token); +} + +#[tokio::test] +async fn a_server_accepting_only_public_clients_is_detected_as_wanting_sign_in() { + let (endpoint, _state) = authority_advertising(Some(json!(["none"]))).await; + let store = store_with_remote(&endpoint); + + let detection = flow().detect(&store, "srv-1").await.unwrap(); + + assert_eq!(detection.kind, AuthKind::Oauth); +} + +#[test] +fn an_incomplete_server_is_not_blamed_on_its_auth_methods() { + let incomplete = tinymcp_bus::AuthorizationServerMetadata { + issuer: "https://auth.test".into(), + authorization_endpoint: None, + token_endpoint: None, + registration_endpoint: None, + response_types_supported: Vec::new(), + grant_types_supported: Vec::new(), + code_challenge_methods_supported: Vec::new(), + token_endpoint_auth_methods_supported: Some(vec!["client_secret_basic".into()]), + }; + + assert!( + crate::registry::oauth::flow::no_drivable_server_reason(&[incomplete]) + .starts_with("no authorization server offers an authorize endpoint") + ); + assert_eq!( + crate::registry::oauth::flow::no_drivable_server_reason(&[]), + "the server advertises no authorization server" + ); +} diff --git a/crates/tinymcp/src/registry/oauth/mod_tests.rs b/crates/tinymcp/src/registry/oauth/mod_tests.rs index 666a8a04..2b5133c6 100644 --- a/crates/tinymcp/src/registry/oauth/mod_tests.rs +++ b/crates/tinymcp/src/registry/oauth/mod_tests.rs @@ -1524,3 +1524,10 @@ mod host_store; #[path = "mod_refresh_tests.rs"] mod flow_refresh; + +// --------------------------------------------------------------------------- +// Confidential and public clients +// --------------------------------------------------------------------------- + +#[path = "mod_public_client_tests.rs"] +mod public_client; From 8ace89cd8f46952ab96435732fed16c983ce39e1 Mon Sep 17 00:00:00 2001 From: M3gA-Mind Date: Wed, 11 Nov 2026 15:10:02 +0530 Subject: [PATCH 3/3] Say when OAuth registration picks a public client The README said a public client (none) is requested only when the server lists nothing else. client_auth_method also picks none when it is listed beside methods tinymcp does not use, such as client_secret_basic. Describe that case, as the CodeRabbit review on this PR pointed out. --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 69149d9e..e10b2610 100644 --- a/README.md +++ b/README.md @@ -312,7 +312,8 @@ the authorization server shows on its consent screen; it defaults to Dynamic registration asks for a confidential client (`client_secret_post`) when the authorization server's `token_endpoint_auth_methods_supported` lists -it or lists nothing, and for a public client (`none`) when it lists only that. +it or lists nothing, and for a public client (`none`) when it lists `none` but +not `client_secret_post`, whatever else it lists. A public client stores no secret, and neither the code exchange nor a refresh sends one. A server that accepts neither is not offered a sign-in: `detect` reports a static token and `begin` refuses before registering.