a2a_protocol_server/dispatch/
base_path.rs1use crate::error::{ServerError, ServerResult};
11
12impl super::DispatchConfig {
13 pub fn with_base_path(mut self, path: impl Into<String>) -> ServerResult<Self> {
23 self.base_path = normalized(&path.into())?;
24 Ok(self)
25 }
26}
27
28fn normalized(path: &str) -> ServerResult<Option<String>> {
31 let trimmed = path.strip_suffix('/').unwrap_or(path);
32 if trimmed.is_empty() {
33 return Ok(None);
34 }
35 let invalid = || {
36 ServerError::InvalidParams(format!(
37 "base path {path:?} must be \"/\" followed by segments of ASCII letters, digits \
38 and -._~ separated by \"/\""
39 ))
40 };
41 let segments = trimmed.strip_prefix('/').ok_or_else(invalid)?;
42 for segment in segments.split('/') {
43 let plain = segment
44 .bytes()
45 .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b));
46 if segment.is_empty() || segment == "." || segment == ".." || !plain {
47 return Err(invalid());
48 }
49 }
50 Ok(Some(trimmed.to_owned()))
51}
52
53fn under<'a>(path: &'a str, base: &str) -> Option<&'a str> {
57 let rest = path.strip_prefix(base)?;
58 if rest.is_empty() {
59 Some("/")
60 } else {
61 rest.starts_with('/').then_some(rest)
62 }
63}
64
65pub fn strip_base_path<B>(req: &mut hyper::Request<B>, base: Option<&str>) {
68 let Some(base) = base else {
69 return;
70 };
71 let Some(rest) = under(req.uri().path(), base) else {
72 return;
73 };
74 let path_and_query = req
75 .uri()
76 .query()
77 .map_or_else(|| rest.to_owned(), |query| format!("{rest}?{query}"));
78 let mut parts = req.uri().clone().into_parts();
79 let Ok(pq) = path_and_query.parse() else {
82 return;
83 };
84 parts.path_and_query = Some(pq);
85 if let Ok(uri) = hyper::Uri::from_parts(parts) {
86 *req.uri_mut() = uri;
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 fn req(uri: &str) -> hyper::Request<()> {
95 hyper::Request::builder().uri(uri).body(()).unwrap()
96 }
97
98 #[test]
99 fn a_path_under_the_base_loses_it_and_keeps_its_query() {
100 let mut r = req("/agents/billing/tasks/t1?historyLength=2");
101 strip_base_path(&mut r, Some("/agents/billing"));
102 assert_eq!(r.uri().path(), "/tasks/t1");
103 assert_eq!(r.uri().query(), Some("historyLength=2"));
104
105 let mut r = req("/agents/billing");
106 strip_base_path(&mut r, Some("/agents/billing"));
107 assert_eq!(r.uri(), "/");
108
109 let mut r = req("/agents/billing/");
110 strip_base_path(&mut r, Some("/agents/billing"));
111 assert_eq!(r.uri(), "/");
112 }
113
114 #[test]
117 fn an_absolute_uri_keeps_its_authority() {
118 let mut r = req("https://gw.example.com/agents/message:send");
119 strip_base_path(&mut r, Some("/agents"));
120 assert_eq!(r.uri(), "https://gw.example.com/message:send");
121 }
122
123 #[test]
124 fn a_path_outside_the_base_is_unchanged() {
125 for uri in ["/agentsX/tasks", "/tasks/agents", "/", "/age"] {
126 let mut r = req(uri);
127 strip_base_path(&mut r, Some("/agents"));
128 assert_eq!(r.uri(), uri);
129 }
130 let mut r = req("/agents/tasks");
131 strip_base_path(&mut r, None);
132 assert_eq!(r.uri(), "/agents/tasks", "no base, no change");
133 }
134
135 #[test]
136 fn under_matches_whole_segments() {
137 assert_eq!(under("/a/b/c", "/a/b"), Some("/c"));
138 assert_eq!(under("/a/b", "/a/b"), Some("/"));
139 assert_eq!(under("/a/bc", "/a/b"), None);
140 assert_eq!(under("/x/a/b", "/a/b"), None);
141 }
142
143 #[test]
144 fn a_base_path_is_normalized_or_refused() {
145 assert_eq!(normalized("/agents/").unwrap().as_deref(), Some("/agents"));
146 assert_eq!(normalized("/a/b").unwrap().as_deref(), Some("/a/b"));
147 assert_eq!(normalized("/").unwrap(), None);
148 assert_eq!(normalized("").unwrap(), None);
149 for bad in [
150 "a", "//", "/a//b", "/./a", "/a/..", "/a b", "/a%2F", "/{x}", "/é",
151 ] {
152 let err = normalized(bad).expect_err(bad);
153 assert!(err.to_string().contains("base path"), "{bad}: {err}");
154 }
155 }
156}