1pub mod azblob;
16pub mod fs;
17pub mod gcs;
18pub mod oss;
19#[cfg(test)]
20mod remote_tests;
21pub mod s3;
22
23use std::collections::HashMap;
24use std::path::{Component, Path, PathBuf};
25use std::sync::Arc;
26
27use common_telemetry::debug;
28use lazy_static::lazy_static;
29use object_store::secure_fs::SecureFsRoot;
30use object_store::util::{with_instrument_layers, with_retry_layers};
31use object_store::{ObjectStore, ObjectStoreBuilder};
32use regex::Regex;
33use snafu::{OptionExt, ResultExt, ensure};
34use url::{ParseError, Url};
35
36use self::azblob::build_azblob_backend;
37use self::fs::build_fs_backend;
38use self::gcs::build_gcs_backend;
39use self::s3::build_s3_backend;
40use crate::error::{self, Result};
41use crate::object_store::oss::build_oss_backend;
42use crate::util::find_dir_and_filename;
43
44pub use object_store::remote_access::RemoteStorageAccess;
45
46pub const FS_SCHEMA: &str = "FS";
47pub const FILE_SCHEMA: &str = "FILE";
48pub const S3_SCHEMA: &str = "S3";
49pub const OSS_SCHEMA: &str = "OSS";
50pub const GCS_SCHEMA: &str = "GCS";
51pub const AZBLOB_SCHEMA: &str = "AZBLOB";
52
53pub struct BuiltBackend {
56 pub object_store: ObjectStore,
57 pub object_path: Option<String>,
58 local_root: Option<SecureFsRoot>,
59}
60
61impl BuiltBackend {
62 pub async fn is_file(&self, path: &str) -> object_store::Result<bool> {
64 let meta = self.object_store.stat(path).await?;
65 self.is_file_with_mode(path, meta.mode()).await
66 }
67
68 pub async fn is_file_with_mode(
70 &self,
71 path: &str,
72 mode: object_store::EntryMode,
73 ) -> object_store::Result<bool> {
74 if mode != object_store::EntryMode::FILE {
75 return Ok(false);
76 }
77 if let Some(root) = &self.local_root {
78 root.is_file(path).await
79 } else {
80 Ok(true)
81 }
82 }
83}
84
85#[derive(Clone, Debug, Default)]
87pub enum LocalFileAccess {
88 #[default]
90 Disabled,
91 Sandboxed { root: LocalFileRoot },
93}
94
95#[derive(Clone, Debug)]
97pub struct LocalFileRoot {
98 root: Arc<SecureFsRoot>,
99 configured_path: Arc<PathBuf>,
100}
101
102impl LocalFileAccess {
103 pub fn sandboxed(root: impl AsRef<Path>) -> Result<Self> {
105 let root_path = root.as_ref();
106 let configured_path =
107 std::path::absolute(root_path).with_context(|_| error::InvalidLocalFileRootSnafu {
108 root: root_path.display().to_string(),
109 })?;
110 let root =
111 SecureFsRoot::open(root_path).with_context(|_| error::InvalidLocalFileRootSnafu {
112 root: root_path.display().to_string(),
113 })?;
114 Ok(Self::Sandboxed {
115 root: LocalFileRoot {
116 root: Arc::new(root),
117 configured_path: Arc::new(configured_path),
118 },
119 })
120 }
121
122 pub fn sandbox_root(&self) -> Option<&Path> {
124 match self {
125 Self::Disabled => None,
126 Self::Sandboxed { root } => Some(root.root.path()),
127 }
128 }
129
130 fn authorize(&self, location: &str, path: &Path, trailing_slash: bool) -> Result<String> {
131 let LocalFileAccess::Sandboxed { root } = self else {
132 return error::LocalFileAccessDisabledSnafu {
133 path: location.to_string(),
134 }
135 .fail();
136 };
137
138 let path = normalize_untrusted_path(path).map_err(|reason| {
139 error::LocalFileAccessDeniedSnafu {
140 path: location.to_string(),
141 reason,
142 }
143 .build()
144 })?;
145 let relative = if path.is_absolute() {
146 strip_local_prefix(&path, root.configured_path.as_path())
147 .or_else(|| strip_local_prefix(&path, root.root.path()))
148 .ok_or_else(|| {
149 error::LocalFileAccessDeniedSnafu {
150 path: location.to_string(),
151 reason: "absolute path is outside the configured copy root".to_string(),
152 }
153 .build()
154 })?
155 } else {
156 path.as_path()
157 };
158
159 let mut authorized = relative
160 .components()
161 .filter_map(|component| match component {
162 Component::CurDir => None,
163 Component::Normal(value) => Some(value.to_string_lossy().into_owned()),
164 _ => None,
165 })
166 .collect::<Vec<_>>()
167 .join("/");
168 if trailing_slash && !authorized.is_empty() {
169 authorized.push('/');
170 }
171 Ok(authorized)
172 }
173
174 async fn open_backend_root(
175 &self,
176 location: &str,
177 relative_root: &str,
178 create: bool,
179 ) -> Result<SecureFsRoot> {
180 let LocalFileAccess::Sandboxed { root } = self else {
181 return error::LocalFileAccessDisabledSnafu {
182 path: location.to_string(),
183 }
184 .fail();
185 };
186
187 let root = root.root.clone();
188 let relative_root = relative_root.trim_matches('/').to_string();
189 common_runtime::spawn_blocking_global(move || {
190 if create {
191 root.create_subdir(relative_root)
192 } else {
193 root.open_subdir(relative_root)
194 }
195 })
196 .await
197 .context(error::JoinHandleSnafu)?
198 .map_err(|error| {
199 debug!(
200 "Failed to open an authorized local SQL path inside the copy root, path: {location}, error: {error:?}"
201 );
202 if error.kind() == std::io::ErrorKind::NotFound {
203 return error::LocalFilePathNotFoundSnafu { path: location }.build();
204 }
205 error::LocalFileAccessDeniedSnafu {
206 path: location.to_string(),
207 reason: "path could not be safely resolved within the configured copy root"
208 .to_string(),
209 }
210 .build()
211 })
212 }
213}
214
215pub fn configured_local_path(location: &str) -> Result<Option<PathBuf>> {
219 #[cfg(windows)]
220 if Path::new(location).is_absolute() {
221 return Ok(Some(PathBuf::from(location)));
222 }
223
224 let (schema, _, path) = parse_url(location)?;
225 match schema.to_uppercase().as_str() {
226 FS_SCHEMA => Ok(Some(PathBuf::from(path))),
227 FILE_SCHEMA => {
228 let url = Url::parse(location).context(error::InvalidUrlSnafu { url: location })?;
229 url.to_file_path().map(Some).map_err(|_| {
230 error::InvalidLocalFileRootConfigSnafu {
231 root: location.to_string(),
232 reason: "file URL must contain a local absolute path".to_string(),
233 }
234 .build()
235 })
236 }
237 _ => Ok(None),
238 }
239}
240
241fn strip_local_prefix<'a>(path: &'a Path, prefix: &Path) -> Option<&'a Path> {
242 #[cfg(not(windows))]
243 {
244 path.strip_prefix(prefix).ok()
245 }
246
247 #[cfg(windows)]
248 {
249 let mut path_components = path.components();
250 for prefix_component in prefix.components() {
251 let path_component = path_components.next()?;
252 if !windows_component_eq(path_component, prefix_component) {
253 return None;
254 }
255 }
256 Some(path_components.as_path())
257 }
258}
259
260#[cfg(windows)]
261fn windows_component_eq(left: Component<'_>, right: Component<'_>) -> bool {
262 match (left, right) {
263 (Component::Prefix(left), Component::Prefix(right)) => {
264 windows_os_str_eq(left.as_os_str(), right.as_os_str())
265 }
266 (Component::Normal(left), Component::Normal(right)) => windows_os_str_eq(left, right),
267 (Component::RootDir, Component::RootDir)
268 | (Component::CurDir, Component::CurDir)
269 | (Component::ParentDir, Component::ParentDir) => true,
270 _ => false,
271 }
272}
273
274#[cfg(windows)]
275fn windows_os_str_eq(left: &std::ffi::OsStr, right: &std::ffi::OsStr) -> bool {
276 use std::os::windows::ffi::OsStrExt;
277
278 fn ascii_lowercase(value: u16) -> u16 {
279 if (u16::from(b'A')..=u16::from(b'Z')).contains(&value) {
280 value + u16::from(b'a' - b'A')
281 } else {
282 value
283 }
284 }
285
286 left.encode_wide()
287 .map(ascii_lowercase)
288 .eq(right.encode_wide().map(ascii_lowercase))
289}
290
291fn normalize_untrusted_path(path: &Path) -> std::result::Result<PathBuf, String> {
292 let mut normalized = PathBuf::new();
293 for component in path.components() {
294 match component {
295 Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
296 Component::RootDir => normalized.push(Path::new(std::path::MAIN_SEPARATOR_STR)),
297 Component::CurDir => {}
298 Component::Normal(value) => {
299 #[cfg(windows)]
300 validate_windows_file_name(&value.to_string_lossy())?;
301 normalized.push(value);
302 }
303 Component::ParentDir => return Err("'..' path components are not allowed".to_string()),
304 }
305 }
306 Ok(normalized)
307}
308
309pub fn validate_windows_file_name(name: &str) -> std::result::Result<(), String> {
311 if name.encode_utf16().count() > 255 {
312 return Err(format!(
313 "Windows file name exceeds 255 UTF-16 units: {name}"
314 ));
315 }
316 if name.chars().any(|c| c < ' ' || "<>:\"/\\|?*".contains(c)) || name.ends_with([' ', '.']) {
317 return Err(format!("invalid Windows file name: {name}"));
318 }
319 let stem = name.split('.').next().unwrap_or(name).trim_end();
320 if matches!(
321 stem.to_ascii_uppercase().as_str(),
322 "CON"
323 | "PRN"
324 | "AUX"
325 | "NUL"
326 | "COM0"
327 | "COM1"
328 | "COM2"
329 | "COM3"
330 | "COM4"
331 | "COM5"
332 | "COM6"
333 | "COM7"
334 | "COM8"
335 | "COM9"
336 | "COM¹"
337 | "COM²"
338 | "COM³"
339 | "LPT0"
340 | "LPT1"
341 | "LPT2"
342 | "LPT3"
343 | "LPT4"
344 | "LPT5"
345 | "LPT6"
346 | "LPT7"
347 | "LPT8"
348 | "LPT9"
349 | "LPT¹"
350 | "LPT²"
351 | "LPT³"
352 ) {
353 return Err(format!("reserved Windows file name: {name}"));
354 }
355 Ok(())
356}
357
358pub fn parse_url(url: &str) -> Result<(String, Option<String>, String)> {
360 #[cfg(windows)]
361 {
362 if handle_windows_path(url).is_some() {
364 return Ok((FS_SCHEMA.to_string(), None, url.to_string()));
365 }
366 }
367 let parsed_url = Url::parse(url);
368 match parsed_url {
369 Ok(url) => Ok((
370 url.scheme().to_string(),
371 url.host_str().map(|s| s.to_string()),
372 url.path().to_string(),
373 )),
374 Err(ParseError::RelativeUrlWithoutBase) => {
375 Ok((FS_SCHEMA.to_string(), None, url.to_string()))
376 }
377 Err(err) => Err(err).context(error::InvalidUrlSnafu { url }),
378 }
379}
380
381pub async fn build_backend(
382 url: &str,
383 connection: &HashMap<String, String>,
384 local_file_access: &LocalFileAccess,
385 remote_storage_access: &RemoteStorageAccess,
386) -> Result<ObjectStore> {
387 Ok(build_backend_inner(
388 url,
389 connection,
390 local_file_access,
391 remote_storage_access,
392 false,
393 false,
394 )
395 .await?
396 .object_store)
397}
398
399pub async fn build_backend_with_path(
401 url: &str,
402 connection: &HashMap<String, String>,
403 local_file_access: &LocalFileAccess,
404 remote_storage_access: &RemoteStorageAccess,
405) -> Result<BuiltBackend> {
406 build_backend_inner(
407 url,
408 connection,
409 local_file_access,
410 remote_storage_access,
411 false,
412 false,
413 )
414 .await
415}
416
417pub async fn build_backend_for_write(
419 url: &str,
420 connection: &HashMap<String, String>,
421 local_file_access: &LocalFileAccess,
422 remote_storage_access: &RemoteStorageAccess,
423) -> Result<ObjectStore> {
424 Ok(build_backend_inner(
425 url,
426 connection,
427 local_file_access,
428 remote_storage_access,
429 true,
430 false,
431 )
432 .await?
433 .object_store)
434}
435
436pub async fn build_backend_for_write_with_path(
438 url: &str,
439 connection: &HashMap<String, String>,
440 local_file_access: &LocalFileAccess,
441 remote_storage_access: &RemoteStorageAccess,
442) -> Result<BuiltBackend> {
443 build_backend_inner(
444 url,
445 connection,
446 local_file_access,
447 remote_storage_access,
448 true,
449 true,
450 )
451 .await
452}
453
454async fn build_backend_inner(
455 url: &str,
456 connection: &HashMap<String, String>,
457 local_file_access: &LocalFileAccess,
458 remote_storage_access: &RemoteStorageAccess,
459 create_local_root: bool,
460 require_object_path: bool,
461) -> Result<BuiltBackend> {
462 let (schema, host, path) = parse_url(url)?;
463 let normalized_schema = schema.to_uppercase();
464
465 if normalized_schema == FS_SCHEMA || normalized_schema == FILE_SCHEMA {
466 let (local_path, trailing_slash) = if normalized_schema == FILE_SCHEMA {
467 let url = Url::parse(url).context(error::InvalidUrlSnafu { url })?;
468 let path = url.to_file_path().map_err(|_| {
469 error::LocalFileAccessDeniedSnafu {
470 path: url.to_string(),
471 reason: "file URL must contain a local absolute path".to_string(),
472 }
473 .build()
474 })?;
475 (path, url.path().ends_with('/'))
476 } else {
477 (
478 PathBuf::from(&path),
479 path.ends_with('/') || cfg!(windows) && path.ends_with(std::path::MAIN_SEPARATOR),
480 )
481 };
482 let authorized = local_file_access.authorize(url, &local_path, trailing_slash)?;
483 let (root, object_path) = find_dir_and_filename(&authorized);
484 if require_object_path && object_path.is_none() {
485 return error::MissingObjectNameSnafu {
486 path: url.to_string(),
487 }
488 .fail();
489 }
490 let root = local_file_access
491 .open_backend_root(url, &root, create_local_root)
492 .await?;
493 return Ok(BuiltBackend {
494 object_store: build_fs_backend(&root)?,
495 object_path,
496 local_root: Some(root),
497 });
498 }
499
500 let (root, object_path) = find_dir_and_filename(&path);
501
502 let object_store = match normalized_schema.as_str() {
503 S3_SCHEMA => {
504 let host = host.context(error::EmptyHostPathSnafu {
505 url: url.to_string(),
506 })?;
507 build_s3_backend(&host, &root, connection, remote_storage_access)?
508 }
509 OSS_SCHEMA => {
510 let host = host.context(error::EmptyHostPathSnafu {
511 url: url.to_string(),
512 })?;
513 build_oss_backend(&host, &root, connection, remote_storage_access)?
514 }
515 GCS_SCHEMA => {
516 let host = host.context(error::EmptyHostPathSnafu {
517 url: url.to_string(),
518 })?;
519 build_gcs_backend(&host, &root, connection, remote_storage_access)?
520 }
521 AZBLOB_SCHEMA => {
522 let host = host.context(error::EmptyHostPathSnafu {
523 url: url.to_string(),
524 })?;
525 build_azblob_backend(&host, &root, connection, remote_storage_access)?
526 }
527 _ => error::UnsupportedBackendProtocolSnafu {
528 protocol: schema,
529 url,
530 }
531 .fail()?,
532 };
533 Ok(BuiltBackend {
534 object_store,
535 object_path,
536 local_root: None,
537 })
538}
539
540fn connection_value<'a>(connection: &'a HashMap<String, String>, key: &str) -> Option<&'a str> {
542 connection
543 .get(key)
544 .map(String::as_str)
545 .filter(|value| !value.is_empty())
546}
547
548fn ensure_server_credentials_allowed(
549 remote_storage_access: &RemoteStorageAccess,
550 backend: &str,
551) -> Result<()> {
552 ensure!(
553 remote_storage_access.allow_server_credentials(),
554 error::ServerCredentialsDisallowedSnafu { backend }
555 );
556 Ok(())
557}
558
559fn finish_remote_backend(
560 builder: impl ObjectStoreBuilder,
561 remote_storage_access: &RemoteStorageAccess,
562) -> Result<ObjectStore> {
563 let object_store = ObjectStore::new(builder).context(error::BuildBackendSnafu)?;
564 Ok(with_instrument_layers(
565 with_retry_layers(remote_storage_access.apply(object_store)),
566 true,
567 ))
568}
569
570lazy_static! {
571 static ref DISK_SYMBOL_PATTERN: Regex = Regex::new(r"^([A-Za-z]:[/\\])").unwrap();
572}
573
574pub fn handle_windows_path(url: &str) -> Option<String> {
575 DISK_SYMBOL_PATTERN
576 .captures(url)
577 .map(|captures| captures[0].to_string())
578}
579
580#[cfg(test)]
581mod tests {
582 use std::collections::HashMap;
583 use std::fs;
584
585 use common_error::ext::{ErrorExt, RetryHint};
586 use common_error::status_code::StatusCode;
587 use common_test_util::temp_dir::create_temp_dir;
588 use url::Url;
589
590 use super::{
591 LocalFileAccess, RemoteStorageAccess, build_backend, build_backend_for_write,
592 build_backend_for_write_with_path, build_backend_with_path, handle_windows_path,
593 };
594 use crate::error::Error;
595
596 #[test]
597 fn test_handle_windows_path() {
598 assert_eq!(
599 handle_windows_path("C:/to/path/file"),
600 Some("C:/".to_string())
601 );
602 assert_eq!(
603 handle_windows_path(r"C:\to\path\file"),
604 Some(r"C:\".to_string())
605 );
606 assert_eq!(handle_windows_path("https://google.com"), None);
607 assert_eq!(handle_windows_path("s3://bucket/path/to"), None);
608 }
609
610 #[test]
611 fn test_windows_file_names() {
612 super::validate_windows_file_name(&format!("{}.parquet", "z".repeat(247))).unwrap();
613 assert!(
614 super::validate_windows_file_name(&format!("{}.parquet", "z".repeat(248))).is_err()
615 );
616 super::validate_windows_file_name(&format!("{}a", "😀".repeat(127))).unwrap();
617 assert!(super::validate_windows_file_name(&"😀".repeat(128)).is_err());
618 for name in [
619 "job:rate5m.parquet",
620 "a:b.parquet",
621 ":leading.parquet",
622 "bad?.csv",
623 "trailing.",
624 "trailing ",
625 ] {
626 assert!(super::validate_windows_file_name(name).is_err(), "{name}");
627 }
628 for name in [
629 "con", "NUL", "aux", "prn", "com0", "COM9", "lpt0", "LPT9", "COM¹", "LPT³",
630 ] {
631 for suffix in ["", ".parquet", ".part.parquet"] {
632 let name = format!("{name}{suffix}");
633 assert!(super::validate_windows_file_name(&name).is_err(), "{name}");
634 }
635 }
636 for name in [
637 "events.parquet",
638 "job.rate5m.parquet",
639 "conifer.csv",
640 "com10.json",
641 "metric#b.parquet",
642 ] {
643 super::validate_windows_file_name(name).unwrap();
644 }
645 }
646
647 #[cfg(windows)]
648 #[tokio::test]
649 async fn test_windows_paths_rejected_before_creating_backend() {
650 let dir = create_temp_dir("windows_copy_paths");
651 let access = LocalFileAccess::sandboxed(dir.path()).unwrap();
652 let sentinel = dir.path().join("b.parquet");
653 fs::write(&sentinel, "preserved").unwrap();
654 for filename in [
655 "job:rate5m.parquet",
656 "job:http:rate5m.parquet",
657 "a:b.parquet",
658 ":leading.parquet",
659 "con.parquet",
660 "nul.part.parquet",
661 ] {
662 let relative = format!("new/{filename}");
663 let absolute = format!("{}/new/{filename}", dir.path().display());
664 let file_url = format!(
665 "{}new/{filename}",
666 Url::from_directory_path(dir.path()).unwrap()
667 );
668 for location in [relative, absolute, file_url] {
669 let result = build_backend_for_write_with_path(
670 &location,
671 &HashMap::new(),
672 &access,
673 &RemoteStorageAccess::unrestricted(),
674 )
675 .await;
676 assert!(
677 matches!(result, Err(Error::LocalFileAccessDenied { .. })),
678 "{location}"
679 );
680 assert!(!dir.path().join("new").exists());
681 assert_eq!(fs::read_to_string(&sentinel).unwrap(), "preserved");
682 }
683 }
684 }
685
686 #[cfg(windows)]
687 #[test]
688 fn test_windows_local_path_detection_and_prefix() {
689 use std::path::{Path, PathBuf};
690
691 let location = r"C:\gtdata";
692 assert_eq!(
693 super::configured_local_path(location).unwrap(),
694 Some(PathBuf::from(location))
695 );
696 assert_eq!(
697 super::parse_url(location).unwrap(),
698 ("FS".to_string(), None, location.to_string())
699 );
700 assert_eq!(
701 super::strip_local_prefix(
702 Path::new(r"c:\Data\Copy\nested\data.parquet"),
703 Path::new(r"C:\data\copy"),
704 ),
705 Some(Path::new(r"nested\data.parquet"))
706 );
707 }
708
709 #[tokio::test]
710 async fn test_local_file_access_policy() {
711 let data_home = create_temp_dir("local_file_access_policy");
712 let copy_root = data_home.path().join("copy");
713 let internal_dir = data_home.path().join("data");
714 fs::create_dir_all(&internal_dir).unwrap();
715 fs::write(internal_dir.join("secret"), "secret").unwrap();
716
717 let access = LocalFileAccess::sandboxed(©_root).unwrap();
718 let connection = HashMap::new();
719
720 let store = build_backend_for_write(
721 "nested/data.txt",
722 &connection,
723 &access,
724 &RemoteStorageAccess::unrestricted(),
725 )
726 .await
727 .unwrap();
728 store.write("data.txt", "first").await.unwrap();
729 store.write("data.txt", "second").await.unwrap();
730 assert_eq!(
731 fs::read_to_string(copy_root.join("nested/data.txt")).unwrap(),
732 "second"
733 );
734
735 let missing = copy_root.join("missing/directory");
736 let error = build_backend(
737 "missing/directory/data.txt",
738 &connection,
739 &access,
740 &RemoteStorageAccess::unrestricted(),
741 )
742 .await
743 .unwrap_err();
744 assert!(matches!(&error, Error::LocalFilePathNotFound { .. }));
745 assert_eq!(error.status_code(), StatusCode::InvalidArguments);
746 assert_eq!(error.retry_hint(), RetryHint::NonRetryable);
747 assert!(
748 error.to_string().contains("does not exist"),
749 "unexpected error: {error}"
750 );
751 assert!(!missing.exists());
752
753 let absolute = copy_root.join("nested/data.txt");
754 let store = build_backend(
755 absolute.to_str().unwrap(),
756 &connection,
757 &access,
758 &RemoteStorageAccess::unrestricted(),
759 )
760 .await
761 .unwrap();
762 assert_eq!(store.read("data.txt").await.unwrap().to_vec(), b"second");
763
764 let file_url = Url::from_file_path(&absolute).unwrap().to_string();
765 let store = build_backend(
766 &file_url,
767 &connection,
768 &access,
769 &RemoteStorageAccess::unrestricted(),
770 )
771 .await
772 .unwrap();
773 assert_eq!(store.read("data.txt").await.unwrap().to_vec(), b"second");
774
775 let internal_file = internal_dir.join("secret");
776 assert!(matches!(
777 build_backend(
778 internal_file.to_str().unwrap(),
779 &connection,
780 &access,
781 &RemoteStorageAccess::unrestricted()
782 )
783 .await,
784 Err(Error::LocalFileAccessDenied { .. })
785 ));
786 assert!(
787 build_backend(
788 "../escape/data.txt",
789 &connection,
790 &access,
791 &RemoteStorageAccess::unrestricted()
792 )
793 .await
794 .is_err()
795 );
796
797 let outside = data_home.path().join("outside/new");
798 assert!(
799 build_backend(
800 outside.to_str().unwrap(),
801 &connection,
802 &access,
803 &RemoteStorageAccess::unrestricted()
804 )
805 .await
806 .is_err()
807 );
808 assert!(!outside.parent().unwrap().exists());
809
810 let prefix_escape = data_home.path().join("copy-not-the-root/new");
811 assert!(matches!(
812 build_backend(
813 prefix_escape.to_str().unwrap(),
814 &connection,
815 &access,
816 &RemoteStorageAccess::unrestricted()
817 )
818 .await,
819 Err(Error::LocalFileAccessDenied { .. })
820 ));
821 assert!(!prefix_escape.parent().unwrap().exists());
822
823 let disabled = LocalFileAccess::Disabled;
824 let error = build_backend(
825 internal_file.to_str().unwrap(),
826 &connection,
827 &disabled,
828 &RemoteStorageAccess::unrestricted(),
829 )
830 .await
831 .unwrap_err();
832 assert!(matches!(&error, Error::LocalFileAccessDisabled { .. }));
833 assert_eq!(error.status_code(), StatusCode::InvalidArguments);
834 assert_eq!(error.retry_hint(), RetryHint::NonRetryable);
835 assert!(matches!(
836 build_backend(
837 &file_url,
838 &connection,
839 &disabled,
840 &RemoteStorageAccess::unrestricted()
841 )
842 .await,
843 Err(Error::LocalFileAccessDisabled { .. })
844 ));
845 assert!(matches!(
846 build_backend(
847 outside.to_str().unwrap(),
848 &connection,
849 &disabled,
850 &RemoteStorageAccess::unrestricted()
851 )
852 .await,
853 Err(Error::LocalFileAccessDisabled { .. })
854 ));
855 assert!(!outside.parent().unwrap().exists());
856 }
857
858 #[tokio::test]
859 async fn test_file_url_returns_decoded_backend_relative_path() {
860 let temp_dir = create_temp_dir("file_url_backend_relative_path");
861 let copy_root = temp_dir.path().join("copy root");
862 let file = copy_root.join("nested dir/data file.txt");
863 fs::create_dir_all(file.parent().unwrap()).unwrap();
864 fs::write(&file, "data").unwrap();
865
866 let location = Url::from_file_path(&file).unwrap().to_string();
867 assert!(location.contains("%20"));
868 let access = LocalFileAccess::sandboxed(©_root).unwrap();
869 let backend = build_backend_with_path(
870 &location,
871 &HashMap::new(),
872 &access,
873 &RemoteStorageAccess::unrestricted(),
874 )
875 .await
876 .unwrap();
877
878 assert_eq!(backend.object_path.as_deref(), Some("data file.txt"));
879 assert_eq!(
880 backend
881 .object_store
882 .read(backend.object_path.as_deref().unwrap())
883 .await
884 .unwrap()
885 .to_vec(),
886 b"data"
887 );
888 }
889
890 #[tokio::test]
891 async fn test_write_with_path_rejects_directory_before_creation() {
892 let temp_dir = create_temp_dir("write_with_path_rejects_directory");
893 let copy_root = temp_dir.path().join("copy");
894 let target = copy_root.join("new directory");
895 let location = Url::from_directory_path(&target).unwrap().to_string();
896 let access = LocalFileAccess::sandboxed(©_root).unwrap();
897
898 let result = build_backend_for_write_with_path(
899 &location,
900 &HashMap::new(),
901 &access,
902 &RemoteStorageAccess::unrestricted(),
903 )
904 .await;
905
906 assert!(matches!(result, Err(Error::MissingObjectName { .. })));
907 assert!(!target.exists());
908
909 let result = build_backend_for_write_with_path(
910 &location,
911 &HashMap::new(),
912 &LocalFileAccess::Disabled,
913 &RemoteStorageAccess::unrestricted(),
914 )
915 .await;
916 assert!(matches!(result, Err(Error::LocalFileAccessDisabled { .. })));
917 assert!(!target.exists());
918
919 let relative_target = copy_root.join("relative directory");
920 let result = build_backend_for_write_with_path(
921 "relative directory/",
922 &HashMap::new(),
923 &access,
924 &RemoteStorageAccess::unrestricted(),
925 )
926 .await;
927 assert!(matches!(result, Err(Error::MissingObjectName { .. })));
928 assert!(!relative_target.exists());
929
930 let allowed_directory = copy_root.join("allowed directory");
931 build_backend_for_write(
932 "allowed directory/",
933 &HashMap::new(),
934 &access,
935 &RemoteStorageAccess::unrestricted(),
936 )
937 .await
938 .unwrap();
939 assert!(allowed_directory.is_dir());
940 }
941
942 #[cfg(windows)]
943 #[tokio::test]
944 async fn test_windows_backslash_path_returns_backend_relative_path() {
945 let temp_dir = create_temp_dir("windows_backend_relative_path");
946 let copy_root = temp_dir.path().join("copy");
947 let directory = copy_root.join("nested");
948 let file = directory.join("data.txt");
949 fs::create_dir_all(&directory).unwrap();
950 fs::write(&file, "data").unwrap();
951
952 let access = LocalFileAccess::sandboxed(©_root).unwrap();
953 let connection = HashMap::new();
954 let file_location = file.to_str().unwrap();
955 assert!(file_location.contains('\\'));
956 let backend = build_backend_with_path(
957 file_location,
958 &connection,
959 &access,
960 &RemoteStorageAccess::unrestricted(),
961 )
962 .await
963 .unwrap();
964 assert_eq!(backend.object_path.as_deref(), Some("data.txt"));
965 assert_eq!(
966 backend
967 .object_store
968 .read(backend.object_path.as_deref().unwrap())
969 .await
970 .unwrap()
971 .to_vec(),
972 b"data"
973 );
974
975 let new_directory = copy_root.join("new directory");
976 let directory_location = format!("{}\\", new_directory.display());
977 assert!(matches!(
978 build_backend_for_write_with_path(
979 &directory_location,
980 &connection,
981 &access,
982 &RemoteStorageAccess::unrestricted()
983 )
984 .await,
985 Err(Error::MissingObjectName { .. })
986 ));
987 assert!(!new_directory.exists());
988 }
989
990 #[tokio::test]
991 async fn test_object_storage_ignores_local_file_policy() {
992 let cases = [
993 (
994 "s3://bucket/path/data%20file.parquet",
995 HashMap::from([
996 ("region".to_string(), "us-east-1".to_string()),
997 ("disable_ec2_metadata".to_string(), "true".to_string()),
998 ]),
999 "data%20file.parquet",
1000 ),
1001 (
1002 "oss://bucket/path/file.parquet",
1003 HashMap::from([
1004 ("endpoint".to_string(), "http://oss.example.com".to_string()),
1005 ("allow_anonymous".to_string(), "true".to_string()),
1006 ]),
1007 "file.parquet",
1008 ),
1009 (
1010 "gcs://bucket/path/file.parquet",
1011 HashMap::from([(
1012 "endpoint".to_string(),
1013 "http://storage.example.com".to_string(),
1014 )]),
1015 "file.parquet",
1016 ),
1017 (
1018 "azblob://container/path/file.parquet",
1019 HashMap::from([
1020 (
1021 "endpoint".to_string(),
1022 "http://storage.example.com".to_string(),
1023 ),
1024 ("account_name".to_string(), "test".to_string()),
1025 ]),
1026 "file.parquet",
1027 ),
1028 ];
1029 for (location, connection, expected_path) in cases {
1030 let backend = build_backend_for_write_with_path(
1031 location,
1032 &connection,
1033 &LocalFileAccess::Disabled,
1034 &RemoteStorageAccess::unrestricted(),
1035 )
1036 .await
1037 .unwrap();
1038 assert_eq!(backend.object_path.as_deref(), Some(expected_path));
1039 }
1040 }
1041
1042 #[cfg(unix)]
1043 #[tokio::test]
1044 async fn test_local_file_access_rejects_symlink_escape() {
1045 use std::os::unix::fs::symlink;
1046
1047 let temp_dir = create_temp_dir("local_file_access_symlink");
1048 let copy_root = temp_dir.path().join("copy");
1049 let outside = temp_dir.path().join("outside");
1050 fs::create_dir_all(©_root).unwrap();
1051 fs::create_dir_all(&outside).unwrap();
1052 fs::write(outside.join("secret"), "secret").unwrap();
1053 symlink(&outside, copy_root.join("escape")).unwrap();
1054 symlink(outside.join("secret"), copy_root.join("secret-link")).unwrap();
1055
1056 let access = LocalFileAccess::sandboxed(©_root).unwrap();
1057 let connection = HashMap::new();
1058
1059 assert!(
1060 build_backend(
1061 "escape/secret",
1062 &connection,
1063 &access,
1064 &RemoteStorageAccess::unrestricted()
1065 )
1066 .await
1067 .is_err()
1068 );
1069 assert!(
1070 build_backend_for_write(
1071 "escape/new",
1072 &connection,
1073 &access,
1074 &RemoteStorageAccess::unrestricted()
1075 )
1076 .await
1077 .is_err()
1078 );
1079 assert!(!outside.join("new").exists());
1080
1081 let store = build_backend(
1082 "secret-link",
1083 &connection,
1084 &access,
1085 &RemoteStorageAccess::unrestricted(),
1086 )
1087 .await
1088 .unwrap();
1089 assert!(store.read("secret-link").await.is_err());
1090 assert!(store.write("secret-link", "overwritten").await.is_err());
1091 assert_eq!(
1092 fs::read_to_string(outside.join("secret")).unwrap(),
1093 "secret"
1094 );
1095 }
1096}