manuzhang commented on code in PR #2396: URL: https://github.com/apache/iceberg-rust/pull/2396#discussion_r3600341999
########## crates/integrations/aws/src/config.rs: ########## @@ -0,0 +1,449 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +//! AWS SDK configuration utilities. + +use std::collections::HashMap; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use aws_config::sts::AssumeRoleProvider; +use aws_config::{BehaviorVersion, Region, SdkConfig}; +use aws_credential_types::Credentials as AwsSdkCredentials; +use aws_credential_types::provider::{ + ProvideCredentials, SharedCredentialsProvider, future as credentials_future, +}; +use aws_sdk_sts::config::Credentials; +use iceberg::io::{ + S3_ACCESS_KEY_ID, S3_ASSUME_ROLE_ARN, S3_ASSUME_ROLE_EXTERNAL_ID, S3_ASSUME_ROLE_SESSION_NAME, + S3_ENDPOINT, S3_REGION, S3_SECRET_ACCESS_KEY, S3_SESSION_TOKEN, +}; +use reqsign_aws_v4::Credential as AwsCredential; +use reqsign_core::time::Timestamp; +use reqsign_core::{Context, Error as ReqsignError, ProvideCredential}; + +use crate::{ + AWS_ACCESS_KEY_ID, AWS_ASSUME_ROLE_ARN, AWS_ASSUME_ROLE_EXTERNAL_ID, + AWS_ASSUME_ROLE_SESSION_NAME, AWS_PROFILE_NAME, AWS_REGION_NAME, AWS_SECRET_ACCESS_KEY, + AWS_SESSION_TOKEN, +}; + +/// Creates an AWS SDK configuration from catalog properties. +/// +/// When `client.assume-role.arn` is set, the configured base credentials, +/// profile, region, and runtime settings are used for the STS request. The +/// returned configuration uses the refreshable assumed-role provider. +pub async fn create_sdk_config( + properties: &HashMap<String, String>, + endpoint_uri: Option<&str>, + default_session_name: &str, +) -> SdkConfig { + let mut loader = aws_config::defaults(BehaviorVersion::latest()); + + if let Some(endpoint) = endpoint_uri { + loader = loader.endpoint_url(endpoint); + } + + if let (Some(access_key), Some(secret_key)) = ( + properties.get(AWS_ACCESS_KEY_ID), + properties.get(AWS_SECRET_ACCESS_KEY), + ) { + let session_token = properties.get(AWS_SESSION_TOKEN).cloned(); + let credentials_provider = + Credentials::new(access_key, secret_key, session_token, None, "properties"); + loader = loader.credentials_provider(credentials_provider); + } + + if let Some(profile_name) = properties.get(AWS_PROFILE_NAME) { + loader = loader.profile_name(profile_name); + } + + if let Some(region_name) = properties.get(AWS_REGION_NAME) { + loader = loader.region(Region::new(region_name.clone())); + } + + let base_config = loader.load().await; + let Some(role_arn) = properties.get(AWS_ASSUME_ROLE_ARN) else { + return base_config; + }; + + let session_name = properties + .get(AWS_ASSUME_ROLE_SESSION_NAME) + .map(String::as_str) + .unwrap_or(default_session_name); + let mut assume_role_builder = AssumeRoleProvider::builder(role_arn) + .session_name(session_name) + .configure(&base_config); + + if let Some(external_id) = properties.get(AWS_ASSUME_ROLE_EXTERNAL_ID) { + assume_role_builder = assume_role_builder.external_id(external_id); + } + + let assume_role_provider = SharedCredentialsProvider::new(RefreshingCredentialsProvider { + inner: assume_role_builder.build().await, + cached: tokio::sync::Mutex::new(None), + }); + base_config + .into_builder() + .credentials_provider(assume_role_provider) + .build() +} + +#[derive(Debug)] +struct RefreshingCredentialsProvider { + inner: AssumeRoleProvider, + cached: tokio::sync::Mutex<Option<AwsSdkCredentials>>, +} + +impl RefreshingCredentialsProvider { + async fn credentials(&self) -> aws_credential_types::provider::Result { + let mut cached = self.cached.lock().await; + if let Some(credentials) = cached + .as_ref() + .filter(|credentials| credentials_are_fresh(credentials, SystemTime::now())) + { + return Ok(credentials.clone()); + } + + let credentials = self.inner.provide_credentials().await?; + *cached = Some(credentials.clone()); + Ok(credentials) + } +} + +impl ProvideCredentials for RefreshingCredentialsProvider { + fn provide_credentials<'a>(&'a self) -> credentials_future::ProvideCredentials<'a> + where Self: 'a { + credentials_future::ProvideCredentials::new(self.credentials()) + } +} + +fn credentials_are_fresh(credentials: &AwsSdkCredentials, now: SystemTime) -> bool { + credentials + .expiry() + .is_none_or(|expiry| expiry > now + Duration::from_secs(300)) +} + +/// A reqsign credential provider backed by an AWS SDK credential provider. +/// +/// Clones share the SDK provider, including its assumed-role credential cache +/// and refresh behavior. +#[derive(Clone, Debug)] +pub struct AwsSdkCredentialProvider { + provider: SharedCredentialsProvider, +} + +impl AwsSdkCredentialProvider { + /// Creates an adapter from the credentials provider in `config`. + pub fn from_sdk_config(config: &SdkConfig) -> Option<Self> { + config + .credentials_provider() + .map(|provider| Self { provider }) + } +} + +impl ProvideCredential for AwsSdkCredentialProvider { + type Credential = AwsCredential; + + async fn provide_credential( + &self, + _ctx: &Context, + ) -> reqsign_core::Result<Option<Self::Credential>> { + let credentials = self.provider.provide_credentials().await.map_err(|error| { + ReqsignError::credential_invalid("failed to load AWS SDK credentials") + .with_source(error) + })?; + + let expires_in = credentials + .expiry() + .map(|expiry| { + let duration = expiry.duration_since(UNIX_EPOCH).map_err(|error| { + ReqsignError::credential_invalid("AWS credential expiry predates Unix epoch") + .with_source(error) + })?; + let millis = i64::try_from(duration.as_millis()).map_err(|error| { + ReqsignError::credential_invalid("AWS credential expiry is out of range") + .with_source(error) + })?; + Timestamp::from_millisecond(millis) + }) + .transpose()?; + + Ok(Some(AwsCredential { + access_key_id: credentials.access_key_id().to_string(), + secret_access_key: credentials.secret_access_key().to_string(), + session_token: credentials.session_token().map(ToString::to_string), + expires_in, + })) + } +} + +/// Returns whether the caller supplied S3-specific static credentials. +pub fn has_explicit_s3_credentials(properties: &HashMap<String, String>) -> bool { + properties.contains_key(S3_ACCESS_KEY_ID) + || properties.contains_key(S3_SECRET_ACCESS_KEY) + || properties.contains_key(S3_SESSION_TOKEN) +} + +/// Removes AssumeRole properties after FileIO has been given the SDK provider. +/// +/// This prevents OpenDAL from performing a second AssumeRole request. +pub fn remove_assume_role_properties(properties: &mut HashMap<String, String>) { + properties.remove(S3_ASSUME_ROLE_ARN); + properties.remove(S3_ASSUME_ROLE_EXTERNAL_ID); + properties.remove(S3_ASSUME_ROLE_SESSION_NAME); +} + +/// Maps generic AWS properties to S3-specific properties. +/// +/// Explicit S3 properties take precedence. When AssumeRole is enabled, the +/// service-specific default session name is materialized for FileIO. +pub fn map_aws_to_s3_properties( + properties: &HashMap<String, String>, + endpoint_uri: Option<&str>, + default_session_name: &str, +) -> HashMap<String, String> { + let mut s3_props = properties.clone(); + + if !s3_props.contains_key(S3_ACCESS_KEY_ID) + && let Some(access_key_id) = s3_props.get(AWS_ACCESS_KEY_ID) + { + s3_props.insert(S3_ACCESS_KEY_ID.to_string(), access_key_id.to_string()); + } + if !s3_props.contains_key(S3_SECRET_ACCESS_KEY) + && let Some(secret_access_key) = s3_props.get(AWS_SECRET_ACCESS_KEY) + { + s3_props.insert( + S3_SECRET_ACCESS_KEY.to_string(), + secret_access_key.to_string(), + ); + } + if !s3_props.contains_key(S3_REGION) Review Comment: This only maps an explicit region_name. The shared provider bridges credentials, but OpenDAL does not load the selected profile’s region; it requires `s3.region`, `client.region`, or an environment region. A profile containing credentials and region can therefore authenticate STS/Glue successfully while FileIO fails with “region is missing” or signs for a different region. Propagate `sdk_config.region()` when no S3 region is explicitly configured. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
