adamreeve commented on code in PR #6637: URL: https://github.com/apache/arrow-rs/pull/6637#discussion_r1948289774
########## parquet/Cargo.toml: ########## @@ -98,7 +101,7 @@ zstd-sys = { version = ">=2.0.0, <2.0.14", default-features = false } all-features = true [features] -default = ["arrow", "snap", "brotli", "flate2", "lz4", "zstd", "base64", "simdutf8"] +default = ["arrow", "snap", "brotli", "flate2", "lz4", "zstd", "base64", "simdutf8", "encryption"] Review Comment: I don't think this should be a default feature as that would make it a breaking change, was this left in accidentally? ########## parquet/Cargo.toml: ########## @@ -30,6 +30,8 @@ rust-version = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dependencies] ahash = { version = "0.8", default-features = false, features = ["compile-time-rng"] } +# See https://github.com/briansmith/ring/issues/918#issuecomment-2077788925 +ring = { version = "0.17", features = ["wasm32_unknown_unknown_js"] } Review Comment: I think this should be optional so it's only required when the encryption feature is used. Also, should this have `default-features = false` and the `std` feature added too to match the non-wasm dependency? ########## parquet/src/file/serialized_reader.rs: ########## @@ -338,14 +344,45 @@ impl<R: 'static + ChunkReader> RowGroupReader for SerializedRowGroupReader<'_, R } /// Reads a [`PageHeader`] from the provided [`Read`] -pub(crate) fn read_page_header<T: Read>(input: &mut T) -> Result<PageHeader> { +pub(crate) fn read_page_header<T: Read>( + input: &mut T, + #[cfg(feature = "encryption")] crypto_context: Option<Arc<CryptoContext>>, +) -> Result<PageHeader> { + #[cfg(feature = "encryption")] + if let Some(crypto_context) = crypto_context { + let data_decryptor = crypto_context.data_decryptor(); + + let module_type = if crypto_context.dictionary_page { + ModuleType::DictionaryPageHeader + } else { + ModuleType::DataPageHeader + }; + let aad = create_page_aad( Review Comment: There are a couple of places where we call this using information derived from a `CryptoContext`. Would it make sense to add a `create_page_aad` method to `CryptoContext` to tidy this up? ########## parquet/src/encryption/decryption.rs: ########## @@ -0,0 +1,228 @@ +// 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::errors::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()) +} + +#[derive(Debug, Clone)] +pub 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 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 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 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 fn data_decryptor(&self) -> &Arc<dyn BlockDecryptor> { + &self.data_decryptor + } + + pub fn metadata_decryptor(&self) -> &Arc<dyn BlockDecryptor> { + &self.metadata_decryptor + } + + pub fn file_aad(&self) -> &Vec<u8> { + &self.file_aad + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct FileDecryptionProperties { + footer_key: Vec<u8>, + column_keys: Option<HashMap<Vec<u8>, Vec<u8>>>, + aad_prefix: Option<Vec<u8>>, +} + +impl FileDecryptionProperties { + pub fn builder(footer_key: Vec<u8>) -> DecryptionPropertiesBuilder { + DecryptionPropertiesBuilder::new(footer_key) + } + + pub fn has_column_keys(&self) -> bool { + self.column_keys.is_some() + } + + pub fn aad_prefix(&self) -> Option<Vec<u8>> { + self.aad_prefix.clone() + } +} + +pub struct DecryptionPropertiesBuilder { + footer_key: Vec<u8>, + column_keys: Option<HashMap<Vec<u8>, Vec<u8>>>, + aad_prefix: Option<Vec<u8>>, +} + +impl DecryptionPropertiesBuilder { + pub fn new(footer_key: Vec<u8>) -> DecryptionPropertiesBuilder { + Self { + footer_key, + column_keys: None, + 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: Vec<u8>) -> Self { + self.aad_prefix = Some(value); + self + } + + pub fn with_column_key(mut self, key: Vec<u8>, value: Vec<u8>) -> Self { Review Comment: This should use more specific names than `key` and `value`, eg. `column_name` and `decryption_key`? ########## parquet/src/file/serialized_reader.rs: ########## @@ -400,6 +442,28 @@ pub(crate) fn decode_page( can_decompress = header_v2.is_compressed.unwrap_or(true); } + #[cfg(feature = "encryption")] + let buffer: Bytes = if crypto_context.is_some() { + let crypto_context = crypto_context.as_ref().unwrap(); Review Comment: ```suggestion let buffer: Bytes = if let Some(crypto_context) = crypto_context { ``` ########## parquet/src/encryption/decryption.rs: ########## @@ -0,0 +1,228 @@ +// 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::errors::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()) +} + +#[derive(Debug, Clone)] +pub 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 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 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 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 fn data_decryptor(&self) -> &Arc<dyn BlockDecryptor> { + &self.data_decryptor + } + + pub fn metadata_decryptor(&self) -> &Arc<dyn BlockDecryptor> { + &self.metadata_decryptor + } + + pub fn file_aad(&self) -> &Vec<u8> { + &self.file_aad + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct FileDecryptionProperties { + footer_key: Vec<u8>, + column_keys: Option<HashMap<Vec<u8>, Vec<u8>>>, + aad_prefix: Option<Vec<u8>>, +} + +impl FileDecryptionProperties { + pub fn builder(footer_key: Vec<u8>) -> DecryptionPropertiesBuilder { + DecryptionPropertiesBuilder::new(footer_key) + } + + pub fn has_column_keys(&self) -> bool { Review Comment: It looks like this isn't used and could be removed? And similarly for the `aad_prefix` method? ########## parquet/src/arrow/async_reader/mod.rs: ########## @@ -172,17 +201,36 @@ impl ArrowReaderMetadata { pub async fn load_async<T: AsyncFileReader>( input: &mut T, options: ArrowReaderOptions, + #[cfg(feature = "encryption")] file_decryption_properties: Option< + &FileDecryptionProperties, + >, ) -> Result<Self> { // TODO: this is all rather awkward. It would be nice if AsyncFileReader::get_metadata // took an argument to fetch the page indexes. - let mut metadata = input.get_metadata().await?; + let mut metadata = input + .get_metadata( + #[cfg(feature = "encryption")] + file_decryption_properties, + ) + .await?; + + #[cfg(feature = "encryption")] + let use_encryption = file_decryption_properties.is_some(); + + #[cfg(not(feature = "encryption"))] + let use_encryption = false; if options.page_index && metadata.column_index().is_none() && metadata.offset_index().is_none() { let m = Arc::try_unwrap(metadata).unwrap_or_else(|e| e.as_ref().clone()); let mut reader = ParquetMetaDataReader::new_with_metadata(m).with_page_indexes(true); + + if use_encryption { + reader = reader.with_decryption_properties(file_decryption_properties); + } Review Comment: `with_decryption_properties` accepts an Option, so you can remove the `let use_encryption` statements above and just change this to: ```suggestion #[cfg(feature = "encryption")] reader = reader.with_decryption_properties(file_decryption_properties); ``` ########## parquet/src/arrow/arrow_reader/mod.rs: ########## @@ -379,10 +380,23 @@ impl ArrowReaderMetadata { /// If `options` has [`ArrowReaderOptions::with_page_index`] true, but /// `Self::metadata` is missing the page index, this function will attempt /// to load the page index by making an object store request. - pub fn load<T: ChunkReader>(reader: &T, options: ArrowReaderOptions) -> Result<Self> { - let metadata = ParquetMetaDataReader::new() - .with_page_indexes(options.page_index) + /// + /// If encryption is enabled and the file is encrypted, the + /// `file_decryption_properties` must be provided. + pub fn load<T: ChunkReader>( + reader: &T, + options: ArrowReaderOptions, + #[cfg(feature = "encryption")] file_decryption_properties: Option< + &FileDecryptionProperties, Review Comment: Would it make sense for the decryption properties to be part of `ArrowReaderOptions`? They aren't really Arrow specific but that might tidy up the API a bit, and there's already a `with_page_index` property there which I don't think is Arrow specific. ########## parquet/src/arrow/async_reader/mod.rs: ########## @@ -853,6 +924,10 @@ struct InMemoryRowGroup<'a> { offset_index: Option<&'a [OffsetIndexMetaData]>, column_chunks: Vec<Option<Arc<ColumnChunkData>>>, row_count: usize, + #[cfg(feature = "encryption")] + row_group_ordinal: usize, + #[cfg(feature = "encryption")] + parquet_metadata: Option<Arc<ParquetMetaData>>, Review Comment: Why is this an `Option`, it looks like it's always `Some`? -- 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