diff --git a/crates/tinymcp-bus/README.md b/crates/tinymcp-bus/README.md index 02b713d3..0c751dba 100644 --- a/crates/tinymcp-bus/README.md +++ b/crates/tinymcp-bus/README.md @@ -90,6 +90,14 @@ 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.30 adds `McpClientConfig::local_oauth_origins` and turns the OAuth +endpoint guard on by default. The authorization, registration and token +endpoints a server advertises are requested from the host, so they must now be +`https` and resolve to public addresses, refusing loopback, private, link-local +and metadata addresses. The exception is a server whose URL has an origin the +operator listed in `local_oauth_origins`, such as a loopback development server; +each exemption is logged. Token refreshes on connect go through the same guard. + 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/config/types.rs b/crates/tinymcp-bus/src/config/types.rs index 629f3355..89ec8064 100644 --- a/crates/tinymcp-bus/src/config/types.rs +++ b/crates/tinymcp-bus/src/config/types.rs @@ -58,6 +58,17 @@ pub struct McpClientConfig { /// one) is refused rather than started unconfined. #[serde(default)] pub stdio_sandbox: Option, + /// Origins (`scheme://host[:port]`) of installed servers the operator + /// declares local, such as `http://localhost:8080`. + /// + /// The OAuth endpoints a server advertises (authorization, registration, + /// token) are requested from the host, so by default they must be `https` + /// and resolve to public addresses. A server whose URL has one of these + /// origins may use loopback, private or plain-`http` endpoints instead; + /// each use is logged. Empty by default: every server is guarded. Added in + /// contract 1.30. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub local_oauth_origins: Vec, } /// The jail a host grants stdio MCP servers. @@ -127,6 +138,7 @@ impl Default for McpClientConfig { registry_auth: McpRegistryAuthConfig::default(), proxy: None, stdio_sandbox: None, + local_oauth_origins: Vec::new(), } } } diff --git a/crates/tinymcp-bus/src/version/mod.rs b/crates/tinymcp-bus/src/version/mod.rs index 200713df..372aba4d 100644 --- a/crates/tinymcp-bus/src/version/mod.rs +++ b/crates/tinymcp-bus/src/version/mod.rs @@ -44,7 +44,10 @@ /// `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.30 adds `McpClientConfig::local_oauth_origins` and turns the OAuth +/// endpoint guard on by default: endpoints a server advertises must be `https` +/// and public unless the operator declared that server local. +pub const CONTRACT_VERSION: (u32, u32) = (1, 30); /// 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..44d5d1bc 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, 30)); } #[test] diff --git a/crates/tinymcp/src/registry/connections/types.rs b/crates/tinymcp/src/registry/connections/types.rs index a40e0867..d1d0f8cf 100644 --- a/crates/tinymcp/src/registry/connections/types.rs +++ b/crates/tinymcp/src/registry/connections/types.rs @@ -11,7 +11,7 @@ use super::dial::{build_http_auth, credential_safe_dial_url, resolve_final_url}; use super::status::{ConnectFailure, classify}; use crate::error::{Error, Result}; use crate::registry::Store; -use crate::registry::oauth::{OAuthFlow, refresh_if_expired}; +use crate::registry::oauth::OAuthFlow; use crate::transport::http::McpHttpClient; use crate::transport::stdio::McpStdioClient; use crate::transport::stdio::jailed::StdioLaunchers; @@ -386,7 +386,9 @@ impl Connections { // Refresh before dialling so a session never opens with a stale token. // A refresh that fails is not fatal: the existing token may still work, // and if it does not, the 401 tells the user to sign in again. - if let Err(error) = refresh_if_expired(store, oauth.http(), &server.server_id).await { + // Through the flow, not the free `refresh_if_expired`: the flow re-checks + // the stored token endpoint against the guard before posting to it. + if let Err(error) = oauth.refresh(store, &server.server_id).await { tracing::warn!( server_id = %server.server_id, "could not refresh the access token; dialling with the existing one: {error}" diff --git a/crates/tinymcp/src/registry/oauth/endpoint_guard.rs b/crates/tinymcp/src/registry/oauth/endpoint_guard.rs index 2709961e..cd253711 100644 --- a/crates/tinymcp/src/registry/oauth/endpoint_guard.rs +++ b/crates/tinymcp/src/registry/oauth/endpoint_guard.rs @@ -4,10 +4,13 @@ //! being signed in to, and the flow then POSTs to them **from the host**. An //! unchecked endpoint is a server-side request-forgery primitive: a hostile //! server can aim the flow at an internal service or the cloud metadata -//! address. A host serving untrusted servers turns this guard on with -//! [`OAuthFlow::require_public_endpoints`](super::OAuthFlow::require_public_endpoints). -//! It is off by default because a desktop host legitimately signs in to -//! loopback development servers. +//! address. [`McpRegistry`](crate::registry::McpRegistry), which every module +//! host goes through, turns this guard on with +//! [`OAuthFlow::require_public_endpoints`](super::OAuthFlow::require_public_endpoints) +//! and exempts only the servers the operator declared local +//! (`McpClientConfig::local_oauth_origins`), so a loopback development server +//! still signs in when its owner says so. A bare `OAuthFlow` stays unguarded +//! for library callers that check endpoints themselves. use std::net::{IpAddr, SocketAddr, ToSocketAddrs}; use std::time::Duration; diff --git a/crates/tinymcp/src/registry/oauth/flow.rs b/crates/tinymcp/src/registry/oauth/flow.rs index 44340e87..bcf1dff6 100644 --- a/crates/tinymcp/src/registry/oauth/flow.rs +++ b/crates/tinymcp/src/registry/oauth/flow.rs @@ -47,6 +47,9 @@ pub struct OAuthFlow { proxy: Option, pending: Arc, public_endpoints_only: bool, + /// Origins (`scheme://host:port`) of servers the operator declared local, + /// exempt from [`Self::require_public_endpoints`]. + local_origins: Vec, client_name: String, } @@ -77,6 +80,7 @@ impl OAuthFlow { proxy, pending: Arc::new(MemoryPendingStore::new()), public_endpoints_only: false, + local_origins: Vec::new(), client_name: DEFAULT_CLIENT_NAME.to_string(), }) } @@ -132,6 +136,46 @@ impl OAuthFlow { self } + /// Exempts servers at `origins` (`scheme://host[:port]`, such as + /// `http://localhost:8080`) from [`Self::require_public_endpoints`]. + /// + /// For servers an operator configured as local, such as a development + /// server on loopback. Every exemption used is logged. An entry that is not + /// a URL with a host is ignored with a warning, never treated as matching. + #[must_use] + pub fn with_local_origins(mut self, origins: I) -> Self + where + I: IntoIterator, + S: AsRef, + { + for raw in origins { + if let Some(origin) = origin_of(raw.as_ref()) { + self.local_origins.push(origin); + } else { + tracing::warn!("ignoring a local oauth origin that is not a url with a host"); + } + } + self + } + + /// Whether the endpoint guard applies to the server at `server_url`: it is + /// on, and the operator has not declared that server local. + fn guards(&self, server_url: &str) -> bool { + if !self.public_endpoints_only { + return false; + } + match origin_of(server_url) { + Some(origin) if self.local_origins.contains(&origin) => { + tracing::warn!( + origin, + "oauth endpoint guard skipped for a server the operator declared local" + ); + false + } + _ => true, + } + } + /// The HTTP client this flow uses, for the refresh path. #[must_use] pub fn http(&self) -> &reqwest::Client { @@ -260,6 +304,7 @@ impl OAuthFlow { let registration_http = self .registration_client( + &url, &authorization_endpoint, &token_endpoint, ®istration_endpoint, @@ -349,7 +394,13 @@ impl OAuthFlow { form.push(("client_secret", secret)); } - let guarded_http = self.token_client(&pending.token_endpoint).await?; + let server_url = store + .remote_url(&pending.server_id) + .await? + .unwrap_or_default(); + let guarded_http = self + .token_client(&server_url, &pending.token_endpoint) + .await?; let http = guarded_http.as_ref().unwrap_or(&self.http); let body = post_form(http, &pending.token_endpoint, &form).await?; let tokens = TokenResponse::parse(&body)?; @@ -392,7 +443,10 @@ impl OAuthFlow { let Some(bundle) = due_refresh(store, server_id).await? else { return Ok(false); }; - let guarded_http = self.token_client(&bundle.token_endpoint).await?; + let server_url = store.remote_url(server_id).await?.unwrap_or_default(); + let guarded_http = self + .token_client(&server_url, &bundle.token_endpoint) + .await?; let http = guarded_http.as_ref().unwrap_or(&self.http); exchange_refresh(store, http, server_id, &bundle).await } @@ -427,11 +481,12 @@ impl OAuthFlow { pub(super) async fn registration_client( &self, + server_url: &str, authorization_endpoint: &str, token_endpoint: &str, registration_endpoint: &str, ) -> Result> { - if self.public_endpoints_only { + if self.guards(server_url) { guard_endpoint(authorization_endpoint, "authorization").await?; guard_endpoint(token_endpoint, "token").await?; Ok(Some( @@ -450,7 +505,7 @@ impl OAuthFlow { let mut builder = McpHttpClient::builder(url.clone()) .timeout_secs(PROBE_TIMEOUT_SECS) .proxy(self.proxy.clone()); - if self.public_endpoints_only { + if self.guards(&url) { builder = builder.pinned_public_endpoint(guard_endpoint(&url, "MCP").await?); } builder.build() @@ -458,9 +513,10 @@ impl OAuthFlow { pub(super) async fn token_client( &self, + server_url: &str, token_endpoint: &str, ) -> Result> { - if self.public_endpoints_only { + if self.guards(server_url) { Ok(Some(guarded_client(token_endpoint, "token").await?)) } else { Ok(None) @@ -572,6 +628,19 @@ fn generate_pkce() -> (String, String) { (verifier, challenge) } +/// `raw`'s origin as `scheme://host:port`, with the host lowercased and the +/// port made explicit, so `http://LocalHost` and `http://localhost:80` match. +pub(super) fn origin_of(raw: &str) -> Option { + let url = reqwest::Url::parse(raw.trim()).ok()?; + let host = url.host_str().filter(|host| !host.is_empty())?; + let port = url.port_or_known_default()?; + Some(format!( + "{}://{}:{port}", + url.scheme(), + host.to_ascii_lowercase() + )) +} + /// Drops authorizations the user never finished. /// /// Each holds a client secret, so leaving them is a slow leak of credentials diff --git a/crates/tinymcp/src/registry/oauth/mod_host_store_tests.rs b/crates/tinymcp/src/registry/oauth/mod_host_store_tests.rs index 994d389a..ec04ee5c 100644 --- a/crates/tinymcp/src/registry/oauth/mod_host_store_tests.rs +++ b/crates/tinymcp/src/registry/oauth/mod_host_store_tests.rs @@ -7,6 +7,9 @@ use crate::registry::OAuthCredentialStore; use std::io::{Read, Write}; use std::net::TcpListener; +/// The server a guard decision is made for: a remote, not one declared local. +const SERVER: &str = "https://mcp.vendor.example/mcp"; + /// A host's secret store: credentials in a map, keyed by whatever server id /// the host chooses — here a tenant-qualified one. #[derive(Debug, Default)] @@ -314,7 +317,7 @@ async fn a_guarded_flow_refuses_an_internal_authorization_server() { ), ] { let error = flow - .registration_client(&authorize, &token, ®ister) + .registration_client(SERVER, &authorize, &token, ®ister) .await .expect_err(what); assert!( @@ -326,6 +329,7 @@ async fn a_guarded_flow_refuses_an_internal_authorization_server() { } assert!( flow.registration_client( + SERVER, &format!("{public}/authorize"), &format!("{public}/token"), &format!("{public}/register"), @@ -368,6 +372,7 @@ async fn public_endpoint_clients_validate_and_pin_registration_and_token_hosts() let flow = flow().require_public_endpoints(); let registration = flow .registration_client( + SERVER, "https://8.8.8.8/authorize", "https://1.1.1.1/token", "https://9.9.9.9/register", @@ -376,7 +381,7 @@ async fn public_endpoint_clients_validate_and_pin_registration_and_token_hosts() .expect("validate public endpoints"); assert!(registration.is_some()); assert!( - flow.token_client("https://8.8.8.8/token") + flow.token_client(SERVER, "https://8.8.8.8/token") .await .expect("build token client") .is_some() @@ -387,13 +392,13 @@ async fn public_endpoint_clients_validate_and_pin_registration_and_token_hosts() async fn desktop_flow_keeps_the_default_clients() { let flow = flow(); assert!( - flow.registration_client("not a url", "not a url", "not a url") + flow.registration_client(SERVER, "not a url", "not a url", "not a url") .await .expect("desktop flow skips public endpoint checks") .is_none() ); assert!( - flow.token_client("not a url") + flow.token_client(SERVER, "not a url") .await .expect("desktop flow skips public endpoint checks") .is_none() @@ -583,3 +588,71 @@ async fn an_expired_authorization_in_a_lazy_store_is_refused() { ); assert_eq!(authority.exchanges.load(Ordering::SeqCst), 0); } + +#[tokio::test] +async fn internal_endpoints_are_refused_for_a_remote_and_allowed_for_a_declared_local_server() { + let local_server = "http://127.0.0.1:8080/mcp"; + let flow = flow() + .require_public_endpoints() + .with_local_origins(["http://127.0.0.1:8080", "not a url"]); + for endpoint in [ + "https://127.0.0.1/token", + "https://169.254.169.254/token", + "http://8.8.8.8/token", + ] { + let refused = flow + .token_client(SERVER, endpoint) + .await + .expect_err(endpoint); + assert!( + refused.to_string().contains("token endpoint refused"), + "{endpoint}: {refused}" + ); + assert!( + flow.token_client(local_server, endpoint) + .await + .expect(endpoint) + .is_none(), + "{endpoint}: a declared-local server keeps the unguarded client" + ); + } + // The registration path makes the same decision per server. + assert!( + flow.registration_client( + SERVER, + "https://169.254.169.254/authorize", + "https://169.254.169.254/token", + "https://169.254.169.254/register", + ) + .await + .is_err() + ); + assert!( + flow.registration_client( + local_server, + "http://127.0.0.1:8080/authorize", + "http://127.0.0.1:8080/token", + "http://127.0.0.1:8080/register", + ) + .await + .expect("declared local") + .is_none() + ); +} + +#[test] +fn origins_compare_by_scheme_host_and_explicit_port() { + assert_eq!( + crate::registry::oauth::flow::origin_of("http://LocalHost/mcp").as_deref(), + Some("http://localhost:80") + ); + assert_eq!( + crate::registry::oauth::flow::origin_of("http://localhost:80").as_deref(), + Some("http://localhost:80") + ); + assert_eq!( + crate::registry::oauth::flow::origin_of("https://mcp.vendor.example/x").as_deref(), + Some("https://mcp.vendor.example:443") + ); + assert_eq!(crate::registry::oauth::flow::origin_of("not a url"), None); +} diff --git a/crates/tinymcp/src/registry/ops/mod_tests.rs b/crates/tinymcp/src/registry/ops/mod_tests.rs index 2961f67c..0ce8410c 100644 --- a/crates/tinymcp/src/registry/ops/mod_tests.rs +++ b/crates/tinymcp/src/registry/ops/mod_tests.rs @@ -709,7 +709,12 @@ fn remote_record(server_id: &str, endpoint: &str) -> InstalledServer { /// A facade holding `server` as an enabled install. fn registry_with(server: &InstalledServer) -> McpRegistry { - let registry = registry(); + // The stand-ins are loopback servers, which the OAuth endpoint guard + // refuses unless the operator declares them local, as a developer would. + let registry = match &server.transport { + Transport::HttpRemote { url } => registry().with_local_oauth_origins([url]), + _ => registry(), + }; registry.store().insert_server(server).expect("insert"); registry } @@ -1716,3 +1721,38 @@ async fn a_supervisor_from_the_registry_steps_over_its_store() { assert!(report.is_empty()); } + +// --------------------------------------------------------------------------- +// The OAuth endpoint guard is on by default +// --------------------------------------------------------------------------- + +#[tokio::test] +async fn a_loopback_server_is_refused_by_the_oauth_guard_unless_declared_local() { + let (endpoint, state) = mcp_server().await; + state.demand_auth.store(true, Ordering::SeqCst); + let record = remote_record("srv-1", &endpoint); + + // A registry built the normal way: nothing declared local. + let guarded = registry(); + guarded.store().insert_server(&record).expect("insert"); + let detected = guarded + .detect_auth("srv-1") + .await + .expect_err("a plain-http loopback server is refused"); + assert!( + detected.to_string().contains("endpoint refused"), + "{detected}" + ); + let begun = guarded + .oauth_begin("srv-1", "http://127.0.0.1:1/callback") + .await + .expect_err("no sign-in is started against it"); + assert!(begun.to_string().contains("endpoint refused"), "{begun}"); + + // The same server, declared local by the operator, is probed. + let local = registry_with(&record); + local + .detect_auth("srv-1") + .await + .expect("a declared-local server is probed"); +} diff --git a/crates/tinymcp/src/registry/ops/types.rs b/crates/tinymcp/src/registry/ops/types.rs index 3e1136aa..f166b023 100644 --- a/crates/tinymcp/src/registry/ops/types.rs +++ b/crates/tinymcp/src/registry/ops/types.rs @@ -63,13 +63,29 @@ impl McpRegistry { store: Arc::new(store), connections: Connections::new(), registries: Registries::new(registry_auth)?, - oauth: OAuthFlow::new(proxy.clone())?, + // Secure by default: the endpoints a server advertises are POSTed + // to from the host, so they must be https and public unless the + // operator declared that server local (`with_local_oauth_origins`). + oauth: OAuthFlow::new(proxy.clone())?.require_public_endpoints(), vault: SecretVault::new(), identity, proxy, }) } + /// Exempts servers at `origins` from the OAuth endpoint guard: the ones an + /// operator configured as local, from + /// [`tinymcp_bus::McpClientConfig::local_oauth_origins`]. + #[must_use] + pub fn with_local_oauth_origins(mut self, origins: I) -> Self + where + I: IntoIterator, + S: AsRef, + { + self.oauth = self.oauth.with_local_origins(origins); + self + } + /// The same registry starting stdio servers through `stdio`. /// /// Without it every installed stdio server is refused: an installed diff --git a/crates/tinymcp/src/tinybus_module/service.rs b/crates/tinymcp/src/tinybus_module/service.rs index c30fa037..df46d155 100644 --- a/crates/tinymcp/src/tinybus_module/service.rs +++ b/crates/tinymcp/src/tinybus_module/service.rs @@ -119,6 +119,7 @@ impl McpService { config.client.client_identity.clone(), config.client.proxy.clone(), )? + .with_local_oauth_origins(&config.client.local_oauth_origins) .with_stdio(stdio.clone()), );