1use std::fmt;
4use std::io;
5use std::path::PathBuf;
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, SystemTime};
8
9use tracing::info;
10
11use super::backend::{S3Backend, Shared};
12use super::cache::MetaCache;
13use super::cachedir::{CacheDir, Recovered, cache_error, identity};
14use super::client::{ListRequest, Location, S3Client, Settings};
15use super::entry::{Entry, Own};
16use super::error::S3Error;
17use super::jobs::{Guard, Jobs};
18use super::keys::{MAX_KEY_LEN, dir_prefix};
19use super::meta::same_times;
20use super::overlay::Overlay;
21use super::parts::{MAX_PART_SIZE, MIN_PART_SIZE};
22use super::readahead::{MAX_CHUNK, MIN_CHUNK, ReadAhead};
23use super::retry::Retry;
24use super::sigv4::Credentials;
25
26const DEFAULT_REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
27const DEFAULT_METADATA_TTL: Duration = Duration::from_secs(30);
28const DEFAULT_LISTING_METADATA_MAX: usize = 1000;
29const DEFAULT_UPLOAD_DELAY: Duration = Duration::from_secs(5);
30const DEFAULT_PART_SIZE: u64 = 16 << 20;
31const DEFAULT_UPLOAD_CONCURRENCY: usize = 4;
32const DEFAULT_READ_CHUNK: u32 = 8 << 20;
33const DEFAULT_MAX_DIR_RENAME_OBJECTS: usize = 10_000;
34
35pub struct S3BackendBuilder {
38 endpoint: String,
39 region: String,
40 bucket: String,
41 credentials: Option<Credentials>,
42 prefix: String,
43 path_style: Option<bool>,
44 cache_dir: Option<PathBuf>,
45 read_only: bool,
46 case_insensitive: bool,
47 request_timeout: Duration,
48 metadata_ttl: Duration,
49 listing_metadata_max: usize,
50 upload_delay: Duration,
51 part_size: u64,
52 upload_concurrency: usize,
53 read_chunk: u32,
54 max_dir_rename_objects: usize,
55 #[cfg(test)]
57 held_uploads: bool,
58}
59
60impl fmt::Debug for S3BackendBuilder {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 f.debug_struct("S3BackendBuilder")
63 .field("endpoint", &origin(&self.endpoint))
64 .field("region", &self.region)
65 .field("bucket", &self.bucket)
66 .field("prefix", &self.prefix)
67 .finish_non_exhaustive()
68 }
69}
70
71fn origin(endpoint: &str) -> String {
74 let start = endpoint.find("://").map_or(0, |at| at + 3);
75 let end = endpoint[start..]
76 .find(['/', '?', '#'])
77 .map_or(endpoint.len(), |at| start + at);
78 let host = endpoint[start..end]
79 .rsplit_once('@')
80 .map_or(&endpoint[start..end], |(_, host)| host);
81 format!("{}{host}", &endpoint[..start])
82}
83
84impl S3Backend {
85 pub fn builder(
89 endpoint: impl Into<String>,
90 region: impl Into<String>,
91 bucket: impl Into<String>,
92 ) -> S3BackendBuilder {
93 S3BackendBuilder {
94 endpoint: endpoint.into(),
95 region: region.into(),
96 bucket: bucket.into(),
97 credentials: None,
98 prefix: String::new(),
99 path_style: None,
100 cache_dir: None,
101 read_only: false,
102 case_insensitive: true,
103 request_timeout: DEFAULT_REQUEST_TIMEOUT,
104 metadata_ttl: DEFAULT_METADATA_TTL,
105 listing_metadata_max: DEFAULT_LISTING_METADATA_MAX,
106 upload_delay: DEFAULT_UPLOAD_DELAY,
107 part_size: DEFAULT_PART_SIZE,
108 upload_concurrency: DEFAULT_UPLOAD_CONCURRENCY,
109 read_chunk: DEFAULT_READ_CHUNK,
110 max_dir_rename_objects: DEFAULT_MAX_DIR_RENAME_OBJECTS,
111 #[cfg(test)]
112 held_uploads: false,
113 }
114 }
115}
116
117impl S3BackendBuilder {
118 #[must_use]
120 pub fn credentials(
121 mut self,
122 access_key: impl Into<String>,
123 secret_key: impl Into<String>,
124 ) -> Self {
125 let session_token = self.credentials.take().and_then(|c| c.session_token);
126 self.credentials = Some(Credentials {
127 access_key: access_key.into(),
128 secret_key: secret_key.into(),
129 session_token,
130 });
131 self
132 }
133
134 #[must_use]
136 pub fn session_token(mut self, token: impl Into<String>) -> Self {
137 let token = Some(token.into());
138 match &mut self.credentials {
139 Some(credentials) => credentials.session_token = token,
140 None => {
141 self.credentials = Some(Credentials {
142 access_key: String::new(),
143 secret_key: String::new(),
144 session_token: token,
145 });
146 }
147 }
148 self
149 }
150
151 #[must_use]
154 pub fn prefix(mut self, prefix: impl AsRef<str>) -> Self {
155 self.prefix = prefix.as_ref().trim_matches('/').to_owned();
156 self
157 }
158
159 #[must_use]
164 pub fn path_style(mut self, path_style: bool) -> Self {
165 self.path_style = Some(path_style);
166 self
167 }
168
169 #[must_use]
181 pub fn cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
182 self.cache_dir = Some(dir.into());
183 self
184 }
185
186 #[must_use]
189 pub fn read_only(mut self) -> Self {
190 self.read_only = true;
191 self
192 }
193
194 #[must_use]
203 pub fn case_insensitive(mut self, case_insensitive: bool) -> Self {
204 self.case_insensitive = case_insensitive;
205 self
206 }
207
208 #[must_use]
211 pub fn request_timeout(mut self, timeout: Duration) -> Self {
212 self.request_timeout = timeout;
213 self
214 }
215
216 #[must_use]
219 pub fn metadata_ttl(mut self, ttl: Duration) -> Self {
220 self.metadata_ttl = ttl;
221 self
222 }
223
224 #[must_use]
231 pub fn listing_metadata_max(mut self, max: usize) -> Self {
232 self.listing_metadata_max = max;
233 self
234 }
235
236 #[must_use]
248 pub fn upload_delay(mut self, delay: Duration) -> Self {
249 self.upload_delay = delay;
250 self
251 }
252
253 #[must_use]
258 pub fn part_size(mut self, bytes: u64) -> Self {
259 self.part_size = bytes;
260 self
261 }
262
263 #[must_use]
267 pub fn upload_concurrency(mut self, concurrency: usize) -> Self {
268 self.upload_concurrency = concurrency;
269 self
270 }
271
272 #[must_use]
280 pub fn read_chunk(mut self, bytes: u32) -> Self {
281 self.read_chunk = bytes;
282 self
283 }
284
285 #[must_use]
292 pub fn max_dir_rename_objects(mut self, max: usize) -> Self {
293 self.max_dir_rename_objects = max;
294 self
295 }
296
297 #[cfg(test)]
300 #[must_use]
301 pub(crate) fn held_uploads(mut self, held: bool) -> Self {
302 self.held_uploads = held;
303 self
304 }
305
306 pub async fn build(self) -> Result<S3Backend, S3Error> {
332 let credentials = self.check()?;
333 let local = match &self.cache_dir {
334 None => None,
335 Some(dir) => {
336 let dir = dir.clone();
337 let who = identity(
338 &origin(&self.endpoint),
339 &self.bucket,
340 &self.prefix,
341 self.case_insensitive,
342 );
343 let opened = tokio::task::spawn_blocking(move || CacheDir::open(&dir, &who))
344 .await
345 .map_err(|e| cache_error(io::Error::other(e)))??;
346 Some(Arc::new(opened))
347 }
348 };
349 let mut settings = Settings::new(
350 Location {
351 endpoint: self.endpoint,
352 region: self.region,
353 bucket: self.bucket,
354 },
355 credentials,
356 );
357 settings.path_style = self.path_style;
358 let client = tokio::task::spawn_blocking(move || S3Client::new(settings))
360 .await
361 .map_err(S3Error::transport)??;
362
363 let root = dir_prefix(&self.prefix);
364 let request = ListRequest {
365 prefix: &root,
366 delimited: false,
367 continuation_token: None,
368 max_keys: Some(1),
369 };
370 client
371 .list_objects(&request, Retry::within(self.request_timeout))
372 .await?;
373
374 let recovered = match &local {
375 None => Recovered::default(),
376 Some(local) => {
377 let local = Arc::clone(local);
378 let (prefix, fold) = (self.prefix.clone(), self.case_insensitive);
379 tokio::task::spawn_blocking(move || local.recover(&prefix, fold))
380 .await
381 .map_err(|e| cache_error(io::Error::other(e)))?
382 .map_err(cache_error)?
383 }
384 };
385
386 let built = SystemTime::now();
387 let ahead = Arc::new(ReadAhead::new());
388 let overlay = Overlay::new(self.case_insensitive, self.upload_delay);
389 let entries = recovered
390 .entries
391 .into_iter()
392 .map(|(record, data)| Entry::recovered(record, data, &ahead))
393 .collect();
394 let restored = overlay.install(entries, recovered.tombstones);
395 if restored > 0 {
396 info!(
397 entries = restored,
398 "entries restored from the cache directory"
399 );
400 }
401
402 let jobs = Jobs::new(self.part_size, self.upload_concurrency);
403 #[cfg(test)]
404 jobs.held
405 .store(self.held_uploads, std::sync::atomic::Ordering::SeqCst);
406 let shared = Arc::new(Shared {
407 client,
408 prefix: self.prefix,
409 case_insensitive: self.case_insensitive,
410 request_timeout: self.request_timeout,
411 listing_metadata_max: self.listing_metadata_max,
412 head_concurrency: head_concurrency(self.upload_concurrency),
413 built,
414 cache: Mutex::new(MetaCache::new(self.metadata_ttl, self.case_insensitive)),
415 read_chunk: u64::from(self.read_chunk),
416 max_dir_rename_objects: self.max_dir_rename_objects,
417 ahead,
418 read_only: self.read_only,
419 overlay,
420 local,
421 root_own: Mutex::new(Own {
422 times: same_times(built),
423 attributes: 0,
424 }),
425 jobs,
426 });
427 let worker = Arc::new(Guard::start(&shared));
428 Ok(S3Backend {
429 shared,
430 _worker: worker,
431 })
432 }
433
434 fn check(&self) -> Result<Credentials, S3Error> {
435 let credentials = match &self.credentials {
436 Some(credentials) if !credentials.access_key.is_empty() => credentials,
437 Some(_) => {
438 return Err(S3Error::InvalidArgument("the access key is empty"));
439 }
440 None => return Err(S3Error::InvalidArgument("the credentials are not set")),
441 };
442 if credentials.secret_key.is_empty() {
443 return Err(S3Error::InvalidArgument("the secret key is empty"));
444 }
445 if credentials.session_token.as_deref() == Some("") {
446 return Err(S3Error::InvalidArgument("the session token is empty"));
447 }
448 if self.request_timeout.is_zero() {
449 return Err(S3Error::InvalidArgument("the request timeout is zero"));
450 }
451 if self.upload_concurrency == 0 {
452 return Err(S3Error::InvalidArgument("the upload concurrency is zero"));
453 }
454 if !(MIN_PART_SIZE..=MAX_PART_SIZE).contains(&self.part_size) {
455 return Err(S3Error::InvalidArgument(
456 "the part size is not between 5 MiB and 5 GiB",
457 ));
458 }
459 if !(MIN_CHUNK..=MAX_CHUNK).contains(&self.read_chunk) {
460 return Err(S3Error::InvalidArgument(
461 "the read chunk is not between 64 KiB and 32 MiB",
462 ));
463 }
464 if self
465 .prefix
466 .split('/')
467 .any(|name| name.is_empty() && !self.prefix.is_empty() || matches!(name, "." | ".."))
468 {
469 return Err(S3Error::InvalidArgument(
470 "the prefix has an empty, . or .. component",
471 ));
472 }
473 if dir_prefix(&self.prefix).len() >= MAX_KEY_LEN {
474 return Err(S3Error::InvalidArgument(
475 "the prefix is too long to leave room for a name",
476 ));
477 }
478 match (self.read_only, &self.cache_dir) {
479 (false, None) => {
480 return Err(S3Error::InvalidArgument(
481 "the cache directory is not set; call cache_dir() or read_only()",
482 ));
483 }
484 (true, Some(_)) => {
485 return Err(S3Error::InvalidArgument(
486 "a read-only backend has no use for a cache directory",
487 ));
488 }
489 _ => {}
490 }
491 Ok(credentials.clone())
492 }
493}
494
495const MAX_HEAD_CONCURRENCY: usize = 64;
497
498fn head_concurrency(upload_concurrency: usize) -> usize {
501 upload_concurrency
502 .saturating_mul(4)
503 .min(MAX_HEAD_CONCURRENCY)
504}
505
506#[cfg(test)]
507mod tests {
508 use super::*;
509
510 fn builder() -> S3BackendBuilder {
511 S3Backend::builder("http://127.0.0.1:1", "us-east-1", "bucket")
512 .credentials("access-key-id", "secret-key-value")
513 .read_only()
514 }
515
516 fn refusal(builder: S3BackendBuilder) -> &'static str {
517 match builder.check() {
518 Err(S3Error::InvalidArgument(why)) => why,
519 other => panic!("not refused: {:?}", other.map(|_| ())),
520 }
521 }
522
523 #[test]
524 fn the_defaults_are_valid() {
525 let credentials = builder().check().unwrap();
526 assert_eq!(credentials.access_key, "access-key-id");
527 assert_eq!(credentials.session_token, None);
528 }
529
530 #[test]
531 fn a_prefix_loses_its_outer_slashes() {
532 for (given, kept) in [
533 ("photos", "photos"),
534 ("/photos/", "photos"),
535 ("///a/b///", "a/b"),
536 ("a/b", "a/b"),
537 ("", ""),
538 ("/", ""),
539 ] {
540 assert_eq!(builder().prefix(given).prefix, kept, "{given:?}");
541 assert!(builder().prefix(given).check().is_ok(), "{given:?}");
542 }
543 }
544
545 #[test]
546 fn a_prefix_with_an_empty_or_dot_component_is_refused() {
547 for prefix in ["a//b", "a/./b", "a/../b", "./a", "a/..", "."] {
548 assert!(
549 refusal(builder().prefix(prefix)).contains("prefix"),
550 "{prefix:?}"
551 );
552 }
553 assert!(builder().prefix("a.b/..c/d..").check().is_ok());
554 }
555
556 #[test]
557 fn a_prefix_that_leaves_no_room_for_a_name_is_refused() {
558 let longest = "p".repeat(MAX_KEY_LEN - 2);
559 assert!(builder().prefix(&longest).check().is_ok());
560 let nested = format!("{}/{}", "p".repeat(500), "q".repeat(MAX_KEY_LEN - 2 - 501));
561 assert!(builder().prefix(&nested).check().is_ok());
562
563 let too_long = "p".repeat(MAX_KEY_LEN - 1);
564 assert!(refusal(builder().prefix(&too_long)).contains("prefix"));
565 let nested = format!("{}/{}", "p".repeat(500), "q".repeat(MAX_KEY_LEN - 1 - 501));
566 assert!(refusal(builder().prefix(&nested)).contains("prefix"));
567 }
568
569 #[test]
570 fn credentials_are_required_and_not_empty() {
571 let bare = S3Backend::builder("http://127.0.0.1:1", "r", "b").read_only();
572 assert!(refusal(bare).contains("credentials"));
573 assert!(refusal(builder().credentials("", "s")).contains("access key"));
574 assert!(refusal(builder().credentials("a", "")).contains("secret key"));
575 assert!(refusal(builder().session_token("")).contains("session token"));
576 let token_alone = S3Backend::builder("http://x", "r", "b")
577 .session_token("t")
578 .read_only();
579 assert!(refusal(token_alone).contains("access key"));
580 }
581
582 #[test]
583 fn a_session_token_survives_credentials_set_after_it() {
584 let set = builder().session_token("t").credentials("a", "s");
585 let credentials = set.check().unwrap();
586 assert_eq!(credentials.session_token.as_deref(), Some("t"));
587 assert_eq!(credentials.access_key, "a");
588 let before = builder().credentials("a", "s").session_token("t");
589 assert_eq!(before.check().unwrap().session_token.as_deref(), Some("t"));
590 }
591
592 #[test]
593 fn zero_limits_are_refused() {
594 assert!(refusal(builder().request_timeout(Duration::ZERO)).contains("timeout"));
595 assert!(refusal(builder().upload_concurrency(0)).contains("concurrency"));
596 assert!(
597 builder()
598 .metadata_ttl(Duration::ZERO)
599 .listing_metadata_max(0)
600 .check()
601 .is_ok()
602 );
603 }
604
605 #[test]
606 fn the_read_chunk_is_between_64_kib_and_32_mib() {
607 for bytes in [0, 1, MIN_CHUNK - 1, MAX_CHUNK + 1, u32::MAX] {
608 assert!(
609 refusal(builder().read_chunk(bytes)).contains("read chunk"),
610 "{bytes}"
611 );
612 }
613 for bytes in [MIN_CHUNK, DEFAULT_READ_CHUNK, MAX_CHUNK] {
614 assert!(builder().read_chunk(bytes).check().is_ok(), "{bytes}");
615 }
616 }
617
618 #[test]
619 fn a_writable_backend_needs_a_cache_directory_and_a_read_only_one_refuses_it() {
620 let writable = S3Backend::builder("http://127.0.0.1:1", "r", "b").credentials("a", "s");
621 let why = refusal(writable);
622 assert!(why.contains("cache_dir()"), "{why}");
623 assert!(why.contains("read_only()"), "{why}");
624
625 let both = builder().cache_dir("cache");
626 assert!(refusal(both).contains("read-only"));
627
628 let writable = S3Backend::builder("http://127.0.0.1:1", "r", "b")
629 .credentials("a", "s")
630 .cache_dir("cache");
631 assert!(writable.check().is_ok());
632 }
633
634 #[test]
635 fn the_part_size_is_between_5_mib_and_5_gib() {
636 assert!(builder().check().is_ok(), "the default");
637 for ok in [5 << 20, (5 << 20) + 1, 64 << 20, 5 << 30] {
638 assert!(builder().part_size(ok).check().is_ok(), "{ok}");
639 }
640 for refused in [0, 1, (5 << 20) - 1, (5 << 30) + 1, u64::MAX] {
641 assert!(
642 refusal(builder().part_size(refused)).contains("part size"),
643 "{refused}"
644 );
645 }
646 }
647
648 #[test]
649 fn head_requests_follow_the_upload_concurrency_within_a_bound() {
650 assert_eq!(head_concurrency(1), 4);
651 assert_eq!(head_concurrency(4), 16);
652 assert_eq!(head_concurrency(16), 64);
653 assert_eq!(head_concurrency(17), 64);
654 assert_eq!(head_concurrency(usize::MAX), 64);
655 }
656
657 #[test]
658 fn the_origin_of_an_endpoint_has_no_user_name_password_path_or_query() {
659 for (endpoint, shown) in [
660 ("https://store.example", "https://store.example"),
661 ("http://127.0.0.1:9000", "http://127.0.0.1:9000"),
662 (
663 "https://user:pass@store.example:9000",
664 "https://store.example:9000",
665 ),
666 (
667 "https://user@store.example/path?a=b@c",
668 "https://store.example",
669 ),
670 ("https://a@b@store.example", "https://store.example"),
671 ("https://store.example/a@b", "https://store.example"),
672 ("https://store.example?token=x#y", "https://store.example"),
673 ("user:pass@store.example", "store.example"),
674 ("", ""),
675 ] {
676 assert_eq!(origin(endpoint), shown, "{endpoint}");
677 }
678 }
679
680 #[test]
681 fn debug_output_hides_the_credentials() {
682 let shown = format!(
683 "{:?}",
684 builder().session_token("token-value").prefix("photos")
685 );
686 for secret in ["access-key-id", "secret-key-value", "token-value"] {
687 assert!(!shown.contains(secret), "{shown}");
688 }
689 assert!(shown.contains("photos"), "{shown}");
690
691 let shown = format!(
692 "{:?}",
693 S3Backend::builder(
694 "https://endpoint-user:endpoint-pass@store.example",
695 "r",
696 "b"
697 )
698 );
699 for secret in ["endpoint-user", "endpoint-pass"] {
700 assert!(!shown.contains(secret), "{shown}");
701 }
702 assert!(shown.contains("https://store.example"), "{shown}");
703 }
704
705 #[tokio::test]
706 async fn the_endpoint_the_region_and_the_bucket_are_checked() {
707 for (endpoint, region, bucket) in [
708 ("ftp://store.example", "us-east-1", "b"),
709 ("https://user:pass@store.example", "us-east-1", "b"),
710 ("https://store.example/path", "us-east-1", "b"),
711 ("store.example", "us-east-1", "b"),
712 ("https://store.example", "", "b"),
713 ("https://store.example", "us east", "b"),
714 ("https://store.example", "us-east-1", ""),
715 ("https://store.example", "us-east-1", "a/b"),
716 ] {
717 let built = S3Backend::builder(endpoint, region, bucket)
718 .credentials("a", "s")
719 .read_only()
720 .build()
721 .await;
722 assert!(
723 matches!(built, Err(S3Error::InvalidArgument(_))),
724 "{endpoint} {region} {bucket}"
725 );
726 }
727 }
728
729 #[cfg(windows)]
733 #[tokio::test]
734 async fn a_cache_directory_on_an_smb_share_is_refused() {
735 use crate::tests::util::{on_admin_share, scratch_dir};
736
737 let local = scratch_dir();
738 let built = S3Backend::builder("http://127.0.0.1:1", "r", "b")
739 .credentials("a", "s")
740 .cache_dir(on_admin_share(local.path()).join("cache"))
741 .build()
742 .await;
743 let Err(e) = built else {
744 panic!("a backend was built");
745 };
746 assert!(
747 matches!(e, S3Error::InvalidArgument(why) if why.contains("local NTFS or ReFS volume")),
748 "{e}"
749 );
750 let left = std::fs::read_dir(local.path().join("cache").join("tmp")).unwrap();
751 assert_eq!(left.count(), 0);
752 }
753}