Repository navigation
Expand file tree
/
Copy pathaws.rs
More file actions
1583 lines (1379 loc) · 59.7 KB
/
Copy pathaws.rs
File metadata and controls
1583 lines (1379 loc) · 59.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright The Lance Authors
use std::{collections::HashMap, str::FromStr, sync::Arc, time::Duration};
#[cfg(test)]
use mock_instant::thread_local::{SystemTime, UNIX_EPOCH};
#[cfg(not(test))]
use std::time::{SystemTime, UNIX_EPOCH};
use object_store::ObjectStore as OSObjectStore;
use object_store::list::PaginatedListStore;
use opendal::{Operator, services::S3};
use aws_config::default_provider::credentials::DefaultCredentialsChain;
use aws_config::ecs::EcsCredentialsProvider;
use aws_config::provider_config::ProviderConfig;
use aws_config::web_identity_token::WebIdentityTokenCredentialsProvider;
use aws_config::{BehaviorVersion, Region, SdkConfig};
use aws_credential_types::provider::ProvideCredentials;
use object_store::{
ClientOptions, CredentialProvider, Result as ObjectStoreResult, RetryConfig,
StaticCredentialProvider,
aws::{
AmazonS3, AmazonS3Builder, AmazonS3ConfigKey, AwsCredential as ObjectStoreAwsCredential,
AwsCredentialProvider,
},
};
use tokio::sync::RwLock;
use url::Url;
use crate::object_store::opendal_store::OpendalStore;
use crate::object_store::{
DEFAULT_CLOUD_BLOCK_SIZE, DEFAULT_CLOUD_IO_PARALLELISM, DEFAULT_MAX_IOP_SIZE, ObjectStore,
ObjectStoreParams, ObjectStoreProvider, StorageOptions, StorageOptionsAccessor,
dynamic_credentials::{NamespaceCredentialsProvider, build_dynamic_credential_provider},
throttle::{AimdThrottleConfig, AimdThrottleState, cloud_http_connector, with_throttling},
};
use lance_core::error::{Error, Result};
use lance_core::utils::parse::str_is_truthy;
#[derive(Default, Debug)]
pub struct AwsStoreProvider;
struct ResolvedS3StorageOptions {
options: HashMap<AmazonS3ConfigKey, String>,
profile_region: Option<String>,
}
impl ResolvedS3StorageOptions {
fn new(
mut options: HashMap<AmazonS3ConfigKey, String>,
profile_config: Option<&SdkConfig>,
) -> Self {
if effective_s3_endpoint(&options).is_none()
&& let Some(endpoint) = profile_config.and_then(SdkConfig::endpoint_url)
{
options.insert(AmazonS3ConfigKey::Endpoint, endpoint.to_string());
}
let profile_region = profile_config
.and_then(SdkConfig::region)
.map(|region| region.as_ref().to_string());
Self {
options,
profile_region,
}
}
fn effective_endpoint(&self) -> Option<&str> {
effective_s3_endpoint(&self.options)
}
fn requires_constant_size_upload_parts(&self) -> bool {
self.effective_endpoint()
.is_some_and(|endpoint| endpoint.contains("r2.cloudflarestorage.com"))
}
}
impl AwsStoreProvider {
async fn build_amazon_s3_store(
&self,
base_path: &mut Url,
params: &ObjectStoreParams,
storage_options: &StorageOptions,
mut resolved_s3_options: ResolvedS3StorageOptions,
is_s3_express: bool,
throttle_state: Option<&AimdThrottleState>,
// Concrete rather than `dyn`, so the caller keeps the handle a paginated listing
// needs: `PaginatedListStore` is a separate trait from `ObjectStore`.
) -> Result<Arc<AmazonS3>> {
// Use a low retry count since the AIMD throttle layer handles
// throttle recovery with its own retry loop.
let retry_config = RetryConfig {
backoff: Default::default(),
max_retries: storage_options.client_max_retries(),
retry_timeout: Duration::from_secs(storage_options.client_retry_timeout()),
};
let region = resolve_s3_region(base_path, &resolved_s3_options).await?;
// Get accessor from params
let accessor = params.get_accessor();
let provider_scheme = storage_options.aws_provider_scheme()?;
let (aws_creds, region) = build_aws_credential(
params.s3_credentials_refresh_offset,
params.aws_credentials.clone(),
Some(&resolved_s3_options.options),
region,
accessor,
provider_scheme,
)
.await?;
// Set S3Express flag if detected
if is_s3_express {
resolved_s3_options
.options
.insert(AmazonS3ConfigKey::S3Express, true.to_string());
}
// Compute the metrics label before rewriting the URL below so it
// matches the prefix the registry uses to key this store.
let store_prefix =
self.calculate_object_store_prefix(base_path, Some(&storage_options.0))?;
// before creating the OSObjectStore we need to rewrite the url to drop ddb related parts
base_path.set_scheme("s3").unwrap();
base_path.set_query(None);
// we can't use parse_url_opts here because we need to manually set the credentials provider
let mut builder =
AmazonS3Builder::new().with_client_options(storage_options.client_options()?);
for (key, value) in resolved_s3_options.options {
builder = builder.with_config(key, value);
}
builder = builder
.with_url(base_path.as_ref())
.with_credentials(aws_creds)
.with_retry(retry_config)
.with_region(region);
builder = builder.with_http_connector(cloud_http_connector(throttle_state, store_prefix));
Ok(Arc::new(builder.build()?))
}
async fn build_opendal_s3_store(
&self,
base_path: &Url,
storage_options: &StorageOptions,
) -> Result<Arc<dyn OSObjectStore>> {
let bucket = base_path
.host_str()
.ok_or_else(|| Error::invalid_input("S3 URL must contain bucket name"))?
.to_string();
let prefix = base_path.path().trim_start_matches('/').to_string();
// Start with all storage options as the config map
// OpenDAL will handle environment variables through its default credentials chain
let mut config_map: HashMap<String, String> = storage_options.0.clone();
if let Some(provider_scheme) = storage_options.aws_provider_scheme()? {
return Result::Err(Error::not_supported(format!(
"OpendalStore does not currently support an explicit provider_scheme (currently set to {:?})",
provider_scheme
)));
}
// Set required OpenDAL configuration
config_map.insert("bucket".to_string(), bucket);
if !prefix.is_empty() {
config_map.insert("root".to_string(), "/".to_string());
}
let operator = Operator::from_iter::<S3>(config_map)
.map_err(|e| Error::invalid_input(format!("Failed to create S3 operator: {:?}", e)))?;
Ok(Arc::new(OpendalStore::new(operator)) as Arc<dyn OSObjectStore>)
}
}
#[async_trait::async_trait]
impl ObjectStoreProvider for AwsStoreProvider {
async fn new_store(
&self,
mut base_path: Url,
params: &ObjectStoreParams,
) -> Result<ObjectStore> {
let block_size = params.block_size.unwrap_or(DEFAULT_CLOUD_BLOCK_SIZE);
let mut storage_options =
StorageOptions::new(params.storage_options().cloned().unwrap_or_default());
storage_options.with_env_s3();
let download_retry_count = storage_options.download_retry_count();
let use_opendal = storage_options
.0
.get("use_opendal")
.map(|v| str_is_truthy(v))
.unwrap_or(false);
let profile_config = if std::env::var_os("AWS_PROFILE").is_some() {
Some(aws_config::load_defaults(BehaviorVersion::latest()).await)
} else {
None
};
let resolved_s3_options =
ResolvedS3StorageOptions::new(storage_options.as_s3_options(), profile_config.as_ref());
// Determine S3 Express and constant size upload parts before building the store
let is_s3_express = check_s3_express(&base_path, &storage_options);
let use_constant_size_upload_parts =
resolved_s3_options.requires_constant_size_upload_parts();
let throttle_config = AimdThrottleConfig::from_storage_options(params.storage_options())?;
let throttle_state = if throttle_config.is_disabled() {
None
} else {
Some(AimdThrottleState::new(throttle_config)?)
};
let (inner, paginated_lister) = if use_opendal {
// Use OpenDAL implementation
// Listed in full: no paginated lister covers OpenDAL yet.
(
self.build_opendal_s3_store(&base_path, &storage_options)
.await?,
None,
)
} else {
// Use default Amazon S3 implementation
let store = self
.build_amazon_s3_store(
&mut base_path,
params,
&storage_options,
resolved_s3_options,
is_s3_express,
throttle_state.as_ref(),
)
.await?;
(
store.clone() as Arc<dyn OSObjectStore>,
Some(store as Arc<dyn PaginatedListStore>),
)
};
let (inner, paginated_lister) =
with_throttling(throttle_state, !use_opendal, inner, paginated_lister);
Ok(ObjectStore {
inner,
local_dir_operations: None,
scheme: String::from(base_path.scheme()),
block_size,
max_iop_size: *DEFAULT_MAX_IOP_SIZE,
use_constant_size_upload_parts,
list_is_lexically_ordered: !is_s3_express,
io_parallelism: DEFAULT_CLOUD_IO_PARALLELISM,
download_retry_count,
io_tracker: Default::default(),
store_prefix: self
.calculate_object_store_prefix(&base_path, params.storage_options())?,
paginated_lister,
})
}
}
/// Check if the storage is S3 Express
fn check_s3_express(url: &Url, storage_options: &StorageOptions) -> bool {
storage_options
.0
.get("s3_express")
.map(|v| str_is_truthy(v))
.unwrap_or(false)
|| url.authority().ends_with("--x-s3")
}
fn effective_s3_endpoint(storage_options: &HashMap<AmazonS3ConfigKey, String>) -> Option<&str> {
storage_options
.get(&AmazonS3ConfigKey::S3Endpoint)
.or_else(|| storage_options.get(&AmazonS3ConfigKey::Endpoint))
.map(String::as_str)
}
/// Figure out the S3 region of the bucket.
///
/// This resolves in order of precedence:
/// 1. The region provided in the storage options
/// 2. The selected AWS profile's region when a custom endpoint is configured
/// 3. (If endpoint is not set), the region returned by the S3 API for the bucket
///
/// It can return None if no region is provided and the endpoint is set.
async fn resolve_s3_region(
url: &Url,
resolved_s3_options: &ResolvedS3StorageOptions,
) -> Result<Option<String>> {
let storage_options = &resolved_s3_options.options;
if let Some(region) = storage_options.get(&AmazonS3ConfigKey::Region) {
Ok(Some(region.clone()))
} else if resolved_s3_options.effective_endpoint().is_none() {
// If no endpoint is set, we can assume this is AWS S3 and the region
// can be resolved from the bucket.
let bucket = url.host_str().ok_or_else(|| {
Error::invalid_input(format!("Could not parse bucket from url: {}", url))
})?;
let mut client_options = ClientOptions::default();
for (key, value) in storage_options {
if let AmazonS3ConfigKey::Client(client_key) = key {
client_options = client_options.with_config(*client_key, value.clone());
}
}
let bucket_region =
object_store::aws::resolve_bucket_region(bucket, &client_options).await?;
Ok(Some(bucket_region))
} else {
Ok(resolved_s3_options.profile_region.clone())
}
}
/// Selects which AWS credential provider to use for a dataset.
///
/// When set, overrides automatic credential resolution for everything except an
/// explicitly-supplied `credentials` provider or `storage_options_accessor`.
#[derive(Debug, Clone, PartialEq)]
pub enum AwsProviderScheme {
/// Require static access-key credentials (`aws_access_key_id` +
/// `aws_secret_access_key`). Returns an error if they are absent.
Token,
/// Use the ECS/Pod Identity container credential endpoint.
/// The endpoint URI is read from the `AWS_CONTAINER_CREDENTIALS_FULL_URI`
/// or `AWS_CONTAINER_CREDENTIALS_RELATIVE_URI` environment variables.
Ecs,
/// Use IRSA (IAM Roles for Service Accounts) web identity token credentials.
/// The token file and role ARN are read from the `AWS_WEB_IDENTITY_TOKEN_FILE`
/// and `AWS_ROLE_ARN` environment variables.
Irsa,
}
/// Build AWS credentials
///
/// This resolves credentials from the following sources in order:
/// 1. An explicit `credentials` provider
/// 2. An explicit `storage_options_accessor` with a provider
/// 3. If `provider_scheme` is set:
/// - [`AwsProviderScheme::Token`]: static access-key credentials (error if absent)
/// - [`AwsProviderScheme::Ecs`]: ECS container credential provider
/// - [`AwsProviderScheme::Irsa`]: web identity token (IRSA) provider
/// 4. Static access-key credentials from `storage_options`, if present
/// 5. The default AWS credential provider chain
///
/// # Storage Options Accessor
///
/// When `storage_options_accessor` is provided and has a dynamic provider,
/// credentials are fetched and cached by the accessor with automatic refresh
/// before expiration.
///
/// `credentials_refresh_offset` is the amount of time before expiry to refresh credentials.
pub async fn build_aws_credential(
credentials_refresh_offset: Duration,
credentials: Option<AwsCredentialProvider>,
storage_options: Option<&HashMap<AmazonS3ConfigKey, String>>,
region: Option<String>,
storage_options_accessor: Option<Arc<StorageOptionsAccessor>>,
provider_scheme: Option<AwsProviderScheme>,
) -> Result<(AwsCredentialProvider, String)> {
use aws_config::meta::region::RegionProviderChain;
const DEFAULT_REGION: &str = "us-west-2";
let region = if let Some(region) = region {
region
} else {
RegionProviderChain::default_provider()
.or_else(DEFAULT_REGION)
.region()
.await
.map(|r| r.as_ref().to_string())
.unwrap_or(DEFAULT_REGION.to_string())
};
// If the user supplied their own credential provider that takes top priority
if let Some(creds) = credentials {
return Ok((creds, region));
}
// Otherwise, if the user provided a storage_options_accessor, try and use that
if let Some(dynamic_creds) = build_dynamic_credential_provider::<ObjectStoreAwsCredential>(
storage_options_accessor.clone(),
)
.await?
{
return Ok((dynamic_creds, region));
}
// If the user provided a storage_options_accessor, then it must not have matched AWS.
// Log a message and ignore it.
if storage_options_accessor
.as_ref()
.is_some_and(|a| a.has_provider())
{
log::debug!(
"Storage options from provider do not contain explicit AWS credentials, \
falling back to default AWS credentials chain."
);
}
// If the caller specified an explicit provider scheme, use only that provider.
if let Some(scheme) = provider_scheme {
return match scheme {
AwsProviderScheme::Token => {
let creds = storage_options
.and_then(extract_static_s3_credentials)
.ok_or_else(|| {
Error::invalid_input(
"aws_provider_scheme=token requires aws_access_key_id \
and aws_secret_access_key to be set",
)
})?;
Ok((Arc::new(creds), region))
}
AwsProviderScheme::Ecs => {
let provider = EcsCredentialsProvider::builder().build();
Ok((
Arc::new(AwsCredentialAdapter::new(
Arc::new(provider),
credentials_refresh_offset,
)),
region,
))
}
AwsProviderScheme::Irsa => {
let conf = ProviderConfig::default().with_region(Some(Region::new(region.clone())));
let provider = WebIdentityTokenCredentialsProvider::builder()
.configure(&conf)
.build();
Ok((
Arc::new(AwsCredentialAdapter::new(
Arc::new(provider),
credentials_refresh_offset,
)),
region,
))
}
};
}
if let Some(opts) = storage_options {
// Check for static credentials (access key & secret)
if let Some(creds) = extract_static_s3_credentials(opts) {
return Ok((Arc::new(creds), region));
}
}
let credentials_provider = DefaultCredentialsChain::builder().build().await;
Ok((
Arc::new(AwsCredentialAdapter::new(
Arc::new(credentials_provider),
credentials_refresh_offset,
)),
region,
))
}
fn extract_static_s3_credentials(
options: &HashMap<AmazonS3ConfigKey, String>,
) -> Option<StaticCredentialProvider<ObjectStoreAwsCredential>> {
let key_id = options.get(&AmazonS3ConfigKey::AccessKeyId).cloned();
let secret_key = options.get(&AmazonS3ConfigKey::SecretAccessKey).cloned();
let token = options.get(&AmazonS3ConfigKey::Token).cloned();
match (key_id, secret_key, token) {
(Some(key_id), Some(secret_key), token) => {
Some(StaticCredentialProvider::new(ObjectStoreAwsCredential {
key_id,
secret_key,
token,
}))
}
_ => None,
}
}
/// Adapt an AWS SDK cred into object_store credentials
#[derive(Debug)]
pub struct AwsCredentialAdapter {
pub inner: Arc<dyn ProvideCredentials>,
// RefCell can't be shared across threads, so we use HashMap
cache: Arc<RwLock<HashMap<String, Arc<aws_credential_types::Credentials>>>>,
// The amount of time before expiry to refresh credentials
credentials_refresh_offset: Duration,
}
impl AwsCredentialAdapter {
pub fn new(
provider: Arc<dyn ProvideCredentials>,
credentials_refresh_offset: Duration,
) -> Self {
Self {
inner: provider,
cache: Arc::new(RwLock::new(HashMap::new())),
credentials_refresh_offset,
}
}
}
const AWS_CREDS_CACHE_KEY: &str = "aws_credentials";
/// Convert std::time::SystemTime from AWS SDK to our mockable SystemTime
fn to_system_time(time: std::time::SystemTime) -> SystemTime {
let duration_since_epoch = time
.duration_since(std::time::UNIX_EPOCH)
.expect("time should be after UNIX_EPOCH");
UNIX_EPOCH + duration_since_epoch
}
#[async_trait::async_trait]
impl CredentialProvider for AwsCredentialAdapter {
type Credential = ObjectStoreAwsCredential;
async fn get_credential(&self) -> ObjectStoreResult<Arc<Self::Credential>> {
let cached_creds = {
let cache_value = self.cache.read().await.get(AWS_CREDS_CACHE_KEY).cloned();
let expired = cache_value
.clone()
.map(|cred| {
cred.expiry()
.map(|exp| {
to_system_time(exp)
.checked_sub(self.credentials_refresh_offset)
.expect("this time should always be valid")
< SystemTime::now()
})
// no expiry is never expire
.unwrap_or(false)
})
.unwrap_or(true); // no cred is the same as expired;
if expired { None } else { cache_value.clone() }
};
if let Some(creds) = cached_creds {
Ok(Arc::new(Self::Credential {
key_id: creds.access_key_id().to_string(),
secret_key: creds.secret_access_key().to_string(),
token: creds.session_token().map(|s| s.to_string()),
}))
} else {
let refreshed_creds = Arc::new(
self.inner
.provide_credentials()
.await
.map_err(|e| Error::io(format!("Failed to get AWS credentials: {:?}", e)))?,
);
self.cache
.write()
.await
.insert(AWS_CREDS_CACHE_KEY.to_string(), refreshed_creds.clone());
Ok(Arc::new(Self::Credential {
key_id: refreshed_creds.access_key_id().to_string(),
secret_key: refreshed_creds.secret_access_key().to_string(),
token: refreshed_creds.session_token().map(|s| s.to_string()),
}))
}
}
}
impl StorageOptions {
/// Add values from the environment to storage options.
///
/// Only adds keys that are not already present, so explicitly-set options
/// (including empty-string sentinels) always take precedence over env vars.
pub fn with_env_s3(&mut self) {
for (os_key, os_value) in std::env::vars_os() {
if let (Some(key), Some(value)) = (os_key.to_str(), os_value.to_str())
&& let Ok(config_key) = AmazonS3ConfigKey::from_str(&key.to_ascii_lowercase())
&& !self.0.contains_key(config_key.as_ref())
{
self.0
.insert(config_key.as_ref().to_string(), value.to_string());
}
}
}
/// Subset of options relevant for s3 storage
pub fn as_s3_options(&self) -> HashMap<AmazonS3ConfigKey, String> {
self.0
.iter()
.filter_map(|(key, value)| {
let s3_key = AmazonS3ConfigKey::from_str(&key.to_ascii_lowercase()).ok()?;
Some((s3_key, value.clone()))
})
.collect()
}
/// Parse the `aws_provider_scheme` storage option, if set.
pub fn aws_provider_scheme(&self) -> Result<Option<AwsProviderScheme>> {
match self.0.get("aws_provider_scheme").map(|s| s.as_str()) {
None | Some("") => Ok(None),
Some("token") => Ok(Some(AwsProviderScheme::Token)),
Some("ecs") => Ok(Some(AwsProviderScheme::Ecs)),
Some("irsa") => Ok(Some(AwsProviderScheme::Irsa)),
Some(other) => Err(Error::invalid_input(format!(
"Invalid aws_provider_scheme '{}'. Valid values are: token, ecs, irsa",
other
))),
}
}
}
impl ObjectStoreParams {
/// Create a new instance of [`ObjectStoreParams`] based on the AWS credentials.
pub fn with_aws_credentials(
aws_credentials: Option<AwsCredentialProvider>,
region: Option<String>,
) -> Self {
let storage_options_accessor = region.map(|region| {
let opts: HashMap<String, String> =
[("region".into(), region)].iter().cloned().collect();
Arc::new(StorageOptionsAccessor::with_static_options(opts))
});
Self {
aws_credentials,
storage_options_accessor,
..Default::default()
}
}
}
pub type DynamicStorageOptionsCredentialProvider =
NamespaceCredentialsProvider<ObjectStoreAwsCredential>;
#[cfg(test)]
mod tests {
use crate::object_store::ObjectStoreRegistry;
use crate::object_store::StorageOptionsProvider;
#[allow(deprecated)]
use aws_config::profile::profile_file::{ProfileFileKind, ProfileFiles};
use aws_credential_types::provider::error::CredentialsError;
use mock_instant::thread_local::MockClock;
use object_store::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use super::*;
#[derive(Debug, Default)]
struct MockAwsCredentialsProvider {
called: AtomicBool,
}
#[async_trait::async_trait]
impl CredentialProvider for MockAwsCredentialsProvider {
type Credential = ObjectStoreAwsCredential;
async fn get_credential(&self) -> ObjectStoreResult<Arc<Self::Credential>> {
self.called.store(true, Ordering::Relaxed);
Ok(Arc::new(Self::Credential {
key_id: "".to_string(),
secret_key: "".to_string(),
token: None,
}))
}
}
#[allow(deprecated)]
async fn load_test_profile(config: &str) -> SdkConfig {
let profile_files = ProfileFiles::builder()
.with_contents(ProfileFileKind::Config, config)
.build();
aws_config::defaults(BehaviorVersion::latest())
.profile_name("selected")
.profile_files(profile_files)
.load()
.await
}
#[derive(Debug)]
struct FailingAwsCredentialsProvider;
impl ProvideCredentials for FailingAwsCredentialsProvider {
fn provide_credentials<'a>(
&'a self,
) -> aws_credential_types::provider::future::ProvideCredentials<'a>
where
Self: 'a,
{
aws_credential_types::provider::future::ProvideCredentials::new(async {
Err(CredentialsError::provider_error(Box::new(
std::io::Error::other("Glue credential endpoint unavailable"),
)))
})
}
}
#[tokio::test]
async fn test_aws_credential_failure_is_io_error() {
let provider = AwsCredentialAdapter::new(
Arc::new(FailingAwsCredentialsProvider),
Duration::from_secs(60),
);
let error = provider.get_credential().await.unwrap_err();
let object_store::Error::Generic { source, .. } = &error else {
panic!("expected a generic object store error, got {error}");
};
assert!(matches!(
source.downcast_ref::<Error>(),
Some(Error::IO { .. })
));
let message = error.to_string();
assert!(message.contains("Failed to get AWS credentials"));
assert!(message.contains("Glue credential endpoint unavailable"));
assert!(!message.contains("Encountered internal error"));
}
#[tokio::test]
async fn test_injected_aws_creds_option_is_used() {
let mock_provider = Arc::new(MockAwsCredentialsProvider::default());
let registry = Arc::new(ObjectStoreRegistry::default());
let params = ObjectStoreParams {
aws_credentials: Some(mock_provider.clone() as AwsCredentialProvider),
..ObjectStoreParams::default()
};
// Not called yet
assert!(!mock_provider.called.load(Ordering::Relaxed));
let (store, _) = ObjectStore::from_uri_and_params(registry, "s3://not-a-bucket", ¶ms)
.await
.unwrap();
// fails, but we don't care
let _ = store
.open(&Path::parse("/").unwrap())
.await
.unwrap()
.get_range(0..1)
.await;
// Not called yet
assert!(mock_provider.called.load(Ordering::Relaxed));
}
#[tokio::test]
async fn test_resolve_s3_region_from_aws_profile() {
let profile_config = load_test_profile(
"[profile selected]\n\
region = us-west-004\n\
endpoint_url = https://s3.us-west-004.backblazeb2.com\n\
aws_access_key_id = test-key\n\
aws_secret_access_key = test-secret",
)
.await;
let url = Url::parse("s3://test-bucket/path").unwrap();
let resolved_s3_options =
ResolvedS3StorageOptions::new(HashMap::new(), Some(&profile_config));
let region = resolve_s3_region(&url, &resolved_s3_options).await.unwrap();
assert_eq!(region.as_deref(), Some("us-west-004"));
assert_eq!(
resolved_s3_options
.options
.get(&AmazonS3ConfigKey::Endpoint),
Some(&"https://s3.us-west-004.backblazeb2.com".to_string())
);
let explicit_options = HashMap::from([
(AmazonS3ConfigKey::Region, "explicit-region".to_string()),
(
AmazonS3ConfigKey::Endpoint,
"https://explicit.example.com".to_string(),
),
]);
let resolved_s3_options =
ResolvedS3StorageOptions::new(explicit_options, Some(&profile_config));
let region = resolve_s3_region(&url, &resolved_s3_options).await.unwrap();
assert_eq!(region.as_deref(), Some("explicit-region"));
assert_eq!(
resolved_s3_options
.options
.get(&AmazonS3ConfigKey::Endpoint),
Some(&"https://explicit.example.com".to_string())
);
}
#[tokio::test]
async fn test_region_only_aws_profile_preserves_bucket_discovery() {
let profile_config = load_test_profile("[profile selected]\nregion = us-east-1").await;
let resolved_s3_options =
ResolvedS3StorageOptions::new(HashMap::new(), Some(&profile_config));
let url = Url::parse("s3:///path").unwrap();
let error = resolve_s3_region(&url, &resolved_s3_options)
.await
.unwrap_err();
assert!(matches!(error, Error::InvalidInput { .. }));
assert!(error.to_string().contains("Could not parse bucket"));
}
#[tokio::test]
async fn test_r2_aws_profile_requires_constant_size_upload_parts() {
let profile_config = load_test_profile(
"[profile selected]\n\
region = auto\n\
endpoint_url = https://account.r2.cloudflarestorage.com",
)
.await;
let resolved_s3_options =
ResolvedS3StorageOptions::new(HashMap::new(), Some(&profile_config));
assert!(resolved_s3_options.requires_constant_size_upload_parts());
}
#[test]
fn test_s3_path_parsing() {
let provider = AwsStoreProvider;
let cases = [
("s3://bucket/path/to/file", "path/to/file"),
// for non ASCII string tests: the URL encodes them, extract_path must decode back
("s3://bucket/测试path/to/file", "测试path/to/file"),
("s3://bucket/path/&to/file", "path/&to/file"),
("s3://bucket/path/=to/file", "path/=to/file"),
(
"s3+ddb://bucket/path/to/file?ddbTableName=test",
"path/to/file",
),
];
for (uri, expected_path) in cases {
let url = Url::parse(uri).unwrap();
let path = provider.extract_path(&url).unwrap();
// extract_path decodes url.path(), so the Path stores the raw (decoded)
// string. Path::parse keeps its input verbatim, matching that, whereas
// Path::from would percent-encode non-ASCII bytes and not match.
let expected_path = Path::parse(expected_path).unwrap();
assert_eq!(path, expected_path)
}
}
// Regression test for https://github.com/lance-format/lance/issues/6643
// extract_path must NOT double-encode paths that contain non-ASCII characters.
// url.path() returns a percent-encoded string; we must decode it back to raw
// UTF-8 before storing it in a Path, so the object store HTTP client can apply
// a single, correct percent-encoding when building the request URL.
#[test]
fn test_s3_non_ascii_path_no_double_encoding() {
let provider = AwsStoreProvider;
// "s3://bucket/中文路径" → url.path() == "/%E4%B8%AD%E6%96%87%E8%B7%AF%E5%BE%84".
// The buggy Path::parse(url.path()) stored "%E4%B8%AD..." verbatim; the S3
// client then percent-encodes the '%' again, yielding "%25E4%25B8%25AD...".
// With Path::from_url_path the Path stores the decoded UTF-8 instead.
let url = Url::parse("s3://bucket/中文路径").unwrap();
let path = provider.extract_path(&url).unwrap();
// The Path must hold the decoded UTF-8, not the percent-encoded form.
assert_eq!(path.as_ref(), "中文路径");
}
#[test]
fn test_is_s3_express() {
let cases = [
(
"s3://bucket/path/to/file",
HashMap::from([("s3_express".to_string(), "true".to_string())]),
true,
),
(
"s3://bucket/path/to/file",
HashMap::from([("s3_express".to_string(), "false".to_string())]),
false,
),
("s3://bucket/path/to/file", HashMap::from([]), false),
(
"s3://bucket--x-s3/path/to/file",
HashMap::from([("s3_express".to_string(), "true".to_string())]),
true,
),
(
"s3://bucket--x-s3/path/to/file",
HashMap::from([("s3_express".to_string(), "false".to_string())]),
true, // URL takes precedence
),
("s3://bucket--x-s3/path/to/file", HashMap::from([]), true),
];
for (uri, storage_map, expected) in cases {
let url = Url::parse(uri).unwrap();
let storage_options = StorageOptions(storage_map);
let is_s3_express = check_s3_express(&url, &storage_options);
assert_eq!(is_s3_express, expected);
}
}
#[tokio::test]
async fn test_use_opendal_flag() {
use crate::object_store::StorageOptionsAccessor;
let provider = AwsStoreProvider;
let url = Url::parse("s3://test-bucket/path").unwrap();
let params_with_flag = ObjectStoreParams {
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
HashMap::from([
("use_opendal".to_string(), "true".to_string()),
("region".to_string(), "us-west-2".to_string()),
]),
))),
..Default::default()
};
let store = provider
.new_store(url.clone(), ¶ms_with_flag)
.await
.unwrap();
assert_eq!(store.scheme, "s3");
}
/// S3 Express ignores `start-after` and does not list in key order, but it does hand back
/// continuation tokens, which is all the native store resumes from — so an Express bucket
/// pages like any other. The OpenDAL arm has no lister to page with at all.
#[rstest::rstest]
#[case::native("false", true)]
#[case::opendal("true", false)]
#[tokio::test]
async fn test_s3_express_is_paged_by_continuation_token(
#[case] use_opendal: &str,
#[case] paginated: bool,
) {
let provider = AwsStoreProvider;
// Express bucket names carry their availability zone, which the S3 client validates.
let url = Url::parse("s3://test-bucket--use1-az4--x-s3/path").unwrap();
let params = ObjectStoreParams {
storage_options_accessor: Some(Arc::new(StorageOptionsAccessor::with_static_options(
HashMap::from([
("use_opendal".to_string(), use_opendal.to_string()),
("region".to_string(), "us-east-1".to_string()),
]),
))),
..Default::default()
};
let store = provider.new_store(url, ¶ms).await.unwrap();
assert!(!store.list_is_lexically_ordered);
assert_eq!(store.paginated_lister.is_some(), paginated);
}
#[derive(Debug)]
struct MockStorageOptionsProvider {
call_count: Arc<RwLock<usize>>,
expires_in_millis: Option<u64>,
}
impl MockStorageOptionsProvider {
fn new(expires_in_millis: Option<u64>) -> Self {
Self {
call_count: Arc::new(RwLock::new(0)),
expires_in_millis,
}
}
async fn get_call_count(&self) -> usize {
*self.call_count.read().await
}
}
#[async_trait::async_trait]
impl StorageOptionsProvider for MockStorageOptionsProvider {
async fn fetch_storage_options(&self) -> Result<Option<HashMap<String, String>>> {
let count = {
let mut c = self.call_count.write().await;
*c += 1;
*c
};
let mut options = HashMap::from([
("aws_access_key_id".to_string(), format!("AKID_{}", count)),
(
"aws_secret_access_key".to_string(),
format!("SECRET_{}", count),
),
("aws_session_token".to_string(), format!("TOKEN_{}", count)),
]);
if let Some(expires_in) = self.expires_in_millis {
let now_ms = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()