tower-mcp 0.25.0

Tower-native Model Context Protocol (MCP) implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//! `Origin` and `Host` validation shared by the HTTP and WebSocket transports.
//!
//! Browsers attach `Origin` to cross-site `fetch` requests and to every
//! WebSocket handshake, and they do not apply CORS to WebSocket connections.
//! Checking it on the server is what keeps an arbitrary web page from driving
//! a locally bound MCP server (#1464).

use std::net::IpAddr;

use axum::http::{HeaderMap, StatusCode, header};
use axum::response::{IntoResponse, Response};

/// Whether `origin` is a well-formed `http(s)://` origin whose host is
/// localhost.
///
/// The origin is parsed (see [`parse_origin`]) before the host is judged, so
/// a string that merely starts with a localhost authority does not qualify:
/// `http://localhost:1@evil.com` carries userinfo and its real host is
/// `evil.com`, and anything with a path, query, or fragment is not an
/// origin at all.
pub(crate) fn is_localhost_origin(origin: &str) -> bool {
    // RFC 3986 makes the URI scheme case-insensitive, so the prefix match
    // must be too. `ws`/`wss` are accepted by `parse_origin` for allowlist
    // entries but are not a scheme a browser sends, so they stay excluded.
    if strip_scheme_ci(origin, "http://")
        .or_else(|| strip_scheme_ci(origin, "https://"))
        .is_none()
    {
        return false;
    }
    // `parse_origin` rejects userinfo, a path, a query, and a fragment, but
    // `http::Uri` is lenient about the authority itself (it reads
    // `[::1]evil.com` as `[::1]` and accepts an out-of-range port). Judge the
    // authority text with the strict host check rather than its parsed parts.
    let authority = origin
        .split_once("://")
        .map_or("", |(_, rest)| rest.strip_suffix('/').unwrap_or(rest));
    parse_origin(origin).is_ok() && is_localhost_host(authority)
}

/// Case-insensitively strip an ASCII scheme prefix (e.g. `"http://"`) from
/// `s`, returning the remainder if `s` starts with it.
fn strip_scheme_ci<'a>(s: &'a str, scheme: &str) -> Option<&'a str> {
    let prefix = scheme.as_bytes();
    if s.len() >= prefix.len() && s.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix) {
        Some(&s[prefix.len()..])
    } else {
        None
    }
}

/// Whether `port` is a decimal port number (digits only, at most 65535).
fn is_valid_port(port: &str) -> bool {
    !port.is_empty() && port.bytes().all(|b| b.is_ascii_digit()) && port.parse::<u16>().is_ok()
}

/// Check if a `host:port` (or `[ipv6]:port`) value refers to localhost.
///
/// Used by both Origin validation (after stripping the `http(s)://` scheme)
/// and Host validation (where there's no scheme to begin with).
pub(crate) fn is_localhost_host(host: &str) -> bool {
    // A bare (unbracketed, port-less) IPv6 literal like `::1` parses whole
    // as an IpAddr. Check this first: the port-splitting logic below would
    // otherwise misread one of its internal colons as a port separator.
    // A bare IPv6 literal with a trailing segment (e.g. `::1:3000`) parses
    // whole as a distinct, non-loopback address rather than `::1` plus a
    // port -- RFC 3986 requires brackets around an IPv6 host whenever a
    // port follows it, so that's the correct outcome, not a special case.
    if let Ok(ip) = host.parse::<IpAddr>() {
        return ip.is_loopback();
    }

    let host_only = if host.starts_with('[') {
        // Bracketed IPv6: [::1]:3000 -> ::1. RFC 3986 permits nothing
        // after the closing bracket but an optional ":port"; a missing
        // closing bracket, or any other trailing content, makes the
        // authority invalid and must be rejected rather than silently
        // discarded (that was the bug: [::1]evil.com used to be read as
        // just [::1]).
        let Some(close) = host.find(']') else {
            return false;
        };
        let after_bracket = &host[close + 1..];
        let port_ok =
            after_bracket.is_empty() || after_bracket.strip_prefix(':').is_some_and(is_valid_port);
        if !port_ok {
            return false;
        }
        &host[1..close]
    } else {
        // Strip the port if present. A port that is not a valid number is
        // not "no port", it makes the authority invalid.
        match host.split_once(':') {
            Some((_, port)) if !is_valid_port(port) => return false,
            Some((name, _)) => name,
            None => host,
        }
    };

    // `localhost`, and its RFC 3986 trailing-dot FQDN form, is
    // case-insensitive like any DNS name.
    if host_only.eq_ignore_ascii_case("localhost") || host_only.eq_ignore_ascii_case("localhost.") {
        return true;
    }

    // Covers the entire 127.0.0.0/8 range and ::1 (the only IPv6 loopback
    // address) in one shot. Rust's std parser requires canonical
    // dotted-decimal IPv4 (rejecting shorthand and hex/octal/decimal
    // obfuscation forms), so this doesn't widen the guard beyond the
    // canonical numeric forms a conforming URL host parser would produce.
    host_only.parse::<IpAddr>().is_ok_and(|ip| ip.is_loopback())
}

