Skip to main content

relate_executor/csv/
remote.rs

1//! The remote-source hook for `LOAD CSV` (ADR-0723): an optional capability
2//! the host supplies, so an http(s) source can be read without the engine
3//! taking a networking dependency. The hook, its closed failure vocabulary
4//! and the source classification live here; the error wording is in
5//! [`super::errors`], and the capability itself rides on
6//! [`super::CsvPolicy`], beside the root and the byte limit.
7
8use std::fmt;
9
10use relate_core::Error;
11
12use super::errors::byte_limit_exceeded;
13
14/// Why a host's fetch failed — a closed vocabulary, so the engine words every
15/// failure itself and no URL, host name, OS error or transport text can reach
16/// a client (the no-leak rule of ADR-0081).
17///
18/// Non-exhaustive: a later decision may add a reason (a host the policy
19/// refuses), and a host only ever constructs these.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21#[non_exhaustive]
22pub enum RemoteFailure {
23    /// The server answered with a non-success HTTP status.
24    Status(u16),
25    /// The body was larger than the byte limit the engine passed.
26    ExceededLimit,
27    /// The request did not finish inside the host's time bound.
28    Timeout,
29    /// A redirect was refused: the hop bound was reached, or a hop would have
30    /// downgraded an `https` source to plaintext.
31    Redirect,
32    /// The source could not be reached or read: name resolution, connection,
33    /// TLS, or a body that broke off.
34    Unreachable,
35}
36
37/// The host-supplied fetcher behind a remote `LOAD CSV` source (ADR-0723).
38///
39/// Set through [`super::CsvPolicy::with_remote`] (the `relate` facade carries
40/// it as `OpenOptions::load_csv_remote`). Without one, every http(s) source
41/// is denied.
42pub trait CsvRemote: Send + Sync + fmt::Debug {
43    /// GET `url` and return its body. The implementation must stop reading at
44    /// `max_bytes + 1` bytes and report [`RemoteFailure::ExceededLimit`]
45    /// rather than truncate (the engine re-checks the length, so a buggy host
46    /// cannot lift the cap), must bound its own time, and decides its own
47    /// redirect policy.
48    fn fetch(&self, url: &str, max_bytes: u64) -> Result<Vec<u8>, RemoteFailure>;
49}
50
51/// One parse of an http(s) `LOAD CSV` source: the single scan of the URL
52/// grammar that every remote rule reads — the scheme test, the credentials
53/// check, the control-character check and the canonical identity — so none of
54/// them can disagree about where the authority ends. The fragment is dropped
55/// here, and nothing past it is ever sent. `None` for every other spelling (a
56/// bare path, `file://`, another scheme), which keeps its local-file handling.
57pub(super) struct RemoteUrl<'a> {
58    scheme: &'a str,
59    authority: &'a str,
60    /// The path and query, from the first `/` or `?` (empty when neither).
61    rest: &'a str,
62}
63
64impl<'a> RemoteUrl<'a> {
65    /// The scheme is matched without regard to case.
66    pub(super) fn parse(source: &'a str) -> Option<Self> {
67        let (scheme, after) = source.split_once("://")?;
68        if !(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https")) {
69            return None;
70        }
71        let after = after.split_once('#').map_or(after, |(url, _)| url);
72        // The authority ends at the first `/` or `?`; with neither, the whole
73        // remainder is the authority.
74        let end = after.find(['/', '?']).unwrap_or(after.len());
75        let (authority, rest) = after.split_at(end);
76        Some(Self {
77            scheme,
78            authority,
79            rest,
80        })
81    }
82
83    /// Whether the authority carries credentials (`user:password@host`):
84    /// refused before any request, so a secret typed into a query never
85    /// reaches a host's transport or a log. An `@` after the authority is
86    /// path or query text, not userinfo.
87    pub(super) fn carries_credentials(&self) -> bool {
88        self.authority.contains('@')
89    }
90
91    /// Whether the URL is free of the characters that make a request line or
92    /// a header injectable — ASCII controls (CR, LF, tab, NUL, …) and the
93    /// space. The engine checks this itself, so a host's fetcher never
94    /// receives them whatever its own URI parser tolerates.
95    pub(super) fn is_well_formed(&self) -> bool {
96        [self.scheme, self.authority, self.rest]
97            .iter()
98            .all(|part| !part.chars().any(|c| c.is_ascii_control() || c == ' '))
99    }
100
101    /// The source's one identity, for the memo and for the host: scheme and
102    /// authority are case-insensitive (RFC 3986 §6.2.2.1) and lowercased, the
103    /// fragment is gone, and the path and query are case-sensitive and kept as
104    /// written. Every such spelling of one URL is one source — and the seeded
105    /// offline fixture answers for all of them, never reaching a fetcher.
106    pub(super) fn canonical(&self) -> String {
107        format!(
108            "{}://{}{}",
109            self.scheme.to_ascii_lowercase(),
110            self.authority.to_ascii_lowercase(),
111            self.rest
112        )
113    }
114}
115
116impl RemoteFailure {
117    /// The one wording of each failure: generic, typed, and free of the URL.
118    pub(super) fn into_error(self) -> Error {
119        match self {
120            Self::Status(status) => {
121                Error::execution(format!("LOAD CSV remote source returned HTTP {status}"))
122            }
123            Self::ExceededLimit => byte_limit_exceeded(),
124            Self::Timeout => Error::execution("LOAD CSV remote source timed out"),
125            Self::Redirect => Error::execution("LOAD CSV remote redirect refused"),
126            Self::Unreachable => Error::execution("LOAD CSV remote source unreachable"),
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134
135    fn canonical(source: &str) -> Option<String> {
136        RemoteUrl::parse(source).map(|url| url.canonical())
137    }
138
139    #[test]
140    fn only_http_and_https_sources_are_remote() {
141        for (source, url) in [
142            ("https://example.org/a.csv", "https://example.org/a.csv"),
143            ("http://example.org/a.csv", "http://example.org/a.csv"),
144            // The scheme and host are case-insensitive and lowercased; the
145            // path is case-sensitive and kept.
146            ("HTTPS://Example.org/A.csv", "https://example.org/A.csv"),
147            ("Http://EXAMPLE.org:8080/a", "http://example.org:8080/a"),
148            // A fragment is dropped; a query string is kept (presigned links).
149            ("https://example.org/a.csv#top", "https://example.org/a.csv"),
150            (
151                "https://example.org/a.csv?sig=1#x",
152                "https://example.org/a.csv?sig=1",
153            ),
154            // No path at all: the whole remainder is the authority.
155            ("HTTPS://Example.ORG", "https://example.org"),
156        ] {
157            assert_eq!(canonical(source).as_deref(), Some(url), "{source}");
158        }
159        for source in [
160            "rows.csv",
161            "dir/rows.csv",
162            "file:///tmp/rows.csv",
163            "ftp://example.org/a.csv",
164            "s3://bucket/a.csv",
165            "https:/example.org/a.csv",
166            "httpsx://example.org/a.csv",
167            "//example.org/a.csv",
168            "",
169        ] {
170            assert!(RemoteUrl::parse(source).is_none(), "{source}");
171        }
172    }
173
174    #[test]
175    fn credentials_are_found_in_the_authority_only() {
176        let carries = |url: &str| RemoteUrl::parse(url).unwrap().carries_credentials();
177        for url in [
178            "https://user@example.org/a.csv",
179            "https://user:secret@example.org/a.csv",
180            "http://:secret@example.org/",
181            "https://user@example.org",
182        ] {
183            assert!(carries(url), "{url}");
184        }
185        for url in [
186            "https://example.org/a.csv",
187            "https://example.org:8443/a.csv",
188            // An `@` after the authority is path or query text, not userinfo.
189            "https://example.org/a@b.csv",
190            "https://example.org/a.csv?mail=a@b.org",
191            // ...and one after the fragment mark is not even part of the URL.
192            "https://example.org/a.csv#x@y",
193        ] {
194            assert!(!carries(url), "{url}");
195        }
196    }
197
198    #[test]
199    fn control_characters_and_spaces_make_a_url_malformed() {
200        let well_formed = |url: &str| RemoteUrl::parse(url).unwrap().is_well_formed();
201        for url in [
202            "https://example.org/a\r\nX-Injected: 1",
203            "https://example.org/a\nb",
204            "https://example.org/a\tb",
205            "https://example.org/a\0b",
206            "https://example.org/a b.csv",
207            "https://example.org/a\x7fb",
208            "https://exam ple.org/",
209            "https://example.org/?q=a b",
210        ] {
211            assert!(!well_formed(url), "{url:?}");
212        }
213        for url in [
214            "https://example.org/a%20b.csv",
215            "https://example.org/a.csv?x=1&y=2",
216            "https://example.org/caf\u{e9}.csv",
217            // Whatever follows the fragment mark is dropped, never sent.
218            "https://example.org/a.csv#frag ment",
219        ] {
220            assert!(well_formed(url), "{url:?}");
221        }
222    }
223
224    #[test]
225    fn every_failure_has_one_generic_wording_without_the_url() {
226        for (failure, message) in [
227            (
228                RemoteFailure::Status(404),
229                "LOAD CSV remote source returned HTTP 404",
230            ),
231            (
232                RemoteFailure::ExceededLimit,
233                "LOAD CSV file exceeds byte limit",
234            ),
235            (RemoteFailure::Timeout, "LOAD CSV remote source timed out"),
236            (RemoteFailure::Redirect, "LOAD CSV remote redirect refused"),
237            (
238                RemoteFailure::Unreachable,
239                "LOAD CSV remote source unreachable",
240            ),
241        ] {
242            assert_eq!(failure.into_error(), Error::execution(message));
243        }
244    }
245}