Skip to main content

shardline_validation/
validation.rs

1use thiserror::Error;
2
3/// Maximum byte length for a validated file identifier.
4const MAX_IDENTIFIER_BYTES: usize = 1024;
5
6/// Validates that a content hash is exactly 64 lowercase hex characters.
7///
8/// # Errors
9///
10/// Returns an error with the given `error_fn` when the hash is malformed.
11pub fn validate_content_hash_with<E>(value: &str, error_fn: fn() -> E) -> Result<(), E> {
12    if value.len() != 64
13        || !value
14            .bytes()
15            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
16    {
17        return Err(error_fn());
18    }
19    Ok(())
20}
21
22/// Validates that a file identifier is safe for use as a single path component.
23///
24/// Rejects empty or `.` values, absolute paths, `..` traversal, backslashes,
25/// control characters, and identifiers longer than 1024 bytes.
26///
27/// # Examples
28///
29/// ```
30/// use shardline_validation::validate_identifier;
31///
32/// assert!(validate_identifier("models.bin").is_ok());
33/// assert!(validate_identifier("nested/model.bin").is_err(), "no path separators");
34/// assert!(validate_identifier("../secret").is_err(), "no traversal");
35/// assert!(validate_identifier("/etc/passwd").is_err(), "no absolute paths");
36/// ```
37///
38/// # Errors
39///
40/// Returns [`ValidateIdentifierError`] if the identifier is empty, contains
41/// path separators, traversal sequences, control characters, or exceeds the
42/// maximum byte length.
43pub fn validate_identifier(value: &str) -> Result<(), ValidateIdentifierError> {
44    if value.trim().is_empty()
45        || value == "."
46        || value.len() > MAX_IDENTIFIER_BYTES
47        || value.starts_with('/')
48        || value.contains("..")
49        || value.contains('\\')
50        || value.contains('/')
51        || value.chars().any(char::is_control)
52    {
53        return Err(ValidateIdentifierError);
54    }
55
56    Ok(())
57}
58
59/// File identifier validation failure.
60#[derive(Debug, Clone, Copy, Error)]
61#[error("file identifier must be relative and must not contain traversal or control characters")]
62pub struct ValidateIdentifierError;
63
64/// Validates that a content hash is exactly 64 lowercase hex characters.
65///
66/// # Examples
67///
68/// ```
69/// use shardline_validation::validate_content_hash;
70///
71/// let hash = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
72/// assert!(validate_content_hash(hash).is_ok());
73/// assert!(validate_content_hash("short").is_err());
74/// ```
75///
76/// # Errors
77///
78/// Returns [`ValidateContentHashError`] if the hash is malformed.
79pub fn validate_content_hash(value: &str) -> Result<(), ValidateContentHashError> {
80    if value.len() != 64
81        || !value
82            .bytes()
83            .all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
84    {
85        return Err(ValidateContentHashError);
86    }
87
88    Ok(())
89}
90
91/// Content hash validation failure.
92#[derive(Debug, Clone, Copy, Error)]
93#[error("content hash must be 64 hexadecimal characters")]
94pub struct ValidateContentHashError;
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99
100    #[test]
101    fn validate_identifier_accepts_simple_name() {
102        assert!(validate_identifier("hello.txt").is_ok());
103    }
104
105    #[test]
106    fn validate_identifier_accepts_dotted_name() {
107        assert!(validate_identifier("file.name.txt").is_ok());
108    }
109
110    #[test]
111    fn validate_identifier_rejects_empty() {
112        assert!(validate_identifier("").is_err());
113    }
114
115    #[test]
116    fn validate_identifier_rejects_whitespace_only() {
117        assert!(validate_identifier("   ").is_err());
118    }
119
120    #[test]
121    fn validate_identifier_rejects_dot() {
122        assert!(validate_identifier(".").is_err());
123    }
124
125    #[test]
126    fn validate_identifier_rejects_leading_slash() {
127        assert!(validate_identifier("/etc/passwd").is_err());
128    }
129
130    #[test]
131    fn validate_identifier_rejects_traversal() {
132        assert!(validate_identifier("foo/../bar").is_err());
133    }
134
135    #[test]
136    fn validate_identifier_rejects_backslash() {
137        assert!(validate_identifier("foo\\bar").is_err());
138    }
139
140    #[test]
141    fn validate_identifier_rejects_control_char() {
142        assert!(validate_identifier("foo\tbar").is_err());
143    }
144
145    #[test]
146    fn validate_identifier_rejects_null_byte() {
147        assert!(validate_identifier("foo\0bar").is_err());
148        assert!(validate_identifier("\0").is_err());
149        assert!(validate_identifier("null\0end").is_err());
150    }
151
152    #[test]
153    fn validate_content_hash_accepts_valid_hash() {
154        let hash = "a".repeat(64);
155        assert!(validate_content_hash(&hash).is_ok());
156    }
157
158    #[test]
159    fn validate_content_hash_rejects_too_short() {
160        assert!(validate_content_hash("abc123").is_err());
161    }
162
163    #[test]
164    fn validate_content_hash_rejects_too_long() {
165        let hash = "a".repeat(65);
166        assert!(validate_content_hash(&hash).is_err());
167    }
168
169    #[test]
170    fn validate_content_hash_rejects_uppercase() {
171        let hash = "A".repeat(64);
172        assert!(validate_content_hash(&hash).is_err());
173    }
174
175    #[test]
176    fn validate_content_hash_rejects_non_hex() {
177        let mut hash = "a".repeat(64);
178        hash.push('g');
179        hash.remove(0);
180        assert!(validate_content_hash(&hash).is_err());
181    }
182
183    #[test]
184    fn validate_content_hash_with_valid_64_hex() {
185        let hash = "0123456789abcdef".repeat(4);
186        assert!(validate_content_hash_with(&hash, || ()).is_ok());
187    }
188
189    #[test]
190    fn validate_content_hash_with_too_short() {
191        assert!(validate_content_hash_with("abc123", || ()).is_err());
192    }
193
194    #[test]
195    fn validate_content_hash_with_uppercase_rejected() {
196        let hash = "A".repeat(64);
197        assert!(validate_content_hash_with(&hash, || ()).is_err());
198    }
199
200    #[test]
201    fn validate_content_hash_with_non_hex_rejected() {
202        let hash = format!("{}g{}", "a".repeat(62), "a");
203        assert!(validate_content_hash_with(&hash, || ()).is_err());
204    }
205
206    #[test]
207    fn validate_identifier_error_display() {
208        let msg = ValidateIdentifierError.to_string();
209        assert!(!msg.is_empty());
210        assert!(msg.contains("identifier"));
211    }
212
213    #[test]
214    fn validate_content_hash_error_display() {
215        let msg = ValidateContentHashError.to_string();
216        assert!(!msg.is_empty());
217        assert!(msg.contains("hexadecimal"));
218    }
219}