Skip to main content

exarch_core/security/
boundary.rs

1//! Raw path string validation shared by FFI bindings.
2//!
3//! Both `exarch-python` and `exarch-node` accept archive/output paths as
4//! plain strings from their host language before any `Path`, `DestDir`, or
5//! `SecurityConfig` exists to run them through `validate_path`. This module
6//! centralizes that pre-flight check so the two bindings cannot drift on what
7//! counts as a well-formed input string. Config list entries are parsed by
8//! [`crate::Extension`] and [`crate::PathComponentName`].
9
10use std::path::Path;
11
12use crate::error::Result;
13use crate::error::Violation;
14
15/// Maximum length, in bytes, of a raw path string accepted at the FFI
16/// boundary.
17///
18/// Linux and macOS define `PATH_MAX` as 4096 bytes. Bindings enforce the
19/// same ceiling on every platform so behavior does not vary by OS and
20/// pathological inputs are rejected before reaching the archive pipeline.
21pub const MAX_PATH_LENGTH: usize = 4096;
22
23/// A caller-supplied path string that passed the boundary checks.
24///
25/// This is the shared boundary check for `exarch-python` and `exarch-node`:
26/// reject overlong strings and null bytes before doing anything else with
27/// them. It intentionally does not perform traversal, symlink, or
28/// destination-boundary checks — those require a `Path`, a `DestDir`, and a
29/// `SecurityConfig`, and are handled later by `validate_path`.
30///
31/// The only constructor is [`BoundaryPath::parse`], so a binding entry point
32/// that takes a `BoundaryPath` cannot receive an unchecked string.
33///
34/// # Check order
35///
36/// Length is checked before scanning for a null byte: `.len()` is an O(1)
37/// lookup, so an oversized input is rejected without ever running the
38/// O(n) null-byte scan below it — this serves the length check's own
39/// `DoS`-prevention purpose.
40///
41/// # Null-byte detection
42///
43/// Uses [`str::contains`], which short-circuits on the first null byte.
44/// This check validates the *format* of caller-supplied input (is this a
45/// well-formed path string?) rather than comparing one secret against
46/// another, so there is no timing side channel to defend against and
47/// short-circuiting is safe.
48///
49/// # Examples
50///
51/// ```
52/// use std::path::Path;
53///
54/// use exarch_core::BoundaryPath;
55///
56/// let path = BoundaryPath::parse("archive.tar.gz".to_owned())?;
57/// assert_eq!(path.as_str(), "archive.tar.gz");
58/// assert_eq!(AsRef::<Path>::as_ref(&path), Path::new("archive.tar.gz"));
59/// assert!(BoundaryPath::parse("bad\0path".to_owned()).is_err());
60/// assert!(BoundaryPath::parse("x".repeat(5000)).is_err());
61/// # Ok::<(), exarch_core::ArchiveError>(())
62/// ```
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub struct BoundaryPath(String);
65
66impl BoundaryPath {
67    /// Checks a raw path string and keeps it as proof of the check.
68    ///
69    /// # Errors
70    ///
71    /// Returns [`crate::ArchiveError::SecurityViolation`] if `path` contains a
72    /// null byte or exceeds [`MAX_PATH_LENGTH`] bytes.
73    pub fn parse(path: String) -> Result<Self> {
74        if path.len() > MAX_PATH_LENGTH {
75            return Err(Violation::PathTooLong {
76                len: path.len(),
77                max: MAX_PATH_LENGTH,
78            }
79            .into());
80        }
81
82        if path.contains('\0') {
83            return Err(Violation::NulInPathArgument.into());
84        }
85
86        Ok(Self(path))
87    }
88
89    /// The checked string.
90    #[must_use]
91    pub fn as_str(&self) -> &str {
92        &self.0
93    }
94
95    /// The checked string, by value.
96    #[must_use]
97    pub fn into_string(self) -> String {
98        self.0
99    }
100}
101
102impl AsRef<Path> for BoundaryPath {
103    fn as_ref(&self) -> &Path {
104        Path::new(&self.0)
105    }
106}
107
108/// Maximum length, in bytes, of a single `SecurityConfig` entry — an
109/// allowed extension or a banned path component.
110pub const MAX_CONFIG_ENTRY_LENGTH: usize = 255;
111
112#[cfg(test)]
113#[allow(clippy::unwrap_used, clippy::expect_used)]
114mod tests {
115    use super::*;
116    use std::assert_matches;
117
118    fn parse(path: &str) -> Result<BoundaryPath> {
119        BoundaryPath::parse(path.to_owned())
120    }
121
122    #[test]
123    fn test_parse_accepts_normal() {
124        assert!(parse("/tmp/test.tar.gz").is_ok());
125        assert!(parse("relative/path.tar").is_ok());
126        assert!(parse("").is_ok());
127    }
128
129    #[test]
130    fn test_parse_keeps_the_checked_string() {
131        let path = parse("a/b.tar").unwrap();
132        assert_eq!(path.as_str(), "a/b.tar");
133        assert_eq!(AsRef::<Path>::as_ref(&path), Path::new("a/b.tar"));
134        assert_eq!(path.into_string(), "a/b.tar");
135    }
136
137    #[test]
138    fn test_parse_rejects_null_bytes() {
139        let err = parse("/tmp/test\0malicious").expect_err("null byte");
140        assert_eq!(
141            err.security_violation(),
142            Some(&Violation::NulInPathArgument)
143        );
144        assert_eq!(
145            err.context().as_deref(),
146            Some("path contains null bytes - potential security issue")
147        );
148    }
149
150    #[test]
151    fn test_parse_rejects_too_long() {
152        let long_path = "x".repeat(MAX_PATH_LENGTH + 1);
153        let err = parse(&long_path).expect_err("too long");
154        assert_eq!(
155            err.security_violation(),
156            Some(&Violation::PathTooLong {
157                len: long_path.len(),
158                max: MAX_PATH_LENGTH
159            })
160        );
161        assert_eq!(
162            err.context().as_deref(),
163            Some(
164                format!(
165                    "path exceeds maximum length of {MAX_PATH_LENGTH} bytes (got {} bytes)",
166                    long_path.len()
167                )
168                .as_str()
169            )
170        );
171    }
172
173    #[test]
174    fn test_parse_checks_length_before_null_byte() {
175        let long_path_with_null = format!("{}\0", "x".repeat(MAX_PATH_LENGTH));
176        let err = parse(&long_path_with_null).expect_err("too long");
177        assert_matches!(
178            err.security_violation(),
179            Some(Violation::PathTooLong { .. })
180        );
181    }
182
183    #[test]
184    fn test_parse_accepts_max_length() {
185        let max_path = "x".repeat(MAX_PATH_LENGTH);
186        assert!(parse(&max_path).is_ok());
187    }
188}