Skip to main content

relate_executor/csv/
policy.rs

1//! The validated local-file capability behind `LOAD CSV` (ADR-0081,
2//! ADR-0108): source-spelling classification and normalization, root
3//! confinement, and the re-verified read. A local target is opened and then
4//! verified against the physical identity recorded at validation, so a
5//! concurrent filesystem mutation between inspection and open cannot
6//! substitute the file that is read.
7
8use std::fs::OpenOptions;
9use std::io::Read;
10use std::path::{Component, Path, PathBuf};
11
12use relate_core::file_identity::{self, FileIdentity};
13use relate_core::{Error, Result};
14
15pub(crate) const DEFAULT_MAX_BYTES: u64 = 8_388_608;
16const MAX_BYTES_CEILING: u64 = 67_108_864;
17
18/// Validated, immutable local-file capability for `LOAD CSV` (ADR-0081).
19#[derive(Debug, Clone)]
20pub struct CsvPolicy {
21    root: Option<PathBuf>,
22    max_bytes: u64,
23}
24
25impl Default for CsvPolicy {
26    fn default() -> Self {
27        Self::new(None, None).expect("default CSV policy is valid")
28    }
29}
30
31pub(super) fn unavailable() -> Error {
32    Error::execution("LOAD CSV file unavailable")
33}
34
35/// The one spelling of the `CsvPolicy::new` denial: an out-of-range byte
36/// limit or a root that is not an existing directory.
37fn invalid_config() -> Error {
38    Error::semantic("LOAD CSV invalid configuration")
39}
40
41/// A canonical local target together with the physical identity observed when
42/// it was validated. `read` requires the opened handle to match it (ADR-0108).
43#[derive(Debug)]
44pub(super) struct VerifiedTarget {
45    pub(super) path: PathBuf,
46    identity: FileIdentity,
47}
48
49/// Canonicalize `candidate`, returning it only when it resolves to a regular
50/// file that stays inside the canonical `root`, together with the physical
51/// identity observed at validation (ADR-0108). Any canonicalization,
52/// inspection or confinement failure is a denial, never an OS error.
53fn confined(candidate: PathBuf, root: &Path) -> Option<VerifiedTarget> {
54    let target = candidate.canonicalize().ok()?;
55    if !target.starts_with(root) {
56        return None;
57    }
58    // Fail closed against a final-component symlink at inspection time; the
59    // identity recorded here is required again on the opened handle.
60    if !std::fs::symlink_metadata(&target).ok()?.is_file() {
61        return None;
62    }
63    let identity = file_identity::of_path(&target).ok()?;
64    Some(VerifiedTarget {
65        path: target,
66        identity,
67    })
68}
69
70/// The drive-rooted path of a local `file:///` URL, or a denial: the URL
71/// must spell `/<drive>:/<rest>` with forward slashes — never a UNC/device
72/// prefix or a drive-relative path, which Windows path normalization would
73/// otherwise reinterpret.
74#[cfg(windows)]
75fn windows_drive_path(url_path: &str) -> Result<&str> {
76    let drive_path = &url_path[1..];
77    let bytes = drive_path.as_bytes();
78    if bytes.len() < 3
79        || !bytes[0].is_ascii_alphabetic()
80        || bytes[1] != b':'
81        || bytes[2] != b'/'
82        || drive_path.contains('\\')
83        || drive_path[3..].contains(':')
84    {
85        return Err(unavailable());
86    }
87    Ok(drive_path)
88}
89
90impl CsvPolicy {
91    /// Validate the byte limit and canonicalize an existing CSV directory.
92    /// A missing root denies local files, even when a limit is configured.
93    pub fn new(root: Option<PathBuf>, max_bytes: Option<u64>) -> Result<Self> {
94        let max_bytes = max_bytes.unwrap_or(DEFAULT_MAX_BYTES);
95        if !(1..=MAX_BYTES_CEILING).contains(&max_bytes) {
96            return Err(invalid_config());
97        }
98        let root = root
99            .map(|dir| {
100                let canonical = dir.canonicalize().map_err(|_| invalid_config())?;
101                if !canonical.is_dir() {
102                    return Err(invalid_config());
103                }
104                Ok(canonical)
105            })
106            .transpose()?;
107        Ok(Self { root, max_bytes })
108    }
109
110    /// The configured per-file byte limit.
111    #[cfg(test)]
112    pub(crate) fn max_bytes(&self) -> u64 {
113        self.max_bytes
114    }
115
116    /// The canonical CSV root, when local files are enabled.
117    #[cfg(test)]
118    pub(crate) fn root(&self) -> Option<&Path> {
119        self.root.as_deref()
120    }
121
122    pub(super) fn target(&self, source: &str) -> Result<VerifiedTarget> {
123        let root = self.root.as_ref().ok_or_else(unavailable)?;
124        // One resolution rule for every spelling: each classified
125        // candidate, in order, must canonicalize to a regular file confined
126        // to the root (`confined`); anything else is a denial.
127        Self::classify(source, root)?
128            .into_iter()
129            .find_map(|candidate| confined(candidate, root))
130            .ok_or_else(unavailable)
131    }
132
133    /// Classify a `LOAD CSV` source spelling into its candidate paths, in
134    /// resolution order, so [`CsvPolicy::target`] applies exactly one
135    /// resolution rule to every spelling:
136    ///
137    /// - `file:///absolute/path` is the only accepted URL form (no
138    ///   authority, `?`, `#` or `%`; on Windows a drive-rooted
139    ///   forward-slash path via `windows_drive_path`). Its candidates are
140    ///   the absolute path as spelled, then the root-relative reading — so
141    ///   the URL and bare-relative spellings of one in-root file resolve to
142    ///   the same canonical target, while the absolute reading still wins
143    ///   when it names a regular file under the root. Either reading is
144    ///   canonicalized and confined to the root.
145    /// - A bare path is rejected with a scheme, a `?`/`#`, a root or prefix,
146    ///   or a parent component; otherwise its one candidate is the path
147    ///   joined to `root`.
148    fn classify(source: &str, root: &Path) -> Result<Vec<PathBuf>> {
149        if let Some(url_path) = source.strip_prefix("file://") {
150            // The only accepted URL form is file:///absolute/path. In
151            // particular, file://localhost and file:////host are rejected.
152            if !url_path.starts_with('/')
153                || url_path.starts_with("//")
154                || url_path.contains(['?', '#', '%'])
155            {
156                return Err(unavailable());
157            }
158            #[cfg(windows)]
159            let url_path = windows_drive_path(url_path)?;
160            let path = Path::new(url_path);
161            if !path.is_absolute() || path.components().any(|c| matches!(c, Component::ParentDir)) {
162                return Err(unavailable());
163            }
164            // A `file:///name.csv` URL is also read as a path relative to
165            // the configured root. The path is known absolute here: a Unix
166            // absolute path strips its leading `/`; a Windows drive-rooted
167            // URL path (`C:/…`) is absolute without that prefix, so it is
168            // used as-is.
169            let relative = path.strip_prefix("/").unwrap_or(path);
170            Ok(vec![path.to_path_buf(), root.join(relative)])
171        } else {
172            let scheme = source.split_once(':').is_some_and(|(prefix, _)| {
173                prefix.starts_with(|c: char| c.is_ascii_alphabetic())
174                    && prefix
175                        .chars()
176                        .all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c))
177            });
178            if scheme || source.contains(['?', '#']) {
179                return Err(unavailable());
180            }
181            let path = Path::new(source);
182            if path.as_os_str().is_empty()
183                || path.has_root()
184                || path
185                    .components()
186                    .any(|c| matches!(c, Component::ParentDir | Component::Prefix(_)))
187            {
188                return Err(unavailable());
189            }
190            Ok(vec![root.join(path)])
191        }
192    }
193
194    pub(super) fn read(&self, target: &VerifiedTarget) -> Result<String> {
195        let mut opts = OpenOptions::new();
196        opts.read(true);
197        // Never follow a symlink substituted at the final component (ADR-0108):
198        // on Unix the open fails, on Windows the link itself is opened and the
199        // identity comparison below denies it.
200        file_identity::nofollow(&mut opts);
201        let file = opts.open(&target.path).map_err(|_| unavailable())?;
202        if file_identity::of_file(&file).map_err(|_| unavailable())? != target.identity
203            || !file.metadata().map_err(|_| unavailable())?.is_file()
204        {
205            return Err(unavailable());
206        }
207        let mut bytes = Vec::new();
208        file.take(self.max_bytes.saturating_add(1))
209            .read_to_end(&mut bytes)
210            .map_err(|_| unavailable())?;
211        if bytes.len() as u64 > self.max_bytes {
212            return Err(Error::execution("LOAD CSV file exceeds byte limit"));
213        }
214        String::from_utf8(bytes).map_err(|_| unavailable())
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::super::{local_file_url, test_root};
221    use super::*;
222    use std::fs;
223
224    /// `CsvPolicy::new`'s own validation: the byte-limit range and the
225    /// existing-directory root rule. The Graph-side surface (defaults,
226    /// `configure_load_csv`, capability preservation) is covered in
227    /// `graph::tests`.
228    #[test]
229    fn new_validates_byte_limit_and_root() {
230        let dir = test_root();
231        let root = dir.path();
232        let file = root.join("rows.csv");
233        fs::write(&file, "safe\n").unwrap();
234        for limit in [0, 67_108_865, u64::MAX] {
235            assert_eq!(
236                CsvPolicy::new(Some(root.to_path_buf()), Some(limit)).unwrap_err(),
237                invalid_config()
238            );
239        }
240        for invalid_root in [root.join("missing"), file] {
241            assert_eq!(
242                CsvPolicy::new(Some(invalid_root), None).unwrap_err(),
243                invalid_config()
244            );
245        }
246        // A relative root is accepted by the constructor but never stored
247        // relative; neither callers nor Graph can manufacture an unchecked one.
248        let relative = CsvPolicy::new(Some(PathBuf::from(".")), None).unwrap();
249        assert!(relative.root.as_ref().unwrap().is_absolute());
250        assert!(CsvPolicy::new(None, Some(MAX_BYTES_CEILING)).is_ok());
251    }
252
253    #[cfg(windows)]
254    #[test]
255    fn local_drive_urls_are_absolute_and_restricted_to_the_csv_root() {
256        let dir = test_root();
257        let root = dir.path();
258        let inside = root.join("rows.csv");
259        fs::write(&inside, "safe\n").unwrap();
260        let outside = root.with_extension("outside.csv");
261        fs::write(&outside, "private\n").unwrap();
262        let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
263        let url = local_file_url(&inside);
264        assert_eq!(
265            policy.target(&url).unwrap().path,
266            inside.canonicalize().unwrap()
267        );
268
269        let root_url = local_file_url(&root);
270        let outside_url = local_file_url(&outside);
271        for source in [
272            outside_url.as_str(),
273            &format!("{root_url}/../outside.csv"),
274            &format!(
275                "{root_url}/../{}/rows.csv",
276                root.file_name().unwrap().to_string_lossy()
277            ),
278            &url.replace("/rows.csv", "/rows%2ecsv"),
279            &url.replace("/rows.csv", "/rows.csv:stream"),
280            &format!("file:///{}", inside.display()),
281            &format!("file://{}", inside.display()),
282            "file://host/C:/rows.csv",
283            "file://C:\\rows.csv",
284            "file:////server/share/rows.csv",
285            r"file:///\\server\share\rows.csv",
286            r"file:///\\?\C:\rows.csv",
287            r"file:///\\.\C:\rows.csv",
288            "file:///C:rows.csv",
289            "C:rows.csv",
290            r"\rows.csv",
291        ] {
292            assert_eq!(
293                policy.target(source).unwrap_err(),
294                unavailable(),
295                "{source}"
296            );
297        }
298        fs::remove_file(outside).unwrap();
299    }
300
301    #[cfg(not(windows))]
302    #[test]
303    fn file_url_paths_resolve_against_the_policy_root() {
304        let dir = test_root();
305        let root = dir.path();
306        let inside = root.join("rows.csv");
307        fs::write(&inside, "safe\n").unwrap();
308        let outside = root.with_extension("outside.csv");
309        fs::write(&outside, "private\n").unwrap();
310        let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
311        let canonical = inside.canonicalize().unwrap();
312
313        // The absolute URL of the in-root file and the root-relative
314        // `file:///name.csv` spelling resolve to the same canonical target.
315        assert_eq!(
316            policy.target(&local_file_url(&inside)).unwrap().path,
317            canonical
318        );
319        assert_eq!(policy.target("file:///rows.csv").unwrap().path, canonical);
320
321        // Neither reading escapes the root or fabricates a missing file.
322        for source in [
323            "file:///missing.csv",
324            "file:///../rows.csv",
325            "file:///rows.csv/../rows.csv",
326            "file:////rows.csv",
327            "file://rows.csv",
328            &local_file_url(&outside),
329        ] {
330            assert_eq!(
331                policy.target(source).unwrap_err(),
332                unavailable(),
333                "{source}"
334            );
335        }
336        fs::remove_file(outside).unwrap();
337    }
338
339    #[cfg(unix)]
340    #[test]
341    fn read_denies_target_swapped_for_out_of_root_symlink() {
342        use std::os::unix::fs::symlink;
343
344        let dir = test_root();
345        let root = dir.path();
346        let outside_dir = test_root();
347        let outside = outside_dir.path();
348        fs::write(root.join("rows.csv"), "inside\n").unwrap();
349        fs::write(outside.join("outside.csv"), "outside\n").unwrap();
350        let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
351        let target = policy.target("rows.csv").unwrap();
352
353        fs::remove_file(root.join("rows.csv")).unwrap();
354        symlink(outside.join("outside.csv"), root.join("rows.csv")).unwrap();
355        assert_eq!(policy.read(&target).unwrap_err(), unavailable());
356    }
357
358    #[test]
359    fn read_denies_target_swapped_for_other_in_root_file() {
360        let dir = test_root();
361        let root = dir.path();
362        fs::write(root.join("rows.csv"), "one\n").unwrap();
363        fs::write(root.join("other.csv"), "two\n").unwrap();
364        let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
365        let target = policy.target("rows.csv").unwrap();
366
367        // The final component is a real regular file, so O_NOFOLLOW does not
368        // refuse it; only the recorded identity catches the substitution.
369        fs::remove_file(root.join("rows.csv")).unwrap();
370        fs::rename(root.join("other.csv"), root.join("rows.csv")).unwrap();
371        assert_eq!(policy.read(&target).unwrap_err(), unavailable());
372    }
373
374    #[cfg(unix)]
375    #[test]
376    fn read_denies_intermediate_directory_swap() {
377        use std::os::unix::fs::symlink;
378
379        let dir = test_root();
380        let root = dir.path();
381        let outside_dir = test_root();
382        let outside = outside_dir.path();
383        fs::create_dir(root.join("sub")).unwrap();
384        fs::write(root.join("sub/rows.csv"), "inside\n").unwrap();
385        fs::write(outside.join("rows.csv"), "outside\n").unwrap();
386        let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
387        let target = policy.target("sub/rows.csv").unwrap();
388
389        // The final component is a real regular file, so O_NOFOLLOW does not
390        // refuse it; only the recorded identity catches the substitution.
391        fs::rename(root.join("sub"), root.join("sub-orig")).unwrap();
392        symlink(outside, root.join("sub")).unwrap();
393        assert_eq!(policy.read(&target).unwrap_err(), unavailable());
394    }
395
396    #[test]
397    fn read_denies_mismatched_recorded_identity() {
398        let dir = test_root();
399        let root = dir.path();
400        let file = root.join("rows.csv");
401        fs::write(&file, "rows\n").unwrap();
402        let other = root.join("other.csv");
403        fs::write(&other, "other\n").unwrap();
404        let policy = CsvPolicy::new(Some(root.to_path_buf()), None).unwrap();
405
406        let target = VerifiedTarget {
407            path: file.canonicalize().unwrap(),
408            identity: file_identity::of_path(&other.canonicalize().unwrap()).unwrap(),
409        };
410        assert_eq!(policy.read(&target).unwrap_err(), unavailable());
411    }
412}