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


##########
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:
   Thanks, this is a nice simplification. I don't see a use case for resolving 
at construction time: the catalog builds its auth manager lazily on the first 
request, so a config error surfaces at the same point either way. I've switched 
to this API in 9a870168. One note: static credentials now take precedence over 
an injected provider, which reverses what I said in my earlier reply. Could you 
take another look when you have 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