safename 0.1.0

Filename and path validation for security hardening
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
//! Filename sanitization.

use crate::constants::{
    DEFAULT_MAX_FILE_LEN, DOT, DOTDOT, REPLACEMENT_CHAR, REPLACEMENT_UNDERSCORE,
};
use crate::error::{SafeNameError, SafeNameResult};
use crate::lookup::{BLOCKED_ALWAYS, BLOCKED_FINAL, BLOCKED_INITIAL};

/// Configuration for filename sanitization.
#[derive(Debug, Clone)]
pub struct FileSanitizationOptions<'a> {
    /// Replacement bytes for invalid characters (default: `_`)
    pub replacement: &'a [u8],
    /// Maximum filename length (default: 255)
    pub max_len: usize,
}

impl Default for FileSanitizationOptions<'_> {
    fn default() -> Self {
        Self {
            replacement: REPLACEMENT_UNDERSCORE,
            max_len: DEFAULT_MAX_FILE_LEN,
        }
    }
}

impl FileSanitizationOptions<'_> {
    /// Create options using Unicode replacement character (U+FFFD).
    pub fn with_unicode_replacement_char() -> Self {
        Self {
            replacement: REPLACEMENT_CHAR,
            ..Default::default()
        }
    }
}

/// Sanitizes a filename by replacing invalid bytes with underscore.
///
/// Accepts any type that can be referenced as bytes: `&[u8]`, `&str`, `String`,
/// `Vec<u8>`, etc. Empty input returns `Ok(replacement)` (default: `_`).
///
/// # Errors
///
/// Returns [`SafeNameError::InvalidLength`] if the sanitized result exceeds max length.
///
/// # Example
///
/// ```
/// use safename::sanitize_file;
///
/// // Leading dash replaced
/// assert_eq!(sanitize_file(b"-rf").unwrap(), b"_rf");
/// assert_eq!(sanitize_file("-rf").unwrap(), b"_rf");
///
/// // Control characters replaced
/// assert_eq!(sanitize_file(b"file\x00name").unwrap(), b"file_name");
///
/// // Valid filenames unchanged
/// assert_eq!(sanitize_file(b"normal.txt").unwrap(), b"normal.txt");
///
/// // Empty input becomes replacement character
/// assert_eq!(sanitize_file(b"").unwrap(), b"_");
/// ```
pub fn sanitize_file(filename: impl AsRef<[u8]>) -> SafeNameResult<Vec<u8>> {
    sanitize_file_with_options(filename, &FileSanitizationOptions::default())
}

/// Sanitizes a filename with custom options.
///
/// # Errors
///
/// Returns [`SafeNameError::InvalidLength`] if the sanitized result exceeds max length.
///
/// # Example
///
/// ```
/// use safename::{sanitize_file_with_options, FileSanitizationOptions, REPLACEMENT_CHAR};
///
/// let opts = FileSanitizationOptions {
///     replacement: REPLACEMENT_CHAR,
///     ..Default::default()
/// };
///
/// // Leading dash replaced with U+FFFD
/// assert_eq!(sanitize_file_with_options(b"-rf", &opts).unwrap(), b"\xEF\xBF\xBDrf");
/// assert_eq!(sanitize_file_with_options("-rf", &opts).unwrap(), b"\xEF\xBF\xBDrf");
///
/// // Or use any custom replacement
/// let opts = FileSanitizationOptions {
///     replacement: b"X",
///     ..Default::default()
/// };
/// assert_eq!(sanitize_file_with_options(b"-rf", &opts).unwrap(), b"Xrf");
/// ```
pub fn sanitize_file_with_options(
    filename: impl AsRef<[u8]>,
    options: &FileSanitizationOptions<'_>,
) -> SafeNameResult<Vec<u8>> {
    let filename = filename.as_ref();

    // Handle empty input
    if filename.is_empty() {
        return Ok(options.replacement.to_vec());
    }

    // Special case: "." and ".." are always valid
    if filename == DOT || filename == DOTDOT {
        return Ok(filename.to_vec());
    }

    let mut result = Vec::with_capacity(filename.len());
    let len = filename.len();
    let last_idx = len - 1;

    for (idx, &byte) in filename.iter().enumerate() {
        let byte_index = byte as usize;
        let is_blocked = BLOCKED_ALWAYS[byte_index]
            || (idx == 0 && BLOCKED_INITIAL[byte_index])
            || (idx == last_idx && BLOCKED_FINAL[byte_index]);

        // Check for non-ASCII bytes if required
        #[cfg(feature = "require-ascii")]
        let is_blocked = is_blocked || byte >= 0x80;

        if is_blocked {
            result.extend_from_slice(options.replacement);
        } else {
            result.push(byte);
        }
    }

    // Handle UTF-8 validation if required
    #[cfg(feature = "require-utf8")]
    {
        if std::str::from_utf8(&result).is_err() {
            result = replace_invalid_utf8(&result, options.replacement);
        }
    }

    // Check length
    if result.len() > options.max_len {
        return Err(SafeNameError::InvalidLength {
            len: result.len(),
            max: options.max_len,
        });
    }

    Ok(result)
}

