1use serde::{Deserialize, Serialize};
4
5pub const VERSION: u8 = 1;
6pub const MAX_BODY_BYTES: usize = crate::MAX_FRAME_BYTES;
7pub const MAX_ENCODED_BYTES: usize = MAX_BODY_BYTES.div_ceil(3) * 4;
8pub const MAX_HEADER_BYTES: usize = 16 * 1024;
9pub const MAX_WIRE_BYTES: usize = MAX_ENCODED_BYTES + MAX_HEADER_BYTES + 16 * 1024;
10pub const MAX_IN_FLIGHT: usize = 4;
11pub const REQUEST_SECONDS: u64 = 30;
12pub const PING: &str = "gent-mcp-ping-v1";
13pub const PONG: &str = "gent-mcp-pong-v1";
14pub const PASSIVE_HEADER: &str = "x-gent-web-passive";
16pub const STANDBY_HEADER: &str = "x-gent-web-standby";
17pub const AVAILABLE: &str = "gent-web-available-v1";
18pub const PROBE: &str = "gent-web-probe-v1";
19pub const ALIVE: &str = "gent-web-alive-v1";
20
21#[derive(Serialize, Deserialize)]
24#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
25pub enum Frame {
26 Ready { version: u8 },
27 Request(HttpRequest),
28 Response(HttpResponse),
29 Manage { id: String, action: ConnectorAction },
30}
31
32#[derive(Serialize, Deserialize)]
34#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
35pub enum ConnectorAction {
36 Status,
37 Url,
38 Fingerprint,
39 Rotate { expected: String },
40}
41
42impl ConnectorAction {
43 pub fn valid(&self) -> bool {
44 match self {
45 Self::Rotate { expected } => {
46 expected.len() == 64
47 && expected
48 .bytes()
49 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
50 }
51 _ => true,
52 }
53 }
54}
55
56#[derive(Serialize, Deserialize)]
57#[serde(deny_unknown_fields)]
58pub struct HttpRequest {
59 pub id: String,
60 pub method: String,
61 pub path: String,
63 pub headers: Vec<(String, String)>,
64 pub body_base64: String,
65}
66
67#[derive(Serialize, Deserialize)]
68#[serde(deny_unknown_fields)]
69pub struct HttpResponse {
70 pub id: String,
71 pub status: u16,
72 pub headers: Vec<(String, String)>,
73 pub body_base64: String,
74}
75
76pub fn valid_id(value: &str) -> bool {
77 uuid::Uuid::parse_str(value).is_ok_and(|id| !id.is_nil() && id.to_string() == value)
78}
79
80pub fn node_base(cluster: &str, node: &str) -> Option<String> {
81 (valid_id(cluster) && valid_id(node)).then(|| format!("/clusters/{cluster}/nodes/{node}"))
82}
83
84pub fn route(path: &str) -> Option<(&str, &str, String)> {
87 fn scope(rest: &str) -> Option<(&str, &str, &str)> {
88 if rest.ends_with('/') {
89 return None;
90 }
91 let (cluster, rest) = rest.split_once("/nodes/")?;
92 let (node, suffix) = rest.split_once('/').unwrap_or((rest, ""));
93 (valid_id(cluster) && valid_id(node)).then_some((cluster, node, suffix))
94 }
95 if let Some(rest) = path.strip_prefix("/clusters/") {
96 let (cluster, node, suffix) = scope(rest)?;
97 let native = format!("/{suffix}");
98 return (matches!(native.as_str(), "/connect" | "/control" | "/manage")
99 || valid_path(&native))
100 .then_some((cluster, node, native));
101 }
102 for (public, native, suffix) in [
103 (
104 "/.well-known/oauth-authorization-server/clusters/",
105 "/.well-known/oauth-authorization-server",
106 "",
107 ),
108 (
109 "/.well-known/oauth-protected-resource/clusters/",
110 "/.well-known/oauth-protected-resource/mcp",
111 "mcp",
112 ),
113 ] {
114 if let Some(rest) = path.strip_prefix(public) {
115 let (cluster, node, tail) = scope(rest)?;
116 return (tail == suffix).then_some((cluster, node, native.into()));
117 }
118 }
119 None
120}
121
122pub fn valid_path(path: &str) -> bool {
123 if path.len() > 8192 || path.contains('#') || path.chars().any(char::is_control) {
124 return false;
125 }
126 let (path, query) = path
127 .split_once('?')
128 .map_or((path, false), |(p, _)| (p, true));
129 if query && !matches!(path, "/oauth/authorize" | "/oauth/continue") {
130 return false;
131 }
132 capability_token(path).is_some()
133 || matches!(
134 path,
135 "/mcp"
136 | "/.well-known/oauth-protected-resource"
137 | "/.well-known/oauth-protected-resource/mcp"
138 | "/.well-known/oauth-authorization-server"
139 | "/oauth/authorize"
140 | "/oauth/continue"
141 | "/oauth/token"
142 )
143}
144
145pub fn capability_token(path: &str) -> Option<&str> {
148 let token = path.strip_prefix("/mcp/")?;
149 let rest = token.strip_prefix("gent_g1.")?;
150 let (id, secret) = rest.split_once('.')?;
151 (valid_id(id)
152 && secret.len() == 64
153 && secret
154 .bytes()
155 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)))
156 .then_some(token)
157}
158
159pub fn request_header(name: &str) -> bool {
160 matches!(
161 name,
162 "authorization"
163 | "content-type"
164 | "accept"
165 | "origin"
166 | "mcp-protocol-version"
167 | "mcp-session-id"
168 | "last-event-id"
169 | "mcp-method"
170 | "mcp-name"
171 ) || name.strip_prefix("mcp-param-").is_some_and(|suffix| {
172 !suffix.is_empty()
173 && suffix
174 .bytes()
175 .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'-' | b'_'))
176 })
177}
178
179pub fn response_header(name: &str) -> bool {
180 matches!(
181 name,
182 "content-type"
183 | "location"
184 | "www-authenticate"
185 | "retry-after"
186 | "cache-control"
187 | "referrer-policy"
188 | "x-content-type-options"
189 | "content-security-policy"
190 | "mcp-protocol-version"
191 | "mcp-session-id"
192 | "allow"
193 )
194}
195
196fn valid_headers(headers: &[(String, String)], allowed: fn(&str) -> bool) -> bool {
197 let mut seen = std::collections::BTreeSet::new();
198 headers.len() <= 24
199 && headers
200 .iter()
201 .map(|(k, v)| k.len() + v.len())
202 .sum::<usize>()
203 <= MAX_HEADER_BYTES
204 && headers.iter().all(|(k, v)| {
205 allowed(k)
206 && seen.insert(k)
207 && v.is_ascii()
208 && !v.bytes().any(|b| b.is_ascii_control() && b != b'\t')
209 })
210}
211
212impl HttpRequest {
213 pub fn valid(&self) -> bool {
214 valid_id(&self.id)
215 && matches!(
216 self.method.as_str(),
217 "GET" | "POST" | "DELETE" | "HEAD" | "OPTIONS"
218 )
219 && valid_path(&self.path)
220 && valid_headers(&self.headers, request_header)
221 && self.body_base64.len() <= MAX_ENCODED_BYTES
222 }
223}
224
225impl HttpResponse {
226 pub fn valid(&self) -> bool {
227 valid_id(&self.id)
228 && (200..=599).contains(&self.status)
229 && valid_headers(&self.headers, response_header)
230 && self.body_base64.len() <= MAX_ENCODED_BYTES
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 const NODE: &str = "f84ce64e-2200-40b0-bc1d-cd64295d9c85";
238 const CLUSTER: &str = "629ec806-dc35-4c93-a174-38133d5b99f7";
239
240 #[test]
241 fn discovery_and_mcp_routes_keep_the_exact_node() {
242 for (public, expected) in [
243 (format!("/clusters/{CLUSTER}/nodes/{NODE}/mcp"), "/mcp"),
244 (
245 format!("/clusters/{CLUSTER}/nodes/{NODE}/oauth/token"),
246 "/oauth/token",
247 ),
248 (
249 format!("/clusters/{CLUSTER}/nodes/{NODE}/connect"),
250 "/connect",
251 ),
252 (
253 format!("/.well-known/oauth-authorization-server/clusters/{CLUSTER}/nodes/{NODE}"),
254 "/.well-known/oauth-authorization-server",
255 ),
256 (
257 format!(
258 "/.well-known/oauth-protected-resource/clusters/{CLUSTER}/nodes/{NODE}/mcp"
259 ),
260 "/.well-known/oauth-protected-resource/mcp",
261 ),
262 ] {
263 assert_eq!(
264 route(&public),
265 Some((CLUSTER, NODE, expected.into())),
266 "{public}"
267 );
268 }
269 for path in [
270 format!("/clusters/{CLUSTER}/nodes/{NODE}/../../oauth/token"),
271 format!("/clusters/{CLUSTER}/nodes/{NODE}/%6dcp"),
272 format!("/clusters/{CLUSTER}/nodes/{NODE}/mcp/"),
273 format!(
274 "/.well-known/oauth-authorization-server/clusters/{CLUSTER}/nodes/{NODE}/other"
275 ),
276 "/nodes/00000000-0000-0000-0000-000000000000/mcp".into(),
277 "/nodes/not-a-node/mcp".into(),
278 ] {
279 assert!(route(&path).is_none(), "{path}");
280 }
281 }
282
283 #[test]
284 fn connector_urls_have_one_canonical_route_and_keep_cluster_and_node_scope() {
285 let token = format!("gent_g1.{NODE}.{}", "a".repeat(64));
286 let native = format!("/mcp/{token}");
287 assert_eq!(capability_token(&native), Some(token.as_str()));
288 assert_eq!(
289 route(&format!("/clusters/{CLUSTER}/nodes/{NODE}{native}")),
290 Some((CLUSTER, NODE, native.clone()))
291 );
292 for invalid in [
293 format!("{native}/"),
294 format!("{native}?x=y"),
295 native.replace("gent_g1.", "gent_a1."),
296 native.replace("gent_g1", "%67ent_g1"),
297 native.replace(NODE, "00000000-0000-0000-0000-000000000000"),
298 ] {
299 assert!(!valid_path(&invalid));
300 assert!(capability_token(&invalid).is_none());
301 }
302 }
303
304 #[test]
305 fn wire_boundary_rejects_proxy_authority_header_injection_and_unbounded_bodies() {
306 let mut request = HttpRequest {
307 id: NODE.into(),
308 method: "POST".into(),
309 path: "/mcp".into(),
310 headers: vec![("authorization".into(), "Bearer opaque".into())],
311 body_base64: String::new(),
312 };
313 assert!(request.valid());
314 request
315 .headers
316 .push(("authorization".into(), "Bearer other".into()));
317 assert!(!request.valid());
318 for (name, value) in [
319 ("host", "evil.example"),
320 ("forwarded", "host=evil.example"),
321 ("authorization", "Bearer a\r\nx-injected:1"),
322 ] {
323 request.headers = vec![(name.into(), value.into())];
324 assert!(!request.valid());
325 }
326 request.headers.clear();
327 request.path = "/mcp?access_token=secret".into();
328 assert!(!request.valid());
329 request.path = "/oauth/authorize?client_id=host&state=opaque%2Fvalue".into();
330 assert!(request.valid());
331 request.body_base64 = "a".repeat(MAX_ENCODED_BYTES + 1);
332 assert!(!request.valid());
333 }
334}