1use 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
29const GLOB_START_CHARS: [char; 3] = ['*', '?', '['];
31
32pub fn looks_like_location(name: &str) -> bool {
34 name.contains(['/', '\\', '.']) || name.contains(GLOB_START_CHARS) || name.starts_with('~')
35}
36
37pub 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
49pub fn table_url(location: &str) -> Result<ListingTableUrl> {
54 table_url_under(None, location)
55}
56
57pub 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
79pub fn split_url_glob(location: &str) -> Option<(&str, &str)> {
85 let scheme_end = location.find("://")?;
86 let scheme = &location[..scheme_end];
87 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 let split = path_start + path[..glob_at].rfind('/')? + 1;
102 Some((&location[..split], &location[split..]))
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
125pub enum Root {
126 Dir(PathBuf),
129 Url(Url),
131}
132
133#[derive(Debug)]
135struct SessionRoot(Option<Root>);
136
137pub fn with_root(config: SessionConfig, root: Option<Root>) -> SessionConfig {
139 config.with_extension(Arc::new(SessionRoot(root.map(absolute))))
140}
141
142pub 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
152pub fn root(config: &SessionConfig) -> Option<Root> {
154 config
155 .get_extension::<SessionRoot>()
156 .and_then(|root| root.0.clone())
157}
158
159pub 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
177fn has_scheme(location: &str) -> bool {
180 matches!(Url::parse(location), Ok(url) if url.scheme().len() > 1)
181}
182
183pub 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#[derive(Debug)]
221struct ReadOnly(bool);
222
223pub 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
235pub fn is_read_only(config: &SessionConfig) -> bool {
237 config.get_extension::<ReadOnly>().is_some_and(|on| on.0)
238}
239
240pub 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
249pub const READ_ONLY: &str =
251 "this session is read-only (ursa serve --read-only), and writes no files";
252
253pub 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 if target.ends_with(['/', std::path::MAIN_SEPARATOR]) {
327 written.push(std::path::MAIN_SEPARATOR);
328 }
329 Ok(written)
330}
331
332pub 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#[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#[cfg(target_arch = "wasm32")]
368fn local_path(_: &Url) -> Option<PathBuf> {
369 None
370}
371
372fn resolve_links(path: &Path) -> std::io::Result<PathBuf> {
377 match std::fs::canonicalize(path) {
378 Ok(real) => Ok(real),
379 Err(e) => {
380 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 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 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 let e = write_target(&config, "dangling.csv")
553 .unwrap_err()
554 .to_string();
555 assert!(e.contains("cannot be followed"), "{e}");
556 assert!(write_target(&config, "here/z.csv").unwrap().is_some());
558 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}