Skip to main content

polars_io/parquet/
encryption.rs

1//! Configuration for reading and writing files encrypted with Parquet modular encryption.
2
3#[cfg(feature = "parquet_kms")]
4pub mod kms;
5
6use std::fmt::Debug;
7use std::hash::Hash;
8use std::sync::Arc;
9
10use polars_error::PolarsResult;
11use polars_parquet::parquet::encryption::decrypt::FileDecryptionProperties;
12use polars_parquet::parquet::encryption::encrypt::{
13    FileEncryptionProperties, validate_encrypted_column_names,
14};
15use polars_parquet::parquet::metadata::SchemaDescriptor;
16use polars_utils::aliases::PlHashMap;
17use polars_utils::unique_id::UniqueId;
18
19/// Creates the properties used to encrypt each Parquet file written.
20pub trait EncryptionPropertiesFactory: Send + Sync {
21    /// Create encryption properties for a new file.
22    fn file_encryption_properties(&self) -> PolarsResult<Arc<FileEncryptionProperties>>;
23
24    /// The dot-separated paths of the columns that are encrypted with their own key,
25    /// or none for uniform encryption.
26    ///
27    /// This is used to validate the columns before any file is written.
28    fn encrypted_column_names(&self) -> Vec<String>;
29}
30
31/// Creates the properties used to decrypt each Parquet file read.
32pub trait DecryptionPropertiesFactory: Send + Sync {
33    /// Create decryption properties for a file.
34    fn file_decryption_properties(&self) -> PolarsResult<Arc<FileDecryptionProperties>>;
35}
36
37/// File encryption properties can be specified directly and used as a factory.
38impl EncryptionPropertiesFactory for Arc<FileEncryptionProperties> {
39    fn file_encryption_properties(&self) -> PolarsResult<Arc<FileEncryptionProperties>> {
40        Ok(Arc::clone(self))
41    }
42
43    fn encrypted_column_names(&self) -> Vec<String> {
44        FileEncryptionProperties::encrypted_column_names(self)
45            .map(str::to_string)
46            .collect()
47    }
48}
49
50/// File decryption properties can be specified directly and used as a factory.
51impl DecryptionPropertiesFactory for Arc<FileDecryptionProperties> {
52    fn file_decryption_properties(&self) -> PolarsResult<Arc<FileDecryptionProperties>> {
53        Ok(Arc::clone(self))
54    }
55}
56
57/// A source of encryption or decryption properties, with an ID that identifies it.
58///
59/// The ID is kept when serializing, so that a deserialized plan has the same equality
60/// as the original, and [`EncryptionSharing`] can share its values again.
61struct Identified<T> {
62    id: UniqueId,
63    source: T,
64}
65
66impl<T> Identified<T> {
67    fn new(source: T) -> Arc<Self> {
68        Arc::new(Self {
69            id: UniqueId::new(),
70            source,
71        })
72    }
73}
74
75/// How encryption properties are created.
76enum EncryptionSource {
77    /// The same properties, with explicit keys, are used for every file.
78    Fixed(Arc<FileEncryptionProperties>),
79    /// Keys are generated for each file, and wrapped using a KMS.
80    #[cfg(feature = "parquet_kms")]
81    Kms(Arc<kms::KmsEncryption>),
82    /// Any other factory, which can't be serialized.
83    Custom(Box<dyn EncryptionPropertiesFactory>),
84}
85
86impl EncryptionSource {
87    fn factory(&self) -> &dyn EncryptionPropertiesFactory {
88        match self {
89            Self::Fixed(properties) => properties,
90            #[cfg(feature = "parquet_kms")]
91            Self::Kms(kms) => kms.as_ref(),
92            Self::Custom(factory) => factory.as_ref(),
93        }
94    }
95}
96
97/// Determines how to encrypt Parquet files when writing.
98///
99/// This is compared and hashed by an ID assigned when it is created, which is kept
100/// when serializing. It can be serialized when it uses fixed properties or a KMS, and
101/// the serialized form includes any secret keys and tokens.
102#[derive(Clone)]
103pub struct ParquetEncryption(Arc<Identified<EncryptionSource>>);
104
105impl ParquetEncryption {
106    /// Create properties for each file using a factory.
107    ///
108    /// A query using a custom factory can't be serialized.
109    pub fn new(factory: impl EncryptionPropertiesFactory + 'static) -> Self {
110        Self(Identified::new(EncryptionSource::Custom(Box::new(factory))))
111    }
112
113    /// Get the properties to use for encrypting a single file.
114    pub fn file_properties(&self) -> PolarsResult<Arc<FileEncryptionProperties>> {
115        self.0.source.factory().file_encryption_properties()
116    }
117
118    /// The dot-separated paths of the columns that are encrypted with their own key,
119    /// or none for uniform encryption.
120    pub fn encrypted_column_names(&self) -> Vec<String> {
121        self.0.source.factory().encrypted_column_names()
122    }
123
124    /// Checks that each column that is to be encrypted with its own key is present in
125    /// the schema exactly once.
126    pub fn validate_encrypted_column_names(&self, schema: &SchemaDescriptor) -> PolarsResult<()> {
127        let encrypted_columns = self.encrypted_column_names();
128        validate_encrypted_column_names(encrypted_columns.iter().map(String::as_str), schema)?;
129        Ok(())
130    }
131}
132
133impl From<Arc<FileEncryptionProperties>> for ParquetEncryption {
134    fn from(properties: Arc<FileEncryptionProperties>) -> Self {
135        Self(Identified::new(EncryptionSource::Fixed(properties)))
136    }
137}
138
139#[cfg(feature = "parquet_kms")]
140impl From<kms::KmsEncryption> for ParquetEncryption {
141    fn from(kms: kms::KmsEncryption) -> Self {
142        Self(Identified::new(EncryptionSource::Kms(Arc::new(kms))))
143    }
144}
145
146/// How decryption properties are created.
147enum DecryptionSource {
148    /// The same properties, with explicit keys, are used for every file.
149    Fixed(Arc<FileDecryptionProperties>),
150    /// Keys are unwrapped using a KMS.
151    #[cfg(feature = "parquet_kms")]
152    Kms(Arc<kms::KmsDecryption>),
153    /// Any other factory, which can't be serialized.
154    Custom(Box<dyn DecryptionPropertiesFactory>),
155}
156
157impl DecryptionSource {
158    fn factory(&self) -> &dyn DecryptionPropertiesFactory {
159        match self {
160            Self::Fixed(properties) => properties,
161            #[cfg(feature = "parquet_kms")]
162            Self::Kms(kms) => kms.as_ref(),
163            Self::Custom(factory) => factory.as_ref(),
164        }
165    }
166}
167
168/// Determines how to decrypt Parquet files when reading.
169///
170/// This is compared and hashed by an ID assigned when it is created, which is kept
171/// when serializing. It can be serialized when it uses fixed properties or a KMS, and
172/// the serialized form includes any secret keys and tokens.
173// This is a thin pointer, keeping `FileScanIR` small.
174#[derive(Clone)]
175pub struct ParquetDecryption(Arc<Identified<DecryptionSource>>);
176
177impl ParquetDecryption {
178    /// Create properties for each file using a factory.
179    ///
180    /// A query using a custom factory can't be serialized.
181    pub fn new(factory: impl DecryptionPropertiesFactory + 'static) -> Self {
182        Self(Identified::new(DecryptionSource::Custom(Box::new(factory))))
183    }
184
185    /// Get the properties to use for decrypting a single file.
186    pub fn file_properties(&self) -> PolarsResult<Arc<FileDecryptionProperties>> {
187        self.0.source.factory().file_decryption_properties()
188    }
189}
190
191impl From<Arc<FileDecryptionProperties>> for ParquetDecryption {
192    fn from(properties: Arc<FileDecryptionProperties>) -> Self {
193        Self(Identified::new(DecryptionSource::Fixed(properties)))
194    }
195}
196
197#[cfg(feature = "parquet_kms")]
198impl From<kms::KmsDecryption> for ParquetDecryption {
199    fn from(kms: kms::KmsDecryption) -> Self {
200        Self(Identified::new(DecryptionSource::Kms(Arc::new(kms))))
201    }
202}
203
204/// Get the properties to use for decrypting a single file, if decryption is configured.
205pub fn file_decryption_properties(
206    decryption: Option<&ParquetDecryption>,
207) -> PolarsResult<Option<Arc<FileDecryptionProperties>>> {
208    decryption
209        .map(ParquetDecryption::file_properties)
210        .transpose()
211}
212
213/// The serialized forms of [`ParquetEncryption`] and [`ParquetDecryption`].
214#[cfg(any(feature = "serde", feature = "dsl-schema"))]
215mod serialization {
216    use super::*;
217
218    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
219    #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
220    #[cfg_attr(feature = "dsl-schema", schemars(rename = "ParquetEncryption"))]
221    pub(super) struct SerializableParquetEncryption {
222        id: UniqueId,
223        source: SerializableEncryptionSource,
224    }
225
226    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
227    #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
228    #[cfg_attr(feature = "dsl-schema", schemars(rename = "ParquetEncryptionSource"))]
229    enum SerializableEncryptionSource {
230        Fixed(Arc<FileEncryptionProperties>),
231        #[cfg(feature = "parquet_kms")]
232        Kms(Arc<kms::KmsEncryption>),
233    }
234
235    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
236    #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
237    #[cfg_attr(feature = "dsl-schema", schemars(rename = "ParquetDecryption"))]
238    pub(super) struct SerializableParquetDecryption {
239        id: UniqueId,
240        source: SerializableDecryptionSource,
241    }
242
243    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
244    #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
245    #[cfg_attr(feature = "dsl-schema", schemars(rename = "ParquetDecryptionSource"))]
246    enum SerializableDecryptionSource {
247        Fixed(Arc<FileDecryptionProperties>),
248        #[cfg(feature = "parquet_kms")]
249        Kms(Arc<kms::KmsDecryption>),
250    }
251
252    #[cfg_attr(not(feature = "serde"), allow(dead_code))]
253    impl ParquetEncryption {
254        pub(super) fn to_serializable(&self) -> Option<SerializableParquetEncryption> {
255            let source = match &self.0.source {
256                EncryptionSource::Fixed(properties) => {
257                    SerializableEncryptionSource::Fixed(Arc::clone(properties))
258                },
259                #[cfg(feature = "parquet_kms")]
260                EncryptionSource::Kms(kms) => SerializableEncryptionSource::Kms(Arc::clone(kms)),
261                EncryptionSource::Custom(_) => return None,
262            };
263            Some(SerializableParquetEncryption {
264                id: self.0.id,
265                source,
266            })
267        }
268
269        #[cfg(feature = "serde")]
270        pub(super) fn from_serializable(serializable: SerializableParquetEncryption) -> Self {
271            let SerializableParquetEncryption { id, source } = serializable;
272            let source = match source {
273                SerializableEncryptionSource::Fixed(properties) => {
274                    EncryptionSource::Fixed(properties)
275                },
276                #[cfg(feature = "parquet_kms")]
277                SerializableEncryptionSource::Kms(kms) => EncryptionSource::Kms(kms),
278            };
279            Self(Arc::new(Identified { id, source }))
280        }
281    }
282
283    #[cfg_attr(not(feature = "serde"), allow(dead_code))]
284    impl ParquetDecryption {
285        pub(super) fn to_serializable(&self) -> Option<SerializableParquetDecryption> {
286            let source = match &self.0.source {
287                DecryptionSource::Fixed(properties) => {
288                    SerializableDecryptionSource::Fixed(Arc::clone(properties))
289                },
290                #[cfg(feature = "parquet_kms")]
291                DecryptionSource::Kms(kms) => SerializableDecryptionSource::Kms(Arc::clone(kms)),
292                DecryptionSource::Custom(_) => return None,
293            };
294            Some(SerializableParquetDecryption {
295                id: self.0.id,
296                source,
297            })
298        }
299
300        #[cfg(feature = "serde")]
301        pub(super) fn from_serializable(serializable: SerializableParquetDecryption) -> Self {
302            let SerializableParquetDecryption { id, source } = serializable;
303            let source = match source {
304                SerializableDecryptionSource::Fixed(properties) => {
305                    DecryptionSource::Fixed(properties)
306                },
307                #[cfg(feature = "parquet_kms")]
308                SerializableDecryptionSource::Kms(kms) => DecryptionSource::Kms(kms),
309            };
310            Self(Arc::new(Identified { id, source }))
311        }
312    }
313}
314
315/// Implement traits that compare and hash by ID, and serialize through the
316/// serializable form.
317macro_rules! impl_opaque_traits {
318    ($t:ident, $serializable:ident, $description:literal) => {
319        impl Debug for $t {
320            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
321                f.write_str(stringify!($t))
322            }
323        }
324
325        impl Eq for $t {}
326
327        impl PartialEq for $t {
328            fn eq(&self, other: &Self) -> bool {
329                self.0.id == other.0.id
330            }
331        }
332
333        impl Hash for $t {
334            fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
335                self.0.id.hash(state)
336            }
337        }
338
339        #[cfg(feature = "serde")]
340        impl<'de> serde::Deserialize<'de> for $t {
341            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
342            where
343                D: serde::Deserializer<'de>,
344            {
345                serialization::$serializable::deserialize(deserializer).map(Self::from_serializable)
346            }
347        }
348
349        #[cfg(feature = "serde")]
350        impl serde::Serialize for $t {
351            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
352            where
353                S: serde::Serializer,
354            {
355                use serde::ser::Error;
356                match self.to_serializable() {
357                    Some(serializable) => serializable.serialize(serializer),
358                    None => Err(S::Error::custom(concat!(
359                        "cannot serialize ",
360                        $description,
361                        " created by a custom factory"
362                    ))),
363                }
364            }
365        }
366
367        #[cfg(feature = "dsl-schema")]
368        impl schemars::JsonSchema for $t {
369            fn schema_name() -> std::borrow::Cow<'static, str> {
370                serialization::$serializable::schema_name()
371            }
372
373            fn schema_id() -> std::borrow::Cow<'static, str> {
374                serialization::$serializable::schema_id()
375            }
376
377            fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
378                serialization::$serializable::json_schema(generator)
379            }
380        }
381    };
382}
383
384impl_opaque_traits!(
385    ParquetEncryption,
386    SerializableParquetEncryption,
387    "parquet encryption properties"
388);
389impl_opaque_traits!(
390    ParquetDecryption,
391    SerializableParquetDecryption,
392    "parquet decryption properties"
393);
394
395/// Shares the encryption and decryption configurations in a plan that have the same
396/// ID, along with the KMS crypto factories they use.
397///
398/// Values with the same ID are separate objects after a plan is deserialized. Sharing
399/// them again means they share caches, such as the KMS clients and keys of a crypto
400/// factory. The first value seen with each ID is used.
401#[derive(Default)]
402pub struct EncryptionSharing {
403    encryption: PlHashMap<UniqueId, ParquetEncryption>,
404    decryption: PlHashMap<UniqueId, ParquetDecryption>,
405    #[cfg(feature = "parquet_kms")]
406    crypto_factories: kms::SeenCryptoFactories,
407}
408
409impl EncryptionSharing {
410    /// Returns the shared encryption with the same ID as `encryption`.
411    pub fn share_encryption(&mut self, encryption: ParquetEncryption) -> ParquetEncryption {
412        let id = encryption.0.id;
413        if let Some(first) = self.encryption.get(&id) {
414            return first.clone();
415        }
416
417        #[cfg(feature = "parquet_kms")]
418        let encryption = match &encryption.0.source {
419            EncryptionSource::Kms(kms) => {
420                match kms.with_shared_crypto_factory(&mut self.crypto_factories) {
421                    Some(kms) => ParquetEncryption(Arc::new(Identified {
422                        id,
423                        source: EncryptionSource::Kms(Arc::new(kms)),
424                    })),
425                    None => encryption,
426                }
427            },
428            _ => encryption,
429        };
430
431        self.encryption.insert(id, encryption.clone());
432        encryption
433    }
434
435    /// Returns the shared decryption with the same ID as `decryption`.
436    pub fn share_decryption(&mut self, decryption: ParquetDecryption) -> ParquetDecryption {
437        let id = decryption.0.id;
438        if let Some(first) = self.decryption.get(&id) {
439            return first.clone();
440        }
441
442        #[cfg(feature = "parquet_kms")]
443        let decryption = match &decryption.0.source {
444            DecryptionSource::Kms(kms) => {
445                match kms.with_shared_crypto_factory(&mut self.crypto_factories) {
446                    Some(kms) => ParquetDecryption(Arc::new(Identified {
447                        id,
448                        source: DecryptionSource::Kms(Arc::new(kms)),
449                    })),
450                    None => decryption,
451                }
452            },
453            _ => decryption,
454        };
455
456        self.decryption.insert(id, decryption.clone());
457        decryption
458    }
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464
465    struct Factory;
466
467    impl DecryptionPropertiesFactory for Factory {
468        fn file_decryption_properties(&self) -> PolarsResult<Arc<FileDecryptionProperties>> {
469            Ok(FileDecryptionProperties::builder(b"0123456789012345".to_vec()).build()?)
470        }
471    }
472
473    #[test]
474    fn test_equality() {
475        let properties = FileDecryptionProperties::builder(b"0123456789012345".to_vec())
476            .build()
477            .unwrap();
478        let a = ParquetDecryption::from(Arc::clone(&properties));
479        assert_eq!(a, a.clone());
480        assert_ne!(a, ParquetDecryption::from(properties));
481
482        let b = ParquetDecryption::new(Factory);
483        assert_eq!(b, b.clone());
484        assert_ne!(b, ParquetDecryption::new(Factory));
485    }
486
487    #[test]
488    fn test_file_properties() {
489        let decryption = ParquetDecryption::new(Factory);
490        let a = decryption.file_properties().unwrap();
491        let b = decryption.file_properties().unwrap();
492        assert!(!Arc::ptr_eq(&a, &b));
493
494        let decryption = ParquetDecryption::from(Arc::clone(&a));
495        assert!(Arc::ptr_eq(&decryption.file_properties().unwrap(), &a));
496    }
497
498    #[test]
499    fn test_thin_pointers() {
500        assert_eq!(
501            std::mem::size_of::<Option<ParquetDecryption>>(),
502            std::mem::size_of::<usize>()
503        );
504        assert_eq!(
505            std::mem::size_of::<Option<ParquetEncryption>>(),
506            std::mem::size_of::<usize>()
507        );
508    }
509
510    #[cfg(feature = "serde")]
511    #[test]
512    fn test_serialize_fixed() {
513        let properties = FileDecryptionProperties::builder(b"0123456789012345".to_vec())
514            .with_aad_prefix(b"prefix".to_vec())
515            .build()
516            .unwrap();
517        let decryption = ParquetDecryption::from(Arc::clone(&properties));
518        let json = serde_json::to_string(&decryption).unwrap();
519        let deserialized: ParquetDecryption = serde_json::from_str(&json).unwrap();
520        assert!(*deserialized.file_properties().unwrap() == *properties);
521
522        let properties = FileEncryptionProperties::builder(b"0123456789012345".to_vec())
523            .with_column_key("a", b"1234567890123450".to_vec())
524            .build()
525            .unwrap();
526        let encryption = ParquetEncryption::from(Arc::clone(&properties));
527        let json = serde_json::to_string(&encryption).unwrap();
528        let deserialized: ParquetEncryption = serde_json::from_str(&json).unwrap();
529        assert_eq!(*deserialized.file_properties().unwrap(), *properties);
530    }
531
532    #[cfg(feature = "serde")]
533    #[test]
534    fn test_serialize_keeps_identity() {
535        use polars_utils::pl_serialize::{deserialize_dsl, serialize_dsl};
536
537        let properties = FileDecryptionProperties::builder(b"0123456789012345".to_vec())
538            .build()
539            .unwrap();
540        let a = ParquetDecryption::from(Arc::clone(&properties));
541        let b = ParquetDecryption::from(properties);
542        let values = vec![a.clone(), b.clone(), a.clone()];
543
544        let mut bytes = Vec::new();
545        serialize_dsl(&mut bytes, &values).unwrap();
546        let deserialized: Vec<ParquetDecryption> = deserialize_dsl(&mut bytes.as_slice()).unwrap();
547
548        // Equality is kept, but each occurrence is a separate object.
549        assert_eq!(deserialized, values);
550        assert_ne!(deserialized[0], deserialized[1]);
551        assert!(!Arc::ptr_eq(&deserialized[0].0, &deserialized[2].0));
552
553        // Sharing uses the first object seen with each ID.
554        let mut sharing = EncryptionSharing::default();
555        let shared: Vec<ParquetDecryption> = deserialized
556            .iter()
557            .map(|d| sharing.share_decryption(d.clone()))
558            .collect();
559        assert_eq!(shared, values);
560        assert!(Arc::ptr_eq(&shared[0].0, &deserialized[0].0));
561        assert!(Arc::ptr_eq(&shared[1].0, &deserialized[1].0));
562        assert!(Arc::ptr_eq(&shared[2].0, &deserialized[0].0));
563    }
564
565    #[cfg(feature = "serde")]
566    #[test]
567    fn test_serialize_custom_factory_fails() {
568        let err = serde_json::to_string(&ParquetDecryption::new(Factory)).unwrap_err();
569        assert!(
570            err.to_string().contains(
571                "cannot serialize parquet decryption properties created by a custom factory"
572            ),
573            "{err}"
574        );
575    }
576}