relate-executor 1.5.0

In-memory graph and Cypher physical executor
Documentation
//! The remote-source hook for `LOAD CSV` (ADR-0723): an optional capability
//! the host supplies, so an http(s) source can be read without the engine
//! taking a networking dependency. The hook, its closed failure vocabulary
//! and the source classification live here; the error wording is in
//! [`super::errors`], and the capability itself rides on
//! [`super::CsvPolicy`], beside the root and the byte limit.

use std::fmt;

use relate_core::Error;

use super::errors::byte_limit_exceeded;

/// Why a host's fetch failed — a closed vocabulary, so the engine words every
/// failure itself and no URL, host name, OS error or transport text can reach
/// a client (the no-leak rule of ADR-0081).
///
/// Non-exhaustive: a later decision may add a reason (a host the policy
/// refuses), and a host only ever constructs these.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum RemoteFailure {
    /// The server answered with a non-success HTTP status.
    Status(u16),
    /// The body was larger than the byte limit the engine passed.
    ExceededLimit,
    /// The request did not finish inside the host's time bound.
    Timeout,
    /// A redirect was refused: the hop bound was reached, or a hop would have
    /// downgraded an `https` source to plaintext.
    Redirect,
    /// The source could not be reached or read: name resolution, connection,
    /// TLS, or a body that broke off.
    Unreachable,
}

/// The host-supplied fetcher behind a remote `LOAD CSV` source (ADR-0723).
///
/// Set through [`super::CsvPolicy::with_remote`] (the `relate` facade carries
/// it as `OpenOptions::load_csv_remote`). Without one, every http(s) source
/// is denied.
pub trait CsvRemote: Send + Sync + fmt::Debug {
    /// GET `url` and return its body. The implementation must stop reading at
    /// `max_bytes + 1` bytes and report [`RemoteFailure::ExceededLimit`]
    /// rather than truncate (the engine re-checks the length, so a buggy host
    /// cannot lift the cap), must bound its own time, and decides its own
    /// redirect policy.
    fn fetch(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>, RemoteFailure>;
}

/// One parse of an http(s) `LOAD CSV` source: the single scan of the URL
/// grammar that every remote rule reads — the scheme test, the credentials
/// check, the control-character check and the canonical identity — so none of
/// them can disagree about where the authority ends. The fragment is dropped
/// here, and nothing past it is ever sent. `None` for every other spelling (a
/// bare path, `file://`, another scheme), which keeps its local-file handling.
pub(super) struct RemoteUrl<'a> {
    scheme: &'a str,
    authority: &'a str,
    /// The path and query, from the first `/` or `?` (empty when neither).
    rest: &'a str,
}

impl<'a> RemoteUrl<'a> {
    /// The scheme is matched without regard to case.
    pub(super) fn parse(source: &'a str) -> Option<Self> {
        let (scheme, after) = source.split_once("://")?;
        if !(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) {
            return None;
        }
        let after = after.split_once('#').map_or(after, |(url, _)| url);
        // The authority ends at the first `/` or `?`; with neither, the whole
        // remainder is the authority.
        let end = after.find(['/', '?']).unwrap_or(after.len());
        let (authority, rest) = after.split_at(end);
        Some(Self {
            scheme,
            authority,
            rest,
        })
    }

    /// Whether the authority carries credentials (`user:password@host`):
    /// refused before any request, so a secret typed into a query never
    /// reaches a host's transport or a log. An `@` after the authority is
    /// path or query text, not userinfo.
    pub(super) fn carries_credentials(&self) -> bool {
        self.authority.contains('@')
    }

    /// Whether the URL is free of the characters that make a request line or
    /// a header injectable — ASCII controls (CR, LF, tab, NUL, …) and the
    /// space. The engine checks this itself, so a host's fetcher never
    /// receives them whatever its own URI parser tolerates.
    pub(super) fn is_well_formed(&self) -> bool {
        [self.scheme, self.authority, self.rest]
            .iter()
            .all(|part| !part.chars().any(|c| c.is_ascii_control() || c == ' '))
    }

    /// The source's one identity, for the memo and for the host: scheme and
    /// authority are case-insensitive (RFC 3986 §6.2.2.1) and lowercased, the
    /// fragment is gone, and the path and query are case-sensitive and kept as
    /// written. Every such spelling of one URL is one source — and the seeded
    /// offline fixture answers for all of them, never reaching a fetcher.
    pub(super) fn canonical(&self) -> String {
        format!(
            "{}://{}{}",
            self.scheme.to_ascii_lowercase(),
            self.authority.to_ascii_lowercase(),
            self.rest
        )
    }
}

