|
| 1 | +use log::warn; |
| 2 | +use std::io; |
| 3 | + |
| 4 | +const TRIM_CHARS: &[char] = &['\0', ' ', '\n', '\t', '\r', '/', '.']; |
| 5 | +const END_OF_STRING_CHARS: &[char] = &['\0', '\n', '\r']; |
| 6 | + |
| 7 | +pub fn sanitize_path(path: &str) -> Result<String, io::Error> { |
| 8 | + let sanitized_path = path.trim_matches(TRIM_CHARS).replace('\\', "/"); |
| 9 | + |
| 10 | + if let Some(idx) = sanitized_path.rfind('/') { |
| 11 | + let (dir_part, _) = sanitized_path.split_at(idx); |
| 12 | + |
| 13 | + // Check for ".." only in the directory part |
| 14 | + if dir_part.contains("..") { |
| 15 | + warn!( |
| 16 | + "path «{}» contains .. in directory part, this isn't supported", |
| 17 | + path |
| 18 | + ); |
| 19 | + return Err(io::Error::new( |
| 20 | + io::ErrorKind::InvalidInput, |
| 21 | + "Path contains invalid '..' in directory part", |
| 22 | + )); |
| 23 | + } |
| 24 | + } |
| 25 | + |
| 26 | + match sanitized_path.find(END_OF_STRING_CHARS) { |
| 27 | + Some(idx) => { |
| 28 | + let (final_path, _) = sanitized_path.split_at(idx); |
| 29 | + Ok(final_path.to_string()) |
| 30 | + } |
| 31 | + None => Ok(sanitized_path), |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +#[cfg(test)] |
| 36 | +mod tests { |
| 37 | + use super::*; |
| 38 | + |
| 39 | + #[test] |
| 40 | + fn test_sanitize_path() { |
| 41 | + // Normal filename |
| 42 | + assert_eq!(sanitize_path("filename.ext").unwrap(), "filename.ext"); |
| 43 | + |
| 44 | + // Normal path |
| 45 | + assert_eq!( |
| 46 | + sanitize_path("folder\\file.ext").unwrap(), |
| 47 | + "folder/file.ext" |
| 48 | + ); |
| 49 | + |
| 50 | + // Unix path |
| 51 | + assert_eq!(sanitize_path("folder/file.ext").unwrap(), "folder/file.ext"); |
| 52 | + |
| 53 | + // Any number or ../ at the start will be removed. |
| 54 | + assert_eq!( |
| 55 | + sanitize_path("../folder/file.ext").unwrap(), |
| 56 | + "folder/file.ext" |
| 57 | + ); |
| 58 | + |
| 59 | + // .. anywhere in the dir part will error out. |
| 60 | + assert!(sanitize_path("folder/../file.ext").is_err()); |
| 61 | + |
| 62 | + // new line/empty chars at the end should be removed |
| 63 | + assert_eq!( |
| 64 | + sanitize_path("folder/file.ext\r\n\0").unwrap(), |
| 65 | + "folder/file.ext" |
| 66 | + ); |
| 67 | + |
| 68 | + // anything after a new line should be trimmed off |
| 69 | + assert_eq!( |
| 70 | + sanitize_path("folder/file.ext\n00").unwrap(), |
| 71 | + "folder/file.ext" |
| 72 | + ); |
| 73 | + } |
| 74 | +} |
0 commit comments