/// A single `allowed_origins` entry, parsed and normalized once when the
/// transport is built.
///
/// Comparing raw strings (the previous behavior) makes an allowlist entry
/// that differs from a browser's exact serialization silently ineffective:
/// `https://example.com:443` never matches `https://example.com`, and
/// likewise for a different-case host or a trailing slash (#1476). Storing
/// the parsed, normalized form instead makes those variants compare equal
/// and does the parsing once at build time rather than on every request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum AllowedOrigin {
    /// `"*"`: matches any Origin.
    Any,
    /// A specific origin: scheme (`"http"` or `"https"` after normalization,
    /// see [`parse_origin`]), lowercased host, and the port with the
    /// scheme's default applied when the entry didn't specify one.
    Origin {
        scheme: &'static str,
        host: String,
        port: u16,
    },
}

/// Parse and normalize a single `Origin` value: either an `allowed_origins`
/// allowlist entry, or an incoming `Origin` header, since both need the same
/// (scheme, host, port) comparison key.
///
/// Rejects anything that is not a bare `scheme://host[:port]` origin -- a
/// path other than `/`, a query, a fragment, userinfo, or a scheme other
/// than `http`/`https`/`ws`/`wss`. `ws` and `wss` are accepted and mapped to
/// `http` and `https` respectively: a browser's `Origin` header is always
/// `http(s)`, even on a WebSocket upgrade (the header reflects the scheme of
/// the page that opened the connection, not the connection's own scheme), so
/// an incoming Origin never actually arrives as `ws://`/`wss://`. Accepting
/// those schemes here is purely a convenience for an operator writing
/// `allowed_origins(vec!["wss://api.example.com"])` for a WebSocket-only
/// server, who is describing the connection scheme rather than the
/// browser-visible one; normalizing it to `https` is what makes it actually
/// match.
fn parse_origin(value: &str) -> Result<(&'static str, String, u16), String> {
    // `Origin` never carries a fragment, but `http::Uri` silently discards
    // one instead of reporting it, so it has to be rejected before parsing
    // rather than after.
    if value.contains('#') {
        return Err(format!(
            "{value:?} has a fragment, which an Origin cannot carry"
        ));
    }

    let uri: axum::http::Uri = value
        .parse()
        .map_err(|e| format!("{value:?} is not a valid Origin: {e}"))?;

    let scheme = uri
        .scheme_str()
        .ok_or_else(|| format!("{value:?} has no scheme"))?;
    let (scheme, default_port) = match scheme.to_ascii_lowercase().as_str() {
        "http" => ("http", 80u16),
        "https" => ("https", 443u16),
        "ws" => ("http", 80u16),
        "wss" => ("https", 443u16),
        other => return Err(format!("{value:?} has unsupported scheme {other:?}")),
    };

    let authority = uri
        .authority()
        .ok_or_else(|| format!("{value:?} has no host"))?;
    if authority.as_str().contains('@') {
        return Err(format!("{value:?} must not contain userinfo"));
    }

    let path = uri.path();
    if !path.is_empty() && path != "/" {
        return Err(format!("{value:?} must not have a path"));
    }
    if uri.query().is_some() {
        return Err(format!("{value:?} must not have a query"));
    }

    Ok((
        scheme,
        authority.host().to_ascii_lowercase(),
        authority.port_u16().unwrap_or(default_port),
    ))
}

