Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions crates/tinymcp-bus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions crates/tinymcp-bus/src/config/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ pub struct McpClientConfig {
/// one) is refused rather than started unconfined.
#[serde(default)]
pub stdio_sandbox: Option<StdioSandboxConfig>,
/// 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<String>,
}

/// The jail a host grants stdio MCP servers.
Expand Down Expand Up @@ -127,6 +138,7 @@ impl Default for McpClientConfig {
registry_auth: McpRegistryAuthConfig::default(),
proxy: None,
stdio_sandbox: None,
local_oauth_origins: Vec::new(),
}
}
}
Expand Down
5 changes: 4 additions & 1 deletion crates/tinymcp-bus/src/version/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 1 addition & 1 deletion crates/tinymcp-bus/src/version/mod_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
6 changes: 4 additions & 2 deletions crates/tinymcp/src/registry/connections/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}"
Expand Down
11 changes: 7 additions & 4 deletions crates/tinymcp/src/registry/oauth/endpoint_guard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
79 changes: 74 additions & 5 deletions crates/tinymcp/src/registry/oauth/flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,9 @@ pub struct OAuthFlow {
proxy: Option<McpProxyConfig>,
pending: Arc<dyn PendingAuthorizationStore>,
public_endpoints_only: bool,
/// Origins (`scheme://host:port`) of servers the operator declared local,
/// exempt from [`Self::require_public_endpoints`].
local_origins: Vec<String>,
client_name: String,
}

Expand Down Expand Up @@ -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(),
})
}
Expand Down Expand Up @@ -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<I, S>(mut self, origins: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
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 {
Expand Down Expand Up @@ -260,6 +304,7 @@ impl OAuthFlow {

let registration_http = self
.registration_client(
&url,
&authorization_endpoint,
&token_endpoint,
&registration_endpoint,
Expand Down Expand Up @@ -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)?;
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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<Option<reqwest::Client>> {
if self.public_endpoints_only {
if self.guards(server_url) {
guard_endpoint(authorization_endpoint, "authorization").await?;
guard_endpoint(token_endpoint, "token").await?;
Ok(Some(
Expand All @@ -450,17 +505,18 @@ 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()
}

pub(super) async fn token_client(
&self,
server_url: &str,
token_endpoint: &str,
) -> Result<Option<reqwest::Client>> {
if self.public_endpoints_only {
if self.guards(server_url) {
Ok(Some(guarded_client(token_endpoint, "token").await?))
} else {
Ok(None)
Expand Down Expand Up @@ -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<String> {
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
Expand Down
81 changes: 77 additions & 4 deletions crates/tinymcp/src/registry/oauth/mod_host_store_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -314,7 +317,7 @@ async fn a_guarded_flow_refuses_an_internal_authorization_server() {
),
] {
let error = flow
.registration_client(&authorize, &token, &register)
.registration_client(SERVER, &authorize, &token, &register)
.await
.expect_err(what);
assert!(
Expand All @@ -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"),
Expand Down Expand Up @@ -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",
Expand All @@ -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()
Expand All @@ -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()
Expand Down Expand Up @@ -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);
}
Loading
Loading