adamreeve commented on code in PR #6637:
URL: https://github.com/apache/arrow-rs/pull/6637#discussion_r1988058499


##########
parquet/src/arrow/arrow_reader/mod.rs:
##########
@@ -1788,6 +1855,241 @@ mod tests {
         assert!(col.value(2).is_nan());
     }
 
+    #[test]
+    #[cfg(feature = "encryption")]
+    fn test_non_uniform_encryption_plaintext_footer() {
+        let testdata = arrow::util::test_util::parquet_test_data();
+        let path = 
format!("{testdata}/encrypt_columns_plaintext_footer.parquet.encrypted");
+        let file = File::open(path).unwrap();
+
+        // There is always a footer key even with a plaintext footer,
+        // but this is used for signing the footer.
+        let footer_key = "0123456789012345".as_bytes(); // 128bit/16
+        let column_1_key = "1234567890123450".as_bytes();
+        let column_2_key = "1234567890123451".as_bytes();
+
+        let decryption_properties = 
FileDecryptionProperties::builder(footer_key.to_vec())
+            .with_column_key("double_field", column_1_key.to_vec())
+            .with_column_key("float_field", column_2_key.to_vec())
+            .build()
+            .unwrap();
+
+        verify_encryption_test_file_read(file, decryption_properties);
+    }
+
+    #[test]
+    #[cfg(feature = "encryption")]
+    fn test_non_uniform_encryption_disabled_aad_storage() {
+        let testdata = arrow::util::test_util::parquet_test_data();
+        let path =
+            
format!("{testdata}/encrypt_columns_and_footer_disable_aad_storage.parquet.encrypted");
+        let file = File::open(path.clone()).unwrap();
+
+        let footer_key = "0123456789012345".as_bytes(); // 128bit/16
+        let column_1_key = "1234567890123450".as_bytes();
+        let column_2_key = "1234567890123451".as_bytes();
+
+        // Provided AAD prefix overrides the one stored in the file

Review Comment:
   ```suggestion
           // Can read successfully when providing the correct AAD prefix
   ```



##########
parquet/src/encryption/decrypt.rs:
##########
@@ -0,0 +1,260 @@
+// 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.
+
+use crate::encryption::ciphers::{BlockDecryptor, RingGcmBlockDecryptor};
+use crate::encryption::modules::{create_module_aad, ModuleType};
+use crate::errors::{ParquetError, Result};
+use std::collections::HashMap;
+use std::io::Read;
+use std::sync::Arc;
+
+pub fn read_and_decrypt<T: Read>(
+    decryptor: &Arc<dyn BlockDecryptor>,
+    input: &mut T,
+    aad: &[u8],
+) -> Result<Vec<u8>> {
+    let mut len_bytes = [0; 4];
+    input.read_exact(&mut len_bytes)?;
+    let ciphertext_len = u32::from_le_bytes(len_bytes) as usize;
+    let mut ciphertext = vec![0; 4 + ciphertext_len];
+    input.read_exact(&mut ciphertext[4..])?;
+
+    decryptor.decrypt(&ciphertext, aad.as_ref())
+}
+
+// CryptoContext is a data structure that holds the context required to
+// decrypt parquet modules (data pages, dictionary pages, etc.).
+#[derive(Debug, Clone)]
+pub(crate) struct CryptoContext {
+    pub(crate) row_group_ordinal: usize,
+    pub(crate) column_ordinal: usize,
+    pub(crate) page_ordinal: Option<usize>,
+    pub(crate) dictionary_page: bool,
+    // We have separate data and metadata decryptors because
+    // in GCM CTR mode, the metadata and data pages use
+    // different algorithms.
+    data_decryptor: Arc<dyn BlockDecryptor>,
+    metadata_decryptor: Arc<dyn BlockDecryptor>,
+    file_aad: Vec<u8>,
+}
+
+impl CryptoContext {
+    pub(crate) fn new(
+        row_group_ordinal: usize,
+        column_ordinal: usize,
+        data_decryptor: Arc<dyn BlockDecryptor>,
+        metadata_decryptor: Arc<dyn BlockDecryptor>,
+        file_aad: Vec<u8>,
+    ) -> Self {
+        Self {
+            row_group_ordinal,
+            column_ordinal,
+            page_ordinal: None,
+            dictionary_page: false,
+            data_decryptor,
+            metadata_decryptor,
+            file_aad,
+        }
+    }
+
+    pub(crate) fn with_page_ordinal(&self, page_ordinal: usize) -> Self {
+        Self {
+            row_group_ordinal: self.row_group_ordinal,
+            column_ordinal: self.column_ordinal,
+            page_ordinal: Some(page_ordinal),
+            dictionary_page: false,
+            data_decryptor: self.data_decryptor.clone(),
+            metadata_decryptor: self.metadata_decryptor.clone(),
+            file_aad: self.file_aad.clone(),
+        }
+    }
+
+    pub(crate) fn create_page_header_aad(&self) -> Result<Vec<u8>> {
+        let module_type = if self.dictionary_page {
+            ModuleType::DictionaryPageHeader
+        } else {
+            ModuleType::DataPageHeader
+        };
+
+        create_module_aad(
+            self.file_aad(),
+            module_type,
+            self.row_group_ordinal,
+            self.column_ordinal,
+            self.page_ordinal,
+        )
+    }
+
+    pub(crate) fn create_page_aad(&self) -> Result<Vec<u8>> {
+        let module_type = if self.dictionary_page {
+            ModuleType::DictionaryPage
+        } else {
+            ModuleType::DataPage
+        };
+
+        create_module_aad(
+            self.file_aad(),
+            module_type,
+            self.row_group_ordinal,
+            self.column_ordinal,
+            self.page_ordinal,
+        )
+    }
+
+    pub(crate) fn for_dictionary_page(&self) -> Self {
+        Self {
+            row_group_ordinal: self.row_group_ordinal,
+            column_ordinal: self.column_ordinal,
+            page_ordinal: self.page_ordinal,
+            dictionary_page: true,
+            data_decryptor: self.data_decryptor.clone(),
+            metadata_decryptor: self.metadata_decryptor.clone(),
+            file_aad: self.file_aad.clone(),
+        }
+    }
+
+    pub(crate) fn data_decryptor(&self) -> &Arc<dyn BlockDecryptor> {
+        &self.data_decryptor
+    }
+
+    pub(crate) fn file_aad(&self) -> &Vec<u8> {
+        &self.file_aad
+    }
+}
+
+/// FileDecryptionProperties hold keys and AAD data required to decrypt a 
Parquet file.
+#[derive(Debug, Clone, PartialEq)]
+pub struct FileDecryptionProperties {
+    footer_key: Vec<u8>,
+    column_keys: HashMap<String, Vec<u8>>,
+    pub(crate) aad_prefix: Option<Vec<u8>>,
+}
+
+impl FileDecryptionProperties {
+    /// Returns a new FileDecryptionProperties builder
+    pub fn builder(footer_key: Vec<u8>) -> DecryptionPropertiesBuilder {
+        DecryptionPropertiesBuilder::new(footer_key)
+    }
+}
+
+pub struct DecryptionPropertiesBuilder {
+    footer_key: Vec<u8>,
+    column_keys: HashMap<String, Vec<u8>>,
+    aad_prefix: Option<Vec<u8>>,
+}
+
+impl DecryptionPropertiesBuilder {
+    pub fn new(footer_key: Vec<u8>) -> DecryptionPropertiesBuilder {
+        Self {
+            footer_key,
+            column_keys: HashMap::default(),
+            aad_prefix: None,
+        }
+    }
+
+    pub fn build(self) -> Result<FileDecryptionProperties> {
+        Ok(FileDecryptionProperties {
+            footer_key: self.footer_key,
+            column_keys: self.column_keys,
+            aad_prefix: self.aad_prefix,
+        })
+    }
+
+    pub fn with_aad_prefix(mut self, value: &str) -> Self {

Review Comment:
   I think we should allow the prefix to be arbitrary bytes, ie. `Vec<u8>` 
rather than `&str`. It isn't necessarily a valid UTF-8 string: 
https://github.com/apache/parquet-format/blob/3d8855afba64b2eca8d09828aa59885727efa85c/src/main/thrift/parquet.thrift#L1214



##########
parquet/src/arrow/arrow_reader/mod.rs:
##########
@@ -1788,6 +1855,241 @@ mod tests {
         assert!(col.value(2).is_nan());
     }
 
+    #[test]
+    #[cfg(feature = "encryption")]
+    fn test_non_uniform_encryption_plaintext_footer() {
+        let testdata = arrow::util::test_util::parquet_test_data();
+        let path = 
format!("{testdata}/encrypt_columns_plaintext_footer.parquet.encrypted");
+        let file = File::open(path).unwrap();
+
+        // There is always a footer key even with a plaintext footer,
+        // but this is used for signing the footer.
+        let footer_key = "0123456789012345".as_bytes(); // 128bit/16
+        let column_1_key = "1234567890123450".as_bytes();
+        let column_2_key = "1234567890123451".as_bytes();
+
+        let decryption_properties = 
FileDecryptionProperties::builder(footer_key.to_vec())
+            .with_column_key("double_field", column_1_key.to_vec())
+            .with_column_key("float_field", column_2_key.to_vec())
+            .build()
+            .unwrap();
+
+        verify_encryption_test_file_read(file, decryption_properties);
+    }
+
+    #[test]
+    #[cfg(feature = "encryption")]
+    fn test_non_uniform_encryption_disabled_aad_storage() {
+        let testdata = arrow::util::test_util::parquet_test_data();
+        let path =
+            
format!("{testdata}/encrypt_columns_and_footer_disable_aad_storage.parquet.encrypted");
+        let file = File::open(path.clone()).unwrap();
+
+        let footer_key = "0123456789012345".as_bytes(); // 128bit/16
+        let column_1_key = "1234567890123450".as_bytes();
+        let column_2_key = "1234567890123451".as_bytes();
+
+        // Provided AAD prefix overrides the one stored in the file
+        let decryption_properties = 
FileDecryptionProperties::builder(footer_key.to_vec())
+            .with_column_key("double_field", column_1_key.to_vec())
+            .with_column_key("float_field", column_2_key.to_vec())
+            .with_aad_prefix("tester")
+            .build()
+            .unwrap();
+
+        verify_encryption_test_file_read(file, decryption_properties);
+
+        // Using wrong AAD prefix should fail
+        let decryption_properties = 
FileDecryptionProperties::builder(footer_key.to_vec())
+            .with_column_key("double_field", column_1_key.to_vec())
+            .with_column_key("float_field", column_2_key.to_vec())
+            .with_aad_prefix("wrong_aad_prefix")
+            .build()
+            .unwrap();
+
+        let file = File::open(path.clone()).unwrap();
+        let options = ArrowReaderOptions::default()
+            .with_file_decryption_properties(decryption_properties.clone());
+        let result = ArrowReaderMetadata::load(&file, options.clone());
+        assert!(result.is_err());
+        assert_eq!(
+            result.unwrap_err().to_string(),
+            "Parquet error: Provided footer key and AAD were unable to decrypt 
parquet footer"
+        );
+
+        // Using wrong AAD prefix stored in the file should fail

Review Comment:
   ```suggestion
           // Not providing any AAD prefix should fail as it isn't stored in 
the file
   ```



##########
parquet/src/file/metadata/reader.rs:
##########
@@ -68,6 +76,28 @@ pub struct ParquetMetaDataReader {
     // Size of the serialized thrift metadata plus the 8 byte footer. Only set 
if
     // `self.parse_metadata` is called.
     metadata_size: Option<usize>,
+    #[cfg(feature = "encryption")]
+    file_decryption_properties: Option<FileDecryptionProperties>,
+}
+
+/// Describes how the footer metadata is stored
+///
+/// This is parsed from the last 8 bytes of the Parquet file
+pub struct FooterTail {
+    metadata_length: usize,
+    pub(crate) encrypted_footer: bool,

Review Comment:
   There's an `is_encrypted_footer` method that can be used to access this, it 
shouldn't need to be `pub(crate)`.



-- 
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: github-unsubscr...@arrow.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org

Reply via email to