/// Parse `allowed_origins` builder entries into their normalized form.
///
/// An entry that is not `"*"` or a bare `scheme://host[:port]` origin (see
/// [`parse_origin`] for exactly what that rejects) is logged at `warn` and
/// skipped. It could never match a real `Origin` header, so skipping it keeps
/// the check failing closed, and the warning names the entry so the
/// misconfiguration is visible at startup instead of as a silent lockout.
/// Allowlists usually come from runtime configuration, so a bad entry is not
/// treated as a programming error worth a panic.
pub(crate) fn parse_allowed_origins(entries: &[String]) -> Vec<AllowedOrigin> {
    entries
        .iter()
        .filter_map(|entry| {
            if entry == "*" {
                return Some(AllowedOrigin::Any);
            }
            match parse_origin(entry) {
                Ok((scheme, host, port)) => Some(AllowedOrigin::Origin { scheme, host, port }),
                Err(reason) => {
                    tracing::warn!(
                        entry = %entry,
                        "Ignoring invalid allowed_origins entry: {reason} (each entry must be \"*\" \
                         or a bare origin like \"https://example.com\" or \"https://example.com:8443\")"
                    );
                    None
                }
            }
        })
        .collect()
}

/// Validate the `Origin` header.
///
/// When `enabled`:
/// - Requests without an Origin header are allowed (same-origin, or a
///   non-browser client)
/// - A request with more than one Origin header is rejected
/// - Localhost origins are always allowed (DNS rebinding protection); a
///   configured `allowed_origins` list adds origins on top of this, it does
///   not replace it
/// - If `allowed_origins` is non-empty, non-localhost origins must match
///   (`"*"` matches any origin, including one that fails to parse)
/// - If `allowed_origins` is empty, non-localhost origins are rejected
///
/// Matching normalizes both sides the same way (see [`parse_origin`]), so
/// `https://example.com:443`, `https://Example.com`, and
/// `https://example.com/` in the allowlist all match a browser's
/// `https://example.com`. An incoming Origin that fails to parse (including
/// the opaque `null` origin) is rejected unless the allowlist contains
/// `"*"`. The localhost allowance applies only to an Origin that parses as a
/// bare `scheme://host[:port]`, so `http://localhost:1@evil.com` is not
/// treated as localhost.
///
/// Returns `Some(403 response)` if validation fails, `None` if it passes.
pub(crate) fn validate_origin(
    headers: &HeaderMap,
    enabled: bool,
    allowed_origins: &[AllowedOrigin],
) -> Option<Response> {
    if !enabled {
        return None;
    }

    // `HeaderMap::get` returns only the first value, which would let a second
    // `Origin` ride along unchecked behind a harmless first one. A browser
    // sends exactly one, so more than one is rejected outright.
    let mut origins = headers.get_all(header::ORIGIN).iter();
    let first = origins.next();
    if origins.next().is_some() {
        tracing::warn!("Rejecting request: multiple Origin headers");
        return Some((StatusCode::FORBIDDEN, "Origin not allowed").into_response());
    }

    if let Some(origin) = first {
        let origin_str = origin.to_str().unwrap_or("");

        // Always allow localhost origins (DNS rebinding protection allows these)
        if is_localhost_origin(origin_str) {
            return None;
        }

        // Non-localhost origin: check against allowed list
        if allowed_origins.is_empty() {
            tracing::warn!(
                origin = %origin_str,
                "Rejecting request: cross-origin not allowed (no allowlist configured)"
            );
            return Some(
                (StatusCode::FORBIDDEN, "Cross-origin requests not allowed").into_response(),
            );
        }

        // "*" matches unconditionally, including an Origin that doesn't
        // even parse -- it means "no restriction", not "any origin that
        // happens to be well-formed".
        if allowed_origins
            .iter()
            .any(|o| matches!(o, AllowedOrigin::Any))
        {
            return None;
        }

        let matched = match parse_origin(origin_str) {
            Ok((scheme, host, port)) => allowed_origins.iter().any(|o| {
                matches!(
                    o,
                    AllowedOrigin::Origin {
                        scheme: s,
                        host: h,
                        port: p,
                    } if *s == scheme && *h == host && *p == port
                )
            }),
            // An Origin that doesn't parse (including the opaque `null`
            // origin) can't match a specific allowlist entry.
            Err(_) => false,
        };

        if !matched {
            tracing::warn!(origin = %origin_str, "Rejecting request: Origin not in allowlist");
            return Some((StatusCode::FORBIDDEN, "Origin not allowed").into_response());
        }
    }

    None
}

