Skip to main content

datafusion_cli/
object_storage.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5pub mod instrumented;
6pub(crate) mod stdin;
7
8pub use stdin::{StdinCarriesCommands, is_stdin_location};
9
10use async_trait::async_trait;
11use aws_config::BehaviorVersion;
12use aws_credential_types::provider::{
13    ProvideCredentials, SharedCredentialsProvider, error::CredentialsError,
14};
15use datafusion::{
16    common::{
17        config::ConfigEntry, config::ConfigExtension, config::ConfigField,
18        config::ExtensionOptions, config::TableOptions, config::Visit, config_err,
19        exec_datafusion_err, exec_err,
20    },
21    error::{DataFusionError, Result},
22    execution::context::SessionState,
23};
24use log::debug;
25use object_store::{
26    ClientOptions, CredentialProvider,
27    Error::Generic,
28    ObjectStore,
29    aws::{AmazonS3Builder, AmazonS3ConfigKey, AwsCredential},
30    gcp::GoogleCloudStorageBuilder,
31    http::HttpBuilder,
32};
33use std::{
34    any::Any,
35    error::Error,
36    fmt::{Debug, Display},
37    sync::Arc,
38};
39use url::Url;
40
41#[cfg(not(test))]
42use object_store::aws::resolve_bucket_region;
43
44// Provide a local mock when running tests so we don't make network calls
45#[cfg(test)]
46#[expect(
47    clippy::unused_async,
48    clippy::result_large_err,
49    reason = "matches object_store::aws::resolve_bucket_region"
50)]
51async fn resolve_bucket_region(
52    _bucket: &str,
53    _client_options: &ClientOptions,
54) -> object_store::Result<String> {
55    Ok("eu-central-1".to_string())
56}
57
58pub async fn get_s3_object_store_builder(
59    url: &Url,
60    aws_options: &AwsOptions,
61    resolve_region: bool,
62) -> Result<AmazonS3Builder> {
63    // Box the inner future to reduce the future size of this async function,
64    // which is deeply nested in the CLI's async call chain.
65    Box::pin(get_s3_object_store_builder_inner(
66        url,
67        aws_options,
68        resolve_region,
69    ))
70    .await
71}
72
73async fn get_s3_object_store_builder_inner(
74    url: &Url,
75    aws_options: &AwsOptions,
76    resolve_region: bool,
77) -> Result<AmazonS3Builder> {
78    let AwsOptions {
79        access_key_id,
80        secret_access_key,
81        session_token,
82        region,
83        endpoint,
84        allow_http,
85        skip_signature,
86    } = aws_options;
87
88    let bucket_name = get_bucket_name(url)?;
89    let mut builder = AmazonS3Builder::from_env().with_bucket_name(bucket_name);
90
91    if let (Some(access_key_id), Some(secret_access_key)) =
92        (access_key_id, secret_access_key)
93    {
94        debug!("Using explicitly provided S3 access_key_id and secret_access_key");
95        builder = builder
96            .with_access_key_id(access_key_id)
97            .with_secret_access_key(secret_access_key);
98
99        if let Some(session_token) = session_token {
100            builder = builder.with_token(session_token);
101        }
102    } else {
103        debug!("Using AWS S3 SDK to determine credentials");
104        let CredentialsFromConfig {
105            region,
106            credentials,
107        } = CredentialsFromConfig::try_new().await?;
108        if let Some(region) = region {
109            builder = builder.with_region(region);
110        }
111        if let Some(credentials) = credentials {
112            let credentials = Arc::new(S3CredentialProvider { credentials });
113            builder = builder.with_credentials(credentials);
114        } else {
115            debug!("No credentials found, defaulting to skip signature ");
116            builder = builder.with_skip_signature(true);
117        }
118    }
119
120    if let Some(region) = region {
121        builder = builder.with_region(region);
122    }
123
124    // If the region is not set or auto_detect_region is true, resolve the region.
125    if builder
126        .get_config_value(&AmazonS3ConfigKey::Region)
127        .is_none()
128        || resolve_region
129    {
130        let region = resolve_bucket_region(bucket_name, &ClientOptions::new()).await?;
131        builder = builder.with_region(region);
132    }
133
134    if let Some(endpoint) = endpoint {
135        // Make a nicer error if the user hasn't allowed http and the endpoint
136        // is http as the default message is "URL scheme is not allowed"
137        if let Ok(endpoint_url) = Url::try_from(endpoint.as_str())
138            && !matches!(allow_http, Some(true))
139            && endpoint_url.scheme() == "http"
140        {
141            return config_err!(
142                "Invalid endpoint: {endpoint}. \
143                HTTP is not allowed for S3 endpoints. \
144                To allow HTTP, set 'aws.allow_http' to true"
145            );
146        }
147
148        builder = builder.with_endpoint(endpoint);
149    }
150
151    if let Some(allow_http) = allow_http {
152        builder = builder.with_allow_http(*allow_http);
153    }
154
155    if let Some(skip_signature) = skip_signature {
156        builder = builder.with_skip_signature(*skip_signature);
157    }
158
159    Ok(builder)
160}
161
162/// Credentials from the AWS SDK
163struct CredentialsFromConfig {
164    region: Option<String>,
165    credentials: Option<SharedCredentialsProvider>,
166}
167
168impl CredentialsFromConfig {
169    /// Attempt find AWS S3 credentials via the AWS SDK
170    pub async fn try_new() -> Result<Self> {
171        // Loading the SDK config produces a large future, so box it to avoid
172        // potentially triggering the `large_futures` clippy lint.
173        let config =
174            Box::pin(aws_config::defaults(BehaviorVersion::latest()).load()).await;
175        let region = config.region().map(|r| r.to_string());
176
177        let credentials = config
178            .credentials_provider()
179            .ok_or_else(|| {
180                DataFusionError::ObjectStore(Box::new(Generic {
181                    store: "S3",
182                    source: "Failed to get S3 credentials aws_config".into(),
183                }))
184            })?
185            .clone();
186
187        // The credential provider is lazy, so it does not fetch credentials
188        // until they are needed. To ensure that the credentials are valid,
189        // we can call `provide_credentials` here.
190        let credentials = match credentials.provide_credentials().await {
191            Ok(_) => Some(credentials),
192            Err(CredentialsError::CredentialsNotLoaded(_)) => {
193                debug!("Could not use AWS SDK to get credentials");
194                None
195            }
196            // other errors like `CredentialsError::InvalidConfiguration`
197            // should be returned to the user so they can be fixed
198            Err(e) => {
199                // Pass back underlying error to the user, including underlying source
200                let source_message = if let Some(source) = e.source() {
201                    format!(": {source}")
202                } else {
203                    String::new()
204                };
205
206                let message = format!(
207                    "Error getting credentials from provider: {e}{source_message}",
208                );
209
210                return Err(DataFusionError::ObjectStore(Box::new(Generic {
211                    store: "S3",
212                    source: message.into(),
213                })));
214            }
215        };
216        Ok(Self {
217            region,
218            credentials,
219        })
220    }
221}
222
223#[derive(Debug)]
224struct S3CredentialProvider {
225    credentials: SharedCredentialsProvider,
226}
227
228#[async_trait]
229impl CredentialProvider for S3CredentialProvider {
230    type Credential = AwsCredential;
231
232    async fn get_credential(&self) -> object_store::Result<Arc<Self::Credential>> {
233        let creds =
234            self.credentials
235                .provide_credentials()
236                .await
237                .map_err(|e| Generic {
238                    store: "S3",
239                    source: Box::new(e),
240                })?;
241        Ok(Arc::new(AwsCredential {
242            key_id: creds.access_key_id().to_string(),
243            secret_key: creds.secret_access_key().to_string(),
244            token: creds.session_token().map(ToString::to_string),
245        }))
246    }
247}
248
249pub fn get_oss_object_store_builder(
250    url: &Url,
251    aws_options: &AwsOptions,
252) -> Result<AmazonS3Builder> {
253    get_object_store_builder(url, aws_options, true)
254}
255
256pub fn get_cos_object_store_builder(
257    url: &Url,
258    aws_options: &AwsOptions,
259) -> Result<AmazonS3Builder> {
260    get_object_store_builder(url, aws_options, false)
261}
262
263fn get_object_store_builder(
264    url: &Url,
265    aws_options: &AwsOptions,
266    virtual_hosted_style_request: bool,
267) -> Result<AmazonS3Builder> {
268    let bucket_name = get_bucket_name(url)?;
269    let mut builder = AmazonS3Builder::from_env()
270        .with_virtual_hosted_style_request(virtual_hosted_style_request)
271        .with_bucket_name(bucket_name)
272        // oss/cos don't care about the "region" field
273        .with_region("do_not_care");
274
275    if let (Some(access_key_id), Some(secret_access_key)) =
276        (&aws_options.access_key_id, &aws_options.secret_access_key)
277    {
278        builder = builder
279            .with_access_key_id(access_key_id)
280            .with_secret_access_key(secret_access_key);
281    }
282
283    if let Some(endpoint) = &aws_options.endpoint {
284        builder = builder.with_endpoint(endpoint);
285    }
286
287    Ok(builder)
288}
289
290pub fn get_gcs_object_store_builder(
291    url: &Url,
292    gs_options: &GcpOptions,
293) -> Result<GoogleCloudStorageBuilder> {
294    let bucket_name = get_bucket_name(url)?;
295    let mut builder = GoogleCloudStorageBuilder::from_env().with_bucket_name(bucket_name);
296
297    if let Some(service_account_path) = &gs_options.service_account_path {
298        builder = builder.with_service_account_path(service_account_path);
299    }
300
301    if let Some(service_account_key) = &gs_options.service_account_key {
302        builder = builder.with_service_account_key(service_account_key);
303    }
304
305    if let Some(application_credentials_path) = &gs_options.application_credentials_path {
306        builder = builder.with_application_credentials(application_credentials_path);
307    }
308
309    Ok(builder)
310}
311
312fn get_bucket_name(url: &Url) -> Result<&str> {
313    url.host_str().ok_or_else(|| {
314        exec_datafusion_err!("Not able to parse bucket name from url: {}", url.as_str())
315    })
316}
317
318/// This struct encapsulates AWS options one uses when setting up object storage.
319#[derive(Default, Debug, Clone)]
320pub struct AwsOptions {
321    /// Access Key ID
322    pub access_key_id: Option<String>,
323    /// Secret Access Key
324    pub secret_access_key: Option<String>,
325    /// Session token
326    pub session_token: Option<String>,
327    /// AWS Region
328    pub region: Option<String>,
329    /// OSS or COS Endpoint
330    pub endpoint: Option<String>,
331    /// Allow HTTP (otherwise will always use https)
332    pub allow_http: Option<bool>,
333    /// Do not fetch credentials and do not sign requests
334    ///
335    /// This can be useful when interacting with public S3 buckets that deny
336    /// authorized requests
337    pub skip_signature: Option<bool>,
338}
339
340impl ExtensionOptions for AwsOptions {
341    fn as_any(&self) -> &dyn Any {
342        self
343    }
344
345    fn as_any_mut(&mut self) -> &mut dyn Any {
346        self
347    }
348
349    fn cloned(&self) -> Box<dyn ExtensionOptions> {
350        Box::new(self.clone())
351    }
352
353    fn set(&mut self, key: &str, value: &str) -> Result<()> {
354        let (_key, aws_key) = key.split_once('.').unwrap_or((key, ""));
355        let (key, rem) = aws_key.split_once('.').unwrap_or((aws_key, ""));
356        match key {
357            "access_key_id" => {
358                self.access_key_id.set(rem, value)?;
359            }
360            "secret_access_key" => {
361                self.secret_access_key.set(rem, value)?;
362            }
363            "session_token" => {
364                self.session_token.set(rem, value)?;
365            }
366            "region" => {
367                self.region.set(rem, value)?;
368            }
369            "oss" | "cos" | "endpoint" => {
370                self.endpoint.set(rem, value)?;
371            }
372            "allow_http" => {
373                self.allow_http.set(rem, value)?;
374            }
375            "skip_signature" | "nosign" => {
376                self.skip_signature.set(rem, value)?;
377            }
378            _ => {
379                return config_err!("Config value \"{}\" not found on AwsOptions", rem);
380            }
381        }
382        Ok(())
383    }
384
385    fn entries(&self) -> Vec<ConfigEntry> {
386        struct Visitor(Vec<ConfigEntry>);
387
388        impl Visit for Visitor {
389            fn some<V: Display>(
390                &mut self,
391                key: &str,
392                value: V,
393                description: &'static str,
394            ) {
395                self.0.push(ConfigEntry {
396                    key: key.to_string(),
397                    value: Some(value.to_string()),
398                    description,
399                })
400            }
401
402            fn none(&mut self, key: &str, description: &'static str) {
403                self.0.push(ConfigEntry {
404                    key: key.to_string(),
405                    value: None,
406                    description,
407                })
408            }
409        }
410
411        let mut v = Visitor(vec![]);
412        self.access_key_id.visit(&mut v, "access_key_id", "");
413        self.secret_access_key
414            .visit(&mut v, "secret_access_key", "");
415        self.session_token.visit(&mut v, "session_token", "");
416        self.region.visit(&mut v, "region", "");
417        self.endpoint.visit(&mut v, "endpoint", "");
418        self.allow_http.visit(&mut v, "allow_http", "");
419        v.0
420    }
421}
422
423impl ConfigExtension for AwsOptions {
424    const PREFIX: &'static str = "aws";
425}
426
427/// This struct encapsulates GCP options one uses when setting up object storage.
428#[derive(Debug, Clone, Default)]
429pub struct GcpOptions {
430    /// Service account path
431    pub service_account_path: Option<String>,
432    /// Service account key
433    pub service_account_key: Option<String>,
434    /// Application credentials path
435    pub application_credentials_path: Option<String>,
436}
437
438impl ExtensionOptions for GcpOptions {
439    fn as_any(&self) -> &dyn Any {
440        self
441    }
442
443    fn as_any_mut(&mut self) -> &mut dyn Any {
444        self
445    }
446
447    fn cloned(&self) -> Box<dyn ExtensionOptions> {
448        Box::new(self.clone())
449    }
450
451    fn set(&mut self, key: &str, value: &str) -> Result<()> {
452        let (_key, rem) = key.split_once('.').unwrap_or((key, ""));
453        match rem {
454            "service_account_path" => {
455                self.service_account_path.set(rem, value)?;
456            }
457            "service_account_key" => {
458                self.service_account_key.set(rem, value)?;
459            }
460            "application_credentials_path" => {
461                self.application_credentials_path.set(rem, value)?;
462            }
463            _ => {
464                return config_err!("Config value \"{}\" not found on GcpOptions", rem);
465            }
466        }
467        Ok(())
468    }
469
470    fn entries(&self) -> Vec<ConfigEntry> {
471        struct Visitor(Vec<ConfigEntry>);
472
473        impl Visit for Visitor {
474            fn some<V: Display>(
475                &mut self,
476                key: &str,
477                value: V,
478                description: &'static str,
479            ) {
480                self.0.push(ConfigEntry {
481                    key: key.to_string(),
482                    value: Some(value.to_string()),
483                    description,
484                })
485            }
486
487            fn none(&mut self, key: &str, description: &'static str) {
488                self.0.push(ConfigEntry {
489                    key: key.to_string(),
490                    value: None,
491                    description,
492                })
493            }
494        }
495
496        let mut v = Visitor(vec![]);
497        self.service_account_path
498            .visit(&mut v, "service_account_path", "");
499        self.service_account_key
500            .visit(&mut v, "service_account_key", "");
501        self.application_credentials_path.visit(
502            &mut v,
503            "application_credentials_path",
504            "",
505        );
506        v.0
507    }
508}
509
510impl ConfigExtension for GcpOptions {
511    const PREFIX: &'static str = "gcp";
512}
513
514pub(crate) async fn get_object_store(
515    state: &SessionState,
516    scheme: &str,
517    url: &Url,
518    table_options: &TableOptions,
519    resolve_region: bool,
520) -> Result<Arc<dyn ObjectStore>, DataFusionError> {
521    let store: Arc<dyn ObjectStore> = match scheme {
522        "s3" => {
523            let Some(options) = table_options.extensions.get::<AwsOptions>() else {
524                return exec_err!(
525                    "Given table options incompatible with the 's3' scheme"
526                );
527            };
528            let builder =
529                get_s3_object_store_builder(url, options, resolve_region).await?;
530            Arc::new(builder.build()?)
531        }
532        "oss" => {
533            let Some(options) = table_options.extensions.get::<AwsOptions>() else {
534                return exec_err!(
535                    "Given table options incompatible with the 'oss' scheme"
536                );
537            };
538            let builder = get_oss_object_store_builder(url, options)?;
539            Arc::new(builder.build()?)
540        }
541        "cos" => {
542            let Some(options) = table_options.extensions.get::<AwsOptions>() else {
543                return exec_err!(
544                    "Given table options incompatible with the 'cos' scheme"
545                );
546            };
547            let builder = get_cos_object_store_builder(url, options)?;
548            Arc::new(builder.build()?)
549        }
550        "gs" | "gcs" => {
551            let Some(options) = table_options.extensions.get::<GcpOptions>() else {
552                return exec_err!(
553                    "Given table options incompatible with the 'gs'/'gcs' scheme"
554                );
555            };
556            let builder = get_gcs_object_store_builder(url, options)?;
557            Arc::new(builder.build()?)
558        }
559        "http" | "https" => Arc::new(
560            HttpBuilder::new()
561                .with_client_options(ClientOptions::new().with_allow_http(true))
562                .with_url(url.origin().ascii_serialization())
563                .build()?,
564        ),
565        _ if scheme == stdin::StdinUtils::SCHEME => {
566            stdin::StdinUtils::get_or_create(state, url).await?
567        }
568        _ => {
569            // For other types, try to get from `object_store_registry`:
570            state
571                .runtime_env()
572                .object_store_registry
573                .get_store(url)
574                .map_err(|_| {
575                    exec_datafusion_err!("Unsupported object store scheme: {}", scheme)
576                })?
577        }
578    };
579    Ok(store)
580}
581
582#[cfg(test)]
583mod tests {
584    use crate::cli_context::CliSessionContext;
585
586    use super::*;
587
588    use datafusion::{
589        datasource::listing::ListingTableUrl,
590        logical_expr::{DdlStatement, LogicalPlan},
591        prelude::SessionContext,
592    };
593
594    use object_store::{aws::AmazonS3ConfigKey, gcp::GoogleConfigKey};
595
596    #[tokio::test]
597    async fn s3_object_store_builder_default() -> Result<()> {
598        if let Err(DataFusionError::Execution(e)) = check_aws_envs() {
599            // Skip test if AWS envs are not set
600            eprintln!("{e}");
601            return Ok(());
602        }
603
604        let location = "s3://bucket/path/FAKE/file.parquet";
605        // Set it to a non-existent file to avoid reading the default configuration file
606        unsafe {
607            std::env::set_var("AWS_CONFIG_FILE", "data/aws.config");
608            std::env::set_var("AWS_SHARED_CREDENTIALS_FILE", "data/aws.credentials");
609        }
610
611        // No options
612        let table_url = ListingTableUrl::parse(location)?;
613        let scheme = table_url.scheme();
614        let sql =
615            format!("CREATE EXTERNAL TABLE test STORED AS PARQUET LOCATION '{location}'");
616
617        let ctx = SessionContext::new();
618        ctx.register_table_options_extension_from_scheme(scheme);
619        let table_options = get_table_options(&ctx, &sql).await;
620        let aws_options = table_options.extensions.get::<AwsOptions>().unwrap();
621        let builder =
622            get_s3_object_store_builder(table_url.as_ref(), aws_options, false).await?;
623
624        // If the environment variables are set (as they are in CI) use them
625        let expected_access_key_id = std::env::var("AWS_ACCESS_KEY_ID").ok();
626        let expected_secret_access_key = std::env::var("AWS_SECRET_ACCESS_KEY").ok();
627        let expected_region = Some(
628            std::env::var("AWS_REGION").unwrap_or_else(|_| "eu-central-1".to_string()),
629        );
630        let expected_endpoint = std::env::var("AWS_ENDPOINT").ok();
631
632        // get the actual configuration information, then assert_eq!
633        assert_eq!(
634            builder.get_config_value(&AmazonS3ConfigKey::AccessKeyId),
635            expected_access_key_id
636        );
637        assert_eq!(
638            builder.get_config_value(&AmazonS3ConfigKey::SecretAccessKey),
639            expected_secret_access_key
640        );
641        // Default is to skip signature when no credentials are provided
642        let expected_skip_signature =
643            if expected_access_key_id.is_none() && expected_secret_access_key.is_none() {
644                Some(String::from("true"))
645            } else {
646                Some(String::from("false"))
647            };
648        assert_eq!(
649            builder.get_config_value(&AmazonS3ConfigKey::Region),
650            expected_region
651        );
652        assert_eq!(
653            builder.get_config_value(&AmazonS3ConfigKey::Endpoint),
654            expected_endpoint
655        );
656        assert_eq!(builder.get_config_value(&AmazonS3ConfigKey::Token), None);
657        assert_eq!(
658            builder.get_config_value(&AmazonS3ConfigKey::SkipSignature),
659            expected_skip_signature
660        );
661        Ok(())
662    }
663
664    #[tokio::test]
665    async fn s3_object_store_builder() -> Result<()> {
666        // "fake" is uppercase to ensure the values are not lowercased when parsed
667        let access_key_id = "FAKE_access_key_id";
668        let secret_access_key = "FAKE_secret_access_key";
669        let region = "fake_us-east-2";
670        let endpoint = "endpoint33";
671        let session_token = "FAKE_session_token";
672        let location = "s3://bucket/path/FAKE/file.parquet";
673
674        let table_url = ListingTableUrl::parse(location)?;
675        let scheme = table_url.scheme();
676        let sql = format!(
677            "CREATE EXTERNAL TABLE test STORED AS PARQUET OPTIONS\
678            ('aws.access_key_id' '{access_key_id}', \
679            'aws.secret_access_key' '{secret_access_key}', \
680            'aws.region' '{region}', \
681            'aws.session_token' {session_token}, \
682            'aws.endpoint' '{endpoint}'\
683            ) LOCATION '{location}'"
684        );
685
686        let ctx = SessionContext::new();
687        ctx.register_table_options_extension_from_scheme(scheme);
688        let table_options = get_table_options(&ctx, &sql).await;
689        let aws_options = table_options.extensions.get::<AwsOptions>().unwrap();
690        let builder =
691            get_s3_object_store_builder(table_url.as_ref(), aws_options, false).await?;
692        // get the actual configuration information, then assert_eq!
693        let config = [
694            (AmazonS3ConfigKey::AccessKeyId, access_key_id),
695            (AmazonS3ConfigKey::SecretAccessKey, secret_access_key),
696            (AmazonS3ConfigKey::Region, region),
697            (AmazonS3ConfigKey::Endpoint, endpoint),
698            (AmazonS3ConfigKey::Token, session_token),
699        ];
700        for (key, value) in config {
701            assert_eq!(value, builder.get_config_value(&key).unwrap());
702        }
703        // Should not skip signature when credentials are provided
704        assert_eq!(
705            builder.get_config_value(&AmazonS3ConfigKey::SkipSignature),
706            Some("false".into())
707        );
708
709        Ok(())
710    }
711
712    #[tokio::test]
713    async fn s3_object_store_builder_allow_http_error() -> Result<()> {
714        let access_key_id = "fake_access_key_id";
715        let secret_access_key = "fake_secret_access_key";
716        let endpoint = "http://endpoint33";
717        let location = "s3://bucket/path/file.parquet";
718
719        let table_url = ListingTableUrl::parse(location)?;
720        let scheme = table_url.scheme();
721        let sql = format!(
722            "CREATE EXTERNAL TABLE test STORED AS PARQUET OPTIONS\
723            ('aws.access_key_id' '{access_key_id}', \
724            'aws.secret_access_key' '{secret_access_key}', \
725            'aws.endpoint' '{endpoint}'\
726            ) LOCATION '{location}'"
727        );
728
729        let ctx = SessionContext::new();
730        ctx.register_table_options_extension_from_scheme(scheme);
731
732        let table_options = get_table_options(&ctx, &sql).await;
733        let aws_options = table_options.extensions.get::<AwsOptions>().unwrap();
734        let err = get_s3_object_store_builder(table_url.as_ref(), aws_options, false)
735            .await
736            .unwrap_err();
737
738        assert_eq!(
739            err.to_string().lines().next().unwrap_or_default(),
740            "Invalid or Unsupported Configuration: Invalid endpoint: http://endpoint33. HTTP is not allowed for S3 endpoints. To allow HTTP, set 'aws.allow_http' to true"
741        );
742
743        // Now add `allow_http` to the options and check if it works
744        let sql = format!(
745            "CREATE EXTERNAL TABLE test STORED AS PARQUET OPTIONS\
746            ('aws.access_key_id' '{access_key_id}', \
747            'aws.secret_access_key' '{secret_access_key}', \
748            'aws.endpoint' '{endpoint}',\
749            'aws.allow_http' 'true'\
750            ) LOCATION '{location}'"
751        );
752        let table_options = get_table_options(&ctx, &sql).await;
753
754        let aws_options = table_options.extensions.get::<AwsOptions>().unwrap();
755        // ensure this isn't an error
756        get_s3_object_store_builder(table_url.as_ref(), aws_options, false).await?;
757
758        Ok(())
759    }
760
761    #[tokio::test]
762    async fn s3_object_store_builder_resolves_region_when_none_provided() -> Result<()> {
763        if let Err(DataFusionError::Execution(e)) = check_aws_envs() {
764            // Skip test if AWS envs are not set
765            eprintln!("{e}");
766            return Ok(());
767        }
768        let location = "s3://test-bucket/path/file.parquet";
769        // Set it to a non-existent file to avoid reading the default configuration file
770        unsafe {
771            std::env::set_var("AWS_CONFIG_FILE", "data/aws.config");
772        }
773
774        let table_url = ListingTableUrl::parse(location)?;
775        let aws_options = AwsOptions {
776            region: None, // No region specified - should auto-detect
777            ..Default::default()
778        };
779
780        let builder =
781            get_s3_object_store_builder(table_url.as_ref(), &aws_options, false).await?;
782
783        // Verify that the region was auto-detected in test environment
784        assert!(
785            builder
786                .get_config_value(&AmazonS3ConfigKey::Region)
787                .is_some()
788        );
789
790        Ok(())
791    }
792
793    #[tokio::test]
794    async fn s3_object_store_builder_overrides_region_when_resolve_region_enabled()
795    -> Result<()> {
796        if let Err(DataFusionError::Execution(e)) = check_aws_envs() {
797            // Skip test if AWS envs are not set
798            eprintln!("{e}");
799            return Ok(());
800        }
801
802        let original_region = "us-east-1";
803        let expected_region = "eu-central-1"; // This should be the auto-detected region
804        let location = "s3://test-bucket/path/file.parquet";
805
806        let table_url = ListingTableUrl::parse(location)?;
807        let aws_options = AwsOptions {
808            region: Some(original_region.to_string()), // Explicit region provided
809            ..Default::default()
810        };
811
812        let builder =
813            get_s3_object_store_builder(table_url.as_ref(), &aws_options, true).await?;
814
815        // Verify that the region was overridden by auto-detection
816        assert_eq!(
817            builder.get_config_value(&AmazonS3ConfigKey::Region),
818            Some(expected_region.to_string())
819        );
820
821        Ok(())
822    }
823
824    #[tokio::test]
825    async fn oss_object_store_builder() -> Result<()> {
826        let access_key_id = "fake_access_key_id";
827        let secret_access_key = "fake_secret_access_key";
828        let endpoint = "fake_endpoint";
829        let location = "oss://bucket/path/file.parquet";
830
831        let table_url = ListingTableUrl::parse(location)?;
832        let scheme = table_url.scheme();
833        let sql = format!(
834            "CREATE EXTERNAL TABLE test STORED AS PARQUET OPTIONS('aws.access_key_id' '{access_key_id}', 'aws.secret_access_key' '{secret_access_key}', 'aws.oss.endpoint' '{endpoint}') LOCATION '{location}'"
835        );
836
837        let ctx = SessionContext::new();
838        ctx.register_table_options_extension_from_scheme(scheme);
839        let table_options = get_table_options(&ctx, &sql).await;
840
841        let aws_options = table_options.extensions.get::<AwsOptions>().unwrap();
842        let builder = get_oss_object_store_builder(table_url.as_ref(), aws_options)?;
843        // get the actual configuration information, then assert_eq!
844        let config = [
845            (AmazonS3ConfigKey::AccessKeyId, access_key_id),
846            (AmazonS3ConfigKey::SecretAccessKey, secret_access_key),
847            (AmazonS3ConfigKey::Endpoint, endpoint),
848        ];
849        for (key, value) in config {
850            assert_eq!(value, builder.get_config_value(&key).unwrap());
851        }
852
853        Ok(())
854    }
855
856    #[tokio::test]
857    async fn gcs_object_store_builder() -> Result<()> {
858        let service_account_path = "fake_service_account_path";
859        let service_account_key = "{\"private_key\": \"fake_private_key.pem\",\"client_email\":\"fake_client_email\"}";
860        let application_credentials_path = "fake_application_credentials_path";
861        let location = "gcs://bucket/path/file.parquet";
862
863        let table_url = ListingTableUrl::parse(location)?;
864        let scheme = table_url.scheme();
865        let sql = format!(
866            "CREATE EXTERNAL TABLE test STORED AS PARQUET OPTIONS('gcp.service_account_path' '{service_account_path}', 'gcp.service_account_key' '{service_account_key}', 'gcp.application_credentials_path' '{application_credentials_path}') LOCATION '{location}'"
867        );
868
869        let ctx = SessionContext::new();
870        ctx.register_table_options_extension_from_scheme(scheme);
871        let table_options = get_table_options(&ctx, &sql).await;
872
873        let gcp_options = table_options.extensions.get::<GcpOptions>().unwrap();
874        let builder = get_gcs_object_store_builder(table_url.as_ref(), gcp_options)?;
875        // get the actual configuration information, then assert_eq!
876        let config = [
877            (GoogleConfigKey::ServiceAccount, service_account_path),
878            (GoogleConfigKey::ServiceAccountKey, service_account_key),
879            (
880                GoogleConfigKey::ApplicationCredentials,
881                application_credentials_path,
882            ),
883        ];
884        for (key, value) in config {
885            assert_eq!(value, builder.get_config_value(&key).unwrap());
886        }
887
888        Ok(())
889    }
890
891    /// Plans the `CREATE EXTERNAL TABLE` SQL statement and returns the
892    /// resulting resolved `CreateExternalTable` command.
893    async fn get_table_options(ctx: &SessionContext, sql: &str) -> TableOptions {
894        let mut plan = ctx.state().create_logical_plan(sql).await.unwrap();
895
896        let LogicalPlan::Ddl(DdlStatement::CreateExternalTable(cmd)) = &mut plan else {
897            panic!("plan is not a CreateExternalTable");
898        };
899
900        let mut table_options = ctx.state().default_table_options();
901        table_options
902            .alter_with_string_hash_map(&cmd.options)
903            .unwrap();
904        table_options
905    }
906
907    fn check_aws_envs() -> Result<()> {
908        let aws_envs = [
909            "AWS_ACCESS_KEY_ID",
910            "AWS_SECRET_ACCESS_KEY",
911            "AWS_REGION",
912            "AWS_ALLOW_HTTP",
913        ];
914        for aws_env in aws_envs {
915            std::env::var(aws_env).map_err(|_| {
916                exec_datafusion_err!("aws envs not set, skipping s3 tests")
917            })?;
918        }
919        Ok(())
920    }
921}