/// Replaces invalid UTF-8 sequences with the given replacement bytes.
///
/// # Replacement Strategy
///
/// This function advances one byte at a time when encountering invalid sequences.
/// This is the safest approach as it avoids skipping potentially valid bytes that
/// follow an invalid byte. However, it means a sequence like `\xF0\x80\x80\x80`
/// (invalid 4-byte sequence) produces 4 replacement characters instead of 1.
///
/// This differs from `String::from_utf8_lossy` which replaces entire invalid
/// sequences with a single U+FFFD. Our approach is arguably more correct for
/// byte-level sanitization where each invalid byte should be explicitly handled.
#[cfg(feature = "require-utf8")]
fn replace_invalid_utf8(bytes: &[u8], replacement: &[u8]) -> Vec<u8> {
    let mut result = Vec::with_capacity(bytes.len());
    let mut idx = 0;

    while idx < bytes.len() {
        let byte = bytes[idx];

        // Determine expected sequence length from first byte.
        // Valid UTF-8 start bytes and their sequence lengths:
        //   0x00-0x7F: 1-byte (ASCII)
        //   0xC2-0xDF: 2-byte (0xC0-0xC1 are overlong encodings, invalid)
        //   0xE0-0xEF: 3-byte
        //   0xF0-0xF4: 4-byte (0xF5-0xFF exceed Unicode range, invalid)
        // Invalid start bytes fall through to the default arm:
        //   0x80-0xBF: continuation bytes, invalid as start
        //   0xC0-0xC1: overlong encodings of ASCII
        //   0xF5-0xFF: would encode values > U+10FFFF
        let seq_len = match byte {
            0x00..=0x7F => 1,
            0xC2..=0xDF => 2,
            0xE0..=0xEF => 3,
            0xF0..=0xF4 => 4,
            _ => {
                result.extend_from_slice(replacement);
                idx += 1;
                continue;
            }
        };

        // Check if we have enough bytes for the expected sequence
        if idx + seq_len > bytes.len() {
            // Truncated sequence at end of input
            result.extend_from_slice(replacement);
            idx += 1;
            continue;
        }

        // Validate the complete sequence (checks continuation bytes and overlong forms)
        let seq = &bytes[idx..idx + seq_len];
        if std::str::from_utf8(seq).is_ok() {
            result.extend_from_slice(seq);
            idx += seq_len;
        } else {
            // Invalid sequence (bad continuation bytes, overlong, or surrogate)
            // Advance only one byte to avoid skipping potentially valid bytes
            result.extend_from_slice(replacement);
            idx += 1;
        }
    }

    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::name::validation::validate_file;
    use proptest::prelude::*;

    #[test]
    #[cfg(feature = "require-utf8")]
    fn test_sanitize_invalid_utf8_uses_custom_replacement() {
        let result = sanitize_file(b"file\x80name").unwrap();
        assert_eq!(result, b"file_name");

        let opts = FileSanitizationOptions {
            replacement: b"X",
            ..Default::default()
        };
        let result = sanitize_file_with_options(b"file\x80name", &opts).unwrap();
        assert_eq!(result, b"fileXname");
    }

    #[test]
    #[cfg(feature = "require-ascii")]
    fn test_sanitize_non_ascii() {
        // Non-ASCII bytes are replaced
        let result = sanitize_file(b"file\x80name").unwrap();
        assert_eq!(result, b"file_name");

        // UTF-8 encoded non-ASCII (α = 0xCE 0xB1) gets each byte replaced
        let result = sanitize_file("fileαname".as_bytes()).unwrap();
        assert_eq!(result, b"file__name"); // α is 2 bytes

        let opts = FileSanitizationOptions {
            replacement: b"X",
            ..Default::default()
        };
        let result = sanitize_file_with_options(b"file\x80name", &opts).unwrap();
        assert_eq!(result, b"fileXname");
    }

    #[test]
    fn test_sanitize_empty() {
        assert_eq!(sanitize_file(b"").unwrap(), b"_");
    }

    #[test]
    fn test_sanitize_valid_unchanged() {
        assert_eq!(sanitize_file(b"normal.txt").unwrap(), b"normal.txt");
        assert_eq!(sanitize_file(b"file-name").unwrap(), b"file-name");
        assert_eq!(sanitize_file(b".hidden").unwrap(), b".hidden");
    }

    #[test]
    fn test_sanitize_replaces_slash() {
        // sanitize_file() is for single filename components, not paths.
        // Forward slash is blocked (it's the path separator).
        // Use sanitize_path() for full paths.
        assert_eq!(sanitize_file(b"/hello/a.txt").unwrap(), b"_hello_a.txt");
        assert_eq!(sanitize_file(b"foo/bar").unwrap(), b"foo_bar");
    }

    #[test]
    fn test_sanitize_dot_dotdot() {
        assert_eq!(sanitize_file(b".").unwrap(), b".");
        assert_eq!(sanitize_file(b"..").unwrap(), b"..");
    }

    #[test]
    fn test_sanitize_leading_dash() {
        assert_eq!(sanitize_file(b"-rf").unwrap(), b"_rf");
        assert!(validate_file(sanitize_file(b"-rf").unwrap()).is_ok());
    }

    #[test]
    fn test_sanitize_leading_tilde() {
        assert_eq!(sanitize_file(b"~user").unwrap(), b"_user");
        assert!(validate_file(sanitize_file(b"~user").unwrap()).is_ok());
    }

    #[test]
    fn test_sanitize_leading_space() {
        assert_eq!(sanitize_file(b" file").unwrap(), b"_file");
        assert!(validate_file(sanitize_file(b" file").unwrap()).is_ok());
    }

    #[test]
    fn test_sanitize_trailing_space() {
        assert_eq!(sanitize_file(b"file ").unwrap(), b"file_");
        assert!(validate_file(sanitize_file(b"file ").unwrap()).is_ok());
    }

    #[test]
    fn test_sanitize_control_char() {
        assert_eq!(sanitize_file(b"file\x00name").unwrap(), b"file_name");
        assert!(validate_file(sanitize_file(b"file\x00name").unwrap()).is_ok());
    }

    #[test]
    fn test_sanitize_with_replacement_char() {
        let opts = FileSanitizationOptions::with_unicode_replacement_char();
        assert_eq!(
            sanitize_file_with_options(b"-rf", &opts).unwrap(),
            b"\xEF\xBF\xBDrf"
        );
        assert_eq!(
            sanitize_file_with_options(b"file ", &opts).unwrap(),
            b"file\xEF\xBF\xBD"
        );
    }

    #[test]
    fn test_sanitize_too_long_returns_error() {
        let long_name = [b'a'; 300];
        let result = sanitize_file(long_name);
        assert_eq!(
            result,
            Err(SafeNameError::InvalidLength { len: 300, max: 255 })
        );
    }

    #[test]
    fn test_sanitize_result_validates() {
        let test_cases: &[&[u8]] = &[
            b"",
            b"-rf",
            b"~user",
            b" leading",
            b"trailing ",
            b"file\x00name",
            b"\x7Fdel",
            b"file\xFFbad",
        ];

        for &input in test_cases {
            if let Ok(result) = sanitize_file(input) {
                assert!(
                    validate_file(&result).is_ok(),
                    "sanitize_file({:?}) = {:?} failed validation",
                    input,
                    result
                );
            }
        }
    }

    #[test]
    #[cfg(feature = "require-utf8")]
    fn test_sanitize_multibyte_utf8_sequences() {
        // Valid 2-byte sequence (ñ = 0xC3 0xB1) should be preserved
        let result = sanitize_file("señor".as_bytes()).unwrap();
        assert_eq!(result, "señor".as_bytes());

        // Valid 3-byte sequence (€ = 0xE2 0x82 0xAC) should be preserved
        let result = sanitize_file("100€".as_bytes()).unwrap();
        assert_eq!(result, "100€".as_bytes());

        // Valid 4-byte sequence (😀 = 0xF0 0x9F 0x98 0x80) should be preserved
        let result = sanitize_file("hi😀".as_bytes()).unwrap();
        assert_eq!(result, "hi😀".as_bytes());
    }

    #[test]
    #[cfg(feature = "require-utf8")]
    fn test_sanitize_truncated_utf8_sequences() {
        // Truncated 2-byte sequence: 0xC3 alone (should be followed by 0x80-0xBF)
        let result = sanitize_file(b"file\xC3").unwrap();
        assert_eq!(result, b"file_");

        // Truncated 3-byte sequence: 0xE2 0x82 (missing third byte)
        let result = sanitize_file(b"file\xE2\x82").unwrap();
        assert_eq!(result, b"file__");

        // Truncated 4-byte sequence: 0xF0 0x9F 0x98 (missing fourth byte)
        let result = sanitize_file(b"file\xF0\x9F\x98").unwrap();
        assert_eq!(result, b"file___");
    }

    #[test]
    #[cfg(feature = "require-utf8")]
    fn test_sanitize_invalid_continuation_bytes() {
        // 2-byte start (0xC3) followed by invalid continuation (0x00 instead of 0x80-0xBF)
        let result = sanitize_file(b"file\xC3\x00name").unwrap();
        // 0xC3 becomes _, 0x00 becomes _ (control char)
        assert_eq!(result, b"file__name");

        // 3-byte start with wrong continuation
        let result = sanitize_file(b"a\xE2\x82\x00b").unwrap();
        // Each invalid byte gets replaced
        assert_eq!(result, b"a___b");

        // 4-byte start with ASCII instead of continuation
        let result = sanitize_file(b"a\xF0\x9F\x98Xb").unwrap();
        // 0xF0 invalid (no valid continuation), then 0x9F invalid, 0x98 invalid, X valid
        assert_eq!(result, b"a___Xb");
    }

    #[test]
    #[cfg(feature = "require-utf8")]
    fn test_sanitize_overlong_utf8_encodings() {
        // Overlong encoding of '/' (0x2F) as 2-byte: 0xC0 0xAF
        // 0xC0 and 0xC1 are always invalid (overlong ASCII)
        let result = sanitize_file(b"file\xC0\xAFname").unwrap();
        assert_eq!(result, b"file__name");

        // 0xC1 is also invalid
        let result = sanitize_file(b"file\xC1\x80name").unwrap();
        assert_eq!(result, b"file__name");
    }

    // Property-based tests
    proptest! {
        /// Any sanitized output must pass validation
        #[test]
        fn prop_sanitized_output_always_valid(input in prop::collection::vec(any::<u8>(), 0..256)) {
            if let Ok(sanitized) = sanitize_file(&input) {
                prop_assert!(
                    validate_file(&sanitized).is_ok(),
                    "sanitize_file({:?}) = {:?} failed validation",
                    input, sanitized
                );
            }
        }

        /// Valid filenames should remain unchanged after sanitization
        #[test]
        fn prop_valid_filenames_unchanged(input in "[a-zA-Z0-9._][a-zA-Z0-9._-]{0,50}") {
            let bytes = input.as_bytes();
            if validate_file(bytes).is_ok() {
                let sanitized = sanitize_file(bytes).unwrap();
                prop_assert_eq!(
                    sanitized.as_slice(), bytes,
                    "Valid filename was modified by sanitization"
                );
            }
        }
    }
}