/// Resolve the effective host for validation.
///
/// Prefers the `Host` header, falling back to the HTTP/2 `:authority`
/// pseudo-header (`request.uri().authority()`) when the header is missing.
/// This matters behind middleware like `axum::Router::nest`, which can
/// strip Hyper's synthesized `Host` before our handler sees it.
pub(crate) fn effective_host<'a>(
    headers: &'a HeaderMap,
    uri: &'a axum::http::Uri,
) -> Option<&'a str> {
    if let Some(value) = headers.get(header::HOST)
        && let Ok(s) = value.to_str()
    {
        return Some(s);
    }
    uri.authority().map(|a| a.as_str())
}

/// Validate the `Host` header (defense-in-depth alongside Origin).
///
/// When `enabled`, localhost hosts are always accepted. Any other host is
/// accepted when `allowed_hosts` is empty, which preserves the historical
/// behavior of not enforcing Host on non-loopback deployments unless the
/// operator opts in, and otherwise must match an entry exactly.
///
/// Returns `Some(400 response)` if validation fails, `None` if it passes.
pub(crate) fn validate_host(
    headers: &HeaderMap,
    uri: &axum::http::Uri,
    enabled: bool,
    allowed_hosts: &[String],
) -> Option<Response> {
    if !enabled {
        return None;
    }

    let Some(host) = effective_host(headers, uri) else {
        if allowed_hosts.is_empty() {
            // No Host header and no allowlist: fall back to permissive
            // behavior matching pre-validation defaults so we don't break
            // existing deployments. (Origin already protects browsers.)
            return None;
        }
        tracing::warn!("Rejecting request: missing Host header and no :authority fallback");
        return Some((StatusCode::BAD_REQUEST, "Missing Host header").into_response());
    };

    if is_localhost_host(host) {
        return None;
    }

    if allowed_hosts.is_empty() {
        // Non-localhost host with no explicit allowlist: keep accepting it.
        // Operators who want strict Host validation must opt in via
        // `.allowed_hosts(...)`. This preserves the historical behavior of
        // not enforcing Host on non-loopback deployments by default.
        return None;
    }

    if allowed_hosts.iter().any(|h| h == host) {
        return None;
    }

    tracing::warn!(host = %host, "Rejecting request: Host not in allowlist");
    Some((StatusCode::BAD_REQUEST, "Host not allowed").into_response())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn header_map(origin: &str) -> HeaderMap {
        let mut headers = HeaderMap::new();
        headers.insert(header::ORIGIN, origin.parse().unwrap());
        headers
    }

    /// Whether `origin` is accepted against an allowlist built from `entries`.
    fn is_allowed(origin: &str, entries: &[&str]) -> bool {
        let allowed =
            parse_allowed_origins(&entries.iter().map(|s| s.to_string()).collect::<Vec<_>>());
        validate_origin(&header_map(origin), true, &allowed).is_none()
    }

    // Each row from the #1476 table: an allowlist entry that differs from
    // the browser's exact serialization must still match.
    #[test]
    fn default_https_port_normalizes() {
        assert!(is_allowed(
            "https://example.com",
            &["https://example.com:443"]
        ));
    }

    #[test]
    fn default_http_port_normalizes() {
        assert!(is_allowed("http://example.com", &["http://example.com:80"]));
    }

    #[test]
    fn host_case_normalizes() {
        assert!(is_allowed("https://example.com", &["https://Example.com"]));
    }

    #[test]
    fn trailing_slash_normalizes() {
        assert!(is_allowed("https://example.com", &["https://example.com/"]));
    }

    #[test]
    fn non_default_port_does_not_match() {
        assert!(!is_allowed(
            "https://example.com",
            &["https://example.com:8443"]
        ));
    }

    #[test]
    fn scheme_mismatch_does_not_match() {
        assert!(!is_allowed("https://example.com", &["http://example.com"]));
    }

    #[test]
    fn ws_and_wss_entries_normalize_to_the_browser_visible_scheme() {
        // Browsers never send Origin: ws://; the entry describes the
        // connection scheme of a WebSocket-only server, and is normalized
        // to the http(s) scheme a browser's Origin header actually carries.
        assert!(is_allowed("https://example.com", &["wss://example.com"]));
        assert!(is_allowed("http://example.com", &["ws://example.com"]));
        assert!(!is_allowed("http://example.com", &["wss://example.com"]));
    }

    #[test]
    fn wildcard_matches_anything_including_an_unparseable_origin() {
        assert!(is_allowed("https://example.com", &["*"]));
        assert!(is_allowed("not a valid origin $$", &["*"]));
    }

    #[test]
    fn unparseable_origin_is_rejected_without_a_wildcard() {
        assert!(!is_allowed(
            "not a valid origin $$",
            &["https://example.com"]
        ));
    }

    fn header_map_all(origins: &[&str]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for origin in origins {
            headers.append(header::ORIGIN, origin.parse().unwrap());
        }
        headers
    }

    #[test]
    fn duplicate_origin_headers_are_rejected() {
        let rejected = |origins: &[&str], entries: &[&str]| {
            let allowed =
                parse_allowed_origins(&entries.iter().map(|s| s.to_string()).collect::<Vec<_>>());
            validate_origin(&header_map_all(origins), true, &allowed)
                .is_some_and(|r| r.status() == StatusCode::FORBIDDEN)
        };
        // Order does not matter, and neither does either value being valid.
        assert!(rejected(&["http://localhost", "https://evil.example"], &[]));
        assert!(rejected(&["https://evil.example", "http://localhost"], &[]));
        assert!(rejected(
            &["https://app.example", "https://app.example"],
            &["https://app.example"]
        ));
        assert!(rejected(&["http://localhost", "http://localhost"], &["*"]));
        // A single header is unaffected.
        assert!(!rejected(&["http://localhost"], &[]));
    }

    #[test]
    fn userinfo_does_not_pass_as_localhost() {
        for origin in [
            "http://localhost:1@evil.com",
            "http://localhost@evil.com",
            "https://127.0.0.1:443@evil.com",
            "http://[::1]:3000@evil.com",
            "http://user:pass@localhost",
        ] {
            assert!(!is_localhost_origin(origin), "{origin}");
            assert!(!is_allowed(origin, &[]), "{origin}");
            assert!(!is_allowed(origin, &["https://app.example"]), "{origin}");
        }
    }

    #[test]
    fn malformed_localhost_lookalikes_are_not_localhost() {
        for origin in [
            "http://localhost/path",
            "http://localhost?x=1",
            "http://localhost#frag",
            "http://localhost:99999",
            "http://localhost:abc",
            "http://localhost evil.com",
            "http://",
            "http:///",
            "http://localhost:3000, http://evil.com",
        ] {
            assert!(!is_localhost_origin(origin), "{origin}");
            assert!(!is_allowed(origin, &["https://app.example"]), "{origin}");
        }
    }

    #[test]
    fn legitimate_localhost_origins_still_pass() {
        for origin in [
            "http://localhost:3000",
            "http://127.0.0.1",
            "http://127.0.0.1:8080",
            "https://localhost",
            "http://[::1]:3000",
            "HTTP://LocalHost:3000",
        ] {
            assert!(is_localhost_origin(origin), "{origin}");
            assert!(is_allowed(origin, &[]), "{origin}");
            assert!(is_allowed(origin, &["https://app.example"]), "{origin}");
        }
    }

    #[test]
    fn invalid_ports_are_not_localhost() {
        for host in [
            "localhost:abc",
            "localhost:",
            "localhost:99999",
            "localhost:+80",
            "localhost:1:2",
        ] {
            assert!(!is_localhost_host(host), "{host}");
        }
        assert!(is_localhost_host("localhost:65535"));
    }

    #[test]
    fn invalid_entries_are_rejected_with_a_reason() {
        for (entry, reason) in [
            ("https://example.com/app", "must not have a path"),
            ("https://example.com?x=1", "must not have a query"),
            ("https://example.com#frag", "has a fragment"),
            ("https://user:pass@example.com", "must not contain userinfo"),
            ("ftp://example.com", "unsupported scheme"),
            ("example.com", "has no scheme"),
        ] {
            let error = parse_origin(entry).expect_err(entry);
            assert!(error.contains(reason), "{entry}: {error}");
        }
    }

    #[test]
    fn invalid_entries_are_skipped_and_valid_ones_kept() {
        let parsed = parse_allowed_origins(&[
            "https://example.com/app".to_string(),
            "https://Example.com:443".to_string(),
            "ftp://example.com".to_string(),
            "*".to_string(),
        ]);
        assert_eq!(parsed.len(), 2, "{parsed:?}");
        assert!(matches!(parsed[1], AllowedOrigin::Any));
    }
}