CTTY commented on code in PR #3092:
URL: https://github.com/apache/iceberg-rust/pull/3092#discussion_r4702128524


##########
crates/catalog/rest/src/auth/sigv4.rs:
##########
@@ -364,8 +371,305 @@ fn relocate_conflicting(
     }
 }
 
+/// SigV4 signing region.
+pub const REST_CATALOG_PROP_SIGNING_REGION: &str = "rest.signing-region";
+/// SigV4 signing name; defaults to [`SIGNING_NAME_DEFAULT`].
+pub const REST_CATALOG_PROP_SIGNING_NAME: &str = "rest.signing-name";
+/// Static SigV4 access key id. Unlike Java, there is no fallback to the AWS
+/// default provider chain.
+pub const REST_CATALOG_PROP_ACCESS_KEY_ID: &str = "rest.access-key-id";
+/// Static SigV4 secret access key (see [`REST_CATALOG_PROP_ACCESS_KEY_ID`]).
+pub const REST_CATALOG_PROP_SECRET_ACCESS_KEY: &str = "rest.secret-access-key";
+/// Static SigV4 session token (see [`REST_CATALOG_PROP_ACCESS_KEY_ID`]).
+pub const REST_CATALOG_PROP_SESSION_TOKEN: &str = "rest.session-token";
+
+/// Java's `REST_SIGNING_NAME_DEFAULT`: API Gateway and Lambda.
+pub const SIGNING_NAME_DEFAULT: &str = "execute-api";
+
+const SIGNER_PROPERTIES: [&str; 2] = [
+    REST_CATALOG_PROP_SIGNING_REGION,
+    REST_CATALOG_PROP_SIGNING_NAME,
+];
+const CREDENTIAL_PROPERTIES: [&str; 3] = [
+    REST_CATALOG_PROP_ACCESS_KEY_ID,
+    REST_CATALOG_PROP_SECRET_ACCESS_KEY,
+    REST_CATALOG_PROP_SESSION_TOKEN,
+];
+const SIGNING_PROPERTIES: [&str; 5] = [
+    REST_CATALOG_PROP_SIGNING_REGION,
+    REST_CATALOG_PROP_SIGNING_NAME,
+    REST_CATALOG_PROP_ACCESS_KEY_ID,
+    REST_CATALOG_PROP_SECRET_ACCESS_KEY,
+    REST_CATALOG_PROP_SESSION_TOKEN,
+];
+
+/// `signer` and `credentials` with the non-blank signing properties 
`overrides`
+/// on top. Overriding any credential replaces `credentials` whole: fields from
+/// two sources never form a valid credential.
+fn overlay_signing(
+    signer: &SigV4Signer,
+    credentials: &SharedCredentialsProvider,
+    overrides: &HashMap<String, String>,
+) -> Result<(SigV4Signer, SharedCredentialsProvider)> {
+    let signer = SigV4Signer {
+        region: non_blank(overrides, REST_CATALOG_PROP_SIGNING_REGION)
+            .unwrap_or_else(|| signer.region.clone()),
+        service: non_blank(overrides, REST_CATALOG_PROP_SIGNING_NAME)
+            .unwrap_or_else(|| signer.service.clone()),
+        mode: signer.mode,
+    };
+    let replaces_credentials = CREDENTIAL_PROPERTIES
+        .iter()
+        .any(|key| overrides.contains_key(*key));
+    let credentials = if replaces_credentials {
+        credentials_from_props(overrides)?
+    } else {
+        credentials.clone()
+    };
+    Ok((signer, credentials))
+}
+
+/// The non-blank values of `keys` in `props`.
+fn signing_overrides(keys: &[&str], props: &HashMap<String, String>) -> 
HashMap<String, String> {
+    keys.iter()
+        .filter_map(|key| Some((key.to_string(), non_blank(props, key)?)))
+        .collect()
+}
+
+/// Trims a property, treating blank as absent.
+fn non_blank(props: &HashMap<String, String>, key: &str) -> Option<String> {
+    props
+        .get(key)
+        .map(|v| v.trim())
+        .filter(|v| !v.is_empty())
+        .map(str::to_string)
+}
+
+/// Builds a signer and static credentials from Java's `AwsProperties` names.
+fn from_props(props: &HashMap<String, String>) -> Result<(SigV4Signer, 
SharedCredentialsProvider)> {
+    let region = non_blank(props, 
REST_CATALOG_PROP_SIGNING_REGION).ok_or_else(|| {
+        Error::new(
+            ErrorKind::DataInvalid,
+            format!("'{REST_CATALOG_PROP_SIGNING_REGION}' is required for 
SigV4 signing"),
+        )
+    })?;
+    let name = non_blank(props, REST_CATALOG_PROP_SIGNING_NAME)
+        .unwrap_or_else(|| SIGNING_NAME_DEFAULT.into());
+
+    let credentials = credentials_from_props(props)?;
+    Ok((
+        SigV4Signer::builder()
+            .region(region)
+            .service(name)
+            .mode(PayloadHashMode::IcebergRest)
+            .build(),
+        credentials,
+    ))
+}
+
+/// Like Java, branches on the access key id alone; a lone secret is an error.
+fn credentials_from_props(props: &HashMap<String, String>) -> 
Result<SharedCredentialsProvider> {
+    let Some(access_key_id) = non_blank(props, 
REST_CATALOG_PROP_ACCESS_KEY_ID) else {
+        if non_blank(props, REST_CATALOG_PROP_SECRET_ACCESS_KEY).is_some() {
+            return Err(Error::new(
+                ErrorKind::DataInvalid,
+                format!(
+                    "'{REST_CATALOG_PROP_SECRET_ACCESS_KEY}' is set without 
'{REST_CATALOG_PROP_ACCESS_KEY_ID}'"
+                ),
+            ));
+        }
+        return Err(Error::new(
+            ErrorKind::DataInvalid,
+            format!(
+                "no SigV4 credentials: set '{REST_CATALOG_PROP_ACCESS_KEY_ID}' 
and \
+                 '{REST_CATALOG_PROP_SECRET_ACCESS_KEY}', or build the catalog 
with a \
+                 `SigV4AuthManager` carrying your own credentials provider"
+            ),
+        ));
+    };
+    let secret_access_key = non_blank(props, 
REST_CATALOG_PROP_SECRET_ACCESS_KEY).ok_or_else(|| {
+        Error::new(
+            ErrorKind::DataInvalid,
+            format!("'{REST_CATALOG_PROP_ACCESS_KEY_ID}' is set without 
'{REST_CATALOG_PROP_SECRET_ACCESS_KEY}'"),
+        )
+    })?;
+    Ok(SharedCredentialsProvider::new(Credentials::new(
+        access_key_id,
+        secret_access_key,
+        non_blank(props, REST_CATALOG_PROP_SESSION_TOKEN),
+        None,
+        "iceberg-rest-properties",
+    )))
+}
+
+/// [`AuthManager`] that SigV4-signs every request on top of a delegate, as
+/// Java's `RESTSigV4AuthManager` does. The delegate's `Authorization` moves to
+/// `Original-Authorization` and is signed over.
+///
+/// Unlike Java, properties configure static credentials only; pass a provider
+/// to [`Self::new`] for anything else. Context values override catalog ones,
+/// and blank context values are ignored. Context credentials replace the
+/// catalog's as a set, except that a provider passed to [`Self::new`] is kept.
+///
+/// Configure signing-relevant headers as `header.*` properties: an injected
+/// client's default headers are added after signing.
+#[derive(Debug)]
+pub struct SigV4AuthManager {
+    delegate: Arc<dyn AuthManager>,
+    signer: SigV4Signer,
+    credentials: SharedCredentialsProvider,
+    /// The properties that override `signer` and `credentials`.
+    overridable: &'static [&'static str],
+}
+
+impl SigV4AuthManager {
+    /// Signs with `signer` and `credentials`. The signing region and name in
+    /// the properties each session method is given override `signer`'s;
+    /// credentials there are ignored.
+    pub fn new(

Review Comment:
   I'm still a bit confused about the existing API design: why do we need two 
constructors for auth manager? 
   
   I took a look at java's sigv4 manager, and found that the props will come 
from context props. `RESTSigV4AuthManager(String name, AuthManager delegate)` 
takes no properties at all: each of initSession / catalogSession / 
contextualSession builds a fresh `AwsProperties` from the properties it 
receives, and AwsProperties.credentialsProvider resolves static keys → 
client.credentials-provider → default chain. I understand that we have to 
inject credential provider here because we have no reflection in rust, but why 
do we need to pass props?



##########
crates/catalog/rest/src/auth/sigv4.rs:
##########
@@ -364,8 +371,305 @@ fn relocate_conflicting(
     }
 }
 
+/// SigV4 signing region.
+pub const REST_CATALOG_PROP_SIGNING_REGION: &str = "rest.signing-region";
+/// SigV4 signing name; defaults to [`SIGNING_NAME_DEFAULT`].
+pub const REST_CATALOG_PROP_SIGNING_NAME: &str = "rest.signing-name";
+/// Static SigV4 access key id. Unlike Java, there is no fallback to the AWS
+/// default provider chain.
+pub const REST_CATALOG_PROP_ACCESS_KEY_ID: &str = "rest.access-key-id";
+/// Static SigV4 secret access key (see [`REST_CATALOG_PROP_ACCESS_KEY_ID`]).
+pub const REST_CATALOG_PROP_SECRET_ACCESS_KEY: &str = "rest.secret-access-key";
+/// Static SigV4 session token (see [`REST_CATALOG_PROP_ACCESS_KEY_ID`]).
+pub const REST_CATALOG_PROP_SESSION_TOKEN: &str = "rest.session-token";
+
+/// Java's `REST_SIGNING_NAME_DEFAULT`: API Gateway and Lambda.
+pub const SIGNING_NAME_DEFAULT: &str = "execute-api";
+
+const SIGNER_PROPERTIES: [&str; 2] = [
+    REST_CATALOG_PROP_SIGNING_REGION,
+    REST_CATALOG_PROP_SIGNING_NAME,
+];
+const CREDENTIAL_PROPERTIES: [&str; 3] = [
+    REST_CATALOG_PROP_ACCESS_KEY_ID,
+    REST_CATALOG_PROP_SECRET_ACCESS_KEY,
+    REST_CATALOG_PROP_SESSION_TOKEN,
+];
+const SIGNING_PROPERTIES: [&str; 5] = [
+    REST_CATALOG_PROP_SIGNING_REGION,
+    REST_CATALOG_PROP_SIGNING_NAME,
+    REST_CATALOG_PROP_ACCESS_KEY_ID,
+    REST_CATALOG_PROP_SECRET_ACCESS_KEY,
+    REST_CATALOG_PROP_SESSION_TOKEN,
+];
+
+/// `signer` and `credentials` with the non-blank signing properties 
`overrides`
+/// on top. Overriding any credential replaces `credentials` whole: fields from
+/// two sources never form a valid credential.
+fn overlay_signing(
+    signer: &SigV4Signer,
+    credentials: &SharedCredentialsProvider,
+    overrides: &HashMap<String, String>,
+) -> Result<(SigV4Signer, SharedCredentialsProvider)> {
+    let signer = SigV4Signer {
+        region: non_blank(overrides, REST_CATALOG_PROP_SIGNING_REGION)
+            .unwrap_or_else(|| signer.region.clone()),
+        service: non_blank(overrides, REST_CATALOG_PROP_SIGNING_NAME)
+            .unwrap_or_else(|| signer.service.clone()),
+        mode: signer.mode,
+    };
+    let replaces_credentials = CREDENTIAL_PROPERTIES
+        .iter()
+        .any(|key| overrides.contains_key(*key));
+    let credentials = if replaces_credentials {
+        credentials_from_props(overrides)?
+    } else {
+        credentials.clone()
+    };
+    Ok((signer, credentials))
+}
+
+/// The non-blank values of `keys` in `props`.
+fn signing_overrides(keys: &[&str], props: &HashMap<String, String>) -> 
HashMap<String, String> {
+    keys.iter()
+        .filter_map(|key| Some((key.to_string(), non_blank(props, key)?)))
+        .collect()
+}
+
+/// Trims a property, treating blank as absent.
+fn non_blank(props: &HashMap<String, String>, key: &str) -> Option<String> {
+    props
+        .get(key)
+        .map(|v| v.trim())
+        .filter(|v| !v.is_empty())
+        .map(str::to_string)
+}
+
+/// Builds a signer and static credentials from Java's `AwsProperties` names.
+fn from_props(props: &HashMap<String, String>) -> Result<(SigV4Signer, 
SharedCredentialsProvider)> {
+    let region = non_blank(props, 
REST_CATALOG_PROP_SIGNING_REGION).ok_or_else(|| {
+        Error::new(
+            ErrorKind::DataInvalid,
+            format!("'{REST_CATALOG_PROP_SIGNING_REGION}' is required for 
SigV4 signing"),
+        )
+    })?;
+    let name = non_blank(props, REST_CATALOG_PROP_SIGNING_NAME)
+        .unwrap_or_else(|| SIGNING_NAME_DEFAULT.into());
+
+    let credentials = credentials_from_props(props)?;
+    Ok((
+        SigV4Signer::builder()
+            .region(region)
+            .service(name)
+            .mode(PayloadHashMode::IcebergRest)
+            .build(),
+        credentials,
+    ))
+}
+
+/// Like Java, branches on the access key id alone; a lone secret is an error.
+fn credentials_from_props(props: &HashMap<String, String>) -> 
Result<SharedCredentialsProvider> {
+    let Some(access_key_id) = non_blank(props, 
REST_CATALOG_PROP_ACCESS_KEY_ID) else {
+        if non_blank(props, REST_CATALOG_PROP_SECRET_ACCESS_KEY).is_some() {
+            return Err(Error::new(
+                ErrorKind::DataInvalid,
+                format!(
+                    "'{REST_CATALOG_PROP_SECRET_ACCESS_KEY}' is set without 
'{REST_CATALOG_PROP_ACCESS_KEY_ID}'"
+                ),
+            ));
+        }
+        return Err(Error::new(
+            ErrorKind::DataInvalid,
+            format!(
+                "no SigV4 credentials: set '{REST_CATALOG_PROP_ACCESS_KEY_ID}' 
and \
+                 '{REST_CATALOG_PROP_SECRET_ACCESS_KEY}', or build the catalog 
with a \
+                 `SigV4AuthManager` carrying your own credentials provider"
+            ),
+        ));
+    };
+    let secret_access_key = non_blank(props, 
REST_CATALOG_PROP_SECRET_ACCESS_KEY).ok_or_else(|| {
+        Error::new(
+            ErrorKind::DataInvalid,
+            format!("'{REST_CATALOG_PROP_ACCESS_KEY_ID}' is set without 
'{REST_CATALOG_PROP_SECRET_ACCESS_KEY}'"),
+        )
+    })?;
+    Ok(SharedCredentialsProvider::new(Credentials::new(
+        access_key_id,
+        secret_access_key,
+        non_blank(props, REST_CATALOG_PROP_SESSION_TOKEN),
+        None,
+        "iceberg-rest-properties",
+    )))
+}
+
+/// [`AuthManager`] that SigV4-signs every request on top of a delegate, as
+/// Java's `RESTSigV4AuthManager` does. The delegate's `Authorization` moves to
+/// `Original-Authorization` and is signed over.
+///
+/// Unlike Java, properties configure static credentials only; pass a provider
+/// to [`Self::new`] for anything else. Context values override catalog ones,
+/// and blank context values are ignored. Context credentials replace the
+/// catalog's as a set, except that a provider passed to [`Self::new`] is kept.
+///
+/// Configure signing-relevant headers as `header.*` properties: an injected
+/// client's default headers are added after signing.
+#[derive(Debug)]
+pub struct SigV4AuthManager {
+    delegate: Arc<dyn AuthManager>,
+    signer: SigV4Signer,
+    credentials: SharedCredentialsProvider,
+    /// The properties that override `signer` and `credentials`.
+    overridable: &'static [&'static str],
+}
+
+impl SigV4AuthManager {
+    /// Signs with `signer` and `credentials`. The signing region and name in
+    /// the properties each session method is given override `signer`'s;
+    /// credentials there are ignored.
+    pub fn new(
+        delegate: Arc<dyn AuthManager>,
+        signer: SigV4Signer,
+        credentials: SharedCredentialsProvider,
+    ) -> Self {
+        Self {
+            delegate,
+            signer,
+            credentials,
+            overridable: &SIGNER_PROPERTIES,
+        }
+    }
+
+    /// Signs as `props` describe. The properties each session method is given
+    /// override them, so `/v1/config` overrides apply.
+    ///
+    /// # Errors
+    ///
+    /// Returns [`ErrorKind::DataInvalid`] if `props` lack a signing region or
+    /// a complete static credential pair.
+    pub fn from_properties(

Review Comment:
   I wonder if we could simplify this further by following Java's manager 
construction model more closely.
   
   `RESTSigV4AuthManager` does not take any signing properties in its 
constructor. Instead, it resolves the signing configuration when creating each 
session.
   
   Since our session methods already receive properties, do we need to 
construct and store a `SigV4Signer` in the manager at all? What about an API 
like this?
   
   ```rust
   impl SigV4AuthManager {
       pub fn new(delegate: Arc<dyn AuthManager>) -> Self;
   
       pub fn with_credentials_provider(
           self,
           provider: SharedCredentialsProvider,
       ) -> Self;
   
       pub fn with_payload_hash_mode(
           self,
           mode: PayloadHashMode,
       ) -> Self;
   }
   ```
   
   The manager would resolve the region, signing name, and credentials provider 
at session creation time. An injected credentials provider could serve as the 
equivalent of Java's `client.credentials-provider`, with explicit static 
credentials taking precedence.
   
   For contextual sessions, we could keep the current parent-session 
inheritance model, allowing region/name overrides and replacing credentials as 
a complete set when provided.
   
   This would remove the need for `from_properties`, the preconfigured signer, 
and the `overridable` field. More importantly, it would give us a single 
configuration resolution model regardless of how the manager is constructed.
   
   Is there a use case that requires resolving signing properties at manager 
construction time rather than session creation time?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to