| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Rules for the names that make up paths. |
| 5 | //! |
| 6 | //! The store accepts nearly any name, about what `git fsck` accepts. It refuses |
| 7 | //! names that cannot be one path component, and names that some file system |
| 8 | //! would treat as `.braid` or `.git`: a crafted repository could otherwise |
| 9 | //! write into the metadata of the checkout that receives it. |
| 10 | |
| 11 | use core::fmt; |
| 12 | |
| 13 | use unicode_normalization::UnicodeNormalization; |
| 14 | |
| 15 | /// Longest name accepted, in bytes. |
| 16 | pub const MAX_NAME_BYTES: usize = 4096; |
| 17 | |
| 18 | /// Directory names that hold version control metadata. |
| 19 | const RESERVED: [&[u8]; 2] = [b".braid", b".git"]; |
| 20 | |
| 21 | /// Their 8.3 short-name stems (without the `~N` suffix). |
| 22 | const RESERVED_SHORT: [&[u8]; 2] = [b"braid", b"git"]; |
| 23 | |
| 24 | /// Files that git or braid read, and that must therefore never be symlinks. |
| 25 | const NO_SYMLINK: [&[u8]; 4] = [ |
| 26 | b".gitmodules", |
| 27 | b".gitignore", |
| 28 | b".gitattributes", |
| 29 | b".braidignore", |
| 30 | ]; |
| 31 | |
| 32 | /// Why a name is not accepted. |
| 33 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 34 | pub enum NameError { |
| 35 | /// The name is empty. |
| 36 | Empty, |
| 37 | /// The name is longer than [`MAX_NAME_BYTES`]. |
| 38 | TooLong(usize), |
| 39 | /// The name contains `/`. |
| 40 | Slash, |
| 41 | /// The name contains a NUL byte. |
| 42 | Nul, |
| 43 | /// The name is `.` or `..`. |
| 44 | DotOrDotDot, |
| 45 | /// Some file system would treat the name as `.braid` or `.git`. |
| 46 | Reserved, |
| 47 | } |
| 48 | |
| 49 | impl fmt::Display for NameError { |
| 50 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 51 | match self { |
| 52 | NameError::Empty => f.write_str("empty name"), |
| 53 | NameError::TooLong(len) => { |
| 54 | write!(f, "name of {len} bytes is longer than {MAX_NAME_BYTES}") |
| 55 | } |
| 56 | NameError::Slash => f.write_str("name contains '/'"), |
| 57 | NameError::Nul => f.write_str("name contains a NUL byte"), |
| 58 | NameError::DotOrDotDot => f.write_str("name is '.' or '..'"), |
| 59 | NameError::Reserved => { |
| 60 | f.write_str("name would be read as .braid or .git on some file system") |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | impl std::error::Error for NameError {} |
| 67 | |
| 68 | /// Why a path is not accepted. |
| 69 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 70 | pub enum PathError { |
| 71 | /// The component at this position (0-based) is not a valid name. An empty |
| 72 | /// component means a leading, trailing or doubled `/`. |
| 73 | Component { index: usize, error: NameError }, |
| 74 | } |
| 75 | |
| 76 | impl fmt::Display for PathError { |
| 77 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 78 | match self { |
| 79 | PathError::Component { index, error } => write!(f, "component {index}: {error}"), |
| 80 | } |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | impl std::error::Error for PathError {} |
| 85 | |
| 86 | /// Checks one name, as stored in a tree. |
| 87 | pub fn validate_name(name: &[u8]) -> Result<(), NameError> { |
| 88 | if name.is_empty() { |
| 89 | return Err(NameError::Empty); |
| 90 | } |
| 91 | if name.len() > MAX_NAME_BYTES { |
| 92 | return Err(NameError::TooLong(name.len())); |
| 93 | } |
| 94 | if name.contains(&b'/') { |
| 95 | return Err(NameError::Slash); |
| 96 | } |
| 97 | if name.contains(&0) { |
| 98 | return Err(NameError::Nul); |
| 99 | } |
| 100 | if name == b"." || name == b".." { |
| 101 | return Err(NameError::DotOrDotDot); |
| 102 | } |
| 103 | if is_reserved(name) { |
| 104 | return Err(NameError::Reserved); |
| 105 | } |
| 106 | Ok(()) |
| 107 | } |
| 108 | |
| 109 | /// Checks a path: names joined by single `/`, no leading or trailing `/`. |
| 110 | pub fn validate_path(path: &[u8]) -> Result<(), PathError> { |
| 111 | for (index, component) in path.split(|byte| *byte == b'/').enumerate() { |
| 112 | validate_name(component).map_err(|error| PathError::Component { index, error })?; |
| 113 | } |
| 114 | Ok(()) |
| 115 | } |
| 116 | |
| 117 | /// Whether some file system would treat `name` as `.braid` or `.git`. |
| 118 | pub fn is_reserved(name: &[u8]) -> bool { |
| 119 | let folded = fold_for_aliases(name); |
| 120 | RESERVED.contains(&folded.as_slice()) || is_short_name(&folded) |
| 121 | } |
| 122 | |
| 123 | /// Whether `name` must not be a symlink. |
| 124 | pub fn forbidden_as_symlink(name: &[u8]) -> bool { |
| 125 | NO_SYMLINK.contains(&fold_for_aliases(name).as_slice()) |
| 126 | } |
| 127 | |
| 128 | /// The name as the most forgiving file systems would compare it: without the |
| 129 | /// code points HFS+ ignores, in Unicode NFC, lowercased, and without anything |
| 130 | /// from the first `:` on (NTFS streams) or trailing dots and spaces (NTFS). |
| 131 | /// |
| 132 | /// Only meant to detect aliases of special names; checkouts use a fold that |
| 133 | /// matches the file system they write to. |
| 134 | pub fn fold_for_aliases(name: &[u8]) -> Vec<u8> { |
| 135 | let mut folded = match core::str::from_utf8(name) { |
| 136 | Ok(text) => text |
| 137 | .chars() |
| 138 | .filter(|c| !is_hfs_ignorable(*c)) |
| 139 | .nfc() |
| 140 | .flat_map(char::to_lowercase) |
| 141 | .collect::<String>() |
| 142 | .into_bytes(), |
| 143 | // A name that is not UTF-8 can only alias an ASCII name byte for byte. |
| 144 | Err(_) => name.to_ascii_lowercase(), |
| 145 | }; |
| 146 | if let Some(colon) = folded.iter().position(|byte| *byte == b':') { |
| 147 | folded.truncate(colon); |
| 148 | } |
| 149 | while matches!(folded.last(), Some(b'.' | b' ')) { |
| 150 | folded.pop(); |
| 151 | } |
| 152 | folded |
| 153 | } |
| 154 | |
| 155 | /// Code points that HFS+ drops when it compares names. |
| 156 | fn is_hfs_ignorable(c: char) -> bool { |
| 157 | matches!( |
| 158 | c, |
| 159 | '\u{200c}'..='\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{206a}'..='\u{206f}' | '\u{feff}' |
| 160 | ) |
| 161 | } |
| 162 | |
| 163 | /// `braid~N` or `git~N`: the 8.3 short names NTFS can give `.braid` and `.git`. |
| 164 | fn is_short_name(folded: &[u8]) -> bool { |
| 165 | RESERVED_SHORT.iter().any(|stem| { |
| 166 | folded.len() == stem.len() + 2 |
| 167 | && folded.starts_with(stem) |
| 168 | && folded[stem.len()] == b'~' |
| 169 | && matches!(folded[stem.len() + 1], b'1'..=b'9') |
| 170 | }) |
| 171 | } |
| 172 | |
| 173 | #[cfg(test)] |
| 174 | mod tests { |
| 175 | use super::*; |
| 176 | |
| 177 | #[test] |
| 178 | fn accepts_ordinary_names() { |
| 179 | for name in [ |
| 180 | &b"README.md"[..], |
| 181 | b"src", |
| 182 | b".github", |
| 183 | b".gitkeep", |
| 184 | b".git-blame-ignore-revs", |
| 185 | b"git", |
| 186 | b"braid", |
| 187 | b"...", |
| 188 | b"a b", |
| 189 | b"caf\xc3\xa9", |
| 190 | b"\xff\xfe", |
| 191 | b"git~10", |
| 192 | ] { |
| 193 | assert_eq!( |
| 194 | validate_name(name), |
| 195 | Ok(()), |
| 196 | "{:?}", |
| 197 | String::from_utf8_lossy(name) |
| 198 | ); |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn rejects_structural_problems() { |
| 204 | assert_eq!(validate_name(b""), Err(NameError::Empty)); |
| 205 | assert_eq!(validate_name(b"a/b"), Err(NameError::Slash)); |
| 206 | assert_eq!(validate_name(b"a\0b"), Err(NameError::Nul)); |
| 207 | assert_eq!(validate_name(b"."), Err(NameError::DotOrDotDot)); |
| 208 | assert_eq!(validate_name(b".."), Err(NameError::DotOrDotDot)); |
| 209 | let long = vec![b'a'; MAX_NAME_BYTES + 1]; |
| 210 | assert_eq!( |
| 211 | validate_name(&long), |
| 212 | Err(NameError::TooLong(MAX_NAME_BYTES + 1)) |
| 213 | ); |
| 214 | assert_eq!(validate_name(&long[..MAX_NAME_BYTES]), Ok(())); |
| 215 | } |
| 216 | |
| 217 | #[test] |
| 218 | fn rejects_aliases_of_metadata_directories() { |
| 219 | let aliases: &[&str] = &[ |
| 220 | ".git", |
| 221 | ".braid", |
| 222 | ".GIT", |
| 223 | ".Braid", |
| 224 | ".git.", |
| 225 | ".git ", |
| 226 | ".git . .", |
| 227 | ".git::$INDEX_ALLOCATION", |
| 228 | ".braid:stream", |
| 229 | "GIT~1", |
| 230 | "git~2", |
| 231 | "BRAID~1", |
| 232 | // HFS+ ignores these code points. |
| 233 | ".g\u{200c}it", |
| 234 | "\u{feff}.git", |
| 235 | ".bra\u{206f}id", |
| 236 | ]; |
| 237 | for alias in aliases { |
| 238 | assert_eq!( |
| 239 | validate_name(alias.as_bytes()), |
| 240 | Err(NameError::Reserved), |
| 241 | "{alias:?}" |
| 242 | ); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn unicode_normalisation_is_applied() { |
| 248 | // "é" precomposed and decomposed fold to the same bytes. |
| 249 | assert_eq!( |
| 250 | fold_for_aliases("caf\u{e9}".as_bytes()), |
| 251 | fold_for_aliases("cafe\u{301}".as_bytes()) |
| 252 | ); |
| 253 | } |
| 254 | |
| 255 | #[test] |
| 256 | fn symlink_restrictions() { |
| 257 | assert!(forbidden_as_symlink(b".gitmodules")); |
| 258 | assert!(forbidden_as_symlink(b".GITIGNORE")); |
| 259 | assert!(forbidden_as_symlink(b".braidignore.")); |
| 260 | assert!(forbidden_as_symlink(".gitattr\u{200d}ibutes".as_bytes())); |
| 261 | assert!(!forbidden_as_symlink(b"gitmodules")); |
| 262 | assert!(!forbidden_as_symlink(b"README")); |
| 263 | } |
| 264 | |
| 265 | #[test] |
| 266 | fn paths() { |
| 267 | assert_eq!(validate_path(b"a"), Ok(())); |
| 268 | assert_eq!(validate_path(b"a/b/c.txt"), Ok(())); |
| 269 | let empty = |index| PathError::Component { |
| 270 | index, |
| 271 | error: NameError::Empty, |
| 272 | }; |
| 273 | assert_eq!(validate_path(b""), Err(empty(0))); |
| 274 | assert_eq!(validate_path(b"/a"), Err(empty(0))); |
| 275 | assert_eq!(validate_path(b"a/"), Err(empty(1))); |
| 276 | assert_eq!(validate_path(b"a//b"), Err(empty(1))); |
| 277 | assert_eq!( |
| 278 | validate_path(b"a/.git/config"), |
| 279 | Err(PathError::Component { |
| 280 | index: 1, |
| 281 | error: NameError::Reserved |
| 282 | }) |
| 283 | ); |
| 284 | assert_eq!( |
| 285 | validate_path(b"a/../b"), |
| 286 | Err(PathError::Component { |
| 287 | index: 1, |
| 288 | error: NameError::DotOrDotDot |
| 289 | }) |
| 290 | ); |
| 291 | } |
| 292 | } |