datafusion_execution/parquet_encryption.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use arrow::datatypes::SchemaRef;
6use async_trait::async_trait;
7use dashmap::DashMap;
8use datafusion_common::config::EncryptionFactoryOptions;
9use datafusion_common::error::Result;
10use datafusion_common::internal_datafusion_err;
11use object_store::path::Path;
12use parquet::encryption::decrypt::FileDecryptionProperties;
13use parquet::encryption::encrypt::FileEncryptionProperties;
14use std::sync::Arc;
15
16/// Trait for types that generate file encryption and decryption properties to
17/// write and read encrypted Parquet files.
18/// This allows flexibility in how encryption keys are managed, for example, to
19/// integrate with a user's key management service (KMS).
20/// For example usage, see the [`parquet_encrypted_with_kms` example].
21///
22/// [`parquet_encrypted_with_kms` example]: https://github.com/apache/datafusion/blob/main/datafusion-examples/examples/data_io/parquet_encrypted_with_kms.rs
23#[async_trait]
24pub trait EncryptionFactory: Send + Sync + std::fmt::Debug + 'static {
25 /// Generate file encryption properties to use when writing a Parquet file.
26 async fn get_file_encryption_properties(
27 &self,
28 config: &EncryptionFactoryOptions,
29 schema: &SchemaRef,
30 file_path: &Path,
31 ) -> Result<Option<Arc<FileEncryptionProperties>>>;
32
33 /// Generate file decryption properties to use when reading a Parquet file.
34 async fn get_file_decryption_properties(
35 &self,
36 config: &EncryptionFactoryOptions,
37 file_path: &Path,
38 ) -> Result<Option<Arc<FileDecryptionProperties>>>;
39}
40
41/// Stores [`EncryptionFactory`] implementations that can be retrieved by a unique string identifier
42#[derive(Clone, Debug, Default)]
43pub struct EncryptionFactoryRegistry {
44 factories: DashMap<String, Arc<dyn EncryptionFactory>>,
45}
46
47impl EncryptionFactoryRegistry {
48 /// Register an [`EncryptionFactory`] with an associated identifier that can be later
49 /// used to configure encryption when reading or writing Parquet.
50 /// If an encryption factory with the same identifier was already registered, it is replaced and returned.
51 pub fn register_factory(
52 &self,
53 id: &str,
54 factory: Arc<dyn EncryptionFactory>,
55 ) -> Option<Arc<dyn EncryptionFactory>> {
56 self.factories.insert(id.to_owned(), factory)
57 }
58
59 /// Retrieve an [`EncryptionFactory`] by its identifier
60 pub fn get_factory(&self, id: &str) -> Result<Arc<dyn EncryptionFactory>> {
61 self.factories
62 .get(id)
63 .map(|f| Arc::clone(f.value()))
64 .ok_or_else(|| {
65 internal_datafusion_err!(
66 "No Parquet encryption factory found for id '{id}'"
67 )
68 })
69 }
70}