use std::ffi::OsString;
use std::path::Path;
use std::path::PathBuf;
use crate::error::Result;
use crate::error::Violation;
pub const MAX_PATH_LENGTH: usize = 4096;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoundaryPath(PathBuf);
impl BoundaryPath {
pub fn parse(path: String) -> Result<Self> {
Self::parse_os(OsString::from(path))
}
pub fn parse_os(path: OsString) -> Result<Self> {
let bytes = path.as_encoded_bytes();
if bytes.len() > MAX_PATH_LENGTH {
return Err(Violation::PathTooLong {
len: bytes.len(),
max: MAX_PATH_LENGTH,
}
.into());
}
if bytes.contains(&0) {
return Err(Violation::NulInPathArgument.into());
}
Ok(Self(PathBuf::from(path)))
}
#[must_use]
pub fn as_path(&self) -> &Path {
&self.0
}
#[must_use]
pub fn into_path_buf(self) -> PathBuf {
self.0
}
}
impl AsRef<Path> for BoundaryPath {
fn as_ref(&self) -> &Path {
&self.0
}
}
pub const MAX_CONFIG_ENTRY_LENGTH: usize = 255;
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
use super::*;
use std::assert_matches;
fn parse(path: &str) -> Result<BoundaryPath> {
BoundaryPath::parse(path.to_owned())
}
#[test]
fn test_parse_accepts_normal() {
assert!(parse("/tmp/test.tar.gz").is_ok());
assert!(parse("relative/path.tar").is_ok());
assert!(parse("").is_ok());
}
#[test]
fn test_parse_keeps_the_checked_string() {
let path = parse("a/b.tar").unwrap();
assert_eq!(path.as_path(), Path::new("a/b.tar"));
assert_eq!(AsRef::<Path>::as_ref(&path), Path::new("a/b.tar"));
assert_eq!(path.into_path_buf(), PathBuf::from("a/b.tar"));
}
#[test]
fn test_parse_rejects_null_bytes() {
let err = parse("/tmp/test\0malicious").expect_err("null byte");
assert_eq!(
err.security_violation(),
Some(&Violation::NulInPathArgument)
);
assert_eq!(
err.context().as_deref(),
Some("path contains null bytes - potential security issue")
);
}
#[test]
fn test_parse_rejects_too_long() {
let long_path = "x".repeat(MAX_PATH_LENGTH + 1);
let err = parse(&long_path).expect_err("too long");
assert_eq!(
err.security_violation(),
Some(&Violation::PathTooLong {
len: long_path.len(),
max: MAX_PATH_LENGTH
})
);
assert_eq!(
err.context().as_deref(),
Some(
format!(
"path exceeds maximum length of {MAX_PATH_LENGTH} bytes (got {} bytes)",
long_path.len()
)
.as_str()
)
);
}
#[test]
fn test_parse_checks_length_before_null_byte() {
let long_path_with_null = format!("{}\0", "x".repeat(MAX_PATH_LENGTH));
let err = parse(&long_path_with_null).expect_err("too long");
assert_matches!(
err.security_violation(),
Some(Violation::PathTooLong { .. })
);
}
#[test]
fn test_parse_accepts_max_length() {
let max_path = "x".repeat(MAX_PATH_LENGTH);
assert!(parse(&max_path).is_ok());
}
}