pub fn base_normalize(base: &str) -> Result<String, String> {
let base = base.trim();
if base.is_empty() || base.chars().all(|c| c == '/') {
return Ok(String::new());
}
let core = base.strip_prefix('/').unwrap_or(base);
let core = core.strip_suffix('/').unwrap_or(core);
for segment in core.split('/') {
if segment.is_empty() {
return Err("empty path segment (`//`)".into());
}
if segment == "." || segment == ".." {
return Err(format!("invalid path segment `{segment}`"));
}
if !segment
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.' | '~'))
{
return Err(format!("invalid character in `{segment}`"));
}
}
Ok(format!("/{core}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn base_normalize_normalizes() {
assert_eq!(base_normalize("").unwrap(), "");
assert_eq!(base_normalize("/").unwrap(), "");
assert_eq!(base_normalize("///").unwrap(), "");
assert_eq!(base_normalize("app").unwrap(), "/app");
assert_eq!(base_normalize("app/").unwrap(), "/app");
assert_eq!(base_normalize("/app/").unwrap(), "/app");
assert_eq!(base_normalize(" /app ").unwrap(), "/app");
assert_eq!(base_normalize("/a/b").unwrap(), "/a/b");
}
#[test]
fn invalid_base_is_rejected() {
for base in [
"//app",
"app//sub",
"/app/../x",
"/app/./x",
"/app?x=1",
"/app#x",
"/{*x}",
"/a:b",
"/a b",
"/a%20b",
"\\app",
"https://example.com/app",
] {
assert!(base_normalize(base).is_err(), "`{base}` must be rejected");
}
}
}