Skip to main content

relate_executor/csv/
policy.rs

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