|
| 1 | +//! Origin-header validation (DNS-rebinding protection) for the MCP endpoint. |
| 2 | +//! |
| 3 | +//! Streamable HTTP §Security: "Servers MUST validate the `Origin` header on |
| 4 | +//! all incoming connections to prevent DNS rebinding attacks. If the |
| 5 | +//! `Origin` header is present and invalid, servers MUST respond with |
| 6 | +//! HTTP 403 Forbidden." Policy semantics are recorded in ADR-031. |
| 7 | +
|
| 8 | +use hyper::HeaderMap; |
| 9 | +use std::net::{Ipv4Addr, Ipv6Addr}; |
| 10 | + |
| 11 | +/// Validation policy for the `Origin` request header on the MCP endpoint. |
| 12 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 13 | +pub enum OriginPolicy { |
| 14 | + /// Default. Origin absent → allowed. Origin present → allowed only if |
| 15 | + /// its host is loopback (`localhost`, `127.0.0.0/8`, `[::1]`) or its |
| 16 | + /// authority matches the request's `Host` header (default-port |
| 17 | + /// normalized). Anything else → HTTP 403. |
| 18 | + #[default] |
| 19 | + SameOriginOrLoopback, |
| 20 | + /// [`OriginPolicy::SameOriginOrLoopback`] semantics plus an explicit |
| 21 | + /// allowlist of origins (`scheme://host[:port]`; host compared |
| 22 | + /// case-insensitively, default-port normalized). The literal entry |
| 23 | + /// `"null"` admits `Origin: null`. |
| 24 | + AllowList(Vec<String>), |
| 25 | + /// No validation — for deployments that enforce origin upstream |
| 26 | + /// (API Gateway / ALB / reverse proxy) or are not browser-reachable. |
| 27 | + Disabled, |
| 28 | +} |
| 29 | + |
| 30 | +/// `(host_lowercase, effective_port)` of a parsed origin. |
| 31 | +type OriginAuthority = (String, u16); |
| 32 | + |
| 33 | +fn default_port(scheme: &str) -> Option<u16> { |
| 34 | + match scheme { |
| 35 | + "http" | "ws" => Some(80), |
| 36 | + "https" | "wss" => Some(443), |
| 37 | + _ => None, |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +/// Parse `scheme://host[:port]` into a normalized authority. |
| 42 | +fn parse_origin(origin: &str) -> Option<OriginAuthority> { |
| 43 | + let (scheme, rest) = origin.split_once("://")?; |
| 44 | + let scheme = scheme.to_ascii_lowercase(); |
| 45 | + // An origin has no path/query, but be lenient about a trailing slash. |
| 46 | + let authority = rest.strip_suffix('/').unwrap_or(rest); |
| 47 | + if authority.is_empty() { |
| 48 | + return None; |
| 49 | + } |
| 50 | + let (host, port) = split_host_port(authority)?; |
| 51 | + let port = match port { |
| 52 | + Some(p) => p, |
| 53 | + None => default_port(&scheme)?, |
| 54 | + }; |
| 55 | + Some((host, port)) |
| 56 | +} |
| 57 | + |
| 58 | +/// Split `host[:port]` handling bracketed IPv6 (`[::1]:8080`). |
| 59 | +fn split_host_port(authority: &str) -> Option<(String, Option<u16>)> { |
| 60 | + if let Some(rest) = authority.strip_prefix('[') { |
| 61 | + let (host, after) = rest.split_once(']')?; |
| 62 | + let port = match after.strip_prefix(':') { |
| 63 | + Some(p) => Some(p.parse().ok()?), |
| 64 | + None if after.is_empty() => None, |
| 65 | + None => return None, |
| 66 | + }; |
| 67 | + Some((host.to_ascii_lowercase(), port)) |
| 68 | + } else if let Some((host, p)) = authority.rsplit_once(':') { |
| 69 | + if host.is_empty() { |
| 70 | + return None; |
| 71 | + } |
| 72 | + Some((host.to_ascii_lowercase(), Some(p.parse().ok()?))) |
| 73 | + } else { |
| 74 | + Some((authority.to_ascii_lowercase(), None)) |
| 75 | + } |
| 76 | +} |
| 77 | + |
| 78 | +fn is_loopback_host(host: &str) -> bool { |
| 79 | + if host == "localhost" { |
| 80 | + return true; |
| 81 | + } |
| 82 | + if let Ok(v4) = host.parse::<Ipv4Addr>() { |
| 83 | + return v4.is_loopback(); |
| 84 | + } |
| 85 | + if let Ok(v6) = host.parse::<Ipv6Addr>() { |
| 86 | + return v6.is_loopback(); |
| 87 | + } |
| 88 | + false |
| 89 | +} |
| 90 | + |
| 91 | +/// Does the origin authority match the request `Host` header? |
| 92 | +/// |
| 93 | +/// `Host` carries no scheme; when it has no explicit port, the origin |
| 94 | +/// matches if its effective port is a scheme default (80/443). |
| 95 | +fn matches_host_header(origin: &OriginAuthority, host_header: &str) -> bool { |
| 96 | + let Some((host, host_port)) = split_host_port(host_header.trim()) else { |
| 97 | + return false; |
| 98 | + }; |
| 99 | + if origin.0 != host { |
| 100 | + return false; |
| 101 | + } |
| 102 | + match host_port { |
| 103 | + Some(p) => origin.1 == p, |
| 104 | + None => origin.1 == 80 || origin.1 == 443, |
| 105 | + } |
| 106 | +} |
| 107 | + |
| 108 | +/// Validate the request's `Origin` header against `policy`. |
| 109 | +/// |
| 110 | +/// `Ok(())` admits the request; `Err(origin_value)` means the caller MUST |
| 111 | +/// respond 403 Forbidden. |
| 112 | +pub(crate) fn validate_origin(headers: &HeaderMap, policy: &OriginPolicy) -> Result<(), String> { |
| 113 | + if matches!(policy, OriginPolicy::Disabled) { |
| 114 | + return Ok(()); |
| 115 | + } |
| 116 | + let Some(origin) = headers.get(hyper::header::ORIGIN) else { |
| 117 | + return Ok(()); // spec constrains only "present and invalid" |
| 118 | + }; |
| 119 | + let Ok(origin) = origin.to_str() else { |
| 120 | + return Err("<non-ascii>".to_string()); |
| 121 | + }; |
| 122 | + |
| 123 | + if let OriginPolicy::AllowList(allowed) = policy |
| 124 | + && allowed.iter().any(|a| { |
| 125 | + a == origin |
| 126 | + || matches!( |
| 127 | + (parse_origin(a), parse_origin(origin)), |
| 128 | + (Some(x), Some(y)) if x == y |
| 129 | + ) |
| 130 | + }) |
| 131 | + { |
| 132 | + return Ok(()); |
| 133 | + } |
| 134 | + |
| 135 | + let Some(parsed) = parse_origin(origin) else { |
| 136 | + return Err(origin.to_string()); // includes `Origin: null` |
| 137 | + }; |
| 138 | + if is_loopback_host(&parsed.0) { |
| 139 | + return Ok(()); |
| 140 | + } |
| 141 | + let host_header = headers |
| 142 | + .get(hyper::header::HOST) |
| 143 | + .and_then(|h| h.to_str().ok()); |
| 144 | + if let Some(host) = host_header |
| 145 | + && matches_host_header(&parsed, host) |
| 146 | + { |
| 147 | + return Ok(()); |
| 148 | + } |
| 149 | + Err(origin.to_string()) |
| 150 | +} |
| 151 | + |
| 152 | +#[cfg(test)] |
| 153 | +mod tests { |
| 154 | + use super::*; |
| 155 | + use hyper::header::{HOST, ORIGIN}; |
| 156 | + |
| 157 | + fn headers(origin: Option<&str>, host: Option<&str>) -> HeaderMap { |
| 158 | + let mut h = HeaderMap::new(); |
| 159 | + if let Some(o) = origin { |
| 160 | + h.insert(ORIGIN, o.parse().unwrap()); |
| 161 | + } |
| 162 | + if let Some(hh) = host { |
| 163 | + h.insert(HOST, hh.parse().unwrap()); |
| 164 | + } |
| 165 | + h |
| 166 | + } |
| 167 | + |
| 168 | + #[test] |
| 169 | + fn absent_origin_is_allowed() { |
| 170 | + let p = OriginPolicy::SameOriginOrLoopback; |
| 171 | + assert!(validate_origin(&headers(None, Some("example.com")), &p).is_ok()); |
| 172 | + } |
| 173 | + |
| 174 | + #[test] |
| 175 | + fn loopback_origins_pass() { |
| 176 | + let p = OriginPolicy::SameOriginOrLoopback; |
| 177 | + for o in [ |
| 178 | + "http://localhost", |
| 179 | + "http://localhost:3000", |
| 180 | + "http://127.0.0.1:9999", |
| 181 | + "http://127.8.4.2", |
| 182 | + "http://[::1]:8080", |
| 183 | + "https://LOCALHOST:8443", |
| 184 | + ] { |
| 185 | + assert!( |
| 186 | + validate_origin(&headers(Some(o), Some("example.com")), &p).is_ok(), |
| 187 | + "{o} should pass" |
| 188 | + ); |
| 189 | + } |
| 190 | + } |
| 191 | + |
| 192 | + #[test] |
| 193 | + fn same_host_passes_with_port_normalization() { |
| 194 | + let p = OriginPolicy::SameOriginOrLoopback; |
| 195 | + for (o, host) in [ |
| 196 | + ("http://app.example:8080", "app.example:8080"), |
| 197 | + ("http://app.example", "app.example"), // 80 vs portless |
| 198 | + ("https://app.example", "app.example"), // 443 vs portless |
| 199 | + ("https://APP.example:443", "app.example:443"), |
| 200 | + ] { |
| 201 | + assert!( |
| 202 | + validate_origin(&headers(Some(o), Some(host)), &p).is_ok(), |
| 203 | + "{o} vs Host {host} should pass" |
| 204 | + ); |
| 205 | + } |
| 206 | + } |
| 207 | + |
| 208 | + #[test] |
| 209 | + fn cross_origin_null_and_garbage_are_rejected() { |
| 210 | + let p = OriginPolicy::SameOriginOrLoopback; |
| 211 | + for (o, host) in [ |
| 212 | + ("http://attacker.example", "127.0.0.1:8641"), |
| 213 | + ("http://app.example:9000", "app.example:8080"), // port mismatch |
| 214 | + ("null", "127.0.0.1:8641"), |
| 215 | + ("not a url", "127.0.0.1:8641"), |
| 216 | + ] { |
| 217 | + assert!( |
| 218 | + validate_origin(&headers(Some(o), Some(host)), &p).is_err(), |
| 219 | + "{o} vs Host {host} should be rejected" |
| 220 | + ); |
| 221 | + } |
| 222 | + } |
| 223 | + |
| 224 | + #[test] |
| 225 | + fn allowlist_is_additive_and_port_normalized() { |
| 226 | + let p = OriginPolicy::AllowList(vec!["https://app.example".into(), "null".into()]); |
| 227 | + let host = Some("127.0.0.1:8641"); |
| 228 | + assert!(validate_origin(&headers(Some("https://app.example"), host), &p).is_ok()); |
| 229 | + assert!(validate_origin(&headers(Some("https://app.example:443"), host), &p).is_ok()); |
| 230 | + assert!(validate_origin(&headers(Some("null"), host), &p).is_ok()); |
| 231 | + // additive: loopback still passes |
| 232 | + assert!(validate_origin(&headers(Some("http://localhost:3000"), host), &p).is_ok()); |
| 233 | + // unlisted still rejected |
| 234 | + assert!(validate_origin(&headers(Some("https://other.example"), host), &p).is_err()); |
| 235 | + } |
| 236 | + |
| 237 | + #[test] |
| 238 | + fn disabled_skips_everything() { |
| 239 | + let p = OriginPolicy::Disabled; |
| 240 | + assert!(validate_origin(&headers(Some("http://attacker.example"), None), &p).is_ok()); |
| 241 | + } |
| 242 | +} |
0 commit comments