blackmwk commented on code in PR #2339:
URL: https://github.com/apache/iceberg-rust/pull/2339#discussion_r3136164218


##########
crates/iceberg/src/encryption/kms/memory.rs:
##########
@@ -0,0 +1,292 @@
+// 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.
+
+//! In-memory KMS implementation for testing and development.
+//!
+//! **WARNING**: This implementation is NOT suitable for production use.
+//! Keys are stored in memory only and will be lost when the process exits.
+
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, PoisonError, RwLock};
+
+use async_trait::async_trait;
+
+use super::KeyManagementClient;
+use crate::encryption::{AesGcmCipher, AesKeySize, SecureKey, SensitiveBytes};
+use crate::{Error, ErrorKind, Result};
+
+fn lock_error<T>(e: PoisonError<T>) -> Error {

Review Comment:
   This should be moved to error module.



##########
crates/iceberg/src/encryption/kms/memory.rs:
##########
@@ -0,0 +1,292 @@
+// 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.
+
+//! In-memory KMS implementation for testing and development.
+//!
+//! **WARNING**: This implementation is NOT suitable for production use.
+//! Keys are stored in memory only and will be lost when the process exits.
+
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, PoisonError, RwLock};
+
+use async_trait::async_trait;
+
+use super::KeyManagementClient;
+use crate::encryption::{AesGcmCipher, AesKeySize, SecureKey, SensitiveBytes};
+use crate::{Error, ErrorKind, Result};
+
+fn lock_error<T>(e: PoisonError<T>) -> Error {
+    Error::new(ErrorKind::Unexpected, format!("Lock poisoned: {e}"))
+}
+
+/// In-memory KMS for testing. Not suitable for production use.
+///
+/// ```
+/// use iceberg::encryption::KeyManagementClient;
+/// use iceberg::encryption::kms::MemoryKeyManagementClient;
+///
+/// # async fn example() -> iceberg::Result<()> {
+/// let kms = MemoryKeyManagementClient::new();
+/// kms.add_master_key("my-master-key")?;
+///
+/// let dek = vec![0u8; 16];
+/// let wrapped = kms.wrap_key(&dek, "my-master-key").await?;
+/// let unwrapped = kms.unwrap_key(&wrapped, "my-master-key").await?;
+/// assert_eq!(dek.as_slice(), unwrapped.as_bytes());
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Clone, Default)]
+pub struct MemoryKeyManagementClient {
+    master_keys: Arc<RwLock<HashMap<String, SensitiveBytes>>>,
+    master_key_size: AesKeySize,
+}
+
+impl fmt::Debug for MemoryKeyManagementClient {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("MemoryKeyManagementClient")
+            .field("master_key_size", &self.master_key_size)
+            .field("key_count", &self.key_count())
+            .finish()
+    }
+}
+
+impl MemoryKeyManagementClient {
+    /// Creates a new in-memory KMS with 128-bit AES keys.
+    pub fn new() -> Self {
+        Self {
+            master_keys: Arc::new(RwLock::new(HashMap::new())),
+            master_key_size: AesKeySize::Bits128,
+        }
+    }
+
+    /// Creates a new in-memory KMS with the specified master key size.
+    pub fn with_master_key_size(master_key_size: AesKeySize) -> Self {
+        Self {
+            master_keys: Arc::new(RwLock::new(HashMap::new())),
+            master_key_size,
+        }
+    }
+
+    /// Adds a randomly generated master key with the given ID.
+    pub fn add_master_key(&self, key_id: impl Into<String>) -> Result<()> {
+        let key = SecureKey::generate(self.master_key_size);
+        self.insert_key(key_id.into(), SensitiveBytes::new(key.as_bytes()))
+    }
+
+    /// Adds a master key with explicit key bytes.
+    ///
+    /// Use this to seed the KMS with known key material, e.g. for
+    /// cross-language integration tests where both Java and Rust must
+    /// share the same master key bytes.
+    pub fn add_master_key_bytes(&self, key_id: impl Into<String>, key_bytes: 
&[u8]) -> Result<()> {
+        let _ = SecureKey::new(key_bytes)?;

Review Comment:
   Why we need this?



##########
crates/iceberg/src/encryption/kms/client.rs:
##########
@@ -0,0 +1,100 @@
+// 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.
+
+//! Key management client trait for encryption key operations.
+//!
+//! Mirrors the Java `KeyManagementClient` interface from the Apache Iceberg 
spec.
+
+use std::sync::Arc;
+
+use async_trait::async_trait;
+
+use crate::Result;
+use crate::encryption::SensitiveBytes;
+
+/// Result of a server-side key generation operation.
+///
+/// Returned by [`KeyManagementClient::generate_key`] when the KMS supports
+/// atomic key generation and wrapping.
+pub struct GeneratedKey {
+    key: SensitiveBytes,
+    wrapped_key: Vec<u8>,
+}
+
+impl GeneratedKey {
+    /// Creates a new `GeneratedKey` from plaintext key bytes and wrapped key 
bytes.
+    pub fn new(key: SensitiveBytes, wrapped_key: Vec<u8>) -> Self {
+        Self { key, wrapped_key }
+    }
+
+    /// Returns the plaintext key bytes. Zeroized on drop, redacted in Debug.
+    pub fn key(&self) -> &SensitiveBytes {
+        &self.key
+    }
+
+    /// Returns the wrapped (encrypted) key bytes.
+    pub fn wrapped_key(&self) -> &[u8] {
+        &self.wrapped_key
+    }
+}
+
+/// Pluggable interface for key management systems (AWS KMS, Azure Key Vault, 
etc.).
+#[async_trait]
+pub trait KeyManagementClient: Send + Sync + std::fmt::Debug {
+    /// Wrap (encrypt) a key using a wrapping key managed by the KMS.
+    async fn wrap_key(&self, key: &[u8], wrapping_key_id: &str) -> 
Result<Vec<u8>>;
+
+    /// Unwrap (decrypt) a previously wrapped key.
+    async fn unwrap_key(&self, wrapped_key: &[u8], wrapping_key_id: &str)
+    -> Result<SensitiveBytes>;
+
+    /// Whether this KMS supports server-side key generation.
+    ///
+    /// If `true`, callers can use [`generate_key`](Self::generate_key) for 
atomic
+    /// key generation and wrapping, which is more secure than generating a key
+    /// locally and then wrapping it.
+    fn supports_key_generation(&self) -> bool;
+
+    /// Generate a new key and wrap it atomically on the server side.
+    ///
+    /// This is only supported when 
[`supports_key_generation`](Self::supports_key_generation)
+    /// returns `true`.
+    async fn generate_key(&self, wrapping_key_id: &str) -> 
Result<GeneratedKey>;
+}
+
+#[async_trait]
+impl KeyManagementClient for Arc<dyn KeyManagementClient> {

Review Comment:
   ```suggestion
   impl<T: AsRef<KeyManagementClient>> KeyManagementClient for T {
   ```



##########
crates/iceberg/src/encryption/kms/memory.rs:
##########
@@ -0,0 +1,292 @@
+// 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.
+
+//! In-memory KMS implementation for testing and development.
+//!
+//! **WARNING**: This implementation is NOT suitable for production use.
+//! Keys are stored in memory only and will be lost when the process exits.
+
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, PoisonError, RwLock};
+
+use async_trait::async_trait;
+
+use super::KeyManagementClient;
+use crate::encryption::{AesGcmCipher, AesKeySize, SecureKey, SensitiveBytes};
+use crate::{Error, ErrorKind, Result};
+
+fn lock_error<T>(e: PoisonError<T>) -> Error {
+    Error::new(ErrorKind::Unexpected, format!("Lock poisoned: {e}"))
+}
+
+/// In-memory KMS for testing. Not suitable for production use.
+///
+/// ```
+/// use iceberg::encryption::KeyManagementClient;
+/// use iceberg::encryption::kms::MemoryKeyManagementClient;
+///
+/// # async fn example() -> iceberg::Result<()> {
+/// let kms = MemoryKeyManagementClient::new();
+/// kms.add_master_key("my-master-key")?;
+///
+/// let dek = vec![0u8; 16];
+/// let wrapped = kms.wrap_key(&dek, "my-master-key").await?;
+/// let unwrapped = kms.unwrap_key(&wrapped, "my-master-key").await?;
+/// assert_eq!(dek.as_slice(), unwrapped.as_bytes());
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Clone, Default)]
+pub struct MemoryKeyManagementClient {
+    master_keys: Arc<RwLock<HashMap<String, SensitiveBytes>>>,
+    master_key_size: AesKeySize,
+}
+
+impl fmt::Debug for MemoryKeyManagementClient {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("MemoryKeyManagementClient")
+            .field("master_key_size", &self.master_key_size)
+            .field("key_count", &self.key_count())
+            .finish()
+    }
+}
+
+impl MemoryKeyManagementClient {
+    /// Creates a new in-memory KMS with 128-bit AES keys.
+    pub fn new() -> Self {
+        Self {

Review Comment:
   nit: Simply delegating to Default?



##########
crates/iceberg/src/encryption/kms/memory.rs:
##########
@@ -0,0 +1,292 @@
+// 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.
+
+//! In-memory KMS implementation for testing and development.
+//!
+//! **WARNING**: This implementation is NOT suitable for production use.
+//! Keys are stored in memory only and will be lost when the process exits.
+
+use std::collections::HashMap;
+use std::fmt;
+use std::sync::{Arc, PoisonError, RwLock};
+
+use async_trait::async_trait;
+
+use super::KeyManagementClient;
+use crate::encryption::{AesGcmCipher, AesKeySize, SecureKey, SensitiveBytes};
+use crate::{Error, ErrorKind, Result};
+
+fn lock_error<T>(e: PoisonError<T>) -> Error {
+    Error::new(ErrorKind::Unexpected, format!("Lock poisoned: {e}"))
+}
+
+/// In-memory KMS for testing. Not suitable for production use.
+///
+/// ```
+/// use iceberg::encryption::KeyManagementClient;
+/// use iceberg::encryption::kms::MemoryKeyManagementClient;
+///
+/// # async fn example() -> iceberg::Result<()> {
+/// let kms = MemoryKeyManagementClient::new();
+/// kms.add_master_key("my-master-key")?;
+///
+/// let dek = vec![0u8; 16];
+/// let wrapped = kms.wrap_key(&dek, "my-master-key").await?;
+/// let unwrapped = kms.unwrap_key(&wrapped, "my-master-key").await?;
+/// assert_eq!(dek.as_slice(), unwrapped.as_bytes());
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Clone, Default)]
+pub struct MemoryKeyManagementClient {
+    master_keys: Arc<RwLock<HashMap<String, SensitiveBytes>>>,
+    master_key_size: AesKeySize,
+}
+
+impl fmt::Debug for MemoryKeyManagementClient {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        f.debug_struct("MemoryKeyManagementClient")
+            .field("master_key_size", &self.master_key_size)
+            .field("key_count", &self.key_count())
+            .finish()
+    }
+}
+
+impl MemoryKeyManagementClient {
+    /// Creates a new in-memory KMS with 128-bit AES keys.
+    pub fn new() -> Self {
+        Self {
+            master_keys: Arc::new(RwLock::new(HashMap::new())),
+            master_key_size: AesKeySize::Bits128,
+        }
+    }
+
+    /// Creates a new in-memory KMS with the specified master key size.
+    pub fn with_master_key_size(master_key_size: AesKeySize) -> Self {
+        Self {
+            master_keys: Arc::new(RwLock::new(HashMap::new())),
+            master_key_size,
+        }
+    }
+
+    /// Adds a randomly generated master key with the given ID.
+    pub fn add_master_key(&self, key_id: impl Into<String>) -> Result<()> {
+        let key = SecureKey::generate(self.master_key_size);
+        self.insert_key(key_id.into(), SensitiveBytes::new(key.as_bytes()))
+    }
+
+    /// Adds a master key with explicit key bytes.
+    ///
+    /// Use this to seed the KMS with known key material, e.g. for
+    /// cross-language integration tests where both Java and Rust must
+    /// share the same master key bytes.
+    pub fn add_master_key_bytes(&self, key_id: impl Into<String>, key_bytes: 
&[u8]) -> Result<()> {

Review Comment:
   ```suggestion
       pub fn add_master_key_bytes(&self, key_id: impl Into<String>, key_bytes: 
SensitiveBytes) -> Result<()> {
   ```
   This seems more resonable?



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