diff --git a/Cargo.lock b/Cargo.lock index ae367e7d8c..918b570671 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3899,6 +3899,7 @@ dependencies = [ "iceberg_test_utils", "itertools 0.13.0", "mockito", + "rand 0.9.5", "reqwest 0.12.28", "serde", "serde_derive", @@ -4059,6 +4060,7 @@ dependencies = [ "opendal", "reqsign-aws-v4", "reqsign-core", + "reqsign-google", "reqwest 0.12.28", "serde", "tokio", diff --git a/crates/catalog/rest/Cargo.toml b/crates/catalog/rest/Cargo.toml index 8dc9a86d7f..f035f0e0ef 100644 --- a/crates/catalog/rest/Cargo.toml +++ b/crates/catalog/rest/Cargo.toml @@ -35,6 +35,7 @@ chrono = { workspace = true } http = { workspace = true } iceberg = { workspace = true } itertools = { workspace = true } +rand = { workspace = true } reqwest = { workspace = true } serde = { workspace = true } serde_derive = { workspace = true } diff --git a/crates/catalog/rest/public-api.txt b/crates/catalog/rest/public-api.txt index 6f3fa58a47..70aad8f7c5 100644 --- a/crates/catalog/rest/public-api.txt +++ b/crates/catalog/rest/public-api.txt @@ -171,6 +171,20 @@ impl serde_core::ser::Serialize for iceberg_catalog_rest::ListTablesResponse pub fn iceberg_catalog_rest::ListTablesResponse::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg_catalog_rest::ListTablesResponse pub fn iceberg_catalog_rest::ListTablesResponse::deserialize<__D>(__deserializer: __D) -> core::result::Result::Error> where __D: serde_core::de::Deserializer<'de> +pub struct iceberg_catalog_rest::LoadCredentialsResponse +pub iceberg_catalog_rest::LoadCredentialsResponse::storage_credentials: alloc::vec::Vec +impl core::clone::Clone for iceberg_catalog_rest::LoadCredentialsResponse +pub fn iceberg_catalog_rest::LoadCredentialsResponse::clone(&self) -> iceberg_catalog_rest::LoadCredentialsResponse +impl core::cmp::Eq for iceberg_catalog_rest::LoadCredentialsResponse +impl core::cmp::PartialEq for iceberg_catalog_rest::LoadCredentialsResponse +pub fn iceberg_catalog_rest::LoadCredentialsResponse::eq(&self, other: &iceberg_catalog_rest::LoadCredentialsResponse) -> bool +impl core::fmt::Debug for iceberg_catalog_rest::LoadCredentialsResponse +pub fn iceberg_catalog_rest::LoadCredentialsResponse::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::StructuralPartialEq for iceberg_catalog_rest::LoadCredentialsResponse +impl serde_core::ser::Serialize for iceberg_catalog_rest::LoadCredentialsResponse +pub fn iceberg_catalog_rest::LoadCredentialsResponse::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer +impl<'de> serde_core::de::Deserialize<'de> for iceberg_catalog_rest::LoadCredentialsResponse +pub fn iceberg_catalog_rest::LoadCredentialsResponse::deserialize<__D>(__deserializer: __D) -> core::result::Result::Error> where __D: serde_core::de::Deserializer<'de> pub struct iceberg_catalog_rest::LoadTableResult pub iceberg_catalog_rest::LoadTableResult::config: std::collections::hash::map::HashMap pub iceberg_catalog_rest::LoadTableResult::metadata: iceberg::spec::table_metadata::TableMetadata @@ -213,6 +227,7 @@ pub fn iceberg_catalog_rest::NoopAuthManager::fmt(&self, f: &mut core::fmt::Form impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::NoopAuthManager pub fn iceberg_catalog_rest::NoopAuthManager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::NoopAuthManager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::NoopAuthManager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, _props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait pub struct iceberg_catalog_rest::OAuth2Manager impl iceberg_catalog_rest::OAuth2Manager pub fn iceberg_catalog_rest::OAuth2Manager::new(token_endpoint: impl core::convert::Into) -> Self @@ -225,6 +240,7 @@ pub fn iceberg_catalog_rest::OAuth2Manager::fmt(&self, f: &mut core::fmt::Format impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::OAuth2Manager pub fn iceberg_catalog_rest::OAuth2Manager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::OAuth2Manager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::OAuth2Manager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait pub struct iceberg_catalog_rest::RegisterTableRequest pub iceberg_catalog_rest::RegisterTableRequest::metadata_location: alloc::string::String pub iceberg_catalog_rest::RegisterTableRequest::name: alloc::string::String @@ -339,16 +355,20 @@ pub const iceberg_catalog_rest::AUTH_TYPE_NONE: &str pub const iceberg_catalog_rest::AUTH_TYPE_OAUTH2: &str pub const iceberg_catalog_rest::REST_CATALOG_PROP_AUTH_TYPE: &str pub const iceberg_catalog_rest::REST_CATALOG_PROP_DISABLE_HEADER_REDACTION: &str +pub const iceberg_catalog_rest::REST_CATALOG_PROP_SCAN_PLAN_ID: &str pub const iceberg_catalog_rest::REST_CATALOG_PROP_URI: &str pub const iceberg_catalog_rest::REST_CATALOG_PROP_WAREHOUSE: &str pub trait iceberg_catalog_rest::AuthManager: core::fmt::Debug + core::marker::Send + core::marker::Sync pub fn iceberg_catalog_rest::AuthManager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::AuthManager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::AuthManager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, _props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::NoopAuthManager pub fn iceberg_catalog_rest::NoopAuthManager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::NoopAuthManager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::NoopAuthManager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, _props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait impl iceberg_catalog_rest::AuthManager for iceberg_catalog_rest::OAuth2Manager pub fn iceberg_catalog_rest::OAuth2Manager::catalog_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait pub fn iceberg_catalog_rest::OAuth2Manager::init_session<'life0, 'life1, 'life2, 'async_trait>(&'life0 self, client: &'life1 iceberg_catalog_rest::HttpClient, props: &'life2 std::collections::hash::map::HashMap) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait +pub fn iceberg_catalog_rest::OAuth2Manager::table_session<'life0, 'life1, 'life2, 'life3, 'async_trait>(&'life0 self, _client: &'life1 iceberg_catalog_rest::HttpClient, _table: &'life2 iceberg::catalog::TableIdent, props: &'life3 std::collections::hash::map::HashMap, parent: alloc::sync::Arc) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait, 'life2: 'async_trait, 'life3: 'async_trait pub trait iceberg_catalog_rest::AuthSession: core::fmt::Debug + core::marker::Send + core::marker::Sync pub fn iceberg_catalog_rest::AuthSession::authenticate<'life0, 'life1, 'async_trait>(&'life0 self, request: &'life1 mut iceberg_catalog_rest::HttpRequest) -> core::pin::Pin> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait diff --git a/crates/catalog/rest/src/auth/mod.rs b/crates/catalog/rest/src/auth/mod.rs index 8f7a3f425a..16faf8c1d7 100644 --- a/crates/catalog/rest/src/auth/mod.rs +++ b/crates/catalog/rest/src/auth/mod.rs @@ -25,7 +25,7 @@ use std::fmt::Debug; use std::sync::Arc; use async_trait::async_trait; -use iceberg::Result; +use iceberg::{Result, TableIdent}; pub use oauth2::OAuth2Manager; use crate::client::HttpClient; @@ -42,9 +42,9 @@ pub const AUTH_TYPE_OAUTH2: &str = "oauth2"; /// property or injected through `RestCatalogBuilder::with_auth_manager`. It /// builds the sessions the catalog then keeps. /// -/// Both methods are handed the catalog's [`HttpClient`], which an -/// implementation may reuse for its own requests (e.g. a token exchange) so -/// that they share the catalog's connection pool and configuration. +/// Session-construction methods are handed the catalog's [`HttpClient`], which +/// an implementation may reuse for its own requests (e.g. a token exchange) +/// so that they share the catalog's connection pool and configuration. #[async_trait] pub trait AuthManager: Debug + Send + Sync { /// Session used for the initial `/v1/config` handshake, given the @@ -69,6 +69,22 @@ pub trait AuthManager: Debug + Send + Sync { client: &HttpClient, props: &HashMap, ) -> Result>; + + /// Returns a session for requests associated with `table`. + /// + /// `props` are the unmerged properties returned by the table endpoint. + /// The default preserves the catalog session; managers should return a + /// child session only when the table properties contain an authentication + /// override. + async fn table_session( + &self, + _client: &HttpClient, + _table: &TableIdent, + _props: &HashMap, + parent: Arc, + ) -> Result> { + Ok(parent) + } } /// Authenticates outgoing REST catalog requests. diff --git a/crates/catalog/rest/src/auth/oauth2.rs b/crates/catalog/rest/src/auth/oauth2.rs index 897fcbb853..8603e58539 100644 --- a/crates/catalog/rest/src/auth/oauth2.rs +++ b/crates/catalog/rest/src/auth/oauth2.rs @@ -21,7 +21,7 @@ use std::sync::Arc; use async_trait::async_trait; use http::StatusCode; -use iceberg::{Credential, Error, ErrorKind, Result}; +use iceberg::{Credential, Error, ErrorKind, Result, TableIdent}; use reqwest::header::HeaderMap; use tokio::sync::Mutex; @@ -45,8 +45,9 @@ struct OAuth2Params { /// Iceberg REST catalogs. /// /// A configured `token` is used directly; otherwise `credential` is exchanged -/// for a token at the token endpoint and cached. The cached token is shared -/// across sessions so it survives the config handshake. +/// for a token at the token endpoint and cached. The cached token is shared by +/// the init and catalog sessions so it survives the config handshake; +/// table-specific tokens use isolated sessions. pub struct OAuth2Manager { token: Arc>>, init_params: OAuth2Params, @@ -143,13 +144,30 @@ impl AuthManager for OAuth2Manager { ) -> Result> { Ok(Arc::new(self.session_from(client, props).await?)) } + + async fn table_session( + &self, + _client: &HttpClient, + _table: &TableIdent, + props: &HashMap, + parent: Arc, + ) -> Result> { + let Some(token) = props.get("token") else { + return Ok(parent); + }; + + Ok(Arc::new(OAuth2Session { + token: Arc::new(Mutex::new(Some(Credential::from(token.clone())))), + token_source: TokenSource::StaticToken, + })) + } } impl OAuth2Manager { /// Builds a session from the manager's options with `props` merged onto /// them, so an injected manager keeps whatever a property doesn't - /// override. The manager's token cell is shared with every session it - /// builds, so a token cached during the handshake survives it. + /// override. The manager's token cell is shared by the init and catalog + /// sessions, so a token cached during the handshake survives it. async fn session_from( &self, client: &HttpClient, @@ -376,4 +394,56 @@ mod tests { "Bearer tok-static" ); } + + #[tokio::test] + async fn test_table_session_inherits_parent_unless_token_is_overridden() { + let manager = OAuth2Manager::new("http://localhost/unused").with_token("catalog-token"); + let client = test_client(); + let parent = manager + .catalog_session(&client, &HashMap::new()) + .await + .unwrap(); + let table = TableIdent::from_strs(["namespace", "table"]).unwrap(); + + let inherited = manager + .table_session(&client, &table, &HashMap::new(), Arc::clone(&parent)) + .await + .unwrap(); + assert!(Arc::ptr_eq(&parent, &inherited)); + + let overridden = manager + .table_session( + &client, + &table, + &HashMap::from([("token".to_string(), "table-token".to_string())]), + Arc::clone(&parent), + ) + .await + .unwrap(); + assert!(!Arc::ptr_eq(&parent, &overridden)); + + let mut parent_request = HttpRequest::new( + Client::new() + .get("https://rest.example.com/catalog") + .build() + .unwrap(), + ); + parent.authenticate(&mut parent_request).await.unwrap(); + assert_eq!( + parent_request.headers().get("authorization").unwrap(), + "Bearer catalog-token" + ); + + let mut table_request = HttpRequest::new( + Client::new() + .get("https://rest.example.com/table") + .build() + .unwrap(), + ); + overridden.authenticate(&mut table_request).await.unwrap(); + assert_eq!( + table_request.headers().get("authorization").unwrap(), + "Bearer table-token" + ); + } } diff --git a/crates/catalog/rest/src/catalog.rs b/crates/catalog/rest/src/catalog.rs index 0c15c50663..5397c1885a 100644 --- a/crates/catalog/rest/src/catalog.rs +++ b/crates/catalog/rest/src/catalog.rs @@ -43,6 +43,7 @@ use crate::auth::{AUTH_TYPE_NONE, AUTH_TYPE_OAUTH2, AuthManager, NoopAuthManager use crate::client::{ HttpClient, deserialize_catalog_response, deserialize_unexpected_catalog_error, }; +use crate::credential::build_vended_credential_provider; use crate::endpoint::{Endpoint, V1_NAMESPACE_EXISTS, V1_TABLE_EXISTS}; use crate::request::HttpRequest; use crate::types::{ @@ -58,6 +59,8 @@ pub const REST_CATALOG_PROP_WAREHOUSE: &str = "warehouse"; /// Disable header redaction in error logs and `Debug` output (defaults to /// false for security) pub const REST_CATALOG_PROP_DISABLE_HEADER_REDACTION: &str = "disable-header-redaction"; +/// Identifier for a server-side scan plan associated with credential requests. +pub const REST_CATALOG_PROP_SCAN_PLAN_ID: &str = "rest.scan.plan-id"; /// Authentication scheme: `none` or `oauth2`. When unset, `oauth2` is used /// if a `token`, `credential` or `oauth2-server-uri` is configured, `none` /// otherwise. @@ -460,6 +463,8 @@ pub(crate) fn oauth_params_from_props(props: &HashMap) -> HashMa #[derive(Debug)] struct RestClient { + /// Creates child authentication sessions for table-scoped requests. + auth_manager: Arc, /// Carries the session the auth manager derived from the merged /// configuration, so every request below is authenticated. http_client: HttpClient, @@ -664,6 +669,7 @@ impl RestCatalog { .await?; Ok(RestClient { + auth_manager, config, http_client: http_client.with_auth_session(session), endpoints, @@ -725,20 +731,22 @@ impl RestCatalog { async fn load_file_io( &self, + table: &TableIdent, metadata_location: Option<&str>, extra_config: Option>, + table_auth_config: Option>, ) -> Result { - let mut props = self.client().await?.config.props.clone(); + let client = self.client().await?; + let mut props = client.config.props.clone(); if let Some(config) = extra_config { props.extend(config); } // If the warehouse is a logical identifier instead of a URL we don't want // to raise an exception - let warehouse_path = match self.client().await?.config.warehouse.as_deref() { + let warehouse_path = match client.config.warehouse.as_deref() { Some(url) if Url::parse(url).is_ok() => Some(url), - Some(_) => None, - None => None, + _ => None, }; if metadata_location.or(warehouse_path).is_none() { @@ -759,9 +767,24 @@ impl RestCatalog { ) })?; - let file_io = FileIOBuilder::new(factory).with_props(props).build(); + // If the catalog vends refreshable credentials for this table's storage, + // attach a provider so the backend re-fetches them before they expire. + let credential_provider = build_vended_credential_provider( + Arc::new(client.http_client.clone()), + client.auth_manager.as_ref(), + table, + &client.config.uri, + &props, + table_auth_config.as_ref(), + ) + .await?; + + let mut builder = FileIOBuilder::new(factory).with_props(props); + if let Some(provider) = credential_provider { + builder = builder.with_credential_provider(provider); + } - Ok(file_io) + Ok(builder.build()) } } @@ -1052,14 +1075,20 @@ impl Catalog for RestCatalog { "Metadata location missing in `create_table` response!", ))?; - let config = response - .config + let table_config = response.config; + let config = table_config + .clone() .into_iter() .chain(self.user_config.props.clone()) .collect(); let file_io = self - .load_file_io(Some(metadata_location), Some(config)) + .load_file_io( + &table_ident, + Some(metadata_location), + Some(config), + Some(table_config), + ) .await?; let mut table_builder = Table::builder() @@ -1113,14 +1142,20 @@ impl Catalog for RestCatalog { } }; - let config = response - .config + let table_config = response.config; + let config = table_config + .clone() .into_iter() .chain(self.user_config.props.clone()) .collect(); let file_io = self - .load_file_io(response.metadata_location.as_deref(), Some(config)) + .load_file_io( + table_ident, + response.metadata_location.as_deref(), + Some(config), + Some(table_config), + ) .await?; let mut table_builder = Table::builder() @@ -1257,7 +1292,20 @@ impl Catalog for RestCatalog { "Metadata location missing in `register_table` response!", ))?; - let file_io = self.load_file_io(Some(metadata_location), None).await?; + let table_config = response.config; + let config = table_config + .clone() + .into_iter() + .chain(self.user_config.props.clone()) + .collect(); + let file_io = self + .load_file_io( + table_ident, + Some(metadata_location), + Some(config), + Some(table_config), + ) + .await?; let mut table_builder = Table::builder() .identifier(table_ident.clone()) @@ -1333,7 +1381,12 @@ impl Catalog for RestCatalog { }; let file_io = self - .load_file_io(Some(&response.metadata_location), None) + .load_file_io( + commit.identifier(), + Some(&response.metadata_location), + None, + None, + ) .await?; let mut table_builder = Table::builder() diff --git a/crates/catalog/rest/src/client.rs b/crates/catalog/rest/src/client.rs index 4ed3d6d023..6787a0fc85 100644 --- a/crates/catalog/rest/src/client.rs +++ b/crates/catalog/rest/src/client.rs @@ -24,8 +24,10 @@ use reqwest::header::HeaderMap; use reqwest::{Client, IntoUrl, Method, RequestBuilder, Response, StatusCode}; use serde::de::DeserializeOwned; -use crate::RestCatalogConfig; use crate::auth::{AuthSession, NoopSession}; +use crate::catalog::{ + REST_CATALOG_PROP_DISABLE_HEADER_REDACTION, RestCatalogConfig, explicit_headers_from_props, +}; use crate::request::HttpRequest; /// The catalog's HTTP client, handed to an [`AuthManager`] so its own @@ -86,7 +88,7 @@ impl HttpClient { /// not merged in. /// /// Like every request, it carries this client's session; call - /// [`Self::without_session`] first to send it unauthenticated. + /// [`Self::without_auth_session`] first to send it unauthenticated. /// /// [`AuthManager`]: crate::auth::AuthManager pub async fn post_form( @@ -145,10 +147,43 @@ impl HttpClient { }) } - /// Testing only: the session authenticating this client's requests. - #[cfg(test)] - pub(crate) fn auth_session(&self) -> &Arc { - &self.auth_session + /// Derives a client for table-scoped requests. + /// + /// The connection pool and catalog headers are inherited, explicit table + /// headers override them, and `auth_session` replaces the catalog session + /// only when the auth manager selected a table-specific child session. + pub(crate) fn for_table( + &self, + props: &HashMap, + auth_session: Arc, + ) -> Result { + let mut extra_headers = self.extra_headers.clone(); + let table_headers = explicit_headers_from_props(props)?; + let has_table_authorization = table_headers.contains_key(http::header::AUTHORIZATION); + + if !Arc::ptr_eq(&self.auth_session, &auth_session) && !has_table_authorization { + // An inherited catalog Authorization header would otherwise be + // applied after, and overwrite, the table session's authentication. + extra_headers.remove(http::header::AUTHORIZATION); + } + extra_headers.extend(table_headers); + + let disable_header_redaction = props + .get(REST_CATALOG_PROP_DISABLE_HEADER_REDACTION) + .map(|value| value.eq_ignore_ascii_case("true")) + .unwrap_or(self.disable_header_redaction); + + Ok(Self { + client: self.client.clone(), + extra_headers, + disable_header_redaction, + auth_session, + }) + } + + /// Returns the session authenticating this client's requests. + pub(crate) fn auth_session(&self) -> Arc { + Arc::clone(&self.auth_session) } /// Testing only: the bearer token `session` would attach. @@ -303,6 +338,19 @@ mod tests { } } + #[derive(Debug)] + struct TableSession; + + #[async_trait::async_trait] + impl AuthSession for TableSession { + async fn authenticate(&self, request: &mut HttpRequest) -> Result<()> { + request + .headers_mut() + .insert("authorization", "Bearer table-token".parse().unwrap()); + Ok(()) + } + } + #[tokio::test] async fn test_post_form_carries_the_session_until_it_is_removed() { // Every request a client sends carries its session; a caller that @@ -340,6 +388,66 @@ mod tests { unsigned.assert_async().await; } + #[tokio::test] + async fn test_table_client_does_not_inherit_conflicting_authorization_header() { + let mut server = mockito::Server::new_async().await; + let table_session = server + .mock("GET", "/session") + .match_header("authorization", "Bearer table-token") + .with_status(200) + .create_async() + .await; + let table_header = server + .mock("GET", "/header") + .match_header("authorization", "Bearer table-header") + .with_status(200) + .create_async() + .await; + + let config = RestCatalogConfig::builder() + .uri(server.url()) + .props(HashMap::from([( + "header.Authorization".to_string(), + "Bearer catalog-header".to_string(), + )])) + .build(); + let catalog_client = HttpClient::new(&config).unwrap(); + + let session_client = catalog_client + .for_table(&HashMap::new(), Arc::new(TableSession)) + .unwrap(); + session_client + .query_catalog( + HttpRequest::build( + session_client.request(Method::GET, format!("{}/session", server.url())), + ) + .unwrap(), + ) + .await + .unwrap(); + table_session.assert_async().await; + + let header_client = catalog_client + .for_table( + &HashMap::from([( + "header.Authorization".to_string(), + "Bearer table-header".to_string(), + )]), + Arc::new(TableSession), + ) + .unwrap(); + header_client + .query_catalog( + HttpRequest::build( + header_client.request(Method::GET, format!("{}/header", server.url())), + ) + .unwrap(), + ) + .await + .unwrap(); + table_header.assert_async().await; + } + #[test] fn test_format_headers_redacted_empty() { let headers = HeaderMap::new(); diff --git a/crates/catalog/rest/src/credential.rs b/crates/catalog/rest/src/credential.rs new file mode 100644 index 0000000000..fcfad7dad3 --- /dev/null +++ b/crates/catalog/rest/src/credential.rs @@ -0,0 +1,1672 @@ +// 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. + +//! Refresh of vended storage credentials against a REST catalog. +//! +//! A REST catalog can vend short-lived storage credentials whose lifetime the +//! client does not control. [`RestVendedCredentialProvider`] implements the +//! core [`StorageCredentialProvider`] trait so storage backends re-fetch those +//! credentials from the catalog's table credentials endpoint before they +//! expire, keeping long-running jobs authenticated instead of failing with a +//! `403` once the initial token's TTL elapses. +//! +//! Unlike the Java client, which has one provider per cloud SDK, this is a +//! single backend-agnostic provider with an independent endpoint and cache for +//! each configured cloud. The path being accessed selects the cloud cache, and +//! the returned [`StorageCredential`] enum lets the storage adapter enforce the +//! expected backend-specific type. This preserves Java's per-cloud credential +//! selection and prefetch policies while supporting mixed-cloud tables through +//! a resolving FileIO. Unlike Java's scheduled refresh, which permanently stops +//! after a failed fetch, transient failures are retried here with jittered +//! exponential backoff while an unexpired credential remains available. +//! +//! # Adding a cloud +//! +//! The refresh policy for each cloud lives in one [`CloudRefresh`] constant. To +//! add a backend, first add its credential type to Iceberg's storage API and +//! teach the storage adapter to consume it. Then write its `parse_*` function, +//! add a `CloudRefresh` constant, and list it in [`CloudRefresh::SUPPORTED`]. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use async_trait::async_trait; +use iceberg::io::{ + AWS_REFRESH_CREDENTIALS_ENABLED, AWS_REFRESH_CREDENTIALS_ENDPOINT, + GCS_REFRESH_CREDENTIALS_ENABLED, GCS_REFRESH_CREDENTIALS_ENDPOINT, GCS_TOKEN, + GCS_TOKEN_EXPIRES_AT, GcsCredential, S3_ACCESS_KEY_ID, S3_SECRET_ACCESS_KEY, S3_SESSION_TOKEN, + S3_SESSION_TOKEN_EXPIRES_AT_MS, S3Credential, StorageCredential, StorageCredentialKind, + StorageCredentialProvider, +}; +use iceberg::{Error, ErrorKind, Result, TableIdent}; +use rand::Rng; +use reqwest::{Method, StatusCode, Url}; +use tokio::sync::Mutex; + +use crate::REST_CATALOG_PROP_SCAN_PLAN_ID; +use crate::auth::AuthManager; +use crate::client::{HttpClient, deserialize_unexpected_catalog_error}; +use crate::request::HttpRequest; +use crate::types::LoadCredentialsResponse; + +/// Cloud-specific details regarding vended-credential refresh. +/// +/// It contains the location schemes it backs, the property keys it is configured +/// with, and how to parse its credential. The generic provider stays free of +/// any per-cloud knowledge. +struct CloudRefresh { + /// Location URL schemes this backend serves. + schemes: &'static [&'static str], + /// Table property naming the refresh endpoint (absolute or catalog-relative). + endpoint_key: &'static str, + /// Table property controlling refresh; only missing or case-insensitive `"true"` enables it. + enabled_key: &'static str, + /// Whether to jitter successful prefetch times like AWS `CachedSupplier`. + jitter_prefetch: bool, + /// Parse a complete credential from catalog-supplied properties. + parse_credential: + fn(config: &HashMap, prefix: Option) -> Result, +} + +impl CloudRefresh { + /// S3 / AWS + const AWS: Self = Self { + schemes: &["s3", "s3a", "s3n"], + endpoint_key: AWS_REFRESH_CREDENTIALS_ENDPOINT, + enabled_key: AWS_REFRESH_CREDENTIALS_ENABLED, + jitter_prefetch: true, + parse_credential: parse_s3_credential, + }; + /// Google Cloud Storage + const GCP: Self = Self { + schemes: &["gs", "gcs"], + endpoint_key: GCS_REFRESH_CREDENTIALS_ENDPOINT, + enabled_key: GCS_REFRESH_CREDENTIALS_ENABLED, + jitter_prefetch: false, + parse_credential: parse_gcs_credential, + }; + // TODO: Azure (ADLS) is not yet supported: opendal's Azdls builder exposes no + // custom credential-provider hook, and reqsign's SAS-token credential has no + // expiry, so reqsign-based refresh isn't possible. + + /// Backends with refresh support + const SUPPORTED: &[Self] = &[Self::AWS, Self::GCP]; + + /// The backend that serves `location`, by its URL scheme, or `None` if no + /// supported backend matches (in which case static credentials are used + /// as-is, as before). + fn for_location(location: &str) -> Option<&'static Self> { + Self::SUPPORTED + .iter() + .find(|cloud| cloud.matches_location(location)) + } + + fn matches_location(&self, location: &str) -> bool { + self.schemes + .iter() + .any(|scheme| location.eq_ignore_ascii_case(scheme)) + || scheme_of(location).is_some_and(|scheme| self.schemes.contains(&scheme.as_str())) + } +} + +/// Re-fetch a credential once it is within this window of expiry, so a fresh +/// token is in hand before the object store would reject the old one. +const REFRESH_BUFFER: Duration = Duration::from_mins(5); + +/// AWS keeps at least one minute between its jittered prefetch time and expiry. +const MIN_REFRESH_BUFFER: Duration = Duration::from_mins(1); + +/// Initial ceiling for failure backoff. Equal jitter chooses from half this +/// value through the full value. +const INITIAL_FAILURE_BACKOFF: Duration = Duration::from_secs(1); + +/// Maximum delay between failed refresh attempts. +const MAX_FAILURE_BACKOFF: Duration = Duration::from_secs(30); + +/// A cached vended credential and its refresh schedule. +#[derive(Clone)] +struct CachedEntry { + credential: StorageCredential, + /// When this entry becomes eligible for prefetch. `None` means it does not + /// expire and therefore never needs proactive refresh. + refresh_at: Option, +} + +impl CachedEntry { + fn new(credential: StorageCredential, jitter_prefetch: bool) -> Self { + let refresh_at = credential + .expires_at() + .map(|expires_at| prefetch_time(expires_at, jitter_prefetch)); + Self { + credential, + refresh_at, + } + } + + /// Seed entries that are already inside the nominal five-minute window are + /// immediately due. Otherwise AWS applies the same jitter as it does to a + /// freshly fetched value. + fn seed(credential: StorageCredential, jitter_prefetch: bool) -> Self { + let due = credential.expires_at().is_some_and(|expires_at| { + SystemTime::now() + .checked_add(REFRESH_BUFFER) + .is_none_or(|refresh_boundary| refresh_boundary >= expires_at) + }); + let mut entry = Self::new(credential, jitter_prefetch); + if due { + entry.refresh_at = Some(UNIX_EPOCH); + } + entry + } + + fn is_fresh(&self, now: SystemTime) -> bool { + self.refresh_at.is_none_or(|refresh_at| now < refresh_at) + } + + fn is_unexpired(&self, now: SystemTime) -> bool { + self.credential + .expires_at() + .is_none_or(|expires_at| now < expires_at) + } +} + +/// Parsed entries from one successful credentials response. +struct ParsedCredentials { + entries: Vec, + errors: Vec, +} + +struct CredentialError { + prefix: String, + error: Error, +} + +/// Cached credentials plus failure-backoff state. +struct CacheState { + entries: Vec, + consecutive_failures: u32, + retry_not_before: Option, +} + +impl CacheState { + fn record_success(&mut self) { + self.consecutive_failures = 0; + self.retry_not_before = None; + } + + fn record_failure(&mut self) { + self.consecutive_failures = self.consecutive_failures.saturating_add(1); + self.retry_not_before = + Instant::now().checked_add(failure_backoff(self.consecutive_failures)); + } + + fn insert_fallback_if_missing(&mut self, fallback: CachedEntry, now: SystemTime) -> bool { + let has_unexpired_entry = self.entries.iter().any(|entry| { + entry.is_unexpired(now) && entry.credential.prefix() == fallback.credential.prefix() + }); + if has_unexpired_entry { + false + } else { + self.entries.push(fallback); + true + } + } +} + +struct ConfiguredCloud { + cloud: &'static CloudRefresh, + endpoint: String, + cache: Mutex, + /// Only one caller fetches at a time. The cache lock is deliberately + /// separate so other callers can keep using an unexpired credential while + /// the refresh is in flight. + refresh: Mutex<()>, +} + +/// Fetches and refreshes vended credentials from a REST catalog's table +/// credentials endpoint. +/// +/// Each cloud cache is seeded with the credential from the initial table +/// properties (when complete) and re-fetched from its endpoint as it +/// nears expiry. +pub(crate) struct RestVendedCredentialProvider { + client: Arc, + /// Optional scan-plan identifier. + plan_id: Option, + /// Independently configured endpoint and cache for each backing cloud. + clouds: Vec, +} + +impl RestVendedCredentialProvider { + fn new(client: Arc, plan_id: Option, clouds: Vec) -> Self { + Self { + client, + plan_id, + clouds, + } + } + + fn configured_cloud_for_location(&self, location: &str) -> Option<&ConfiguredCloud> { + self.clouds + .iter() + .find(|configured| configured.cloud.matches_location(location)) + } + + /// Fetch fresh credentials from the catalog's credentials endpoint. + async fn fetch(&self, configured: &ConfiguredCloud) -> Result { + let mut request = self.client.request(Method::GET, &configured.endpoint); + if let Some(plan_id) = &self.plan_id { + request = request.query(&[("planId", plan_id)]); + } + let request = HttpRequest::build(request)?; + let response = self.client.query_catalog(request).await?; + + match response.status() { + StatusCode::OK => { + let parsed: LoadCredentialsResponse = response.json().await?; + let mut entries = Vec::new(); + let mut errors = Vec::new(); + let matching_credentials = parsed + .storage_credentials + .into_iter() + .filter(|credential| configured.cloud.matches_location(&credential.prefix)); + let parse_credential = configured.cloud.parse_credential; + let now = SystemTime::now(); + + for storage_credential in matching_credentials { + let prefix = storage_credential.prefix; + let parsed_credential = + parse_credential(&storage_credential.config, Some(prefix.clone())); + match parsed_credential { + Ok(credential) => { + let entry = + CachedEntry::new(credential, configured.cloud.jitter_prefetch); + if entry.is_unexpired(now) { + entries.push(entry); + } else { + errors.push(CredentialError { + prefix, + error: Error::new( + ErrorKind::DataInvalid, + "invalid vended credential: credential is already expired", + ), + }); + } + } + Err(error) => errors.push(CredentialError { prefix, error }), + } + } + Ok(ParsedCredentials { entries, errors }) + } + _ => Err(deserialize_unexpected_catalog_error( + response, + self.client.disable_header_redaction(), + ) + .await), + } + } + + async fn refresh_credential( + &self, + configured: &ConfiguredCloud, + path: &str, + fallback: Option, + ) -> Result { + match self.fetch(configured).await { + Ok(ParsedCredentials { entries, errors }) => { + let invalid_prefixes = errors + .iter() + .map(|error| error.prefix.clone()) + .collect::>(); + let credential_error = errors + .into_iter() + .filter(|error| path.starts_with(&error.prefix)) + .max_by_key(|error| error.prefix.len()); + let failure = credential_error + .map(|error| error.error) + .unwrap_or_else(|| { + Error::new( + ErrorKind::Unexpected, + format!( + "no unexpired vended credential matches storage location: {path}" + ), + ) + }); + + let mut cache = configured.cache.lock().await; + if entries.is_empty() { + cache.record_failure(); + return fallback + .filter(|entry| entry.is_unexpired(SystemTime::now())) + .map(|entry| entry.credential) + .ok_or(failure); + } + + let now = SystemTime::now(); + let invalid_fallbacks = cache + .entries + .iter() + .filter(|entry| entry.is_unexpired(now)) + .filter(|entry| { + entry + .credential + .prefix() + .is_some_and(|prefix| invalid_prefixes.contains(prefix)) + }) + .cloned() + .collect::>(); + cache.entries = entries; + + // An invalid replacement for one prefix must not evict that + // prefix's still-valid cached credential. Iterate in reverse + // because equal-length prefix selection uses the last cached entry. + // This preserves the same credential if a bad response follows a + // response with duplicate prefixes. + let mut restored_fallback_prefixes = HashSet::new(); + for fallback in invalid_fallbacks.into_iter().rev() { + let prefix = fallback.credential.prefix().map(str::to_owned); + if cache.insert_fallback_if_missing(fallback, now) + && let Some(prefix) = prefix + { + restored_fallback_prefixes.insert(prefix); + } + } + + let selected = longest_prefix_match(&cache.entries, path) + .filter(|entry| entry.is_unexpired(now)) + .map(|entry| { + let is_restored_fallback = entry + .credential + .prefix() + .is_some_and(|prefix| restored_fallback_prefixes.contains(prefix)); + (entry.credential.clone(), is_restored_fallback) + }); + + if let Some((credential, is_restored_fallback)) = selected { + if is_restored_fallback { + cache.record_failure(); + } else { + cache.record_success(); + } + return Ok(credential); + } + + // Cache valid credentials for other prefixes while retaining this + // path's still-usable credential when its replacement was absent or + // invalid. Backoff ensures the failed path is retried promptly. + if let Some(fallback) = fallback.filter(|entry| entry.is_unexpired(now)) { + let credential = fallback.credential.clone(); + cache.insert_fallback_if_missing(fallback, now); + cache.record_failure(); + return Ok(credential); + } + + cache.record_failure(); + Err(failure) + } + Err(fetch_error) => { + let mut cache = configured.cache.lock().await; + cache.record_failure(); + + // Graceful degradation: while the cached credential remains + // usable, serve it and retry after jittered backoff. Expired + // credentials are never served. + fallback + .filter(|entry| entry.is_unexpired(SystemTime::now())) + .map(|entry| entry.credential) + .ok_or(fetch_error) + } + } + } +} + +impl std::fmt::Debug for RestVendedCredentialProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RestVendedCredentialProvider") + .field("configured_clouds", &self.clouds.len()) + .finish_non_exhaustive() + } +} + +enum CacheDecision { + Use(StorageCredential), + Refresh(Option), + Backoff, +} + +fn refresh_backoff_error(path: &str) -> Error { + Error::new( + ErrorKind::Unexpected, + format!("vended credential refresh is temporarily backed off for storage location: {path}"), + ) +} + +async fn cache_decision(configured: &ConfiguredCloud, path: &str) -> CacheDecision { + let cache = configured.cache.lock().await; + let current = longest_prefix_match(&cache.entries, path).cloned(); + let now = SystemTime::now(); + + if let Some(entry) = current.as_ref().filter(|entry| entry.is_fresh(now)) { + return CacheDecision::Use(entry.credential.clone()); + } + + if cache + .retry_not_before + .is_some_and(|retry_at| Instant::now() < retry_at) + { + return current + .as_ref() + .filter(|entry| entry.is_unexpired(now)) + .map(|entry| CacheDecision::Use(entry.credential.clone())) + .unwrap_or(CacheDecision::Backoff); + } + + CacheDecision::Refresh(current) +} + +#[async_trait] +impl StorageCredentialProvider for RestVendedCredentialProvider { + fn supports_path(&self, path: &str) -> bool { + self.configured_cloud_for_location(path).is_some() + } + + async fn load_credential(&self, path: &str) -> Result { + if CloudRefresh::for_location(path).is_none() { + return Err(Error::new( + ErrorKind::FeatureUnsupported, + format!("no credential refresh implementation for storage location: {path}"), + )); + } + let configured = self.configured_cloud_for_location(path).ok_or_else(|| { + Error::new( + ErrorKind::FeatureUnsupported, + format!("credential refresh is not configured for storage location: {path}"), + ) + })?; + + let current = match cache_decision(configured, path).await { + CacheDecision::Use(credential) => return Ok(credential), + CacheDecision::Refresh(current) => current, + CacheDecision::Backoff => return Err(refresh_backoff_error(path)), + }; + + // One caller refreshes, while concurrent callers immediately keep using the + // unexpired cached credential. With no usable credential, callers wait + // for the in-flight refresh instead. + let usable = current + .as_ref() + .filter(|entry| entry.is_unexpired(SystemTime::now())); + let _refresh_guard = if let Some(entry) = usable { + match configured.refresh.try_lock() { + Ok(guard) => guard, + Err(_) => return Ok(entry.credential.clone()), + } + } else { + configured.refresh.lock().await + }; + + // Another caller may have completed a refresh between our cache check + // and acquiring the single-flight guard. + let current = match cache_decision(configured, path).await { + CacheDecision::Use(credential) => return Ok(credential), + CacheDecision::Refresh(current) => current, + CacheDecision::Backoff => return Err(refresh_backoff_error(path)), + }; + + self.refresh_credential(configured, path, current).await + } +} + +/// Select the credential whose prefix is the longest match for `path`. +fn longest_prefix_match<'a>(entries: &'a [CachedEntry], path: &str) -> Option<&'a CachedEntry> { + entries + .iter() + .filter(|entry| { + entry + .credential + .prefix() + .is_none_or(|prefix| path.starts_with(prefix)) + }) + .max_by_key(|entry| entry.credential.prefix().map_or(0, str::len)) +} + +/// Compute a successful credential's prefetch time. +fn prefetch_time(expires_at: SystemTime, jitter: bool) -> SystemTime { + let base = expires_at.checked_sub(REFRESH_BUFFER).unwrap_or(UNIX_EPOCH); + if !jitter { + return base; + } + + let jitter_window = REFRESH_BUFFER.saturating_sub(MIN_REFRESH_BUFFER); + let jitter_millis = rand::rng().random_range(0..jitter_window.as_millis() as u64); + base.checked_add(Duration::from_millis(jitter_millis)) + .unwrap_or(base) +} + +/// Equal-jitter exponential backoff. The random lower half avoids both hot +/// retry loops and synchronized retries across clients. +fn failure_backoff(consecutive_failures: u32) -> Duration { + let exponent = consecutive_failures.saturating_sub(1).min(5); + let ceiling = INITIAL_FAILURE_BACKOFF + .checked_mul(1 << exponent) + .unwrap_or(MAX_FAILURE_BACKOFF) + .min(MAX_FAILURE_BACKOFF); + let ceiling_millis = ceiling.as_millis() as u64; + let floor_millis = ceiling_millis / 2; + Duration::from_millis(rand::rng().random_range(floor_millis..=ceiling_millis)) +} + +/// Build a credential provider from a table's properties, +/// or `None` when no supported cloud advertises an enabled refresh endpoint. +/// +/// `base_uri` is the catalog URI, used to resolve a relative endpoint. +/// `table_auth_props` is the unmerged config returned by the table endpoint: +/// keeping it separate prevents local FileIO overrides from masking table auth. +/// `auth_manager` derives an isolated child session when those properties +/// override authentication for `table`. +pub(crate) async fn build_vended_credential_provider( + client: Arc, + auth_manager: &dyn AuthManager, + table: &TableIdent, + base_uri: &str, + props: &HashMap, + table_auth_props: Option<&HashMap>, +) -> Result>> { + let clouds = CloudRefresh::SUPPORTED + .iter() + .filter_map(|cloud| { + let enabled = props + .get(cloud.enabled_key) + .is_none_or(|value| value.eq_ignore_ascii_case("true")); + if !enabled { + return None; + } + + let endpoint = resolve_endpoint( + base_uri, + props + .get(cloud.endpoint_key) + .filter(|value| !value.is_empty())?, + ); + let entries = (cloud.parse_credential)(props, None) + .ok() + .map(|credential| vec![CachedEntry::seed(credential, cloud.jitter_prefetch)]) + .unwrap_or_default(); + + Some(ConfiguredCloud { + cloud, + endpoint, + cache: Mutex::new(CacheState { + entries, + consecutive_failures: 0, + retry_not_before: None, + }), + refresh: Mutex::new(()), + }) + }) + .collect::>(); + + if clouds.is_empty() { + return Ok(None); + } + + let empty_auth_props = HashMap::new(); + let table_auth_props = table_auth_props.unwrap_or(&empty_auth_props); + let table_session = auth_manager + .table_session( + &client.without_auth_session(), + table, + table_auth_props, + client.auth_session(), + ) + .await?; + let table_client = Arc::new(client.for_table(table_auth_props, table_session)?); + let plan_id = props.get(REST_CATALOG_PROP_SCAN_PLAN_ID).cloned(); + Ok(Some(Arc::new(RestVendedCredentialProvider::new( + table_client, + plan_id, + clouds, + )))) +} + +/// Resolve a possibly-relative refresh endpoint against the catalog base URI. +fn resolve_endpoint(base_uri: &str, endpoint: &str) -> String { + if endpoint.starts_with("http://") || endpoint.starts_with("https://") { + return endpoint.to_string(); + } + + let base = base_uri.trim_end_matches('/'); + let separator = if endpoint.starts_with('/') { "" } else { "/" }; + format!("{base}{separator}{endpoint}") +} + +/// The URL scheme of `location`, lowercased (e.g. `"s3"` for `s3://bucket/k`). +fn scheme_of(location: &str) -> Option { + Url::parse(location) + .ok() + .map(|url| url.scheme().to_string()) +} + +/// Parse a complete S3 credential returned by the credentials endpoint. +fn parse_s3_credential( + config: &HashMap, + prefix: Option, +) -> Result { + let access_key_id = required_nonempty(config, S3_ACCESS_KEY_ID)?; + let secret_access_key = required_nonempty(config, S3_SECRET_ACCESS_KEY)?; + let session_token = required_nonempty(config, S3_SESSION_TOKEN)?; + let expires_at = required_epoch_millis(config, S3_SESSION_TOKEN_EXPIRES_AT_MS)?; + let credential = StorageCredential::new(StorageCredentialKind::S3(S3Credential::new( + access_key_id, + secret_access_key, + Some(session_token), + ))) + .with_expiration(expires_at); + Ok(match prefix { + Some(prefix) => credential.with_prefix(prefix), + None => credential, + }) +} + +/// Parse a complete GCS credential returned by the credentials endpoint. +fn parse_gcs_credential( + config: &HashMap, + prefix: Option, +) -> Result { + let token = required_nonempty(config, GCS_TOKEN)?; + let expires_at = required_epoch_millis(config, GCS_TOKEN_EXPIRES_AT)?; + let credential = StorageCredential::new(StorageCredentialKind::Gcs(GcsCredential::new(token))) + .with_expiration(expires_at); + Ok(match prefix { + Some(prefix) => credential.with_prefix(prefix), + None => credential, + }) +} + +fn required_nonempty(config: &HashMap, key: &str) -> Result { + config + .get(key) + .filter(|value| !value.is_empty()) + .cloned() + .ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + format!("invalid vended credential: {key} is missing or empty"), + ) + }) +} + +fn required_epoch_millis(config: &HashMap, key: &str) -> Result { + let value = required_nonempty(config, key)?; + parse_epoch_millis(&value).ok_or_else(|| { + Error::new( + ErrorKind::DataInvalid, + format!("invalid vended credential: {key} is not a valid epoch-millisecond timestamp"), + ) + }) +} + +/// Parse an epoch-millisecond timestamp into a [`SystemTime`]. +fn parse_epoch_millis(millis: &str) -> Option { + millis + .parse() + .ok() + .and_then(|millis| UNIX_EPOCH.checked_add(Duration::from_millis(millis))) +} + +#[cfg(test)] +mod tests { + use std::sync::{Barrier, mpsc}; + + use mockito::{Matcher, Server}; + + use super::*; + use crate::RestCatalogConfig; + use crate::auth::{NoopAuthManager, OAuth2Manager}; + + fn epoch_millis(time: SystemTime) -> String { + time.duration_since(UNIX_EPOCH) + .unwrap() + .as_millis() + .to_string() + } + + fn s3_cred( + prefix: Option<&str>, + access_key_id: &str, + expires_at: Option, + ) -> StorageCredential { + let mut credential = StorageCredential::new(StorageCredentialKind::S3(S3Credential::new( + access_key_id, + "secret", + None, + ))); + if let Some(prefix) = prefix { + credential = credential.with_prefix(prefix); + } + if let Some(expires_at) = expires_at { + credential = credential.with_expiration(expires_at); + } + credential + } + + fn s3_access_key_id(credential: &StorageCredential) -> &str { + match credential.kind() { + StorageCredentialKind::S3(s3) => s3.access_key_id(), + other => panic!("expected S3 credential, got {other:?}"), + } + } + + fn cached_s3(prefix: &str, access_key_id: &str, expires_at: Option) -> CachedEntry { + CachedEntry::new(s3_cred(Some(prefix), access_key_id, expires_at), false) + } + + fn test_client(base_uri: &str) -> Arc { + let config = RestCatalogConfig::builder() + .uri(base_uri.to_string()) + .build(); + Arc::new(HttpClient::new(&config).unwrap()) + } + + fn aws_refresh_props(endpoint: &str) -> HashMap { + HashMap::from([( + CloudRefresh::AWS.endpoint_key.to_string(), + endpoint.to_string(), + )]) + } + + fn with_s3_seed( + mut props: HashMap, + access_key_id: &str, + expires_at: SystemTime, + ) -> HashMap { + props.extend([ + (S3_ACCESS_KEY_ID.to_string(), access_key_id.to_string()), + (S3_SECRET_ACCESS_KEY.to_string(), "SEED_SK".to_string()), + (S3_SESSION_TOKEN.to_string(), "SEED_TOK".to_string()), + ( + S3_SESSION_TOKEN_EXPIRES_AT_MS.to_string(), + epoch_millis(expires_at), + ), + ]); + props + } + + fn test_table() -> TableIdent { + TableIdent::from_strs(["namespace", "table"]).unwrap() + } + + async fn build_test_provider( + client: Arc, + base_uri: &str, + props: &HashMap, + table_auth_props: Option<&HashMap>, + ) -> Result>> { + build_vended_credential_provider( + client, + &NoopAuthManager, + &test_table(), + base_uri, + props, + table_auth_props, + ) + .await + } + + async fn test_provider( + base_uri: &str, + props: &HashMap, + ) -> Arc { + build_test_provider(test_client(base_uri), base_uri, props, None) + .await + .expect("provider construction should succeed") + .expect("provider should be built") + } + + fn s3_response(prefix: &str, access_key_id: &str, expires_at: SystemTime) -> String { + let expires_at = epoch_millis(expires_at); + format!( + r#"{{"storage-credentials":[{{"prefix":"{prefix}","config":{{"s3.access-key-id":"{access_key_id}","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expires_at}"}}}}]}}"# + ) + } + + #[test] + fn resolve_endpoint_matches_java_semantics() { + assert_eq!( + resolve_endpoint("https://catalog/", "https://other/creds"), + "https://other/creds" + ); + assert_eq!( + resolve_endpoint("https://catalog", "http://other/creds"), + "http://other/creds" + ); + assert_eq!( + resolve_endpoint("https://catalog", "v1/creds"), + "https://catalog/v1/creds" + ); + assert_eq!( + resolve_endpoint("https://catalog/", "v1/creds"), + "https://catalog/v1/creds" + ); + // All trailing slashes stripped from the base (Java stripTrailingSlash). + assert_eq!( + resolve_endpoint("https://catalog///", "/v1/creds"), + "https://catalog/v1/creds" + ); + // Existing leading slashes on the endpoint are preserved, not collapsed + // (matches Java's resolveEndpoint, which only prepends when absent). + assert_eq!( + resolve_endpoint("https://catalog/", "//v1/creds"), + "https://catalog//v1/creds" + ); + } + + #[test] + fn cloud_selection_accepts_root_prefixes_and_url_schemes() { + // Java uses these root prefixes for its fallback clients and accepts + // credentials scoped directly to them. + assert!(CloudRefresh::for_location("s3").is_some()); + assert!(CloudRefresh::for_location("gs").is_some()); + assert!(CloudRefresh::for_location("s3://b/k").is_some()); + assert!(CloudRefresh::for_location("S3://b/k").is_some()); + assert!(CloudRefresh::for_location("s3a://b/k").is_some()); + assert!(CloudRefresh::for_location("s3n://b/k").is_some()); + assert!(CloudRefresh::for_location("gs://b/k").is_some()); + assert!(CloudRefresh::for_location("gcs://b/k").is_some()); + assert!(CloudRefresh::for_location("not a url").is_none()); + // Azure not supported yet -> no provider, static creds used as-is. + assert!(CloudRefresh::for_location("abfss://fs@acct.dfs.core.windows.net/k").is_none()); + assert!(CloudRefresh::AWS.matches_location("s3://bucket/path")); + assert!(!CloudRefresh::AWS.matches_location("s3evil://bucket/path")); + } + + #[test] + fn parses_s3_credential() { + let mut config = HashMap::new(); + assert!(parse_s3_credential(&config, None).is_err()); + config.insert(S3_ACCESS_KEY_ID.to_string(), "AK".to_string()); + assert!(parse_s3_credential(&config, None).is_err()); + config.insert(S3_SECRET_ACCESS_KEY.to_string(), "SK".to_string()); + assert!(parse_s3_credential(&config, None).is_err()); + + config.insert(S3_SESSION_TOKEN.to_string(), "TOK".to_string()); + config.insert( + S3_SESSION_TOKEN_EXPIRES_AT_MS.to_string(), + "1500".to_string(), + ); + let credential = parse_s3_credential(&config, Some("s3://bucket".to_string())).unwrap(); + assert_eq!(credential.prefix(), Some("s3://bucket")); + assert_eq!( + credential.expires_at(), + Some(UNIX_EPOCH + Duration::from_millis(1500)) + ); + match credential.kind() { + StorageCredentialKind::S3(s3) => assert_eq!(s3.session_token(), Some("TOK")), + other => panic!("expected S3, got {other:?}"), + } + } + + #[test] + fn parse_gcs_requires_token_and_expiry() { + let mut config = HashMap::new(); + assert!(parse_gcs_credential(&config, None).is_err()); + config.insert(GCS_TOKEN.to_string(), "ya29.token".to_string()); + assert!(parse_gcs_credential(&config, None).is_err()); + + config.insert(GCS_TOKEN_EXPIRES_AT.to_string(), "2000".to_string()); + let credential = parse_gcs_credential(&config, Some("gs://bucket".to_string())).unwrap(); + assert_eq!(credential.prefix(), Some("gs://bucket")); + match credential.kind() { + StorageCredentialKind::Gcs(gcs) => assert_eq!(gcs.token(), "ya29.token"), + other => panic!("expected GCS, got {other:?}"), + } + assert_eq!( + credential.expires_at(), + Some(UNIX_EPOCH + Duration::from_millis(2000)) + ); + } + + #[test] + fn cached_entry_freshness() { + let no_expiry = cached_s3("", "a", None); + let far = cached_s3( + "", + "a", + Some(SystemTime::now() + REFRESH_BUFFER + Duration::from_secs(60)), + ); + // Within the buffer but not yet expired: stale for a fast-path read, but + // still usable for graceful degradation. + let soon = cached_s3("", "a", Some(SystemTime::now() + Duration::from_secs(60))); + let past = cached_s3("", "a", Some(SystemTime::now() - Duration::from_secs(60))); + + let now = SystemTime::now(); + assert!(no_expiry.is_fresh(now)); + assert!(no_expiry.is_unexpired(now)); + assert!(far.is_fresh(now)); + assert!(!soon.is_fresh(now)); + assert!(soon.is_unexpired(now)); + assert!(!past.is_unexpired(now)); + } + + #[test] + fn prefetch_time_matches_cloud_policy() { + let expires_at = SystemTime::now() + Duration::from_secs(3600); + assert_eq!( + prefetch_time(expires_at, false), + expires_at - REFRESH_BUFFER + ); + + for _ in 0..16 { + let refresh_at = prefetch_time(expires_at, true); + assert!(refresh_at >= expires_at - REFRESH_BUFFER); + assert!(refresh_at < expires_at - MIN_REFRESH_BUFFER); + } + } + + #[test] + fn seed_inside_nominal_window_is_immediately_due() { + let credential = s3_cred( + None, + "a", + Some(SystemTime::now() + REFRESH_BUFFER - Duration::from_secs(1)), + ); + let entry = CachedEntry::seed(credential, true); + let now = SystemTime::now(); + assert!(!entry.is_fresh(now)); + assert!(entry.is_unexpired(now)); + } + + #[test] + fn failure_backoff_is_jittered_and_capped() { + for (failures, ceiling) in [ + (1, Duration::from_secs(1)), + (2, Duration::from_secs(2)), + (5, Duration::from_secs(16)), + (6, MAX_FAILURE_BACKOFF), + (u32::MAX, MAX_FAILURE_BACKOFF), + ] { + for _ in 0..16 { + let backoff = failure_backoff(failures); + assert!(backoff >= ceiling / 2); + assert!(backoff <= ceiling); + } + } + } + + #[test] + fn longest_prefix_match_ignores_freshness() { + let far = Some(SystemTime::now() + REFRESH_BUFFER + Duration::from_secs(3600)); + let entries = vec![ + cached_s3("s3://bucket", "wide", far), + cached_s3("s3://bucket/warehouse/db", "narrow", far), + ]; + let got = longest_prefix_match(&entries, "s3://bucket/warehouse/db/t/f").unwrap(); + assert_eq!(s3_access_key_id(&got.credential), "narrow"); + assert_eq!(got.credential.prefix(), Some("s3://bucket/warehouse/db")); + assert!(longest_prefix_match(&entries, "s3://other/x").is_none()); + + let fresh = Some(SystemTime::now() + REFRESH_BUFFER + Duration::from_secs(60)); + let stale = Some(SystemTime::now() - Duration::from_secs(60)); + let entries = vec![ + cached_s3("s3://bucket", "wide", fresh), + cached_s3("s3://bucket/table", "narrow-stale", stale), + ]; + let selected = longest_prefix_match(&entries, "s3://bucket/table/f").unwrap(); + assert_eq!(s3_access_key_id(&selected.credential), "narrow-stale"); + assert!(!selected.is_fresh(SystemTime::now())); + } + + #[tokio::test] + async fn provider_support_tracks_configured_cloud_endpoints() { + let client = test_client("http://cat"); + let props = aws_refresh_props("/v1/creds"); + + // The provider is configured independently of the table metadata scheme, + // but advertises support only for clouds whose endpoint is present. + let provider = build_test_provider(client.clone(), "http://cat", &props, None) + .await + .unwrap() + .unwrap(); + assert!(provider.supports_path("s3://b/k")); + assert!(!provider.supports_path("abfss://fs@acct.dfs.core.windows.net/k")); + let enabled = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/creds".to_string(), + ), + ( + CloudRefresh::AWS.enabled_key.to_string(), + "True".to_string(), + ), + ]); + assert!( + build_test_provider(client.clone(), "http://cat", &enabled, None) + .await + .unwrap() + .is_some() + ); + // No endpoint advertised. + assert!( + build_test_provider(client.clone(), "http://cat", &HashMap::new(), None) + .await + .unwrap() + .is_none() + ); + // Explicitly disabled. + let disabled = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/creds".to_string(), + ), + ( + CloudRefresh::AWS.enabled_key.to_string(), + "false".to_string(), + ), + ]); + assert!( + build_test_provider(client, "http://cat", &disabled, None) + .await + .unwrap() + .is_none() + ); + // Java's `Strings.isNullOrEmpty` check treats an empty endpoint as absent. + let empty = HashMap::from([(CloudRefresh::AWS.endpoint_key.to_string(), String::new())]); + let client = test_client("http://cat"); + assert!( + build_test_provider(client, "http://cat", &empty, None) + .await + .unwrap() + .is_none() + ); + } + + #[tokio::test] + async fn refresh_includes_scan_plan_id() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .match_query(Matcher::UrlEncoded( + "planId".to_string(), + "scan-plan-1".to_string(), + )) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + // No static creds -> no seed -> first load fetches from the endpoint. + let mut props = aws_refresh_props("/v1/credentials"); + props.insert( + REST_CATALOG_PROP_SCAN_PLAN_ID.to_string(), + "scan-plan-1".to_string(), + ); + + let provider = test_provider(&server.url(), &props).await; + let credential = provider + .load_credential("s3://bucket/warehouse/f") + .await + .unwrap(); + assert_eq!(credential.prefix(), Some("s3://bucket")); + + match credential.kind() { + StorageCredentialKind::S3(s3) => { + assert_eq!(s3.access_key_id(), "AK"); + assert_eq!(s3.session_token(), Some("TOK")); + } + other => panic!("expected S3, got {other:?}"), + } + mock.assert_async().await; + } + + #[tokio::test] + async fn successful_refresh_caches_entries_before_selecting_path() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket/table-a", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let props = aws_refresh_props("/v1/credentials"); + let provider = test_provider(&server.url(), &props).await; + + assert!( + provider + .load_credential("s3://bucket/table-b/file") + .await + .is_err() + ); + // A successful response with no matching credential is negatively + // cached instead of immediately hitting the endpoint again. + assert!( + provider + .load_credential("s3://bucket/table-b/file") + .await + .is_err() + ); + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/table-a/file") + .await + .unwrap() + ), + "AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn malformed_entry_does_not_discard_valid_entries() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket/invalid","config":{{"s3.access-key-id":"BAD"}}}}, + {{"prefix":"s3://bucket/valid","config":{{"s3.access-key-id":"AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expires}"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let props = aws_refresh_props("/v1/credentials"); + let provider = test_provider(&server.url(), &props).await; + + assert!( + provider + .load_credential("s3://bucket/invalid/file") + .await + .is_err() + ); + assert!( + provider + .load_credential("s3://bucket/invalid/file") + .await + .is_err() + ); + assert_eq!( + s3_access_key_id( + &provider + .load_credential("s3://bucket/valid/file") + .await + .unwrap() + ), + "AK" + ); + mock.assert_async().await; + } + + #[tokio::test] + async fn fresh_seed_is_served_without_fetching() { + let mut server = Server::new_async().await; + // Any call to the server is a failure: the fresh seed must be reused. + let mock = server + .mock("GET", Matcher::Any) + .expect(0) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(3600), + ); + + let provider = test_provider(&server.url(), &props).await; + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + + assert_eq!(credential.prefix(), None); + assert_eq!(s3_access_key_id(&credential), "SEED_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn failed_refresh_is_backed_off_while_credential_is_unexpired() { + let mut server = Server::new_async().await; + // A refresh is due (the seed is within the buffer) but the catalog errors. + let mock = server + .mock("GET", Matcher::Any) + .expect(1) + .with_status(500) + .create_async() + .await; + + // Seeded credential is within the refresh buffer but not yet expired. + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + ); + + let provider = test_provider(&server.url(), &props).await; + // The first refresh fails, but the still-valid seed is served. Immediate + // follow-up operations stay inside the first jittered backoff window. + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "SEED_AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn empty_refresh_preserves_unexpired_seed() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(r#"{"storage-credentials":[]}"#) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + ); + let provider = test_provider(&server.url(), &props).await; + + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "SEED_AK"); + } + mock.assert_async().await; + } + + #[tokio::test] + async fn malformed_specific_refresh_prefers_fallback_over_valid_broader_entry() { + let mut server = Server::new_async().await; + let refreshed_expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket/requested","config":{{"s3.access-key-id":"BAD"}}}}, + {{"prefix":"s3://bucket","config":{{"s3.access-key-id":"NEW_AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{refreshed_expires}"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let provider = RestVendedCredentialProvider::new(test_client(&server.url()), None, vec![ + ConfiguredCloud { + cloud: &CloudRefresh::AWS, + endpoint: format!("{}/v1/credentials", server.url()), + cache: Mutex::new(CacheState { + entries: vec![cached_s3( + "s3://bucket/requested", + "SEED_AK", + Some(SystemTime::now() + Duration::from_secs(60)), + )], + consecutive_failures: 0, + retry_not_before: None, + }), + refresh: Mutex::new(()), + }, + ]); + + let fallback = provider + .load_credential("s3://bucket/requested/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "SEED_AK"); + + // The malformed specific replacement is a failed refresh for this path. + // Its still-valid fallback wins over the broader fetched credential and + // is backed off, so an immediate retry does not fetch again. + let fallback = provider + .load_credential("s3://bucket/requested/other-file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "SEED_AK"); + + let refreshed = provider + .load_credential("s3://bucket/other/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&refreshed), "NEW_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn invalid_refresh_preserves_other_prefix_fallbacks() { + let mut server = Server::new_async().await; + let refreshed_expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let expired = epoch_millis(SystemTime::now() - Duration::from_secs(60)); + let body = format!( + r#"{{"storage-credentials":[ + {{"prefix":"s3://bucket/table-a","config":{{"s3.access-key-id":"NEW_AK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{refreshed_expires}"}}}}, + {{"prefix":"s3://bucket/table-b","config":{{"s3.access-key-id":"BAD"}}}}, + {{"prefix":"s3://bucket/table-c","config":{{"s3.access-key-id":"EXPIRED_CK","s3.secret-access-key":"SK","s3.session-token":"TOK","s3.session-token-expires-at-ms":"{expired}"}}}} + ]}}"# + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let provider = RestVendedCredentialProvider::new(test_client(&server.url()), None, vec![ + ConfiguredCloud { + cloud: &CloudRefresh::AWS, + endpoint: format!("{}/v1/credentials", server.url()), + cache: Mutex::new(CacheState { + entries: vec![ + cached_s3( + "s3://bucket/table-a", + "OLD_AK", + Some(SystemTime::now() + Duration::from_secs(60)), + ), + cached_s3( + "s3://bucket/table-b", + "OLDER_BK", + Some(SystemTime::now() + Duration::from_secs(3600)), + ), + cached_s3( + "s3://bucket/table-b", + "LATEST_BK", + Some(SystemTime::now() + Duration::from_secs(3600)), + ), + cached_s3( + "s3://bucket/table-c", + "VALID_CK", + Some(SystemTime::now() + Duration::from_secs(3600)), + ), + ], + consecutive_failures: 0, + retry_not_before: None, + }), + refresh: Mutex::new(()), + }, + ]); + + let refreshed = provider + .load_credential("s3://bucket/table-a/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&refreshed), "NEW_AK"); + + let fallback = provider + .load_credential("s3://bucket/table-b/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "LATEST_BK"); + + let fallback = provider + .load_credential("s3://bucket/table-c/file") + .await + .unwrap(); + assert_eq!(s3_access_key_id(&fallback), "VALID_CK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn concurrent_prefetch_serves_unexpired_credential_without_waiting() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "NEW_AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let (started_tx, started_rx) = mpsc::channel(); + let release = Arc::new(Barrier::new(2)); + let callback_release = Arc::clone(&release); + let mock = server + .mock("GET", "/v1/credentials") + .expect(1) + .with_status(200) + .with_header("content-type", "application/json") + .with_chunked_body(move |writer| { + started_tx.send(()).unwrap(); + callback_release.wait(); + writer.write_all(body.as_bytes()) + }) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "SEED_AK", + SystemTime::now() + Duration::from_secs(60), + ); + let provider = test_provider(&server.url(), &props).await; + + let first_provider = Arc::clone(&provider); + let first = + tokio::spawn(async move { first_provider.load_credential("s3://bucket/x/f").await }); + tokio::task::spawn_blocking(move || { + started_rx.recv_timeout(Duration::from_secs(5)).unwrap() + }) + .await + .unwrap(); + + let second_provider = Arc::clone(&provider); + let second = + tokio::spawn(async move { second_provider.load_credential("s3://bucket/x/f").await }); + for _ in 0..100 { + if second.is_finished() { + break; + } + tokio::task::yield_now().await; + } + let completed_without_waiting = second.is_finished(); + release.wait(); + + assert!( + completed_without_waiting, + "a concurrent prefetch waited instead of using the unexpired credential" + ); + assert_eq!(s3_access_key_id(&second.await.unwrap().unwrap()), "SEED_AK"); + assert_eq!(s3_access_key_id(&first.await.unwrap().unwrap()), "NEW_AK"); + mock.assert_async().await; + } + + #[tokio::test] + async fn refresh_uses_table_scoped_token() { + let mut server = Server::new_async().await; + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let mock = server + .mock("GET", "/v1/credentials") + .match_header("authorization", "Bearer table-token") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + let config = RestCatalogConfig::builder() + .uri(server.url()) + .props(HashMap::from([( + "token".to_string(), + "catalog-token".to_string(), + )])) + .build(); + let client = Arc::new(HttpClient::new(&config).unwrap()); + let props = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/credentials".to_string(), + ), + // Local properties win in the FileIO configuration merge, but must + // not mask auth returned by the table endpoint. + ("token".to_string(), "user-token".to_string()), + ]); + let table_auth = HashMap::from([("token".to_string(), "table-token".to_string())]); + let auth_manager = OAuth2Manager::new(format!("{}/v1/oauth/tokens", server.url())); + let provider = build_vended_credential_provider( + client, + &auth_manager, + &test_table(), + &server.url(), + &props, + Some(&table_auth), + ) + .await + .unwrap() + .unwrap(); + + provider.load_credential("s3://bucket/x/f").await.unwrap(); + mock.assert_async().await; + } + + #[tokio::test] + async fn one_provider_refreshes_multiple_clouds() { + let mut server = Server::new_async().await; + let expires = epoch_millis(SystemTime::now() + Duration::from_secs(3600)); + let aws_body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(3600), + ); + let gcp_body = format!( + r#"{{"storage-credentials":[{{"prefix":"gs://bucket","config":{{"gcs.oauth2.token":"GCS","gcs.oauth2.token-expires-at":"{expires}"}}}}]}}"# + ); + let aws_mock = server + .mock("GET", "/v1/aws-credentials") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(aws_body) + .create_async() + .await; + let gcp_mock = server + .mock("GET", "/v1/gcp-credentials") + .with_status(200) + .with_header("content-type", "application/json") + .with_body(gcp_body) + .create_async() + .await; + + let props = HashMap::from([ + ( + CloudRefresh::AWS.endpoint_key.to_string(), + "/v1/aws-credentials".to_string(), + ), + ( + CloudRefresh::GCP.endpoint_key.to_string(), + "/v1/gcp-credentials".to_string(), + ), + ]); + let provider = test_provider(&server.url(), &props).await; + + assert!(provider.supports_path("s3://bucket/x")); + assert!(provider.supports_path("gs://bucket/x")); + assert_eq!( + s3_access_key_id(&provider.load_credential("s3://bucket/x").await.unwrap()), + "AK" + ); + match provider + .load_credential("gs://bucket/x") + .await + .unwrap() + .kind() + { + StorageCredentialKind::Gcs(gcs) => assert_eq!(gcs.token(), "GCS"), + other => panic!("expected GCS credential, got {other:?}"), + } + aws_mock.assert_async().await; + gcp_mock.assert_async().await; + } + + #[tokio::test] + async fn refresh_failure_never_serves_expired_credential() { + let mut server = Server::new_async().await; + let mock = server + .mock("GET", Matcher::Any) + .expect(1) + .with_status(500) + .create_async() + .await; + + let props = with_s3_seed( + aws_refresh_props("/v1/credentials"), + "EXPIRED_AK", + SystemTime::now() - Duration::from_secs(60), + ); + + let provider = test_provider(&server.url(), &props).await; + + assert!(provider.load_credential("s3://bucket/x/f").await.is_err()); + assert!(provider.load_credential("s3://bucket/x/f").await.is_err()); + mock.assert_async().await; + } + + #[tokio::test] + async fn sub_buffer_ttl_is_refetched_on_each_sequential_operation() { + let mut server = Server::new_async().await; + // The vended TTL (60s) is shorter than REFRESH_BUFFER, so every operation + // is eligible for refresh. This matches AWS CachedSupplier: successful + // results do not receive failure backoff. + let body = s3_response( + "s3://bucket", + "AK", + SystemTime::now() + Duration::from_secs(60), + ); + let mock = server + .mock("GET", "/v1/credentials") + .expect(2) + .with_status(200) + .with_header("content-type", "application/json") + .with_body(body) + .create_async() + .await; + + // No static creds -> no seed -> each sequential load fetches because the + // returned credential is already inside its prefetch window. + let props = aws_refresh_props("/v1/credentials"); + + let provider = test_provider(&server.url(), &props).await; + + for _ in 0..2 { + let credential = provider.load_credential("s3://bucket/x/f").await.unwrap(); + assert_eq!(s3_access_key_id(&credential), "AK"); + } + mock.assert_async().await; + } +} diff --git a/crates/catalog/rest/src/lib.rs b/crates/catalog/rest/src/lib.rs index 5670ef3c9c..1b8d3acc29 100644 --- a/crates/catalog/rest/src/lib.rs +++ b/crates/catalog/rest/src/lib.rs @@ -54,6 +54,7 @@ mod auth; mod catalog; mod client; +mod credential; pub use client::HttpClient; mod request; pub use request::{HttpRequest, HttpRequestBody}; diff --git a/crates/catalog/rest/src/types.rs b/crates/catalog/rest/src/types.rs index 390521229e..8265ceb40b 100644 --- a/crates/catalog/rest/src/types.rs +++ b/crates/catalog/rest/src/types.rs @@ -101,7 +101,7 @@ impl From for Error { } } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Serialize, Deserialize)] pub(super) struct TokenResponse { pub(super) access_token: String, pub(super) token_type: String, @@ -205,7 +205,7 @@ pub struct RenameTableRequest { pub destination: TableIdent, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] /// Result returned when a table is successfully loaded or created. /// @@ -231,7 +231,18 @@ pub struct LoadTableResult { pub storage_credentials: Option>, } -#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +impl std::fmt::Debug for LoadTableResult { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("LoadTableResult") + .field("metadata_location", &self.metadata_location) + .field("metadata", &self.metadata) + .field("config_keys", &self.config.keys().collect::>()) + .field("storage_credentials", &self.storage_credentials) + .finish_non_exhaustive() + } +} + +#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)] /// Storage credential for a specific location prefix. /// /// Indicates a storage location prefix where the credential is relevant. Clients should @@ -244,6 +255,27 @@ pub struct StorageCredential { pub config: HashMap, } +impl std::fmt::Debug for StorageCredential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("StorageCredential") + .field("prefix", &self.prefix) + .field("config_keys", &self.config.keys().collect::>()) + .finish_non_exhaustive() + } +} + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "kebab-case")] +/// Response from the table credentials endpoint +/// (`GET /v1/{prefix}/namespaces/{namespace}/tables/{table}/credentials`). +/// +/// Returns freshly vended storage credentials so clients can refresh temporary +/// credentials before they expire. +pub struct LoadCredentialsResponse { + /// Storage credentials, one entry per location prefix. + pub storage_credentials: Vec, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "kebab-case")] /// Request to create a new table in a namespace. diff --git a/crates/iceberg/public-api.txt b/crates/iceberg/public-api.txt index 24e276db56..41b63384bb 100644 --- a/crates/iceberg/public-api.txt +++ b/crates/iceberg/public-api.txt @@ -693,6 +693,13 @@ pub fn iceberg::inspect::SnapshotsTable<'a>::new(table: &'a iceberg::table::Tabl pub async fn iceberg::inspect::SnapshotsTable<'a>::scan(&self) -> iceberg::Result pub fn iceberg::inspect::SnapshotsTable<'a>::schema(&self) -> iceberg::spec::Schema pub mod iceberg::io +pub enum iceberg::io::StorageCredentialKind +pub iceberg::io::StorageCredentialKind::Gcs(iceberg::io::GcsCredential) +pub iceberg::io::StorageCredentialKind::S3(iceberg::io::S3Credential) +impl core::clone::Clone for iceberg::io::StorageCredentialKind +pub fn iceberg::io::StorageCredentialKind::clone(&self) -> iceberg::io::StorageCredentialKind +impl core::fmt::Debug for iceberg::io::StorageCredentialKind +pub fn iceberg::io::StorageCredentialKind::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct iceberg::io::AzdlsConfig pub iceberg::io::AzdlsConfig::account_key: core::option::Option pub iceberg::io::AzdlsConfig::account_name: core::option::Option @@ -743,6 +750,7 @@ impl iceberg::io::FileIOBuilder pub fn iceberg::io::FileIOBuilder::build(self) -> iceberg::io::FileIO pub fn iceberg::io::FileIOBuilder::config(&self) -> &iceberg::io::StorageConfig pub fn iceberg::io::FileIOBuilder::new(factory: alloc::sync::Arc) -> Self +pub fn iceberg::io::FileIOBuilder::with_credential_provider(self, provider: alloc::sync::Arc) -> Self pub fn iceberg::io::FileIOBuilder::with_prop(self, key: impl alloc::string::ToString, value: impl alloc::string::ToString) -> Self pub fn iceberg::io::FileIOBuilder::with_props(self, args: impl core::iter::traits::collect::IntoIterator) -> Self impl core::clone::Clone for iceberg::io::FileIOBuilder @@ -779,6 +787,15 @@ impl serde_core::ser::Serialize for iceberg::io::GcsConfig pub fn iceberg::io::GcsConfig::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::GcsConfig pub fn iceberg::io::GcsConfig::deserialize<__D>(__deserializer: __D) -> core::result::Result::Error> where __D: serde_core::de::Deserializer<'de> +pub struct iceberg::io::GcsCredential +impl iceberg::io::GcsCredential +pub fn iceberg::io::GcsCredential::into_token(self) -> alloc::string::String +pub fn iceberg::io::GcsCredential::new(token: impl core::convert::Into) -> Self +pub fn iceberg::io::GcsCredential::token(&self) -> &str +impl core::clone::Clone for iceberg::io::GcsCredential +pub fn iceberg::io::GcsCredential::clone(&self) -> iceberg::io::GcsCredential +impl core::fmt::Debug for iceberg::io::GcsCredential +pub fn iceberg::io::GcsCredential::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct iceberg::io::HfConfig pub iceberg::io::HfConfig::endpoint: core::option::Option pub iceberg::io::HfConfig::revision: core::option::Option @@ -846,6 +863,7 @@ impl core::fmt::Debug for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::StorageFactory for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::LocalFsStorageFactory::build_with_credentials(&self, config: &iceberg::io::StorageConfig, credential_provider: core::option::Option>) -> iceberg::Result> impl serde_core::ser::Serialize for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::LocalFsStorageFactory @@ -884,6 +902,7 @@ impl core::fmt::Debug for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::StorageFactory for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::MemoryStorageFactory::build_with_credentials(&self, config: &iceberg::io::StorageConfig, credential_provider: core::option::Option>) -> iceberg::Result> impl serde_core::ser::Serialize for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::MemoryStorageFactory @@ -959,6 +978,17 @@ impl serde_core::ser::Serialize for iceberg::io::S3Config pub fn iceberg::io::S3Config::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::S3Config pub fn iceberg::io::S3Config::deserialize<__D>(__deserializer: __D) -> core::result::Result::Error> where __D: serde_core::de::Deserializer<'de> +pub struct iceberg::io::S3Credential +impl iceberg::io::S3Credential +pub fn iceberg::io::S3Credential::access_key_id(&self) -> &str +pub fn iceberg::io::S3Credential::into_parts(self) -> (alloc::string::String, alloc::string::String, core::option::Option) +pub fn iceberg::io::S3Credential::new(access_key_id: impl core::convert::Into, secret_access_key: impl core::convert::Into, session_token: core::option::Option) -> Self +pub fn iceberg::io::S3Credential::secret_access_key(&self) -> &str +pub fn iceberg::io::S3Credential::session_token(&self) -> core::option::Option<&str> +impl core::clone::Clone for iceberg::io::S3Credential +pub fn iceberg::io::S3Credential::clone(&self) -> iceberg::io::S3Credential +impl core::fmt::Debug for iceberg::io::S3Credential +pub fn iceberg::io::S3Credential::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub struct iceberg::io::StorageConfig impl iceberg::io::StorageConfig pub fn iceberg::io::StorageConfig::from_props(props: std::collections::hash::map::HashMap) -> Self @@ -996,6 +1026,19 @@ impl serde_core::ser::Serialize for iceberg::io::StorageConfig pub fn iceberg::io::StorageConfig::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg::io::StorageConfig pub fn iceberg::io::StorageConfig::deserialize<__D>(__deserializer: __D) -> core::result::Result::Error> where __D: serde_core::de::Deserializer<'de> +pub struct iceberg::io::StorageCredential +impl iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::expires_at(&self) -> core::option::Option +pub fn iceberg::io::StorageCredential::into_kind(self) -> iceberg::io::StorageCredentialKind +pub fn iceberg::io::StorageCredential::kind(&self) -> &iceberg::io::StorageCredentialKind +pub fn iceberg::io::StorageCredential::new(kind: iceberg::io::StorageCredentialKind) -> Self +pub fn iceberg::io::StorageCredential::prefix(&self) -> core::option::Option<&str> +pub fn iceberg::io::StorageCredential::with_expiration(self, expires_at: std::time::SystemTime) -> Self +pub fn iceberg::io::StorageCredential::with_prefix(self, prefix: impl core::convert::Into) -> Self +impl core::clone::Clone for iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::clone(&self) -> iceberg::io::StorageCredential +impl core::fmt::Debug for iceberg::io::StorageCredential +pub fn iceberg::io::StorageCredential::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result pub const iceberg::io::ADLS_ACCOUNT_KEY: &str pub const iceberg::io::ADLS_ACCOUNT_NAME: &str pub const iceberg::io::ADLS_AUTHORITY_HOST: &str @@ -1004,6 +1047,8 @@ pub const iceberg::io::ADLS_CLIENT_SECRET: &str pub const iceberg::io::ADLS_CONNECTION_STRING: &str pub const iceberg::io::ADLS_SAS_TOKEN: &str pub const iceberg::io::ADLS_TENANT_ID: &str +pub const iceberg::io::AWS_REFRESH_CREDENTIALS_ENABLED: &str +pub const iceberg::io::AWS_REFRESH_CREDENTIALS_ENDPOINT: &str pub const iceberg::io::CLIENT_REGION: &str pub const iceberg::io::GCS_ALLOW_ANONYMOUS: &str pub const iceberg::io::GCS_CREDENTIALS_JSON: &str @@ -1011,8 +1056,11 @@ pub const iceberg::io::GCS_DISABLE_CONFIG_LOAD: &str pub const iceberg::io::GCS_DISABLE_VM_METADATA: &str pub const iceberg::io::GCS_NO_AUTH: &str pub const iceberg::io::GCS_PROJECT_ID: &str +pub const iceberg::io::GCS_REFRESH_CREDENTIALS_ENABLED: &str +pub const iceberg::io::GCS_REFRESH_CREDENTIALS_ENDPOINT: &str pub const iceberg::io::GCS_SERVICE_HOST: &str pub const iceberg::io::GCS_TOKEN: &str +pub const iceberg::io::GCS_TOKEN_EXPIRES_AT: &str pub const iceberg::io::GCS_USER_PROJECT: &str pub const iceberg::io::HF_ENDPOINT: &str pub const iceberg::io::HF_REVISION: &str @@ -1032,6 +1080,7 @@ pub const iceberg::io::S3_PATH_STYLE_ACCESS: &str pub const iceberg::io::S3_REGION: &str pub const iceberg::io::S3_SECRET_ACCESS_KEY: &str pub const iceberg::io::S3_SESSION_TOKEN: &str +pub const iceberg::io::S3_SESSION_TOKEN_EXPIRES_AT_MS: &str pub const iceberg::io::S3_SSE_KEY: &str pub const iceberg::io::S3_SSE_MD5: &str pub const iceberg::io::S3_SSE_TYPE: &str @@ -1083,12 +1132,18 @@ pub fn iceberg::io::MemoryStorage::read<'life0, 'life1, 'async_trait>(&'life0 se pub fn iceberg::io::MemoryStorage::reader<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg::io::MemoryStorage::write<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str, bs: bytes::bytes::Bytes) -> core::pin::Pin> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait pub fn iceberg::io::MemoryStorage::writer<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str) -> core::pin::Pin>> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait +pub trait iceberg::io::StorageCredentialProvider: core::fmt::Debug + core::marker::Send + core::marker::Sync +pub fn iceberg::io::StorageCredentialProvider::load_credential<'life0, 'life1, 'async_trait>(&'life0 self, path: &'life1 str) -> core::pin::Pin> + core::marker::Send + 'async_trait)>> where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait +pub fn iceberg::io::StorageCredentialProvider::supports_path(&self, _path: &str) -> bool pub trait iceberg::io::StorageFactory: core::fmt::Debug + core::marker::Send + core::marker::Sync + typetag::Serialize + typetag::Deserialize pub fn iceberg::io::StorageFactory::build(&self, config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::StorageFactory::build_with_credentials(&self, config: &iceberg::io::StorageConfig, credential_provider: core::option::Option>) -> iceberg::Result> impl iceberg::io::StorageFactory for iceberg::io::LocalFsStorageFactory pub fn iceberg::io::LocalFsStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::LocalFsStorageFactory::build_with_credentials(&self, config: &iceberg::io::StorageConfig, credential_provider: core::option::Option>) -> iceberg::Result> impl iceberg::io::StorageFactory for iceberg::io::MemoryStorageFactory pub fn iceberg::io::MemoryStorageFactory::build(&self, _config: &iceberg::io::StorageConfig) -> iceberg::Result> +pub fn iceberg::io::MemoryStorageFactory::build_with_credentials(&self, config: &iceberg::io::StorageConfig, credential_provider: core::option::Option>) -> iceberg::Result> pub mod iceberg::memory pub struct iceberg::memory::MemoryCatalog impl core::fmt::Debug for iceberg::memory::MemoryCatalog diff --git a/crates/iceberg/src/io/file_io.rs b/crates/iceberg/src/io/file_io.rs index cd0a4434c4..0257e6a5b2 100644 --- a/crates/iceberg/src/io/file_io.rs +++ b/crates/iceberg/src/io/file_io.rs @@ -22,7 +22,8 @@ use bytes::Bytes; use futures::{Stream, StreamExt}; use super::storage::{ - LocalFsStorageFactory, MemoryStorageFactory, Storage, StorageConfig, StorageFactory, + LocalFsStorageFactory, MemoryStorageFactory, Storage, StorageConfig, StorageCredentialProvider, + StorageFactory, }; use crate::Result; @@ -65,6 +66,8 @@ pub struct FileIO { config: StorageConfig, /// Factory for creating storage instances factory: Arc, + /// Optional provider of refreshable, backend-specific credentials + credential_provider: Option>, /// Cached storage instance (lazily initialized) storage: Arc>>, } @@ -77,6 +80,7 @@ impl FileIO { Self { config: StorageConfig::new(), factory: Arc::new(MemoryStorageFactory), + credential_provider: None, storage: Arc::new(OnceLock::new()), } } @@ -88,6 +92,7 @@ impl FileIO { Self { config: StorageConfig::new(), factory: Arc::new(LocalFsStorageFactory), + credential_provider: None, storage: Arc::new(OnceLock::new()), } } @@ -107,8 +112,11 @@ impl FileIO { return Ok(storage.clone()); } - // Build the storage - let storage = self.factory.build(&self.config)?; + // Build the storage, passing any credential provider so backends that + // support refreshable credentials can wire it into their operators. + let storage = self + .factory + .build_with_credentials(&self.config, self.credential_provider.clone())?; // Try to set it (another thread might have set it first) let _ = self.storage.set(storage.clone()); @@ -191,6 +199,8 @@ pub struct FileIOBuilder { factory: Arc, /// Storage configuration config: StorageConfig, + /// Optional provider of refreshable, backend-specific credentials + credential_provider: Option>, } impl FileIOBuilder { @@ -199,6 +209,7 @@ impl FileIOBuilder { Self { factory, config: StorageConfig::new(), + credential_provider: None, } } @@ -224,11 +235,21 @@ impl FileIOBuilder { &self.config } + /// Attach a provider of refreshable, backend-specific credentials. + pub fn with_credential_provider( + mut self, + provider: Arc, + ) -> Self { + self.credential_provider = Some(provider); + self + } + /// Builds [`FileIO`]. pub fn build(self) -> FileIO { FileIO { config: self.config, factory: self.factory, + credential_provider: self.credential_provider, storage: Arc::new(OnceLock::new()), } } @@ -397,7 +418,20 @@ mod tests { use tempfile::TempDir; use super::{FileIO, FileIOBuilder}; - use crate::io::{LocalFsStorageFactory, MemoryStorageFactory}; + use crate::io::{ + LocalFsStorageFactory, MemoryStorageFactory, StorageCredential, StorageCredentialProvider, + }; + use crate::{ErrorKind, Result}; + + #[derive(Debug)] + struct TestCredentialProvider; + + #[async_trait::async_trait] + impl StorageCredentialProvider for TestCredentialProvider { + async fn load_credential(&self, _path: &str) -> Result { + unreachable!("unsupported factories must reject the provider before loading from it") + } + } fn create_local_file_io() -> FileIO { FileIO::new_with_fs() @@ -544,4 +578,14 @@ mod tests { assert_eq!(file_io.config().get("key1"), Some(&"value1".to_string())); assert_eq!(file_io.config().get("key2"), Some(&"value2".to_string())); } + + #[tokio::test] + async fn test_file_io_rejects_credentials_for_unsupported_factory() { + let file_io = FileIOBuilder::new(Arc::new(MemoryStorageFactory)) + .with_credential_provider(Arc::new(TestCredentialProvider)) + .build(); + + let err = file_io.exists("memory://file").await.unwrap_err(); + assert_eq!(err.kind(), ErrorKind::FeatureUnsupported, "{err}"); + } } diff --git a/crates/iceberg/src/io/storage/config/gcs.rs b/crates/iceberg/src/io/storage/config/gcs.rs index d9e57e1100..48f146008a 100644 --- a/crates/iceberg/src/io/storage/config/gcs.rs +++ b/crates/iceberg/src/io/storage/config/gcs.rs @@ -41,6 +41,12 @@ pub const GCS_NO_AUTH: &str = "gcs.no-auth"; pub const GCS_CREDENTIALS_JSON: &str = "gcs.credentials-json"; /// Google Cloud Storage token. pub const GCS_TOKEN: &str = "gcs.oauth2.token"; +/// Epoch-millisecond timestamp at which the vended GCS OAuth2 token expires. +pub const GCS_TOKEN_EXPIRES_AT: &str = "gcs.oauth2.token-expires-at"; +/// Endpoint used to fetch and refresh vended GCS OAuth2 credentials. +pub const GCS_REFRESH_CREDENTIALS_ENDPOINT: &str = "gcs.oauth2.refresh-credentials-endpoint"; +/// Whether vended GCS OAuth2 credentials should be refreshed. Defaults to `true`. +pub const GCS_REFRESH_CREDENTIALS_ENABLED: &str = "gcs.oauth2.refresh-credentials-enabled"; /// Option to skip signing requests (e.g. for public buckets/folders). pub const GCS_ALLOW_ANONYMOUS: &str = "gcs.allow-anonymous"; /// Option to skip loading the credential from GCE metadata server. diff --git a/crates/iceberg/src/io/storage/config/mod.rs b/crates/iceberg/src/io/storage/config/mod.rs index 2350aab6dd..a79f871e8d 100644 --- a/crates/iceberg/src/io/storage/config/mod.rs +++ b/crates/iceberg/src/io/storage/config/mod.rs @@ -51,12 +51,22 @@ use serde::{Deserialize, Serialize}; /// which storage backend to use. The storage type is determined by the /// explicit factory selection. /// ``` -#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Default)] +#[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)] pub struct StorageConfig { /// Configuration properties for the storage backend props: HashMap, } +impl std::fmt::Debug for StorageConfig { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // Property values may hold vended credentials (e.g. `s3.secret-access-key`, + // `s3.session-token`) + f.debug_struct("StorageConfig") + .field("keys", &self.props.keys().collect::>()) + .finish_non_exhaustive() + } +} + impl StorageConfig { /// Create a new empty StorageConfig. pub fn new() -> Self { diff --git a/crates/iceberg/src/io/storage/config/s3.rs b/crates/iceberg/src/io/storage/config/s3.rs index 664e8637b8..eb8c9f54c5 100644 --- a/crates/iceberg/src/io/storage/config/s3.rs +++ b/crates/iceberg/src/io/storage/config/s3.rs @@ -35,10 +35,16 @@ pub const S3_ACCESS_KEY_ID: &str = "s3.access-key-id"; pub const S3_SECRET_ACCESS_KEY: &str = "s3.secret-access-key"; /// S3 session token (required when using temporary credentials). pub const S3_SESSION_TOKEN: &str = "s3.session-token"; +/// Epoch-millisecond timestamp at which the vended S3 session token expires. +pub const S3_SESSION_TOKEN_EXPIRES_AT_MS: &str = "s3.session-token-expires-at-ms"; /// S3 region. pub const S3_REGION: &str = "s3.region"; /// Region to use for the S3 client (takes precedence over [`S3_REGION`]). pub const CLIENT_REGION: &str = "client.region"; +/// Endpoint used to fetch and refresh vended AWS credentials. +pub const AWS_REFRESH_CREDENTIALS_ENDPOINT: &str = "client.refresh-credentials-endpoint"; +/// Whether vended AWS credentials should be refreshed. Defaults to `true`. +pub const AWS_REFRESH_CREDENTIALS_ENABLED: &str = "client.refresh-credentials-enabled"; /// S3 Path Style Access. pub const S3_PATH_STYLE_ACCESS: &str = "s3.path-style-access"; /// S3 Server Side Encryption Type. diff --git a/crates/iceberg/src/io/storage/mod.rs b/crates/iceberg/src/io/storage/mod.rs index 5276c7771f..70542c5fa3 100644 --- a/crates/iceberg/src/io/storage/mod.rs +++ b/crates/iceberg/src/io/storage/mod.rs @@ -23,6 +23,7 @@ mod memory; use std::fmt::Debug; use std::sync::Arc; +use std::time::SystemTime; use async_trait::async_trait; use bytes::Bytes; @@ -32,7 +33,7 @@ pub use local_fs::{LocalFsStorage, LocalFsStorageFactory}; pub use memory::{MemoryStorage, MemoryStorageFactory}; use super::{FileMetadata, FileRead, FileWrite, InputFile, OutputFile}; -use crate::Result; +use crate::{Error, ErrorKind, Result}; /// Trait for storage operations in Iceberg. /// @@ -139,4 +140,208 @@ pub trait StorageFactory: Debug + Send + Sync { /// A `Result` containing an `Arc` on success, or an error /// if the storage could not be created. fn build(&self, config: &StorageConfig) -> Result>; + + /// Build a new Storage instance, optionally supplying a credential provider + /// that the backend can call to obtain and refresh short-lived credentials. + fn build_with_credentials( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + if credential_provider.is_some() { + return Err(Error::new( + ErrorKind::FeatureUnsupported, + "Storage factory does not support refreshable credential providers", + )); + } + + self.build(config) + } +} + +/// Supplies fresh, backend-specific storage credentials on demand. +/// +/// A catalog that vends temporary credentials implements this trait so that +/// storage backends can re-fetch credentials as they approach expiry instead +/// of failing once the initial token's TTL runs out. +/// +/// # Caching +/// +/// [`load_credential`](Self::load_credential) may be called very frequently. +/// Implementations must cache internally and only re-fetch when the current +/// credential is at or near expiry; otherwise every object-store request could +/// trigger a call back to the catalog. +#[async_trait] +pub trait StorageCredentialProvider: Debug + Send + Sync { + /// Return whether this provider has refresh configuration for `path`. + /// + /// Backends use this before replacing their normal credential chain. The + /// default is `true` for single-backend providers; multi-backend providers + /// should return `false` for schemes they do not configure. + fn supports_path(&self, _path: &str) -> bool { + true + } + + /// Load a fresh credential for the storage location identified by `path`. + /// + /// `path` is the absolute location being accessed (e.g. + /// `s3://bucket/warehouse/db/table/...`). Providers that vend distinct + /// credentials per location prefix use it to select the most specific + /// match. When the selected credential has a declared + /// [`StorageCredential::prefix`], it must cover `path`. + async fn load_credential(&self, path: &str) -> Result; +} + +/// A vended storage credential together with its scope and expiry. +#[derive(Clone, Debug)] +pub struct StorageCredential { + /// Storage-location prefix this credential is scoped to. `None` represents a + /// credential without a declared scope, sourced from flat storage properties. + prefix: Option, + /// The backend-specific credential material. + kind: StorageCredentialKind, + /// When the credential expires, if known. `None` means non-expiring and + /// backends treat such a credential as always valid and never refresh it. + expires_at: Option, +} + +impl StorageCredential { + /// Create a storage credential with no declared scope or expiration. + pub fn new(kind: StorageCredentialKind) -> Self { + Self { + prefix: None, + kind, + expires_at: None, + } + } + + /// Set the storage-location prefix this credential is scoped to. + pub fn with_prefix(mut self, prefix: impl Into) -> Self { + self.prefix = Some(prefix.into()); + self + } + + /// Set when this credential expires. + pub fn with_expiration(mut self, expires_at: SystemTime) -> Self { + self.expires_at = Some(expires_at); + self + } + + /// Return the storage-location prefix this credential is scoped to. + pub fn prefix(&self) -> Option<&str> { + self.prefix.as_deref() + } + + /// Return the backend-specific credential material. + pub fn kind(&self) -> &StorageCredentialKind { + &self.kind + } + + /// Consume this credential and return its backend-specific material. + pub fn into_kind(self) -> StorageCredentialKind { + self.kind + } + + /// Return when this credential expires. + pub fn expires_at(&self) -> Option { + self.expires_at + } +} + +/// Backend-specific credential material. +#[derive(Clone, Debug)] +pub enum StorageCredentialKind { + /// Amazon S3 credentials. + S3(S3Credential), + /// Google Cloud Storage credentials. + Gcs(GcsCredential), +} + +/// Temporary Amazon S3 credentials. +#[derive(Clone)] +pub struct S3Credential { + /// AWS access key ID. + access_key_id: String, + /// AWS secret access key. + secret_access_key: String, + /// AWS session token, set for temporary (STS/vended) credentials. + session_token: Option, +} + +impl S3Credential { + /// Create temporary Amazon S3 credentials. + pub fn new( + access_key_id: impl Into, + secret_access_key: impl Into, + session_token: Option, + ) -> Self { + Self { + access_key_id: access_key_id.into(), + secret_access_key: secret_access_key.into(), + session_token, + } + } + + /// Return the AWS access key ID. + pub fn access_key_id(&self) -> &str { + &self.access_key_id + } + + /// Return the AWS secret access key. + pub fn secret_access_key(&self) -> &str { + &self.secret_access_key + } + + /// Return the AWS session token, if present. + pub fn session_token(&self) -> Option<&str> { + self.session_token.as_deref() + } + + /// Consume these credentials and return their component values. + pub fn into_parts(self) -> (String, String, Option) { + let Self { + access_key_id, + secret_access_key, + session_token, + } = self; + (access_key_id, secret_access_key, session_token) + } +} + +impl Debug for S3Credential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("S3Credential").finish_non_exhaustive() + } +} + +/// Temporary Google Cloud Storage credentials (an OAuth2 access token). +#[derive(Clone)] +pub struct GcsCredential { + /// OAuth2 bearer token used to access GCS. + token: String, +} + +impl GcsCredential { + /// Create a Google Cloud Storage credential. + pub fn new(token: impl Into) -> Self { + Self { + token: token.into(), + } + } + + /// Return the OAuth2 bearer token used to access GCS. + pub fn token(&self) -> &str { + &self.token + } + + /// Consume this credential and return its OAuth2 bearer token. + pub fn into_token(self) -> String { + self.token + } +} + +impl Debug for GcsCredential { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("GcsCredential").finish_non_exhaustive() + } } diff --git a/crates/storage/opendal/Cargo.toml b/crates/storage/opendal/Cargo.toml index e43e7845b3..4cbf2892d9 100644 --- a/crates/storage/opendal/Cargo.toml +++ b/crates/storage/opendal/Cargo.toml @@ -41,7 +41,7 @@ opendal-all = [ opendal-azdls = ["opendal/services-azdls"] opendal-fs = ["opendal/services-fs"] -opendal-gcs = ["opendal/services-gcs"] +opendal-gcs = ["opendal/services-gcs", "reqsign-google", "reqsign-core"] opendal-hf = ["opendal/services-hf"] opendal-memory = ["opendal/services-memory"] opendal-oss = ["opendal/services-oss"] @@ -57,6 +57,7 @@ iceberg = { workspace = true } opendal = { workspace = true } reqsign-aws-v4 = { version = "3.0.0", optional = true } reqsign-core = { version = "3.0.0", optional = true } +reqsign-google = { version = "3.0.0", optional = true } serde = { workspace = true } typetag = { workspace = true } url = { workspace = true } diff --git a/crates/storage/opendal/public-api.txt b/crates/storage/opendal/public-api.txt index d8c4ecdb38..b253478947 100644 --- a/crates/storage/opendal/public-api.txt +++ b/crates/storage/opendal/public-api.txt @@ -6,6 +6,7 @@ pub iceberg_storage_opendal::OpenDalStorage::Azdls pub iceberg_storage_opendal::OpenDalStorage::Azdls::config: alloc::sync::Arc pub iceberg_storage_opendal::OpenDalStorage::Gcs pub iceberg_storage_opendal::OpenDalStorage::Gcs::config: alloc::sync::Arc +pub iceberg_storage_opendal::OpenDalStorage::Gcs::credential_provider: core::option::Option> pub iceberg_storage_opendal::OpenDalStorage::Hf pub iceberg_storage_opendal::OpenDalStorage::Hf::config: alloc::sync::Arc pub iceberg_storage_opendal::OpenDalStorage::LocalFs @@ -14,6 +15,7 @@ pub iceberg_storage_opendal::OpenDalStorage::Oss pub iceberg_storage_opendal::OpenDalStorage::Oss::config: alloc::sync::Arc pub iceberg_storage_opendal::OpenDalStorage::S3 pub iceberg_storage_opendal::OpenDalStorage::S3::config: alloc::sync::Arc +pub iceberg_storage_opendal::OpenDalStorage::S3::credential_provider: core::option::Option> pub iceberg_storage_opendal::OpenDalStorage::S3::customized_credential_load: core::option::Option impl core::clone::Clone for iceberg_storage_opendal::OpenDalStorage pub fn iceberg_storage_opendal::OpenDalStorage::clone(&self) -> iceberg_storage_opendal::OpenDalStorage @@ -50,6 +52,7 @@ impl core::fmt::Debug for iceberg_storage_opendal::OpenDalStorageFactory pub fn iceberg_storage_opendal::OpenDalStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::storage::StorageFactory for iceberg_storage_opendal::OpenDalStorageFactory pub fn iceberg_storage_opendal::OpenDalStorageFactory::build(&self, config: &iceberg::io::storage::config::StorageConfig) -> iceberg::error::Result> +pub fn iceberg_storage_opendal::OpenDalStorageFactory::build_with_credentials(&self, config: &iceberg::io::storage::config::StorageConfig, credential_provider: core::option::Option>) -> iceberg::error::Result> impl serde_core::ser::Serialize for iceberg_storage_opendal::OpenDalStorageFactory pub fn iceberg_storage_opendal::OpenDalStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg_storage_opendal::OpenDalStorageFactory @@ -92,6 +95,7 @@ impl core::fmt::Debug for iceberg_storage_opendal::OpenDalResolvingStorageFactor pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result impl iceberg::io::storage::StorageFactory for iceberg_storage_opendal::OpenDalResolvingStorageFactory pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::build(&self, config: &iceberg::io::storage::config::StorageConfig) -> iceberg::error::Result> +pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::build_with_credentials(&self, config: &iceberg::io::storage::config::StorageConfig, credential_provider: core::option::Option>) -> iceberg::error::Result> impl serde_core::ser::Serialize for iceberg_storage_opendal::OpenDalResolvingStorageFactory pub fn iceberg_storage_opendal::OpenDalResolvingStorageFactory::serialize<__S>(&self, __serializer: __S) -> core::result::Result<<__S as serde_core::ser::Serializer>::Ok, <__S as serde_core::ser::Serializer>::Error> where __S: serde_core::ser::Serializer impl<'de> serde_core::de::Deserialize<'de> for iceberg_storage_opendal::OpenDalResolvingStorageFactory diff --git a/crates/storage/opendal/src/gcs.rs b/crates/storage/opendal/src/gcs.rs index a00282cc22..f17b927d23 100644 --- a/crates/storage/opendal/src/gcs.rs +++ b/crates/storage/opendal/src/gcs.rs @@ -17,17 +17,23 @@ //! Google Cloud Storage properties use std::collections::HashMap; +use std::sync::Arc; use iceberg::io::{ GCS_ALLOW_ANONYMOUS, GCS_CREDENTIALS_JSON, GCS_DISABLE_CONFIG_LOAD, GCS_DISABLE_VM_METADATA, - GCS_NO_AUTH, GCS_SERVICE_HOST, GCS_TOKEN, + GCS_NO_AUTH, GCS_SERVICE_HOST, GCS_TOKEN, StorageCredentialKind, StorageCredentialProvider, }; use iceberg::{Error, ErrorKind, Result}; -use opendal::Operator; use opendal::services::GcsConfig; +use opendal::{Configurator, Operator}; +use reqsign_core::{Context, Error as ReqsignError, ProvideCredential, Result as ReqsignResult}; +use reqsign_google::{Credential as GoogleCredential, Token as GoogleToken}; use url::Url; -use crate::utils::{from_opendal_error, is_truthy}; +use crate::DynamicCredentialScope; +use crate::utils::{ + from_opendal_error, is_truthy, system_time_to_timestamp, validate_credential_prefix, +}; /// Parse iceberg properties to [`GcsConfig`]. pub(crate) fn gcs_config_parse(mut m: HashMap) -> Result { @@ -45,7 +51,9 @@ pub(crate) fn gcs_config_parse(mut m: HashMap) -> Result) -> Result Result { +pub(crate) fn gcs_config_build( + cfg: &GcsConfig, + credential_provider: &Option>, + path: &str, + credential_scope: Option<&DynamicCredentialScope>, +) -> Result { let url = Url::parse(path)?; + if !matches!(url.scheme(), "gs" | "gcs") { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid gcs url: {path}, expected gs:// or gcs://"), + )); + } let bucket = url.host_str().ok_or_else(|| { Error::new( ErrorKind::DataInvalid, @@ -82,5 +101,203 @@ pub(crate) fn gcs_config_build(cfg: &GcsConfig, path: &str) -> Result let mut cfg = cfg.clone(); cfg.bucket = bucket.to_string(); - Operator::from_config(cfg).map_err(from_opendal_error) + + // When a catalog-supplied provider is present, make it the sole credential + // source. `reqsign_google` only prepends a custom provider (unlike S3, which + // replaces the chain) and its chain continues to the next provider on error, + // so without this a failed refresh would silently fall back to the stale seed + // token or ambient GCP credentials. + let credential_provider = credential_provider + .as_ref() + .filter(|provider| provider.supports_path(path)); + if credential_provider.is_some() { + if cfg.skip_signature { + return Err(Error::new( + ErrorKind::DataInvalid, + "Invalid GCS auth settings: anonymous access cannot be combined with refreshable credentials", + )); + } + cfg.token = None; + cfg.credential = None; + cfg.disable_vm_metadata = true; + cfg.disable_config_load = true; + } + + let mut builder = cfg.into_builder(); + + // A catalog-supplied provider re-fetches the vended OAuth2 token as it nears expiry + if let Some(provider) = credential_provider { + builder = builder.credential_provider(VendedGcsCredentialProvider::new( + Arc::clone(provider), + path.to_string(), + credential_scope.cloned(), + )); + } + + Operator::new(builder).map_err(from_opendal_error) +} + +/// Adapts a generic [`StorageCredentialProvider`] into a `reqsign` +/// [`ProvideCredential`], so the GCS signer can obtain and refresh vended OAuth2 +/// tokens. +struct VendedGcsCredentialProvider { + provider: Arc, + /// Absolute path this operator serves: handed back to the provider so it can + /// select the vended credential whose prefix best matches the location. + path: String, + /// Exact scope selected when a bulk-delete operator was created. Ordinary + /// operators are unbound so they can follow the provider's best match. + credential_scope: Option, +} + +impl std::fmt::Debug for VendedGcsCredentialProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VendedGcsCredentialProvider") + .field("path", &self.path) + .field("credential_scope", &self.credential_scope) + .finish_non_exhaustive() + } +} + +impl VendedGcsCredentialProvider { + fn new( + provider: Arc, + path: String, + credential_scope: Option, + ) -> Self { + Self { + provider, + path, + credential_scope, + } + } +} + +impl ProvideCredential for VendedGcsCredentialProvider { + type Credential = GoogleCredential; + + async fn provide_credential(&self, _ctx: &Context) -> ReqsignResult> { + let credential = self + .provider + .load_credential(&self.path) + .await + .map_err(|e| { + ReqsignError::unexpected(format!( + "failed to load vended GCS credential for {}", + self.path + )) + .with_source(e) + })?; + + validate_credential_prefix( + &self.path, + credential.prefix(), + self.credential_scope.as_ref(), + )?; + + let expires_at = credential + .expires_at() + .map(system_time_to_timestamp) + .transpose()?; + match credential.into_kind() { + StorageCredentialKind::Gcs(gcs) => { + Ok(Some(GoogleCredential::with_token(GoogleToken { + access_token: gcs.into_token(), + expires_at, + }))) + } + _ => Err(ReqsignError::unexpected( + "GCS storage received a non-GCS credential from the provider", + )), + } + } +} + +#[cfg(test)] +mod tests { + use async_trait::async_trait; + use iceberg::io::{GcsCredential, StorageCredential}; + + use super::*; + + #[derive(Debug)] + struct FixedCredentialProvider(StorageCredential); + + #[async_trait] + impl StorageCredentialProvider for FixedCredentialProvider { + async fn load_credential(&self, _path: &str) -> Result { + Ok(self.0.clone()) + } + } + + fn credential(prefix: Option<&str>) -> StorageCredential { + let credential = StorageCredential::new(StorageCredentialKind::Gcs(GcsCredential::new( + "access-token", + ))); + match prefix { + Some(prefix) => credential.with_prefix(prefix), + None => credential, + } + } + + fn provider( + path: &str, + returned_prefix: Option<&str>, + credential_scope: Option, + ) -> VendedGcsCredentialProvider { + VendedGcsCredentialProvider::new( + Arc::new(FixedCredentialProvider(credential(returned_prefix))), + path.to_string(), + credential_scope, + ) + } + + #[tokio::test] + async fn vended_provider_enforces_bound_credential_scope() { + let path = "gs://bucket/table/file.parquet"; + let table_prefix = "gs://bucket/table"; + + assert!( + provider( + path, + Some(table_prefix), + Some(DynamicCredentialScope::Prefix(table_prefix.to_string())), + ) + .provide_credential(&Context::default()) + .await + .is_ok() + ); + assert!( + provider( + path, + Some("gs://bucket"), + Some(DynamicCredentialScope::Prefix(table_prefix.to_string())), + ) + .provide_credential(&Context::default()) + .await + .is_err() + ); + assert!( + provider(path, Some("gs://bucket"), None) + .provide_credential(&Context::default()) + .await + .is_ok() + ); + assert!( + provider(path, None, Some(DynamicCredentialScope::Unscoped)) + .provide_credential(&Context::default()) + .await + .is_ok() + ); + assert!( + provider( + path, + Some(table_prefix), + Some(DynamicCredentialScope::Unscoped), + ) + .provide_credential(&Context::default()) + .await + .is_err() + ); + } } diff --git a/crates/storage/opendal/src/lib.rs b/crates/storage/opendal/src/lib.rs index 768d3ff77f..e58b94575e 100644 --- a/crates/storage/opendal/src/lib.rs +++ b/crates/storage/opendal/src/lib.rs @@ -35,7 +35,7 @@ use futures::StreamExt; use futures::stream::BoxStream; use iceberg::io::{ FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, - StorageFactory, + StorageCredentialProvider, StorageFactory, }; use iceberg::{Error, ErrorKind, Result}; use opendal::Operator; @@ -135,8 +135,31 @@ pub enum OpenDalStorageFactory { #[typetag::serde(name = "OpenDalStorageFactory")] impl StorageFactory for OpenDalStorageFactory { - #[allow(unused_variables)] fn build(&self, config: &StorageConfig) -> Result> { + self.build_with_credentials(config, None) + } + + #[allow(unused_variables)] + fn build_with_credentials( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + #[allow(unreachable_patterns)] + let supports_credential_provider = match self { + #[cfg(feature = "opendal-s3")] + OpenDalStorageFactory::S3 { .. } => true, + #[cfg(feature = "opendal-gcs")] + OpenDalStorageFactory::Gcs => true, + _ => false, + }; + if credential_provider.is_some() && !supports_credential_provider { + return Err(Error::new( + ErrorKind::FeatureUnsupported, + "OpenDAL storage factory does not support refreshable credentials for this backend", + )); + } + match self { #[cfg(feature = "opendal-memory")] OpenDalStorageFactory::Memory => { @@ -150,10 +173,12 @@ impl StorageFactory for OpenDalStorageFactory { } => Ok(Arc::new(OpenDalStorage::S3 { config: s3_config_parse(config.props().clone())?.into(), customized_credential_load: customized_credential_load.clone(), + credential_provider, })), #[cfg(feature = "opendal-gcs")] OpenDalStorageFactory::Gcs => Ok(Arc::new(OpenDalStorage::Gcs { config: gcs_config_parse(config.props().clone())?.into(), + credential_provider, })), #[cfg(feature = "opendal-oss")] OpenDalStorageFactory::Oss => Ok(Arc::new(OpenDalStorage::Oss { @@ -210,12 +235,18 @@ pub enum OpenDalStorage { /// Custom AWS credential loader. #[serde(skip)] customized_credential_load: Option, + /// Provider of refreshable vended credentials, supplied by the catalog. + #[serde(skip)] + credential_provider: Option>, }, /// GCS storage variant. #[cfg(feature = "opendal-gcs")] Gcs { /// GCS configuration. config: Arc, + /// Provider of refreshable vended credentials, supplied by the catalog. + #[serde(skip)] + credential_provider: Option>, }, /// OSS storage variant. #[cfg(feature = "opendal-oss")] @@ -246,6 +277,33 @@ pub enum OpenDalStorage { }, } +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +enum DeleteCredentialScope { + Static, + Dynamic(DynamicCredentialScope), +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +enum DynamicCredentialScope { + Unscoped, + Prefix(String), +} + +impl DynamicCredentialScope { + fn from_prefix(prefix: Option<&str>) -> Self { + match prefix { + Some(prefix) => Self::Prefix(prefix.to_string()), + None => Self::Unscoped, + } + } +} + +#[derive(Clone, Debug, Eq, Hash, PartialEq)] +struct DeleteBatchKey { + storage: String, + credential_scope: DeleteCredentialScope, +} + impl OpenDalStorage { /// Creates operator from path. /// @@ -263,6 +321,17 @@ impl OpenDalStorage { pub(crate) fn create_operator<'a>( &self, path: &'a impl AsRef, + ) -> Result<(Operator, &'a str)> { + self.create_operator_with_scope(path, None) + } + + /// Creates an operator, optionally binding dynamic credentials to the exact + /// scope used to group a bulk-delete batch. + #[allow(unreachable_code, unused_variables)] + fn create_operator_with_scope<'a>( + &self, + path: &'a impl AsRef, + credential_scope: Option<&DynamicCredentialScope>, ) -> Result<(Operator, &'a str)> { let path = path.as_ref(); let (operator, relative_path): (Operator, &str) = match self { @@ -287,8 +356,15 @@ impl OpenDalStorage { OpenDalStorage::S3 { config, customized_credential_load, + credential_provider, } => { - let op = s3_config_build(config, customized_credential_load, path)?; + let op = s3_config_build( + config, + customized_credential_load, + credential_provider, + path, + credential_scope, + )?; let op_info = op.info(); // Use the URL scheme in the path for prefix matching. This enables @@ -310,9 +386,19 @@ impl OpenDalStorage { } } #[cfg(feature = "opendal-gcs")] - OpenDalStorage::Gcs { config } => { - let operator = gcs_config_build(config, path)?; - let prefix = format!("gs://{}/", operator.info().name()); + OpenDalStorage::Gcs { + config, + credential_provider, + } => { + let operator = + gcs_config_build(config, credential_provider, path, credential_scope)?; + let url = url::Url::parse(path).map_err(|e| { + Error::new( + ErrorKind::DataInvalid, + format!("Invalid gcs url: {path}: {e}"), + ) + })?; + let prefix = format!("{}://{}/", url.scheme(), operator.info().name()); if path.starts_with(&prefix) { (operator, &path[prefix.len()..]) } else { @@ -384,6 +470,60 @@ impl OpenDalStorage { } } + /// Return the dynamic credential provider that serves `path`, if any. + fn credential_provider_for_path( + &self, + path: &str, + ) -> Option<&Arc> { + let provider: &Arc = (match self { + #[cfg(feature = "opendal-s3")] + OpenDalStorage::S3 { + customized_credential_load: None, + credential_provider: Some(provider), + .. + } => Some(provider), + #[cfg(feature = "opendal-gcs")] + OpenDalStorage::Gcs { + credential_provider: Some(provider), + .. + } => Some(provider), + _ => None, + })?; + provider.supports_path(path).then_some(provider) + } + + /// Returns a key that keeps bulk deletes within one operator and credential + /// scope. Loading the credential is normally a cache hit and avoids rebuilding + /// an operator for every path while preventing a batch from crossing prefixes. + async fn delete_batch_key_for_path(&self, path: &str) -> Result { + let credential_scope = match self.credential_provider_for_path(path) { + Some(provider) => { + let credential = provider.load_credential(path).await?; + if credential + .prefix() + .is_some_and(|prefix| prefix.is_empty() || !path.starts_with(prefix)) + { + return Err(Error::new( + ErrorKind::DataInvalid, + format!( + "vended credential prefix {:?} does not cover storage location {path:?}", + credential.prefix() + ), + )); + } + DeleteCredentialScope::Dynamic(DynamicCredentialScope::from_prefix( + credential.prefix(), + )) + } + None => DeleteCredentialScope::Static, + }; + + Ok(DeleteBatchKey { + storage: self.batch_key_for_path(path), + credential_scope, + }) + } + /// Extracts the relative path from an absolute path without building an operator. /// /// This is a lightweight alternative to [`create_operator`](Self::create_operator) for cases @@ -418,13 +558,19 @@ impl OpenDalStorage { #[cfg(feature = "opendal-gcs")] OpenDalStorage::Gcs { .. } => { let url = url::Url::parse(path)?; + if !matches!(url.scheme(), "gs" | "gcs") { + return Err(Error::new( + ErrorKind::DataInvalid, + format!("Invalid gcs url: {path}, expected gs:// or gcs://"), + )); + } let bucket = url.host_str().ok_or_else(|| { Error::new( ErrorKind::DataInvalid, format!("Invalid gcs url: {path}, missing bucket"), ) })?; - let prefix = format!("gs://{}/", bucket); + let prefix = format!("{}://{}/", url.scheme(), bucket); if path.starts_with(&prefix) { Ok(&path[prefix.len()..]) } else { @@ -550,17 +696,21 @@ impl Storage for OpenDalStorage { } async fn delete_stream(&self, mut paths: BoxStream<'static, String>) -> Result<()> { - let mut deleters: HashMap = HashMap::new(); + let mut deleters: HashMap = HashMap::new(); while let Some(path) = paths.next().await { - let bucket = self.batch_key_for_path(&path); + let batch_key = self.delete_batch_key_for_path(&path).await?; - let (relative_path, deleter) = match deleters.entry(bucket) { + let (relative_path, deleter) = match deleters.entry(batch_key) { Entry::Occupied(entry) => { (self.relativize_path(&path)?.to_string(), entry.into_mut()) } Entry::Vacant(entry) => { - let (op, rel) = self.create_operator(&path)?; + let credential_scope = match &entry.key().credential_scope { + DeleteCredentialScope::Static => None, + DeleteCredentialScope::Dynamic(scope) => Some(scope), + }; + let (op, rel) = self.create_operator_with_scope(&path, credential_scope)?; let rel = rel.to_string(); let deleter = op.deleter().await.map_err(from_opendal_error)?; (rel, entry.insert(deleter)) @@ -631,6 +781,28 @@ impl FileWrite for OpenDalWriter { mod tests { use super::*; + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + #[derive(Debug)] + struct AlwaysSupportedCredentialProvider; + + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + #[async_trait] + impl StorageCredentialProvider for AlwaysSupportedCredentialProvider { + async fn load_credential(&self, path: &str) -> Result { + let prefix = if path.contains("/table-a/") { + "s3://bucket/table-a" + } else { + "s3://bucket/table-b" + }; + Ok( + iceberg::io::StorageCredential::new(iceberg::io::StorageCredentialKind::S3( + iceberg::io::S3Credential::new("access-key", "secret-key", None), + )) + .with_prefix(prefix), + ) + } + } + #[cfg(feature = "opendal-memory")] #[test] fn test_default_memory_operator() { @@ -638,6 +810,22 @@ mod tests { assert_eq!(op.info().scheme().to_string(), "memory"); } + #[cfg(all( + feature = "opendal-memory", + any(feature = "opendal-s3", feature = "opendal-gcs") + ))] + #[test] + fn test_factory_rejects_credentials_for_unsupported_backend() { + let error = OpenDalStorageFactory::Memory + .build_with_credentials( + &StorageConfig::new(), + Some(Arc::new(AlwaysSupportedCredentialProvider)), + ) + .expect_err("memory must reject a credential provider"); + + assert_eq!(error.kind(), ErrorKind::FeatureUnsupported); + } + #[cfg(feature = "opendal-memory")] #[test] fn test_relativize_path_memory() { @@ -677,6 +865,7 @@ mod tests { let storage = OpenDalStorage::S3 { config: Arc::new(S3Config::default()), customized_credential_load: None, + credential_provider: None, }; // All S3-family schemes are accepted by the same storage instance. @@ -692,19 +881,106 @@ mod tests { } } + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_dynamic_credentials_batch_by_prefix() { + let storage = OpenDalStorage::S3 { + config: Arc::new(S3Config::default()), + customized_credential_load: None, + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + }; + let first = "s3://bucket/table-a/file.parquet"; + let same_scope = "s3://bucket/table-a/other.parquet"; + let other_scope = "s3://bucket/table-b/file.parquet"; + + let first_key = storage.delete_batch_key_for_path(first).await.unwrap(); + assert_eq!( + first_key.credential_scope, + DeleteCredentialScope::Dynamic(DynamicCredentialScope::Prefix( + "s3://bucket/table-a".to_string() + )) + ); + assert_eq!( + first_key, + storage.delete_batch_key_for_path(same_scope).await.unwrap() + ); + assert_ne!( + first_key, + storage + .delete_batch_key_for_path(other_scope) + .await + .unwrap() + ); + } + + #[cfg(feature = "opendal-s3")] + #[tokio::test] + async fn test_custom_s3_credential_loader_ignores_dynamic_provider_for_batching() { + let storage = OpenDalStorage::S3 { + config: Arc::new(S3Config::default()), + customized_credential_load: Some(CustomAwsCredentialLoader::new( + reqsign_aws_v4::StaticCredentialProvider::new("access-key", "secret-key"), + )), + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + }; + + let key = storage + .delete_batch_key_for_path("s3://bucket/table-a/file.parquet") + .await + .unwrap(); + assert_eq!(key.credential_scope, DeleteCredentialScope::Static); + } + + #[cfg(feature = "opendal-s3")] + #[test] + fn test_s3_rejects_anonymous_dynamic_credentials() { + let mut config = S3Config::default(); + config.skip_signature = true; + let storage = OpenDalStorage::S3 { + config: Arc::new(config), + customized_credential_load: None, + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + }; + + let error = storage + .create_operator(&"s3://bucket/file.parquet") + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::DataInvalid); + } + + #[cfg(feature = "opendal-gcs")] + #[test] + fn test_gcs_rejects_anonymous_dynamic_credentials() { + let mut config = GcsConfig::default(); + config.skip_signature = true; + let storage = OpenDalStorage::Gcs { + config: Arc::new(config), + credential_provider: Some(Arc::new(AlwaysSupportedCredentialProvider)), + }; + + let error = storage + .create_operator(&"gs://bucket/file.parquet") + .unwrap_err(); + assert_eq!(error.kind(), ErrorKind::DataInvalid); + } + #[cfg(feature = "opendal-gcs")] #[test] fn test_relativize_path_gcs() { let storage = OpenDalStorage::Gcs { config: Arc::new(GcsConfig::default()), + credential_provider: None, }; - assert_eq!( - storage - .relativize_path("gs://my-bucket/path/to/file.parquet") - .unwrap(), - "path/to/file.parquet" - ); + for scheme in ["gs", "gcs"] { + let path = format!("{scheme}://my-bucket/path/to/file.parquet"); + assert_eq!( + storage.relativize_path(&path).unwrap(), + "path/to/file.parquet" + ); + let (_, relative) = storage.create_operator(&path).unwrap(); + assert_eq!(relative, "path/to/file.parquet"); + } } #[cfg(feature = "opendal-gcs")] @@ -712,6 +988,7 @@ mod tests { fn test_relativize_path_gcs_invalid_scheme() { let storage = OpenDalStorage::Gcs { config: Arc::new(GcsConfig::default()), + credential_provider: None, }; assert!( @@ -719,6 +996,11 @@ mod tests { .relativize_path("s3://my-bucket/path/to/file.parquet") .is_err() ); + assert!( + storage + .create_operator(&"s3://my-bucket/path/to/file.parquet") + .is_err() + ); } #[cfg(feature = "opendal-oss")] diff --git a/crates/storage/opendal/src/resolving.rs b/crates/storage/opendal/src/resolving.rs index 86993220a8..05194bb292 100644 --- a/crates/storage/opendal/src/resolving.rs +++ b/crates/storage/opendal/src/resolving.rs @@ -27,7 +27,7 @@ use futures::StreamExt; use futures::stream::BoxStream; use iceberg::io::{ FileMetadata, FileRead, FileWrite, InputFile, OutputFile, Storage, StorageConfig, - StorageFactory, + StorageCredentialProvider, StorageFactory, }; use iceberg::{Error, ErrorKind, Result}; use serde::{Deserialize, Serialize}; @@ -80,11 +80,25 @@ fn extract_scheme(path: &str) -> Result<&'static str> { parse_scheme(url.scheme()) } +#[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] +fn supports_dynamic_credentials(scheme: &str) -> bool { + match scheme { + #[cfg(feature = "opendal-s3")] + "s3" => true, + #[cfg(feature = "opendal-gcs")] + "gcs" => true, + _ => false, + } +} + /// Build an [`OpenDalStorage`] variant for the given scheme and config properties. fn build_storage_for_scheme( scheme: &'static str, props: &HashMap, #[cfg(feature = "opendal-s3")] customized_credential_load: &Option, + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] credential_provider: &Option< + Arc, + >, ) -> Result { match scheme { #[cfg(feature = "opendal-s3")] @@ -93,6 +107,7 @@ fn build_storage_for_scheme( Ok(OpenDalStorage::S3 { config: Arc::new(config), customized_credential_load: customized_credential_load.clone(), + credential_provider: credential_provider.clone(), }) } #[cfg(feature = "opendal-gcs")] @@ -100,6 +115,7 @@ fn build_storage_for_scheme( let config = crate::gcs::gcs_config_parse(props.clone())?; Ok(OpenDalStorage::Gcs { config: Arc::new(config), + credential_provider: credential_provider.clone(), }) } #[cfg(feature = "opendal-oss")] @@ -186,11 +202,30 @@ impl OpenDalResolvingStorageFactory { #[typetag::serde] impl StorageFactory for OpenDalResolvingStorageFactory { fn build(&self, config: &StorageConfig) -> Result> { + self.build_with_credentials(config, None) + } + + #[allow(unused_variables)] + fn build_with_credentials( + &self, + config: &StorageConfig, + credential_provider: Option>, + ) -> Result> { + #[cfg(not(any(feature = "opendal-s3", feature = "opendal-gcs")))] + if credential_provider.is_some() { + return Err(Error::new( + ErrorKind::FeatureUnsupported, + "OpenDAL resolving storage does not support refreshable credentials because no compatible backend is enabled", + )); + } + Ok(Arc::new(OpenDalResolvingStorage { props: config.props().clone(), storages: RwLock::new(HashMap::new()), #[cfg(feature = "opendal-s3")] customized_credential_load: self.customized_credential_load.clone(), + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + credential_provider, })) } } @@ -201,7 +236,7 @@ impl StorageFactory for OpenDalResolvingStorageFactory { /// Sub-storages are lazily created on first use for each scheme and cached /// for subsequent operations. Scheme aliases like `s3`/`s3a`/`s3n` map to /// the same canonical scheme, so they share a storage instance. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Serialize, Deserialize)] pub struct OpenDalResolvingStorage { /// Configuration properties shared across all backends. props: HashMap, @@ -212,6 +247,20 @@ pub struct OpenDalResolvingStorage { #[cfg(feature = "opendal-s3")] #[serde(skip)] customized_credential_load: Option, + /// Provider of refreshable vended credentials. + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + #[serde(skip)] + credential_provider: Option>, +} + +impl std::fmt::Debug for OpenDalResolvingStorage { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // `props` can contain storage secrets, and a custom credential provider + // may carry secret state in its own Debug implementation + f.debug_struct("OpenDalResolvingStorage") + .field("property_keys", &self.props.keys().collect::>()) + .finish_non_exhaustive() + } } impl OpenDalResolvingStorage { @@ -220,6 +269,21 @@ impl OpenDalResolvingStorage { fn resolve(&self, path: &str) -> Result> { let scheme = extract_scheme(path)?; + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + if self + .credential_provider + .as_ref() + .is_some_and(|provider| provider.supports_path(path)) + && !supports_dynamic_credentials(scheme) + { + return Err(Error::new( + ErrorKind::FeatureUnsupported, + format!( + "OpenDAL resolving storage does not support refreshable credentials for scheme: {scheme}" + ), + )); + } + // Fast path: check read lock first. { let cache = self @@ -247,6 +311,8 @@ impl OpenDalResolvingStorage { &self.props, #[cfg(feature = "opendal-s3")] &self.customized_credential_load, + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + &self.credential_provider, )?; let storage = Arc::new(storage); cache.insert(scheme, storage.clone()); @@ -326,14 +392,44 @@ impl Storage for OpenDalResolvingStorage { mod tests { use super::*; + #[derive(Debug)] + struct AllPathsCredentialProvider; + + #[async_trait] + impl StorageCredentialProvider for AllPathsCredentialProvider { + async fn load_credential(&self, _path: &str) -> Result { + unreachable!("unsupported backends must reject the provider before loading") + } + } + + #[cfg(not(any(feature = "opendal-s3", feature = "opendal-gcs")))] + #[test] + fn test_factory_rejects_credentials_without_compatible_backend() { + let error = OpenDalResolvingStorageFactory::new() + .build_with_credentials( + &StorageConfig::new(), + Some(Arc::new(AllPathsCredentialProvider)), + ) + .expect_err("a provider must not be silently discarded"); + + assert_eq!(error.kind(), ErrorKind::FeatureUnsupported); + } + /// Builds a resolving storage with empty props, suitable for `resolve()` /// calls that don't actually hit any backend. + #[cfg(any( + feature = "opendal-s3", + feature = "opendal-gcs", + feature = "opendal-azdls" + ))] fn empty_resolving_storage() -> OpenDalResolvingStorage { OpenDalResolvingStorage { props: HashMap::new(), storages: RwLock::new(HashMap::new()), #[cfg(feature = "opendal-s3")] customized_credential_load: None, + #[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] + credential_provider: None, } } @@ -353,6 +449,21 @@ mod tests { assert!(Arc::ptr_eq(&a, &c), "s3 and s3n should share one instance"); } + #[cfg(all( + feature = "opendal-memory", + any(feature = "opendal-s3", feature = "opendal-gcs") + ))] + #[test] + fn test_resolver_rejects_credentials_for_unsupported_backend() { + let mut storage = empty_resolving_storage(); + storage.credential_provider = Some(Arc::new(AllPathsCredentialProvider)); + + let error = storage + .resolve("memory:/key") + .expect_err("memory must reject a credential provider"); + assert_eq!(error.kind(), ErrorKind::FeatureUnsupported); + } + #[cfg(feature = "opendal-azdls")] #[test] fn test_resolve_azdls_aliases_share_instance() { diff --git a/crates/storage/opendal/src/s3.rs b/crates/storage/opendal/src/s3.rs index 2997fa81d9..e06bcdefdf 100644 --- a/crates/storage/opendal/src/s3.rs +++ b/crates/storage/opendal/src/s3.rs @@ -22,7 +22,8 @@ use iceberg::io::{ CLIENT_REGION, S3_ACCESS_KEY_ID, S3_ALLOW_ANONYMOUS, S3_ASSUME_ROLE_ARN, S3_ASSUME_ROLE_EXTERNAL_ID, S3_ASSUME_ROLE_SESSION_NAME, S3_DISABLE_CONFIG_LOAD, S3_DISABLE_EC2_METADATA, S3_ENDPOINT, S3_PATH_STYLE_ACCESS, S3_REGION, S3_SECRET_ACCESS_KEY, - S3_SESSION_TOKEN, S3_SSE_KEY, S3_SSE_MD5, S3_SSE_TYPE, + S3_SESSION_TOKEN, S3_SSE_KEY, S3_SSE_MD5, S3_SSE_TYPE, StorageCredentialKind, + StorageCredentialProvider, }; use iceberg::{Error, ErrorKind, Result}; use opendal::services::S3Config; @@ -31,10 +32,16 @@ use opendal::{Configurator, Operator}; pub use reqsign_aws_v4::Credential as AwsCredential; /// Trait for types that can asynchronously supply [`AwsCredential`] to a [`CustomAwsCredentialLoader`]. pub use reqsign_core::ProvideCredential; -use reqsign_core::{ProvideCredentialChain, ProvideCredentialDyn}; +use reqsign_core::{ + Context, Error as ReqsignError, ProvideCredentialChain, ProvideCredentialDyn, + Result as ReqsignResult, +}; use url::Url; -use crate::utils::{from_opendal_error, is_truthy}; +use crate::DynamicCredentialScope; +use crate::utils::{ + from_opendal_error, is_truthy, system_time_to_timestamp, validate_credential_prefix, +}; /// Parse iceberg props to s3 config. pub(crate) fn s3_config_parse(mut m: HashMap) -> Result { @@ -129,7 +136,9 @@ pub(crate) fn s3_config_parse(mut m: HashMap) -> Result, + credential_provider: &Option>, path: &str, + credential_scope: Option<&DynamicCredentialScope>, ) -> Result { let url = Url::parse(path)?; let bucket = url.host_str().ok_or_else(|| { @@ -139,6 +148,19 @@ pub(crate) fn s3_config_build( ) })?; + // Preserve the existing custom-loader precedence: an explicitly configured loader + // is the sole source, otherwise install the catalog provider as a replacement chain so + // refresh failures cannot fall through to broader ambient AWS credentials. + let credential_provider = credential_provider + .as_ref() + .filter(|provider| provider.supports_path(path)); + if customized_credential_load.is_none() && credential_provider.is_some() && cfg.skip_signature { + return Err(Error::new( + ErrorKind::DataInvalid, + "Invalid S3 auth settings: anonymous access cannot be combined with refreshable credentials", + )); + } + let mut builder = cfg .clone() .into_builder() @@ -148,11 +170,97 @@ pub(crate) fn s3_config_build( if let Some(loader) = customized_credential_load { let chain = ProvideCredentialChain::new().push(Arc::clone(&loader.0)); builder = builder.credential_provider_chain(chain); + } else if let Some(provider) = credential_provider { + let chain = ProvideCredentialChain::new().push(VendedS3CredentialProvider::new( + Arc::clone(provider), + path.to_string(), + credential_scope.cloned(), + )); + builder = builder.credential_provider_chain(chain); } Operator::new(builder).map_err(from_opendal_error) } +/// Adapts a generic [`StorageCredentialProvider`] into a reqsign +/// [`ProvideCredential`], so the S3 signer can obtain and refresh vended +/// credentials. +struct VendedS3CredentialProvider { + provider: Arc, + /// Absolute path this operator serves; handed back to the provider so it can + /// select the vended credential whose prefix best matches the location. + path: String, + /// Exact scope selected when a bulk-delete operator was created. Ordinary + /// operators are unbound so they can follow the provider's best match. + credential_scope: Option, +} + +impl std::fmt::Debug for VendedS3CredentialProvider { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VendedS3CredentialProvider") + .field("path", &self.path) + .field("credential_scope", &self.credential_scope) + .finish_non_exhaustive() + } +} + +impl VendedS3CredentialProvider { + fn new( + provider: Arc, + path: String, + credential_scope: Option, + ) -> Self { + Self { + provider, + path, + credential_scope, + } + } +} + +impl ProvideCredential for VendedS3CredentialProvider { + type Credential = AwsCredential; + + async fn provide_credential(&self, _ctx: &Context) -> ReqsignResult> { + let credential = self + .provider + .load_credential(&self.path) + .await + .map_err(|e| { + ReqsignError::unexpected(format!( + "failed to load vended S3 credential for {}", + self.path + )) + .with_source(e) + })?; + + validate_credential_prefix( + &self.path, + credential.prefix(), + self.credential_scope.as_ref(), + )?; + + let expires_in = credential + .expires_at() + .map(system_time_to_timestamp) + .transpose()?; + match credential.into_kind() { + StorageCredentialKind::S3(s3) => { + let (access_key_id, secret_access_key, session_token) = s3.into_parts(); + Ok(Some(AwsCredential { + access_key_id, + secret_access_key, + session_token, + expires_in, + })) + } + _ => Err(ReqsignError::unexpected( + "S3 storage received a non-S3 credential from the provider", + )), + } + } +} + /// Custom AWS credential loader. /// /// Wraps any [`ProvideCredential`] implementation for use with the S3 storage backend. @@ -176,7 +284,7 @@ impl std::fmt::Debug for CustomAwsCredentialLoader { impl CustomAwsCredentialLoader { /// Create a new custom AWS credential loader from any [`ProvideCredential`] implementation. pub fn new(provider: impl ProvideCredential + 'static) -> Self { - Self(Arc::new(provider) as Arc>) + Self(Arc::new(provider)) } } @@ -184,9 +292,44 @@ impl CustomAwsCredentialLoader { mod tests { use std::collections::HashMap; - use iceberg::io::S3_PATH_STYLE_ACCESS; + use async_trait::async_trait; + use iceberg::io::{S3_PATH_STYLE_ACCESS, S3Credential, StorageCredential}; + + use super::*; + + #[derive(Debug)] + struct FixedCredentialProvider(StorageCredential); - use super::s3_config_parse; + #[async_trait] + impl StorageCredentialProvider for FixedCredentialProvider { + async fn load_credential(&self, _path: &str) -> Result { + Ok(self.0.clone()) + } + } + + fn credential(prefix: Option<&str>) -> StorageCredential { + let credential = StorageCredential::new(StorageCredentialKind::S3(S3Credential::new( + "access-key", + "secret-key", + Some("session-token".to_string()), + ))); + match prefix { + Some(prefix) => credential.with_prefix(prefix), + None => credential, + } + } + + fn provider( + path: &str, + returned_prefix: Option<&str>, + credential_scope: Option, + ) -> VendedS3CredentialProvider { + VendedS3CredentialProvider::new( + Arc::new(FixedCredentialProvider(credential(returned_prefix))), + path.to_string(), + credential_scope, + ) + } fn parse_with(prop: Option<&str>) -> bool { let mut props = HashMap::new(); @@ -203,4 +346,53 @@ mod tests { assert!(parse_with(Some("false"))); assert!(!parse_with(Some("true"))); } + + #[tokio::test] + async fn vended_provider_enforces_bound_credential_scope() { + let path = "s3://bucket/table/file.parquet"; + let table_prefix = "s3://bucket/table"; + + assert!( + provider( + path, + Some(table_prefix), + Some(DynamicCredentialScope::Prefix(table_prefix.to_string())), + ) + .provide_credential(&Context::default()) + .await + .is_ok() + ); + assert!( + provider( + path, + Some("s3://bucket"), + Some(DynamicCredentialScope::Prefix(table_prefix.to_string())), + ) + .provide_credential(&Context::default()) + .await + .is_err() + ); + assert!( + provider(path, Some("s3://bucket"), None) + .provide_credential(&Context::default()) + .await + .is_ok() + ); + assert!( + provider(path, None, Some(DynamicCredentialScope::Unscoped)) + .provide_credential(&Context::default()) + .await + .is_ok() + ); + assert!( + provider( + path, + Some(table_prefix), + Some(DynamicCredentialScope::Unscoped), + ) + .provide_credential(&Context::default()) + .await + .is_err() + ); + } } diff --git a/crates/storage/opendal/src/utils.rs b/crates/storage/opendal/src/utils.rs index 56f8c18059..ddb4f08b2d 100644 --- a/crates/storage/opendal/src/utils.rs +++ b/crates/storage/opendal/src/utils.rs @@ -15,6 +15,9 @@ // specific language governing permissions and limitations // under the License. +#[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] +use crate::DynamicCredentialScope; + pub(crate) fn is_truthy(value: &str) -> bool { ["true", "t", "1", "on"].contains(&value.to_lowercase().as_str()) } @@ -27,3 +30,56 @@ pub(crate) fn from_opendal_error(e: opendal::Error) -> iceberg::Error { ) .with_source(e) } + +/// Convert a [`SystemTime`](std::time::SystemTime) credential expiry into the +/// `reqsign` [`Timestamp`](reqsign_core::time::Timestamp) used on backend +/// credential types (e.g. `AwsCredential::expires_in`, `google::Token::expires_at`). +#[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] +pub(crate) fn system_time_to_timestamp( + time: std::time::SystemTime, +) -> reqsign_core::Result { + let millis = time + .duration_since(std::time::UNIX_EPOCH) + .map_err(|e| { + reqsign_core::Error::unexpected(format!( + "credential expiry precedes the UNIX epoch: {e}" + )) + })? + .as_millis(); + let millis = i64::try_from(millis).map_err(|_| { + reqsign_core::Error::unexpected("credential expiry overflows i64 milliseconds") + })?; + reqsign_core::time::Timestamp::from_millisecond(millis) + .map_err(|e| reqsign_core::Error::unexpected(format!("invalid credential expiry: {e}"))) +} + +/// Validate that a provider's declared credential prefix covers the path for +/// which the backend requested the credential. +#[cfg(any(feature = "opendal-s3", feature = "opendal-gcs"))] +pub(crate) fn validate_credential_prefix( + path: &str, + prefix: Option<&str>, + credential_scope: Option<&DynamicCredentialScope>, +) -> reqsign_core::Result<()> { + match prefix { + Some("") => Err(reqsign_core::Error::unexpected( + "vended credential has an empty storage prefix", + )), + Some(prefix) if !path.starts_with(prefix) => Err(reqsign_core::Error::unexpected(format!( + "vended credential prefix {prefix:?} does not cover storage location {path:?}" + ))), + _ => match credential_scope { + Some(DynamicCredentialScope::Unscoped) if prefix.is_some() => { + Err(reqsign_core::Error::unexpected( + "vended credential scope changed while a bulk-delete operator was active", + )) + } + Some(DynamicCredentialScope::Prefix(expected)) if prefix != Some(expected.as_str()) => { + Err(reqsign_core::Error::unexpected( + "vended credential scope changed while a bulk-delete operator was active", + )) + } + _ => Ok(()), + }, + } +}