Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,29 @@ impl CanonicalHostedMcpEndpoint {
pub fn parse(input: &HostedMcpEndpoint) -> Result<Self, HostedMcpAdmissionError> {
let url = url::Url::parse(input.as_str())
.map_err(|_| HostedMcpAdmissionError::InvalidEndpoint)?;
if url.scheme() != "https"
|| url.host_str().is_none()
let host = url
.host()
.ok_or(HostedMcpAdmissionError::InvalidEndpoint)?;
// A literal loopback IP (127.0.0.0/8 or ::1) is a safe, non-rebindable
// on-device target: it is the single case where `http` is admitted and
// where an IP literal is allowed. Every other endpoint must be a public
// `https` URL, exactly as before.
let loopback_literal = is_loopback_ip_literal(&host);
let scheme_ok = url.scheme() == "https" || (url.scheme() == "http" && loopback_literal);
if !scheme_ok
|| !url.username().is_empty()
|| url.password().is_some()
|| url.fragment().is_some()
{
return Err(HostedMcpAdmissionError::InvalidEndpoint);
}
let host = url
let host_str = url
.host_str()
.ok_or(HostedMcpAdmissionError::InvalidEndpoint)?;
if host.eq_ignore_ascii_case("localhost")
|| matches!(
url.host(),
Some(url::Host::Ipv4(_)) | Some(url::Host::Ipv6(_))
)
{
// `localhost` (a DNS name a resolver could rebind) stays rejected; IP
// literals stay rejected unless they are a literal loopback address.
let is_ip_literal = matches!(host, url::Host::Ipv4(_) | url::Host::Ipv6(_));
if host_str.eq_ignore_ascii_case("localhost") || (is_ip_literal && !loopback_literal) {
return Err(HostedMcpAdmissionError::InvalidEndpoint);
}
// Denylist, not allowlist: query parameters are load-bearing identity
Expand Down Expand Up @@ -81,6 +87,19 @@ impl CanonicalHostedMcpEndpoint {
}
}

/// A literal IPv4/IPv6 loopback address (`127.0.0.0/8` or `::1`). Hostnames
/// such as `localhost` are intentionally excluded: only a literal loopback IP
/// is exempted, so no DNS name can later rebind to a non-loopback address.
/// Shared by the admission gate above and the hosted-MCP egress planner in
/// [`crate::mcp`] so the two agree on exactly what "loopback" means.
pub(crate) fn is_loopback_ip_literal(host: &url::Host<&str>) -> bool {
match host {
url::Host::Ipv4(ip) => ip.is_loopback(),
url::Host::Ipv6(ip) => ip.is_loopback(),
url::Host::Domain(_) => false,
}
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostedMcpAdmissionError {
InvalidEndpoint,
Expand Down Expand Up @@ -108,11 +127,14 @@ mod tests {
fn canonical_endpoint_rejects_credential_and_private_literal_forms() {
for endpoint in [
"https://user@example.test",
"https://127.0.0.1/mcp",
"http://mcp.example.test",
"https://mcp.example.test/rpc?Access_Token=must-not-persist",
"https://[::1]/mcp",
// `localhost` is a DNS name, not a literal loopback IP: rejected.
"http://localhost/mcp",
"https://localhost/mcp",
// A non-loopback IP literal stays rejected.
"https://[2001:db8::1]/mcp",
"https://192.168.1.10/mcp",
"https://mcp.example.test/rpc?client_secret=must-not-persist",
"https://mcp.example.test/rpc?Password=must-not-persist",
"https://mcp.example.test/rpc?signature=must-not-persist",
Expand All @@ -126,6 +148,26 @@ mod tests {
}
}

#[test]
fn canonical_endpoint_admits_literal_loopback_over_http_or_https() {
// A literal loopback IP is a safe on-device target: `http` is admitted
// and the IP literal is allowed, with the scheme/port preserved.
for endpoint in [
"http://127.0.0.1:5001/mcp",
"https://127.0.0.1/mcp",
"http://[::1]:5001/mcp",
"https://[::1]/mcp",
] {
let input = HostedMcpEndpoint::new(endpoint).expect("wire endpoint");
CanonicalHostedMcpEndpoint::parse(&input)
.unwrap_or_else(|_| panic!("loopback endpoint should be admitted: {endpoint}"));
}

let input = HostedMcpEndpoint::new("http://127.0.0.1:5001/mcp").expect("wire endpoint");
let endpoint = CanonicalHostedMcpEndpoint::parse(&input).expect("canonical endpoint");
assert_eq!(endpoint.as_str(), "http://127.0.0.1:5001/mcp");
}

#[test]
fn canonical_endpoint_keeps_query_identity_and_normalizes_path() {
let input = HostedMcpEndpoint::new("https://MCP.example.test/a/../rpc?b=2&a=1")
Expand Down
66 changes: 59 additions & 7 deletions crates/extensions/ironclaw_extension_host/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ use ironclaw_mcp::{
McpHostHttpEgressPlanner, McpRuntime, McpRuntimeConfig, McpRuntimeHttpAdapter,
};

use crate::hosted_mcp_admission::is_loopback_ip_literal;

pub const MCP_RESPONSE_BODY_LIMIT: u64 = 2 * 1024 * 1024;
const MCP_NETWORK_EGRESS_LIMIT: u64 = 2 * 1024 * 1024;
const MCP_TIMEOUT_MS: u32 = 60_000;
Expand Down Expand Up @@ -106,6 +108,11 @@ impl McpHostHttpEgressPlanner for RegistryMcpEgressPlanner {

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostedMcpEgressEndpoint {
scheme: NetworkScheme,
/// True when `host_pattern` is a literal loopback IP. Such endpoints are
/// exempt from the private-range denial (see
/// [`hosted_mcp_network_policy_for_endpoint`]).
loopback: bool,
host_pattern: String,
port: Option<u16>,
path: String,
Expand All @@ -115,14 +122,24 @@ pub struct HostedMcpEgressEndpoint {
impl HostedMcpEgressEndpoint {
fn parse(url: &str) -> Option<Self> {
let parsed = url::Url::parse(url).ok()?;
if parsed.scheme() != "https"
|| !parsed.username().is_empty()
let host = parsed.host()?;
let loopback = is_loopback_ip_literal(&host);
// `http` is admitted only for a literal loopback IP; every other target
// must be `https`. Mirrors the admission gate in `hosted_mcp_admission`.
let scheme = match parsed.scheme() {
"https" => NetworkScheme::Https,
"http" if loopback => NetworkScheme::Http,
_ => return None,
};
if !parsed.username().is_empty()
|| parsed.password().is_some()
|| parsed.fragment().is_some()
{
return None;
}
Some(Self {
scheme,
loopback,
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
host_pattern: parsed.host_str()?.to_ascii_lowercase(),
port: parsed.port(),
path: normalize_mcp_path(parsed.path()),
Expand All @@ -131,7 +148,7 @@ impl HostedMcpEgressEndpoint {
}

fn allows_target(&self, target: &NetworkTargetPattern) -> bool {
target.scheme == Some(NetworkScheme::Https)
target.scheme == Some(self.scheme)
&& target.host_pattern.eq_ignore_ascii_case(&self.host_pattern)
&& target.port == self.port
}
Expand Down Expand Up @@ -187,13 +204,15 @@ pub(crate) fn hosted_mcp_network_policy(package: &ExtensionPackage) -> Option<Ne
fn hosted_mcp_network_policy_for_endpoint(endpoint: &HostedMcpEgressEndpoint) -> NetworkPolicy {
NetworkPolicy {
allowed_targets: vec![NetworkTargetPattern {
scheme: Some(NetworkScheme::Https),
scheme: Some(endpoint.scheme),
host_pattern: endpoint.host_pattern.clone(),
port: endpoint.port,
}],
// Matches the bundled manifest's deny_private_ip_ranges default.
// Dispatcher would reject anyway, but the plan must agree.
deny_private_ip_ranges: true,
// A literal loopback endpoint is exempt from the private-range denial:
// it is a safe on-device target and the dispatcher already permits
// loopback when this is false. Every other endpoint keeps the deny in
// force to match the bundled manifest's default.
deny_private_ip_ranges: !endpoint.loopback,
max_egress_bytes: Some(MCP_NETWORK_EGRESS_LIMIT),
}
}
Expand All @@ -220,6 +239,39 @@ mod tests {
const NOTION_MCP_HOST: &str = "mcp.notion.com";
const NOTION_MCP_URL: &str = "https://mcp.notion.com/mcp";

// ── loopback endpoints ─────────────────────────────────────────────────

#[test]
fn loopback_endpoint_admits_http_and_waives_private_range_denial() {
let endpoint = HostedMcpEgressEndpoint::parse("http://127.0.0.1:5001/mcp")
.expect("literal loopback http endpoint is admitted");
assert_eq!(endpoint.scheme, NetworkScheme::Http);
assert!(endpoint.loopback);

let policy = hosted_mcp_network_policy_for_endpoint(&endpoint);
assert!(!policy.deny_private_ip_ranges);
assert_eq!(policy.allowed_targets.len(), 1);
assert_eq!(policy.allowed_targets[0].scheme, Some(NetworkScheme::Http));
assert_eq!(policy.allowed_targets[0].host_pattern, "127.0.0.1");
assert_eq!(policy.allowed_targets[0].port, Some(5001));
}

#[test]
fn non_loopback_endpoints_keep_https_and_private_range_denial() {
// Public `http` is not an MCP endpoint at all.
assert!(HostedMcpEgressEndpoint::parse("http://mcp.example.test/mcp").is_none());
// `localhost` is a DNS name, not a literal loopback IP, so `http` is refused.
assert!(HostedMcpEgressEndpoint::parse("http://localhost:5001/mcp").is_none());

// A public `https` endpoint keeps the private-range denial and https scheme.
let public = HostedMcpEgressEndpoint::parse(NOTION_MCP_URL).expect("public https endpoint");
assert_eq!(public.scheme, NetworkScheme::Https);
assert!(!public.loopback);
let policy = hosted_mcp_network_policy_for_endpoint(&public);
assert!(policy.deny_private_ip_ranges);
assert_eq!(policy.allowed_targets[0].scheme, Some(NetworkScheme::Https));
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// ── credential projection ──────────────────────────────────────────────

#[test]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,29 @@ test("keeps the generated ID hidden until Advanced options and validates each co
assert.match(document.body.textContent || "", /customMcpIdInvalid/);
});

test("accepts a literal loopback IP over http and advances to review", () => {
renderModal();
setInput(document.querySelectorAll<HTMLInputElement>("input")[0], "Pantry Host MCP");
setInput(document.querySelectorAll<HTMLInputElement>("input")[2], "http://127.0.0.1:5001/mcp");
clickButton("common.continue");

// A literal loopback IP is a safe on-device target: no endpoint error, and
// the wizard advances to the Review step.
assert.doesNotMatch(document.body.textContent || "", /customMcpEndpointHttps/);
assert.match(document.body.textContent || "", /customMcpReviewHint/);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

test("still rejects localhost as a hosted MCP endpoint", () => {
renderModal();
setInput(document.querySelectorAll<HTMLInputElement>("input")[0], "Local MCP");
// `localhost` is a DNS name that could rebind, so it stays rejected even
// though a literal loopback IP is now allowed.
setInput(document.querySelectorAll<HTMLInputElement>("input")[2], "http://localhost:5001/mcp");
clickButton("common.continue");

assert.match(document.body.textContent || "", /customMcpEndpointHttps/);
});

test("review submits automatic authentication without asking the user to classify the server", () => {
let payload: CustomMcpRegistrationPayload | null = null;
renderModal({ onRegister: (request) => { payload = request; } });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,20 @@ function connectionErrors(name: string, id: string, endpoint: string, t: (key: s
const parsed = new URL(trimmedEndpoint);
const host = parsed.hostname.toLowerCase();
const isIpLiteral = /^\d{1,3}(?:\.\d{1,3}){3}$/.test(host) || host.includes(":");
// A literal loopback IP (127.0.0.0/8 or ::1) is a safe, non-rebindable
// on-device target: the one case where `http` and an IP literal are
// allowed. Mirrors the backend admission gate in `hosted_mcp_admission`.
// `localhost` (a DNS name) stays rejected.
const isLoopbackLiteral =
/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(host) || host === "[::1]" || host === "::1";
const schemeOk =
parsed.protocol === "https:" || (parsed.protocol === "http:" && isLoopbackLiteral);
const hasCredentialQuery = Array.from(parsed.searchParams.keys()).some((key) =>
CREDENTIAL_QUERY_KEYS.has(key.toLowerCase()),
);
if (
parsed.protocol !== "https:" || !host || parsed.username || parsed.password || parsed.hash ||
host === "localhost" || isIpLiteral || hasCredentialQuery ||
!schemeOk || !host || parsed.username || parsed.password || parsed.hash ||
host === "localhost" || (isIpLiteral && !isLoopbackLiteral) || hasCredentialQuery ||
trimmedEndpoint.length > 2048 || CONTROL_CHARACTER_PATTERN.test(trimmedEndpoint)
) throw new Error("invalid hosted MCP endpoint");
} catch {
Expand Down