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


##########
crates/catalog/rest/src/auth/sigv4.rs:
##########
@@ -364,8 +371,359 @@ 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 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,
+];
+
+/// `base` with `overrides` on top. Overriding any credential replaces the
+/// base's credentials whole: fields from two sources never form a valid
+/// credential.
+fn overlay_signing(
+    base: &HashMap<String, SensitiveString>,
+    overrides: HashMap<String, String>,
+) -> HashMap<String, String> {
+    let replaces_credentials = CREDENTIAL_PROPERTIES
+        .iter()
+        .any(|key| overrides.contains_key(*key));
+    let mut props: HashMap<_, _> = base
+        .iter()
+        .filter(|(k, _)| !(replaces_credentials && 
CREDENTIAL_PROPERTIES.contains(&k.as_str())))
+        .map(|(k, v)| (k.clone(), v.expose().to_string()))
+        .collect();
+    props.extend(overrides);
+    props
+}
+
+/// The non-blank [`SIGNING_PROPERTIES`] of `props`.
+fn signing_overrides(props: &HashMap<String, String>) -> HashMap<String, 
String> {
+    SIGNING_PROPERTIES
+        .iter()
+        .filter_map(|key| Some((key.to_string(), non_blank(props, key)?)))
+        .collect()
+}
+
+fn sensitive(props: HashMap<String, String>) -> HashMap<String, 
SensitiveString> {
+    props.into_iter().map(|(k, v)| (k, v.into())).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,
+/// blank context values are ignored, and context credentials replace the
+/// catalog's as a set.
+///
+/// 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>,
+    signing: Signing,
+    catalog: OnceLock<SigV4CatalogState>,

Review Comment:
   Removed. The manager is now stateless, so `catalog_session` can run again, 
e.g. after a failed init. `AuthSession` gains an `Any` supertrait for the 
downcast.
   



##########
crates/catalog/rest/src/auth/sigv4.rs:
##########
@@ -364,8 +371,359 @@ 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 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,
+];
+
+/// `base` with `overrides` on top. Overriding any credential replaces the
+/// base's credentials whole: fields from two sources never form a valid
+/// credential.
+fn overlay_signing(
+    base: &HashMap<String, SensitiveString>,
+    overrides: HashMap<String, String>,
+) -> HashMap<String, String> {
+    let replaces_credentials = CREDENTIAL_PROPERTIES
+        .iter()
+        .any(|key| overrides.contains_key(*key));
+    let mut props: HashMap<_, _> = base
+        .iter()
+        .filter(|(k, _)| !(replaces_credentials && 
CREDENTIAL_PROPERTIES.contains(&k.as_str())))
+        .map(|(k, v)| (k.clone(), v.expose().to_string()))
+        .collect();
+    props.extend(overrides);
+    props
+}
+
+/// The non-blank [`SIGNING_PROPERTIES`] of `props`.
+fn signing_overrides(props: &HashMap<String, String>) -> HashMap<String, 
String> {
+    SIGNING_PROPERTIES
+        .iter()
+        .filter_map(|key| Some((key.to_string(), non_blank(props, key)?)))
+        .collect()
+}
+
+fn sensitive(props: HashMap<String, String>) -> HashMap<String, 
SensitiveString> {
+    props.into_iter().map(|(k, v)| (k, v.into())).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,
+/// blank context values are ignored, and context credentials replace the
+/// catalog's as a set.
+///
+/// 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>,
+    signing: Signing,
+    catalog: OnceLock<SigV4CatalogState>,
+}
+
+#[derive(Debug)]
+enum Signing {
+    Injected {
+        signer: SigV4Signer,
+        credentials: SharedCredentialsProvider,
+    },
+    /// The constructor's signing properties, which each session method's
+    /// properties override, as Java rebuilds `AwsProperties` in each.
+    FromProperties(HashMap<String, SensitiveString>),

Review Comment:
   Agreed, decoupled. Catalog and context properties override region and 
signing name; an injected provider is kept and credential properties are 
ignored.
   



-- 
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