Skip to main content

ursa_engine/
paths.rs

1//! Turning a name in `FROM` into a file location.
2//!
3//! `SELECT * FROM 'edges.parquet'` names a file where a table would go. A name
4//! that reads as a location (it has a scheme, a path separator, an extension or
5//! a glob) is opened as a listing table; anything else is left to the catalog,
6//! so a misspelt table name still reports "table not found".
7//!
8//! DataFusion's [`ListingTableUrl::parse`] expands a glob only in a scheme-less
9//! local path. [`table_url`] also expands one in a URL (`s3://bucket/dir/*.parquet`,
10//! `file:///data/*.csv`): the URL is split at the path segment where the glob
11//! begins, the part before it becomes the listing prefix, and the rest filters
12//! the listing.
13//!
14//! A relative path resolves against the session's [`Root`]: a directory
15//! natively, a URL in the browser, or, natively with none, the working
16//! directory. A session with a directory root also writes only under it
17//! ([`write_target`], [`check_write`]), and a read-only session writes
18//! nothing ([`set_read_only`]).
19
20use std::path::{Component, Path, PathBuf};
21use std::sync::Arc;
22
23use datafusion::datasource::listing::ListingTableUrl;
24use datafusion::error::{DataFusionError, Result};
25use datafusion::prelude::{SessionConfig, SessionContext};
26use glob::Pattern;
27use url::Url;
28
29/// The characters that start a glob, as DataFusion's local-path parser has them.
30const GLOB_START_CHARS: [char; 3] = ['*', '?', '['];
31
32/// Whether a table name reads as a file location rather than a table name.
33pub fn looks_like_location(name: &str) -> bool {
34    name.contains(['/', '\\', '.']) || name.contains(GLOB_START_CHARS) || name.starts_with('~')
35}
36
37/// `~` or `~/…` with the home directory put in for the `~`.
38pub fn expand_tilde(location: &str) -> String {
39    if location == "~" || location.starts_with("~/") {
40        if let Some(home) = std::env::var_os("HOME").and_then(|h| h.into_string().ok()) {
41            if !home.is_empty() {
42                return format!("{home}{}", &location[1..]);
43            }
44        }
45    }
46    location.to_string()
47}
48
49/// The listing table URL for a location: a local path (with globs, as DataFusion
50/// expands them), or a URL whose path may contain a glob. A relative path is
51/// relative to the process's working directory; [`session_table_url`]
52/// resolves it against a session's [`Root`].
53pub fn table_url(location: &str) -> Result<ListingTableUrl> {
54    table_url_under(None, location)
55}
56
57/// [`table_url`] in the session with `config`: a relative path resolves
58/// against the session's [`Root`], if it has one.
59pub fn session_table_url(config: &SessionConfig, location: &str) -> Result<ListingTableUrl> {
60    table_url_under(root(config).as_ref(), location)
61}
62
63fn table_url_under(root: Option<&Root>, location: &str) -> Result<ListingTableUrl> {
64    let location = resolve_under(root, location)?;
65    if let Some((base, pattern)) = split_url_glob(&location) {
66        let url = Url::parse(base)
67            .map_err(|e| DataFusionError::Plan(format!("'{location}' is not a valid URL: {e}")))?;
68        let glob = Pattern::new(pattern).map_err(|e| {
69            DataFusionError::Plan(format!(
70                "'{pattern}' in '{location}' is not a valid glob: {e}"
71            ))
72        })?;
73        return ListingTableUrl::try_new(url, Some(glob));
74    }
75    ListingTableUrl::parse(&location)
76        .map_err(|e| DataFusionError::Plan(format!("'{location}' is not a valid path or URL: {e}")))
77}
78
79/// For a URL with a scheme, split it at the start of the path segment that holds
80/// the first glob character: `s3://b/data/*.parquet` gives `("s3://b/data/",
81/// "*.parquet")`. `None` for a local path (DataFusion expands its globs itself),
82/// a URL without a glob, and `http(s)` URLs, where `?` starts a query and a
83/// server cannot be listed anyway.
84pub fn split_url_glob(location: &str) -> Option<(&str, &str)> {
85    let scheme_end = location.find("://")?;
86    let scheme = &location[..scheme_end];
87    // A one-letter "scheme" is a Windows drive letter.
88    if scheme.len() < 2
89        || !scheme
90            .chars()
91            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
92        || matches!(scheme, "http" | "https")
93    {
94        return None;
95    }
96    let authority_start = scheme_end + 3;
97    let path_start = authority_start + location[authority_start..].find('/')?;
98    let path = &location[path_start..];
99    let glob_at = path.find(GLOB_START_CHARS)?;
100    // `path` starts with '/', so there is always a separator before the glob.
101    let split = path_start + path[..glob_at].rfind('/')? + 1;
102    Some((&location[..split], &location[split..]))
103}
104
105/// Where a session's relative paths resolve: its root.
106///
107/// The root travels with the session, as an extension of its
108/// [`SessionConfig`] ([`set_root`], [`with_root`]), so two sessions in one
109/// process can each have their own.
110///
111/// - **No root:** natively, a relative path is relative to the process's
112///   working directory, as the CLI has always read it. The browser has no
113///   working directory, so there a relative path is an error.
114/// - **[`Root::Dir`]:** a directory, natively (`ursa serve DIR`). `'edges.csv'`
115///   is `DIR/edges.csv`. Reads are not confined: an absolute path, `~/…` or a
116///   URL reads what it names, as anywhere else in the native engine. Writes
117///   are: `COPY … TO` and `.output` write only under the root
118///   ([`write_target`]), and `INSERT INTO` a table of files only into files
119///   under it ([`check_write`]).
120/// - **[`Root::Url`]:** a URL, such as the browser shell's `https://…/data/`.
121///   A relative path, or an absolute one (`/data/x.csv`), is joined to it as
122///   a browser joins a link. It confines no write: a browser writes only the
123///   session's own files (`crate::session_files`).
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum Root {
126    /// A directory. A relative one is made absolute (against the working
127    /// directory) when it is set.
128    Dir(PathBuf),
129    /// A URL. One that names a directory ends in `/`, as in a browser.
130    Url(Url),
131}
132
133/// The session's root, as its config holds it.
134#[derive(Debug)]
135struct SessionRoot(Option<Root>);
136
137/// `config` with `root` as its session's root (`None`: none).
138pub fn with_root(config: SessionConfig, root: Option<Root>) -> SessionConfig {
139    config.with_extension(Arc::new(SessionRoot(root.map(absolute))))
140}
141
142/// Set (or clear) the root of the session `ctx`. It applies from the next
143/// statement on.
144pub fn set_root(ctx: &SessionContext, root: Option<Root>) {
145    let state = ctx.state_ref();
146    let mut state = state.write();
147    state
148        .config_mut()
149        .set_extension(Arc::new(SessionRoot(root.map(absolute))));
150}
151
152/// The root of the session with `config`, if it has one.
153pub fn root(config: &SessionConfig) -> Option<Root> {
154    config
155        .get_extension::<SessionRoot>()
156        .and_then(|root| root.0.clone())
157}
158
159/// The directory a native session's relative local paths are relative to:
160/// its root, if that is a directory, else the working directory. `None` if
161/// the working directory cannot be read (or the root is a URL).
162pub fn base_dir(config: &SessionConfig) -> Option<PathBuf> {
163    match root(config) {
164        Some(Root::Dir(dir)) => Some(dir),
165        Some(Root::Url(_)) => None,
166        None => std::env::current_dir().ok(),
167    }
168}
169
170fn absolute(root: Root) -> Root {
171    match root {
172        Root::Dir(dir) if dir.is_relative() => Root::Dir(std::path::absolute(&dir).unwrap_or(dir)),
173        root => root,
174    }
175}
176
177/// Whether `location` is a URL: it has a scheme of two letters or more (a
178/// one-letter one is a Windows drive).
179fn has_scheme(location: &str) -> bool {
180    matches!(Url::parse(location), Ok(url) if url.scheme().len() > 1)
181}
182
183/// `location` (a path, glob or URL, as `FROM` names it) resolved in the
184/// session with `config`: `~` expanded, then a relative path joined to the
185/// session's [`Root`]. With no root, a relative path is left as it is (the
186/// working directory's), except in the browser, which has none.
187pub fn resolve(config: &SessionConfig, location: &str) -> Result<String> {
188    resolve_under(root(config).as_ref(), location)
189}
190
191fn resolve_under(root: Option<&Root>, location: &str) -> Result<String> {
192    let location = expand_tilde(location);
193    if has_scheme(&location) {
194        return Ok(location);
195    }
196    match root {
197        Some(Root::Url(base)) => base.join(&location).map(String::from).map_err(|e| {
198            DataFusionError::Plan(format!("'{location}' is not a valid path or URL: {e}"))
199        }),
200        Some(Root::Dir(_)) if Path::new(&location).is_absolute() => Ok(location),
201        Some(Root::Dir(dir)) => dir
202            .join(&location)
203            .into_os_string()
204            .into_string()
205            .map_err(|_| {
206                DataFusionError::Plan(format!(
207                    "'{location}' cannot be read: the session's root, {}, is not valid UTF-8",
208                    dir.display()
209                ))
210            }),
211        None if cfg!(target_arch = "wasm32") => Err(DataFusionError::Plan(format!(
212            "'{location}' is a relative path, and the browser has no current directory; \
213             use an http:// or https:// URL"
214        ))),
215        None => Ok(location),
216    }
217}
218
219/// Whether a session writes no files ([`set_read_only`]).
220#[derive(Debug)]
221struct ReadOnly(bool);
222
223/// Make the session `ctx` read-only (`ursa serve --read-only`): it writes no
224/// files. [`write_target`] and [`check_write`] refuse every write, and
225/// `ursa-sql` refuses `COPY … TO` (also to the session's files in memory),
226/// `INSERT INTO` a table that is not in memory, and `ATTACH` of a database
227/// that does not exist; it opens one that does read-only. Reads, and what a
228/// session defines in memory (views, tables, graphs), are as before.
229pub fn set_read_only(ctx: &SessionContext, on: bool) {
230    let state = ctx.state_ref();
231    let mut state = state.write();
232    state.config_mut().set_extension(Arc::new(ReadOnly(on)));
233}
234
235/// Whether the session with `config` is read-only ([`set_read_only`]).
236pub fn is_read_only(config: &SessionConfig) -> bool {
237    config.get_extension::<ReadOnly>().is_some_and(|on| on.0)
238}
239
240/// Refuse a write in a read-only session ([`set_read_only`]), with a reason
241/// that does not name what was refused, for the caller to say that.
242pub fn check_writable(config: &SessionConfig) -> Result<()> {
243    if is_read_only(config) {
244        return Err(DataFusionError::Plan(READ_ONLY.into()));
245    }
246    Ok(())
247}
248
249/// Why a read-only session refuses a write.
250pub const READ_ONLY: &str =
251    "this session is read-only (ursa serve --read-only), and writes no files";
252
253/// Where a write to `target` (`COPY … TO 'target'`, `.output target`) goes in
254/// the session with `config`: `Ok(None)` to write it as named, in a session
255/// with no directory [`Root`]; in a session with one, the absolute path under
256/// the root that `target` names, or why it may not be written (a reason
257/// that does not repeat `target`, for the caller to say what was refused).
258/// A read-only session ([`set_read_only`]) refuses every target.
259///
260/// A rooted session writes only under its root. `target` must be a relative
261/// path with no `..` (not absolute, not `~/…`, not a URL), and no part of it
262/// that exists may be a symbolic link that leads outside the root. The check
263/// is made before the write, not during it: it keeps a client of the session
264/// (a page, an agent) inside the root, not another process that swaps a
265/// directory for a link in between.
266pub fn write_target(config: &SessionConfig, target: &str) -> Result<Option<String>> {
267    check_writable(config)?;
268    match root(config) {
269        Some(Root::Dir(dir)) => under_root(&dir, target).map(Some),
270        _ => Ok(None),
271    }
272}
273
274fn under_root(dir: &Path, target: &str) -> Result<String> {
275    let outside = |why: &str| {
276        DataFusionError::Plan(format!(
277            "it is outside this session's root, {} ({why}); a session with a root writes \
278             only under it, to a relative path such as 'out/result.parquet'",
279            dir.display()
280        ))
281    };
282    if has_scheme(target) {
283        return Err(outside("it is a URL"));
284    }
285    if target.starts_with('~') {
286        return Err(outside("it is in the home directory"));
287    }
288    let mut parts = Vec::new();
289    for component in Path::new(target).components() {
290        match component {
291            Component::Normal(part) => parts.push(part),
292            Component::CurDir => {}
293            Component::ParentDir => return Err(outside("it has '..' in it")),
294            Component::RootDir | Component::Prefix(_) => {
295                return Err(outside("it is an absolute path"))
296            }
297        }
298    }
299    if parts.is_empty() {
300        return Err(outside("it names the root itself"));
301    }
302    let root = std::fs::canonicalize(dir).map_err(|e| {
303        DataFusionError::Plan(format!(
304            "the session's root, {}, cannot be read: {e}",
305            dir.display()
306        ))
307    })?;
308    let mut path = root.clone();
309    path.extend(&parts);
310    match resolve_links(&path) {
311        Ok(real) if real.starts_with(&root) => {}
312        Ok(_) => return Err(outside("a symbolic link in it leads outside the root")),
313        Err(e) => {
314            return Err(DataFusionError::Plan(format!(
315                "a symbolic link in it cannot be followed: {e}"
316            )))
317        }
318    }
319    let mut written = path.into_os_string().into_string().map_err(|_| {
320        DataFusionError::Plan(format!(
321            "the session's root, {}, is not valid UTF-8",
322            dir.display()
323        ))
324    })?;
325    // `COPY … TO 'out/'` writes a directory of files.
326    if target.ends_with(['/', std::path::MAIN_SEPARATOR]) {
327        written.push(std::path::MAIN_SEPARATOR);
328    }
329    Ok(written)
330}
331
332/// Refuse a write to the files at `url` (an `INSERT INTO` a table of files)
333/// in a session with a directory [`Root`], unless they are under it: a local
334/// path whose links stay inside the root. Any write is allowed in a session
335/// without one, unless it is read-only ([`set_read_only`]).
336pub fn check_write(config: &SessionConfig, url: &Url) -> Result<()> {
337    if is_read_only(config) {
338        return Err(DataFusionError::Plan(format!(
339            "cannot write to {url}: {READ_ONLY}"
340        )));
341    }
342    let Some(Root::Dir(dir)) = root(config) else {
343        return Ok(());
344    };
345    let refused = || {
346        DataFusionError::Plan(format!(
347            "cannot write to {url}: it is outside this session's root, {}, and a session \
348             with a root writes only under it",
349            dir.display()
350        ))
351    };
352    let path = local_path(url).ok_or_else(refused)?;
353    let root = std::fs::canonicalize(&dir).map_err(|_| refused())?;
354    match resolve_links(&path) {
355        Ok(real) if real.starts_with(&root) => Ok(()),
356        _ => Err(refused()),
357    }
358}
359
360/// The local path a `file://` URL names.
361#[cfg(not(target_arch = "wasm32"))]
362fn local_path(url: &Url) -> Option<PathBuf> {
363    (url.scheme() == "file").then(|| url.to_file_path().ok())?
364}
365
366/// The browser has no local paths.
367#[cfg(target_arch = "wasm32")]
368fn local_path(_: &Url) -> Option<PathBuf> {
369    None
370}
371
372/// `path` (absolute, without `..`) with its symbolic links resolved as far as
373/// it exists, and the rest, which does not exist yet, as it is. An error for
374/// a link that cannot be followed (one that leads nowhere, or a loop): a
375/// write would create its target, wherever it is.
376fn resolve_links(path: &Path) -> std::io::Result<PathBuf> {
377    match std::fs::canonicalize(path) {
378        Ok(real) => Ok(real),
379        Err(e) => {
380            // It is there (a link), but cannot be followed.
381            if std::fs::symlink_metadata(path).is_ok() {
382                return Err(e);
383            }
384            match (path.parent(), path.file_name()) {
385                (Some(parent), Some(name)) => Ok(resolve_links(parent)?.join(name)),
386                _ => Err(e),
387            }
388        }
389    }
390}
391
392#[cfg(test)]
393mod tests {
394    use super::*;
395
396    #[test]
397    fn locations_and_table_names() {
398        assert!(looks_like_location("edges.csv"));
399        assert!(looks_like_location("data/edges"));
400        assert!(looks_like_location("s3://bucket/x"));
401        assert!(looks_like_location("*.parquet"));
402        assert!(looks_like_location("~/edges"));
403        assert!(!looks_like_location("edges"));
404        assert!(!looks_like_location("my_table"));
405    }
406
407    #[test]
408    fn splits_url_globs() {
409        assert_eq!(
410            split_url_glob("s3://bucket/data/*.parquet"),
411            Some(("s3://bucket/data/", "*.parquet"))
412        );
413        assert_eq!(
414            split_url_glob("gs://bucket/a/b/part-?.csv"),
415            Some(("gs://bucket/a/b/", "part-?.csv"))
416        );
417        assert_eq!(
418            split_url_glob("s3://bucket/year=*/x.parquet"),
419            Some(("s3://bucket/", "year=*/x.parquet"))
420        );
421        assert_eq!(
422            split_url_glob("file:///tmp/x/[ab].csv"),
423            Some(("file:///tmp/x/", "[ab].csv"))
424        );
425        assert_eq!(split_url_glob("s3://bucket/data/x.parquet"), None);
426        assert_eq!(split_url_glob("https://host/x.csv?y=1"), None);
427        assert_eq!(split_url_glob("data/*.csv"), None);
428        assert_eq!(split_url_glob("C://data/*.csv"), None);
429    }
430
431    #[test]
432    fn remote_glob_url_lists_its_prefix() {
433        let url = table_url("s3://bucket/data/*.parquet").unwrap();
434        assert_eq!(url.scheme(), "s3");
435        assert_eq!(url.prefix().as_ref(), "data");
436        assert!(url.is_collection());
437        assert_eq!(url.get_glob().as_ref().unwrap().as_str(), "*.parquet");
438    }
439
440    fn rooted(dir: &Path) -> SessionConfig {
441        with_root(SessionConfig::new(), Some(Root::Dir(dir.to_path_buf())))
442    }
443
444    #[cfg(unix)]
445    #[test]
446    fn a_relative_path_resolves_against_the_root() {
447        let config = rooted(Path::new("/srv/data"));
448        assert_eq!(
449            resolve(&config, "edges.csv").unwrap(),
450            "/srv/data/edges.csv"
451        );
452        assert_eq!(
453            resolve(&config, "./sub/*.csv").unwrap(),
454            "/srv/data/./sub/*.csv"
455        );
456        assert_eq!(
457            resolve(&config, "/abs/edges.csv").unwrap(),
458            "/abs/edges.csv"
459        );
460        assert_eq!(
461            resolve(&config, "s3://bucket/x.parquet").unwrap(),
462            "s3://bucket/x.parquet"
463        );
464        let url = with_root(
465            SessionConfig::new(),
466            Some(Root::Url(Url::parse("https://example.com/data/").unwrap())),
467        );
468        assert_eq!(
469            resolve(&url, "karate_edges.csv").unwrap(),
470            "https://example.com/data/karate_edges.csv"
471        );
472        assert_eq!(
473            resolve(&url, "/other/x.csv").unwrap(),
474            "https://example.com/other/x.csv"
475        );
476        // No root: as written, the working directory's (natively).
477        assert_eq!(
478            resolve(&SessionConfig::new(), "edges.csv").unwrap(),
479            "edges.csv"
480        );
481        let table = session_table_url(&config, "edges.csv").unwrap();
482        assert_eq!(table.get_url().as_str(), "file:///srv/data/edges.csv");
483    }
484
485    #[test]
486    fn a_relative_root_is_made_absolute() {
487        let config = with_root(SessionConfig::new(), Some(Root::Dir("data".into())));
488        let Some(Root::Dir(dir)) = root(&config) else {
489            panic!("a directory root")
490        };
491        assert_eq!(dir, std::env::current_dir().unwrap().join("data"));
492    }
493
494    #[test]
495    fn writes_stay_under_the_root() {
496        let dir = tempfile::tempdir().unwrap();
497        let root_dir = std::fs::canonicalize(dir.path()).unwrap();
498        let config = rooted(dir.path());
499        let target = |t: &str| write_target(&config, t);
500        assert_eq!(
501            target("out.parquet").unwrap().unwrap(),
502            root_dir.join("out.parquet").to_str().unwrap()
503        );
504        assert_eq!(
505            target("./new/dir/out.csv").unwrap().unwrap(),
506            root_dir.join("new/dir/out.csv").to_str().unwrap()
507        );
508        assert!(target("parts/").unwrap().unwrap().ends_with("parts/"));
509        for (refused, why) in [
510            ("../out.csv", "'..'"),
511            ("a/../../out.csv", "'..'"),
512            ("/tmp/out.csv", "absolute"),
513            ("~/out.csv", "home directory"),
514            ("file:///tmp/out.csv", "URL"),
515            ("s3://bucket/out.csv", "URL"),
516            ("memory://uploads/out.csv", "URL"),
517            (".", "the root itself"),
518        ] {
519            let e = target(refused).unwrap_err().to_string();
520            assert!(
521                e.contains("outside this session's root") && e.contains(why),
522                "{refused}: {e}"
523            );
524        }
525        // No root: as written.
526        assert_eq!(
527            write_target(&SessionConfig::new(), "/tmp/x.csv").unwrap(),
528            None
529        );
530    }
531
532    #[cfg(unix)]
533    #[test]
534    fn a_symbolic_link_out_of_the_root_is_refused() {
535        let dir = tempfile::tempdir().unwrap();
536        let outside = tempfile::tempdir().unwrap();
537        let root_dir = dir.path().join("root");
538        std::fs::create_dir(&root_dir).unwrap();
539        std::fs::create_dir(root_dir.join("inside")).unwrap();
540        std::os::unix::fs::symlink(outside.path(), root_dir.join("away")).unwrap();
541        std::os::unix::fs::symlink(root_dir.join("inside"), root_dir.join("here")).unwrap();
542        std::os::unix::fs::symlink(outside.path().join("x.csv"), root_dir.join("dangling.csv"))
543            .unwrap();
544        std::os::unix::fs::symlink(outside.path().join("y.csv"), root_dir.join("inside/y.csv"))
545            .unwrap();
546        let config = rooted(&root_dir);
547        for refused in ["away/x.csv", "away/new/x.csv", "here/y.csv"] {
548            let e = write_target(&config, refused).unwrap_err().to_string();
549            assert!(e.contains("symbolic link"), "{refused}: {e}");
550        }
551        // A link that leads nowhere would be created wherever it points.
552        let e = write_target(&config, "dangling.csv")
553            .unwrap_err()
554            .to_string();
555        assert!(e.contains("cannot be followed"), "{e}");
556        // A link that stays inside the root is fine.
557        assert!(write_target(&config, "here/z.csv").unwrap().is_some());
558        // A root that is itself a link is followed.
559        let linked = dir.path().join("linked");
560        std::os::unix::fs::symlink(&root_dir, &linked).unwrap();
561        assert!(write_target(&rooted(&linked), "inside/z.csv")
562            .unwrap()
563            .is_some());
564
565        let inside = Url::from_file_path(root_dir.join("inside/t.csv")).unwrap();
566        check_write(&config, &inside).unwrap();
567        let away = Url::from_file_path(root_dir.join("away/t.csv")).unwrap();
568        assert!(check_write(&config, &away).is_err());
569        let s3 = Url::parse("s3://bucket/t.csv").unwrap();
570        assert!(check_write(&config, &s3).is_err());
571        check_write(&SessionConfig::new(), &s3).unwrap();
572    }
573
574    #[test]
575    fn a_read_only_session_writes_nothing() {
576        let dir = tempfile::tempdir().unwrap();
577        let read_only = |config: SessionConfig| config.with_extension(Arc::new(ReadOnly(true)));
578        for config in [
579            read_only(rooted(dir.path())),
580            read_only(SessionConfig::new()),
581        ] {
582            assert!(is_read_only(&config));
583            let e = write_target(&config, "out.csv").unwrap_err().to_string();
584            assert!(e.contains("read-only"), "{e}");
585            let inside = Url::from_file_path(dir.path().join("t.csv")).unwrap();
586            let e = check_write(&config, &inside).unwrap_err().to_string();
587            assert!(e.contains("read-only"), "{e}");
588        }
589        assert!(!is_read_only(&rooted(dir.path())));
590        assert!(write_target(&rooted(dir.path()), "out.csv")
591            .unwrap()
592            .is_some());
593    }
594}