1use crate::{StorageError, StorageErrorCode};
4
5pub fn validate_folder_id(id: &str) -> Result<(), StorageError> {
6 let parts: Vec<_> = id.split('/').collect();
7 let valid = id.len() <= 1024
8 && parts.len() <= 16
9 && parts.iter().all(|part| {
10 !part.is_empty()
11 && *part == part.trim()
12 && *part != "."
13 && *part != ".."
14 && part.chars().count() <= 80
15 && !part.chars().any(|c| c.is_control() || c == '\\')
16 })
17 && match parts.first().copied() {
18 Some("artifact") => parts.len() == 1,
19 Some("home") => parts.len() >= 2,
20 Some("plugin") => parts.len() >= 4,
21 Some("core") => parts.len() >= 3,
22 _ => false,
23 };
24 if valid {
25 Ok(())
26 } else {
27 Err(StorageError::new(StorageErrorCode::InvalidInput, "Invalid Folder path: use home/<path>, plugin/<name>/<instance>/<path>, or core/<module>/<path>; artifact is reserved"))
28 }
29}
30
31pub fn is_folder_within(id: &str, parent: &str) -> bool {
33 id == parent
34 || id
35 .strip_prefix(parent)
36 .is_some_and(|rest| rest.starts_with('/'))
37}
38
39#[cfg(test)]
40mod tests {
41 use super::*;
42 #[test]
43 fn paths_are_exact_bounded_and_segment_scoped() {
44 for id in [
45 "artifact",
46 "home/照片",
47 "home/a_b%/c",
48 "plugin/camera/one/recordings",
49 "core/cache/files",
50 ] {
51 assert!(validate_folder_id(id).is_ok(), "{id}");
52 }
53 for id in [
54 "",
55 "home",
56 "home/",
57 "/home/a",
58 "home/../b",
59 "home/a//b",
60 "home/ a",
61 "home/a\\b",
62 "artifact/a",
63 "plugin/camera/a",
64 "other/a",
65 ] {
66 assert!(validate_folder_id(id).is_err(), "{id}");
67 }
68 assert!(is_folder_within("home/a/b", "home/a"));
69 assert!(!is_folder_within("home/ab", "home/a"));
70 assert!(!is_folder_within("home/A", "home/a"));
71 }
72}