1use std::fmt;
3
4use crate::sanitize;
5
6#[derive(Clone, Debug, PartialEq, Eq)]
10pub struct LinkBase {
11 page: Address,
12 root: Option<Root>,
13}
14
15#[derive(Clone, Debug, PartialEq, Eq)]
17struct Root {
18 prefix: String,
19 address: Address,
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
24struct Address {
25 url: String,
26 origin_end: usize,
27 path_end: usize,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum LinkBaseError {
34 TooLong,
36 Unprintable,
38 NotHttp,
40 BadHost,
42 BadPrefix,
44}
45
46impl fmt::Display for LinkBaseError {
47 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 Self::TooLong => write!(formatter, "the link base is longer than {} bytes", sanitize::MAX_LINK_BYTES),
50 Self::Unprintable => formatter.write_str("the link base holds a character outside printable ASCII"),
51 Self::NotHttp => formatter.write_str("the link base is not an absolute http or https URL"),
52 Self::BadHost => formatter.write_str("the link base names no plain host"),
53 Self::BadPrefix => formatter.write_str("the link root's prefix is not a path starting with /"),
54 }
55 }
56}
57
58impl std::error::Error for LinkBaseError {}
59
60impl LinkBase {
61 pub fn new(page_url: &str) -> Result<Self, LinkBaseError> {
63 Ok(Self { page: Address::new(page_url)?, root: None })
64 }
65
66 pub fn rooted_at(self, prefix: &str, root_url: &str) -> Result<Self, LinkBaseError> {
71 let is_path = prefix.starts_with('/') && prefix.bytes().all(|byte| byte.is_ascii_graphic());
72 if !is_path {
73 return Err(LinkBaseError::BadPrefix);
74 }
75 Ok(Self { root: Some(Root { prefix: prefix.to_owned(), address: Address::new(root_url)? }), ..self })
76 }
77
78 pub fn as_str(&self) -> &str {
80 &self.page.url
81 }
82
83 pub(crate) fn resolve(&self, target: &str) -> String {
87 let target = sanitize::text(target);
88 if sanitize::scheme(&target).is_some() {
89 return target;
90 }
91 let page = &self.page;
92 match target.as_bytes() {
93 [] => page.url.clone(),
94 [b'/', b'/', ..] => format!("{}:{target}", sanitize::scheme(&page.url).unwrap_or_default()),
95 [b'?', ..] => format!("{}{}{target}", page.origin(), page.path()),
96 [b'#', ..] => format!("{}{}{}{target}", page.origin(), page.path(), page.query()),
97 [b'/', ..] => self.root_relative(&without_dot_segments(&target)),
98 _ => format!("{}{}", page.origin(), without_dot_segments(&format!("{}{target}", page.folder()))),
99 }
100 }
101
102 fn root_relative(&self, target: &str) -> String {
103 match &self.root {
104 Some(root) if target.starts_with(&root.prefix) => {
105 format!("{}{}{target}", root.address.origin(), root.address.path().trim_end_matches('/'))
106 }
107 _ => format!("{}{target}", self.page.origin()),
108 }
109 }
110}
111
112impl Address {
113 fn new(url: &str) -> Result<Self, LinkBaseError> {
114 let url = url.split_once('#').map_or(url, |(page, _)| page);
115 if url.len() > sanitize::MAX_LINK_BYTES {
116 return Err(LinkBaseError::TooLong);
117 }
118 if !url.bytes().all(|byte| byte.is_ascii_graphic()) {
119 return Err(LinkBaseError::Unprintable);
120 }
121 let scheme = sanitize::scheme(url).filter(|scheme| is_http(scheme)).ok_or(LinkBaseError::NotHttp)?;
122 let after_slashes = url[scheme.len() + 1..].strip_prefix("//").ok_or(LinkBaseError::NotHttp)?;
123 let host = &after_slashes[..after_slashes.find(['/', '?']).unwrap_or(after_slashes.len())];
124 if host.is_empty() || host.contains(['@', '\\']) {
125 return Err(LinkBaseError::BadHost);
126 }
127 let origin_end = url.len() - after_slashes.len() + host.len();
128 let path_end = url.find('?').unwrap_or(url.len());
129 Ok(Self { url: url.to_owned(), origin_end, path_end })
130 }
131
132 fn origin(&self) -> &str {
133 &self.url[..self.origin_end]
134 }
135
136 fn path(&self) -> &str {
138 let path = &self.url[self.origin_end..self.path_end];
139 if path.is_empty() { "/" } else { path }
140 }
141
142 fn folder(&self) -> &str {
143 let path = self.path();
144 &path[..=path.rfind('/').unwrap_or(0)]
145 }
146
147 fn query(&self) -> &str {
148 &self.url[self.path_end..]
149 }
150}
151
152fn is_http(scheme: &str) -> bool {
153 scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")
154}
155
156fn without_dot_segments(target: &str) -> String {
160 let (path, rest) = target.split_at(target.find(['?', '#']).unwrap_or(target.len()));
161 let path = path.replace('\\', "/");
162 let mut kept = Vec::new();
163 for segment in path.split('/').skip(1) {
164 match dot_segment(segment) {
165 Some(".") => {}
166 Some(_) => {
167 kept.pop();
168 }
169 None => kept.push(segment),
170 }
171 }
172 if path.rsplit('/').next().and_then(dot_segment).is_some() {
173 kept.push("");
174 }
175 format!("/{}{rest}", kept.join("/"))
176}
177
178fn dot_segment(segment: &str) -> Option<&'static str> {
180 match segment.to_ascii_lowercase().replace("%2e", ".").as_str() {
181 "." => Some("."),
182 ".." => Some(".."),
183 _ => None,
184 }
185}
186
187#[cfg(test)]
188mod tests {
189 #![allow(clippy::unwrap_used)]
190
191 use super::*;
192
193 const BASE: &str = "https://gitlab.example.com/group/project/-/merge_requests/7?tab=notes#note_1";
194
195 fn resolved(target: &str) -> String {
196 LinkBase::new(BASE).unwrap().resolve(target)
197 }
198
199 #[test]
200 fn a_root_relative_target_starts_at_the_host() {
201 assert_eq!(resolved("/uploads/ab12/report.pdf"), "https://gitlab.example.com/uploads/ab12/report.pdf");
202 }
203
204 #[test]
205 fn a_relative_target_starts_in_the_page_folder() {
206 assert_eq!(resolved("docs/x.md"), "https://gitlab.example.com/group/project/-/merge_requests/docs/x.md");
207 assert_eq!(resolved("./docs/x.md"), "https://gitlab.example.com/group/project/-/merge_requests/docs/x.md");
208 }
209
210 #[test]
211 fn dot_dot_climbs_folders_but_never_above_the_host() {
212 assert_eq!(resolved("../../blob/main/a.rs#L3"), "https://gitlab.example.com/group/project/blob/main/a.rs#L3");
213 assert_eq!(resolved("/a/../../../b"), "https://gitlab.example.com/b");
214 assert_eq!(resolved(".."), "https://gitlab.example.com/group/project/-/");
215 }
216
217 #[test]
218 fn the_rfc_3986_examples_resolve_as_the_rfc_says() {
219 let base = LinkBase::new("http://a/b/c/d;p?q").unwrap();
220 let cases = [
221 ("g:h", "g:h"),
222 ("g", "http://a/b/c/g"),
223 ("./g", "http://a/b/c/g"),
224 ("g/", "http://a/b/c/g/"),
225 ("/g", "http://a/g"),
226 ("//g", "http://g"),
227 ("?y", "http://a/b/c/d;p?y"),
228 ("g?y", "http://a/b/c/g?y"),
229 ("#s", "http://a/b/c/d;p?q#s"),
230 ("g#s", "http://a/b/c/g#s"),
231 ("g?y#s", "http://a/b/c/g?y#s"),
232 (";x", "http://a/b/c/;x"),
233 ("g;x", "http://a/b/c/g;x"),
234 ("g;x?y#s", "http://a/b/c/g;x?y#s"),
235 ("", "http://a/b/c/d;p?q"),
236 (".", "http://a/b/c/"),
237 ("./", "http://a/b/c/"),
238 ("..", "http://a/b/"),
239 ("../", "http://a/b/"),
240 ("../g", "http://a/b/g"),
241 ("../..", "http://a/"),
242 ("../../", "http://a/"),
243 ("../../g", "http://a/g"),
244 ("../../../g", "http://a/g"),
245 ("../../../../g", "http://a/g"),
246 ("/./g", "http://a/g"),
247 ("/../g", "http://a/g"),
248 ("g.", "http://a/b/c/g."),
249 (".g", "http://a/b/c/.g"),
250 ("g..", "http://a/b/c/g.."),
251 ("..g", "http://a/b/c/..g"),
252 ("./../g", "http://a/b/g"),
253 ("./g/.", "http://a/b/c/g/"),
254 ("g/./h", "http://a/b/c/g/h"),
255 ("g/../h", "http://a/b/c/h"),
256 ("g;x=1/./y", "http://a/b/c/g;x=1/y"),
257 ("g;x=1/../y", "http://a/b/c/y"),
258 ("g?y/./x", "http://a/b/c/g?y/./x"),
259 ("g?y/../x", "http://a/b/c/g?y/../x"),
260 ("g#s/./x", "http://a/b/c/g#s/./x"),
261 ("g#s/../x", "http://a/b/c/g#s/../x"),
262 ("http:g", "http:g"),
263 ];
264
265 for (target, expected) in cases {
266 assert_eq!(base.resolve(target), expected, "{target:?}");
267 }
268 }
269
270 #[test]
271 fn dot_segments_a_browser_reads_count_as_dot_segments() {
272 for target in ["/a/%2e%2E/%2e/b", "/a/.%2e/b", "/a\\..\\b", "/a/.\n./b"] {
273 assert_eq!(resolved(target), "https://gitlab.example.com/b", "{target:?}");
274 }
275 }
276
277 #[test]
278 fn a_scheme_split_by_a_control_is_still_a_scheme() {
279 assert_eq!(resolved("java\nscript:alert(1)"), "javascript:alert(1)");
280 }
281
282 #[test]
283 fn dot_segments_in_the_query_or_fragment_stay() {
284 assert_eq!(resolved("/a/./b?x=../y#./z"), "https://gitlab.example.com/a/b?x=../y#./z");
285 }
286
287 #[test]
288 fn a_query_or_fragment_alone_stays_on_the_page() {
289 assert_eq!(resolved("?tab=diffs"), "https://gitlab.example.com/group/project/-/merge_requests/7?tab=diffs");
290 assert_eq!(resolved("#note_2"), "https://gitlab.example.com/group/project/-/merge_requests/7?tab=notes#note_2");
291 }
292
293 #[test]
294 fn a_scheme_relative_target_takes_the_base_scheme() {
295 assert_eq!(resolved("//cdn.example.org/a.png"), "https://cdn.example.org/a.png");
296 }
297
298 #[test]
299 fn a_bare_host_reads_as_its_root() {
300 let base = LinkBase::new("http://forge.test").unwrap();
301
302 assert_eq!(base.resolve("a.md"), "http://forge.test/a.md");
303 assert_eq!(base.resolve("#top"), "http://forge.test/#top");
304 }
305
306 #[test]
307 fn a_target_with_a_scheme_is_left_as_written() {
308 for target in ["https://other.test/a", "mailto:me@x.y", "javascript:alert(1)", "data:text/html,<b>"] {
309 assert_eq!(resolved(target), target);
310 }
311 }
312
313 #[test]
314 fn the_base_drops_its_fragment() {
315 assert_eq!(LinkBase::new(BASE).unwrap().as_str(), "https://gitlab.example.com/group/project/-/merge_requests/7?tab=notes");
316 }
317
318 #[test]
319 fn a_base_that_is_not_a_plain_http_address_is_refused() {
320 let cases = [
321 ("javascript:alert(1)", LinkBaseError::NotHttp),
322 ("data:text/html,x", LinkBaseError::NotHttp),
323 ("file:///etc/", LinkBaseError::NotHttp),
324 ("ftp://host/", LinkBaseError::NotHttp),
325 ("/relative/path", LinkBaseError::NotHttp),
326 ("https:/host", LinkBaseError::NotHttp),
327 ("https:///path", LinkBaseError::BadHost),
328 ("https://user:pw@host/", LinkBaseError::BadHost),
329 ("https://host\\evil/", LinkBaseError::BadHost),
330 ("https://host/a\x1b]52;c;x\x07", LinkBaseError::Unprintable),
331 ("https://host/a\nb", LinkBaseError::Unprintable),
332 ("https://host/a b", LinkBaseError::Unprintable),
333 ("https://hôst/", LinkBaseError::Unprintable),
334 ];
335
336 for (base, error) in cases {
337 assert_eq!(LinkBase::new(base), Err(error), "{base:?}");
338 }
339 }
340
341 #[test]
342 fn a_base_over_the_link_limit_is_refused() {
343 let at_limit = format!("https://h/{}", "a".repeat(sanitize::MAX_LINK_BYTES - "https://h/".len()));
344
345 assert!(LinkBase::new(&at_limit).is_ok());
346 assert_eq!(LinkBase::new(&format!("{at_limit}a")), Err(LinkBaseError::TooLong));
347 }
348
349 const ROOT: &str = "https://gitlab.example.com/group/project";
350
351 fn rooted(prefix: &str, target: &str) -> String {
352 LinkBase::new(BASE).unwrap().rooted_at(prefix, ROOT).unwrap().resolve(target)
353 }
354
355 #[test]
356 fn a_gitlab_upload_resolves_under_the_project() {
357 assert_eq!(rooted("/uploads/", "/uploads/ab/x.pdf"), "https://gitlab.example.com/group/project/uploads/ab/x.pdf");
358 }
359
360 #[test]
361 fn a_root_relative_target_outside_the_prefix_starts_at_the_page_host() {
362 assert_eq!(rooted("/uploads/", "/other/group/-/issues/1"), "https://gitlab.example.com/other/group/-/issues/1");
363 assert_eq!(rooted("/uploads/", "/uploads/../secret"), "https://gitlab.example.com/secret");
364 }
365
366 #[test]
367 fn dot_dot_never_climbs_above_the_root() {
368 assert_eq!(rooted("/", "/a/../../../b?x#y"), "https://gitlab.example.com/group/project/b?x#y");
369 }
370
371 #[test]
372 fn an_encoded_or_split_dot_dot_never_climbs_above_the_root() {
373 for target in ["/uploads/%2e%2e/%2e%2e/%2e%2e/x", "/uploads\\..\\..\\..\\x", "/uploads/.\n./.\n./.\n./x"] {
374 assert_eq!(rooted("/uploads/", target), "https://gitlab.example.com/x", "{target:?}");
375 }
376 }
377
378 #[test]
379 fn a_root_changes_only_root_relative_targets() {
380 for target in ["docs/x.md", "../y", "?tab=diffs", "#note_2", "//cdn.example.org/a", "https://other.test/a"] {
381 assert_eq!(rooted("/", target), resolved(target), "{target}");
382 }
383 }
384
385 #[test]
386 fn a_root_may_sit_on_another_host_and_drops_its_query() {
387 let base = LinkBase::new(BASE).unwrap().rooted_at("/", "https://pages.example.org/site/?v=1#top").unwrap();
388
389 assert_eq!(base.resolve("/a.html"), "https://pages.example.org/site/a.html");
390 }
391
392 #[test]
393 fn a_root_is_checked_like_a_base() {
394 let base = || LinkBase::new(BASE).unwrap();
395
396 assert_eq!(base().rooted_at("/", "javascript:alert(1)"), Err(LinkBaseError::NotHttp));
397 assert_eq!(base().rooted_at("/", "https://h/\x1b]52;c;x\x07"), Err(LinkBaseError::Unprintable));
398 assert_eq!(base().rooted_at("/", "https://u@h/"), Err(LinkBaseError::BadHost));
399 for prefix in ["uploads/", "", "/a b", "/a\nb"] {
400 assert_eq!(base().rooted_at(prefix, ROOT), Err(LinkBaseError::BadPrefix), "{prefix:?}");
401 }
402 }
403}