impl RemoteFailure {
    /// The one wording of each failure: generic, typed, and free of the URL.
    pub(super) fn into_error(self) -> Error {
        match self {
            Self::Status(status) => {
                Error::execution(format!("LOAD CSV remote source returned HTTP {status}"))
            }
            Self::ExceededLimit => byte_limit_exceeded(),
            Self::Timeout => Error::execution("LOAD CSV remote source timed out"),
            Self::Redirect => Error::execution("LOAD CSV remote redirect refused"),
            Self::Unreachable => Error::execution("LOAD CSV remote source unreachable"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn canonical(source: &str) -> Option<String> {
        RemoteUrl::parse(source).map(|url| url.canonical())
    }

    #[test]
    fn only_http_and_https_sources_are_remote() {
        for (source, url) in [
            ("https://example.org/a.csv", "https://example.org/a.csv"),
            ("http://example.org/a.csv", "http://example.org/a.csv"),
            // The scheme and host are case-insensitive and lowercased; the
            // path is case-sensitive and kept.
            ("HTTPS://Example.org/A.csv", "https://example.org/A.csv"),
            ("Http://EXAMPLE.org:8080/a", "http://example.org:8080/a"),
            // A fragment is dropped; a query string is kept (presigned links).
            ("https://example.org/a.csv#top", "https://example.org/a.csv"),
            (
                "https://example.org/a.csv?sig=1#x",
                "https://example.org/a.csv?sig=1",
            ),
            // No path at all: the whole remainder is the authority.
            ("HTTPS://Example.ORG", "https://example.org"),
        ] {
            assert_eq!(canonical(source).as_deref(), Some(url), "{source}");
        }
        for source in [
            "rows.csv",
            "dir/rows.csv",
            "file:///tmp/rows.csv",
            "ftp://example.org/a.csv",
            "s3://bucket/a.csv",
            "https:/example.org/a.csv",
            "httpsx://example.org/a.csv",
            "//example.org/a.csv",
            "",
        ] {
            assert!(RemoteUrl::parse(source).is_none(), "{source}");
        }
    }

    #[test]
    fn credentials_are_found_in_the_authority_only() {
        let carries = |url: &str| RemoteUrl::parse(url).unwrap().carries_credentials();
        for url in [
            "https://user@example.org/a.csv",
            "https://user:secret@example.org/a.csv",
            "http://:secret@example.org/",
            "https://user@example.org",
        ] {
            assert!(carries(url), "{url}");
        }
        for url in [
            "https://example.org/a.csv",
            "https://example.org:8443/a.csv",
            // An `@` after the authority is path or query text, not userinfo.
            "https://example.org/a@b.csv",
            "https://example.org/a.csv?mail=a@b.org",
            // ...and one after the fragment mark is not even part of the URL.
            "https://example.org/a.csv#x@y",
        ] {
            assert!(!carries(url), "{url}");
        }
    }

    #[test]
    fn control_characters_and_spaces_make_a_url_malformed() {
        let well_formed = |url: &str| RemoteUrl::parse(url).unwrap().is_well_formed();
        for url in [
            "https://example.org/a\r\nX-Injected: 1",
            "https://example.org/a\nb",
            "https://example.org/a\tb",
            "https://example.org/a\0b",
            "https://example.org/a b.csv",
            "https://example.org/a\x7fb",
            "https://exam ple.org/",
            "https://example.org/?q=a b",
        ] {
            assert!(!well_formed(url), "{url:?}");
        }
        for url in [
            "https://example.org/a%20b.csv",
            "https://example.org/a.csv?x=1&y=2",
            "https://example.org/caf\u{e9}.csv",
            // Whatever follows the fragment mark is dropped, never sent.
            "https://example.org/a.csv#frag ment",
        ] {
            assert!(well_formed(url), "{url:?}");
        }
    }

    #[test]
    fn every_failure_has_one_generic_wording_without_the_url() {
        for (failure, message) in [
            (
                RemoteFailure::Status(404),
                "LOAD CSV remote source returned HTTP 404",
            ),
            (
                RemoteFailure::ExceededLimit,
                "LOAD CSV file exceeds byte limit",
            ),
            (RemoteFailure::Timeout, "LOAD CSV remote source timed out"),
            (RemoteFailure::Redirect, "LOAD CSV remote redirect refused"),
            (
                RemoteFailure::Unreachable,
                "LOAD CSV remote source unreachable",
            ),
        ] {
            assert_eq!(failure.into_error(), Error::execution(message));
        }
    }
}