1use std::sync::Arc;
8
9use parquet_key_management::crypto_factory::{
10 CryptoFactory, DecryptionConfiguration, EncryptionConfiguration,
11};
12use parquet_key_management::errors::Error as KmsError;
13use parquet_key_management::key_unwrapper::KeyUnwrapper;
14use parquet_key_management::kms::{
15 KmsClient, KmsClientFactory, KmsClientRef, KmsConnectionConfig, KmsConnectionInfo,
16};
17use polars_core::runtime::ASYNC;
18use polars_error::{PolarsError, PolarsResult, polars_err};
19use polars_parquet::parquet::encryption::decrypt::{FileDecryptionProperties, KeyRetriever};
20use polars_parquet::parquet::encryption::encrypt::FileEncryptionProperties;
21use polars_parquet::parquet::error::{ParquetError, ParquetResult};
22use polars_utils::aliases::PlHashMap;
23use polars_utils::python_function::PythonObject;
24use polars_utils::unique_id::UniqueId;
25use pyo3::exceptions::{PyTypeError, PyValueError};
26use pyo3::prelude::*;
27use pyo3::types::{PyBytes, PyDict, PyMemoryView, PyString};
28
29use super::{DecryptionPropertiesFactory, EncryptionPropertiesFactory};
30
31fn kms_error_to_polars(err: KmsError) -> PolarsError {
32 polars_err!(ComputeError: "{}", err)
33}
34
35struct PyKmsClient(Py<PyAny>);
37
38impl KmsClient for PyKmsClient {
39 fn wrap_key(
40 &self,
41 key_bytes: &[u8],
42 master_key_identifier: &str,
43 ) -> parquet_key_management::errors::Result<String> {
44 Python::attach(|py| {
45 let wrapped = self.0.call_method1(
46 py,
47 "wrap_key",
48 (PyBytes::new(py, key_bytes), master_key_identifier),
49 )?;
50 let wrapped = wrapped.bind(py);
52 if let Ok(wrapped) = wrapped.cast::<PyBytes>() {
53 String::from_utf8(wrapped.as_bytes().to_vec())
54 .map_err(|_| PyValueError::new_err("wrapped key bytes must be valid UTF-8"))
55 } else {
56 wrapped.extract::<String>()
57 }
58 })
59 .map_err(|err: PyErr| KmsError::General(err.to_string()))
60 }
61
62 fn unwrap_key(
63 &self,
64 wrapped_key: &str,
65 master_key_identifier: &str,
66 ) -> parquet_key_management::errors::Result<Vec<u8>> {
67 Python::attach(|py| {
68 let key =
69 self.0
70 .call_method1(py, "unwrap_key", (wrapped_key, master_key_identifier))?;
71 let key = key.bind(py);
72 if let Ok(bytes) = key.cast::<PyBytes>() {
73 return Ok(bytes.as_bytes().to_vec());
74 }
75 let invalid_type = || {
79 let type_name = key
80 .get_type()
81 .qualname()
82 .map_or_else(|_| "unknown".to_string(), |name| name.to_string());
83 PyTypeError::new_err(format!(
84 "`unwrap_key` must return a bytes-like object, got '{type_name}'"
85 ))
86 };
87 let view = PyMemoryView::from(key).map_err(|_| invalid_type())?;
88 if view.getattr("itemsize")?.extract::<usize>()? != 1 {
89 return Err(invalid_type());
90 }
91 let bytes = view.call_method0("tobytes")?;
92 Ok(bytes.cast::<PyBytes>()?.as_bytes().to_vec())
93 })
94 .map_err(|err: PyErr| KmsError::General(err.to_string()))
95 }
96}
97
98struct PyKmsClientFactory(Arc<PythonObject>);
100
101impl KmsClientFactory for PyKmsClientFactory {
102 fn create_client(
103 &self,
104 kms_connection_info: &KmsConnectionInfo,
105 ) -> parquet_key_management::errors::Result<KmsClientRef> {
106 let config = PyKmsConnectionConfig {
107 inner: ConnectionConfig::Info(kms_connection_info.clone()),
108 };
109 Python::attach(|py| {
110 let client = self.0.call1(py, (config,))?;
111 Ok(Arc::new(PyKmsClient(client)) as KmsClientRef)
112 })
113 .map_err(|err: PyErr| KmsError::General(err.to_string()))
114 }
115}
116
117enum ConnectionConfig {
118 Config(Arc<KmsConnectionConfig>),
119 Info(KmsConnectionInfo),
120}
121
122#[pyclass(frozen)]
127pub struct PyKmsConnectionConfig {
128 inner: ConnectionConfig,
129}
130
131impl PyKmsConnectionConfig {
132 pub fn config(&self) -> PyResult<&Arc<KmsConnectionConfig>> {
134 match &self.inner {
135 ConnectionConfig::Config(config) => Ok(config),
136 ConnectionConfig::Info(_) => Err(PyValueError::new_err(
137 "the KMS connection configuration passed to the KMS client factory \
138 can't be used to read or write files",
139 )),
140 }
141 }
142}
143
144#[pymethods]
145impl PyKmsConnectionConfig {
146 #[new]
147 #[pyo3(signature = (kms_instance_id, kms_instance_url, key_access_token, custom_kms_conf))]
148 fn new(
149 kms_instance_id: String,
150 kms_instance_url: String,
151 key_access_token: String,
152 custom_kms_conf: Vec<(String, String)>,
153 ) -> Self {
154 let mut builder = KmsConnectionConfig::builder()
155 .set_kms_instance_id(kms_instance_id)
156 .set_kms_instance_url(kms_instance_url)
157 .set_key_access_token(key_access_token);
158 for (key, value) in custom_kms_conf {
159 builder = builder.set_custom_kms_conf_option(key, value);
160 }
161 Self {
162 inner: ConnectionConfig::Config(Arc::new(builder.build())),
163 }
164 }
165
166 #[getter]
167 fn kms_instance_id(&self) -> &str {
168 match &self.inner {
169 ConnectionConfig::Config(config) => config.kms_instance_id(),
170 ConnectionConfig::Info(info) => info.kms_instance_id(),
171 }
172 }
173
174 #[getter]
175 fn kms_instance_url(&self) -> &str {
176 match &self.inner {
177 ConnectionConfig::Config(config) => config.kms_instance_url(),
178 ConnectionConfig::Info(info) => info.kms_instance_url(),
179 }
180 }
181
182 #[getter]
183 fn key_access_token(&self) -> String {
184 match &self.inner {
185 ConnectionConfig::Config(config) => config.key_access_token(),
186 ConnectionConfig::Info(info) => info.key_access_token().to_owned(),
187 }
188 }
189
190 #[getter]
191 fn custom_kms_conf<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PyDict>> {
192 let custom_kms_conf = match &self.inner {
193 ConnectionConfig::Config(config) => config.custom_kms_conf(),
194 ConnectionConfig::Info(info) => info.custom_kms_conf(),
195 };
196 let dict = PyDict::new(py);
197 for (key, value) in custom_kms_conf {
198 dict.set_item(PyString::new(py, key), PyString::new(py, value))?;
199 }
200 Ok(dict)
201 }
202
203 fn refresh_key_access_token(&self, value: String) -> PyResult<()> {
204 match &self.inner {
205 ConnectionConfig::Config(config) => {
206 config.refresh_key_access_token(value);
207 Ok(())
208 },
209 ConnectionConfig::Info(_) => Err(PyValueError::new_err(
210 "The key access token cannot be refreshed using the read-only KMS connection \
211 configuration passed to the KMS client factory; refresh the token using \
212 the original configuration",
213 )),
214 }
215 }
216}
217
218#[derive(Clone)]
223pub struct PythonCryptoFactory {
224 id: UniqueId,
227 kms_client_factory: Arc<PythonObject>,
228 crypto_factory: Arc<CryptoFactory>,
229}
230
231impl PythonCryptoFactory {
232 pub fn new(kms_client_factory: Py<PyAny>) -> Self {
233 Self::from_python_object(UniqueId::new(), Arc::new(PythonObject(kms_client_factory)))
234 }
235
236 fn from_python_object(id: UniqueId, kms_client_factory: Arc<PythonObject>) -> Self {
237 let crypto_factory = Arc::new(CryptoFactory::new(PyKmsClientFactory(Arc::clone(
238 &kms_client_factory,
239 ))));
240 Self {
241 id,
242 kms_client_factory,
243 crypto_factory,
244 }
245 }
246}
247
248pub struct KmsEncryption {
250 crypto_factory: PythonCryptoFactory,
251 kms_connection_config: Arc<KmsConnectionConfig>,
252 encryption_configuration: EncryptionConfiguration,
253}
254
255impl KmsEncryption {
256 pub fn new(
257 crypto_factory: PythonCryptoFactory,
258 kms_connection_config: Arc<KmsConnectionConfig>,
259 encryption_configuration: EncryptionConfiguration,
260 ) -> Self {
261 Self {
262 crypto_factory,
263 kms_connection_config,
264 encryption_configuration,
265 }
266 }
267}
268
269impl EncryptionPropertiesFactory for KmsEncryption {
270 fn file_encryption_properties(&self) -> PolarsResult<Arc<FileEncryptionProperties>> {
271 let keys = ASYNC
274 .block_in_place(|| {
275 self.crypto_factory.crypto_factory.file_encryption_keys(
276 Arc::clone(&self.kms_connection_config),
277 &self.encryption_configuration,
278 )
279 })
280 .map_err(kms_error_to_polars)?;
281 let footer_key = keys.footer_key();
282 let mut builder = FileEncryptionProperties::builder(footer_key.key().to_vec())
283 .with_footer_key_metadata(footer_key.metadata().to_vec())
284 .with_plaintext_footer(keys.plaintext_footer());
285 for (column_path, column_key) in keys.column_keys() {
286 builder = builder.with_column_key_and_metadata(
287 column_path,
288 column_key.key().to_vec(),
289 column_key.metadata().to_vec(),
290 );
291 }
292 Ok(builder.build()?)
293 }
294
295 fn encrypted_column_names(&self) -> Vec<String> {
296 self.encryption_configuration
297 .column_key_ids()
298 .values()
299 .flatten()
300 .cloned()
301 .collect()
302 }
303}
304
305struct KeyUnwrapperRetriever(KeyUnwrapper);
307
308impl KeyRetriever for KeyUnwrapperRetriever {
309 fn retrieve_key(&self, key_metadata: &[u8]) -> ParquetResult<Vec<u8>> {
310 ASYNC
313 .block_in_place(|| self.0.unwrap_key(key_metadata))
314 .map_err(|err| ParquetError::Encryption(err.to_string()))
315 }
316}
317
318pub struct KmsDecryption {
320 crypto_factory: PythonCryptoFactory,
321 kms_connection_config: Arc<KmsConnectionConfig>,
322 decryption_configuration: DecryptionConfiguration,
323}
324
325impl KmsDecryption {
326 pub fn new(
327 crypto_factory: PythonCryptoFactory,
328 kms_connection_config: Arc<KmsConnectionConfig>,
329 decryption_configuration: DecryptionConfiguration,
330 ) -> Self {
331 Self {
332 crypto_factory,
333 kms_connection_config,
334 decryption_configuration,
335 }
336 }
337}
338
339impl DecryptionPropertiesFactory for KmsDecryption {
340 fn file_decryption_properties(&self) -> PolarsResult<Arc<FileDecryptionProperties>> {
341 let key_unwrapper = self
342 .crypto_factory
343 .crypto_factory
344 .key_unwrapper(
345 Arc::clone(&self.kms_connection_config),
346 self.decryption_configuration.clone(),
347 )
348 .map_err(kms_error_to_polars)?;
349 Ok(
350 FileDecryptionProperties::with_key_retriever(Arc::new(KeyUnwrapperRetriever(
351 key_unwrapper,
352 )))
353 .build()?,
354 )
355 }
356}
357
358pub(super) type SeenCryptoFactories = PlHashMap<UniqueId, PythonCryptoFactory>;
360
361impl PythonCryptoFactory {
362 fn shared(&self, seen: &mut SeenCryptoFactories) -> Option<Self> {
364 let first = seen.entry(self.id).or_insert_with(|| self.clone());
365 (!Arc::ptr_eq(&first.crypto_factory, &self.crypto_factory)).then(|| first.clone())
366 }
367}
368
369impl KmsEncryption {
370 pub(super) fn with_shared_crypto_factory(
373 &self,
374 seen: &mut SeenCryptoFactories,
375 ) -> Option<Self> {
376 Some(Self {
377 crypto_factory: self.crypto_factory.shared(seen)?,
378 kms_connection_config: Arc::clone(&self.kms_connection_config),
379 encryption_configuration: self.encryption_configuration.clone(),
380 })
381 }
382}
383
384impl KmsDecryption {
385 pub(super) fn with_shared_crypto_factory(
388 &self,
389 seen: &mut SeenCryptoFactories,
390 ) -> Option<Self> {
391 Some(Self {
392 crypto_factory: self.crypto_factory.shared(seen)?,
393 kms_connection_config: Arc::clone(&self.kms_connection_config),
394 decryption_configuration: self.decryption_configuration.clone(),
395 })
396 }
397}
398
399#[cfg(any(feature = "serde", feature = "dsl-schema"))]
404#[cfg_attr(not(feature = "serde"), allow(dead_code))]
405mod serialization {
406 use std::collections::BTreeMap;
407 use std::time::Duration;
408
409 use super::*;
410
411 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
413 #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
414 #[cfg_attr(feature = "dsl-schema", schemars(rename = "KmsConnectionConfig"))]
415 struct SerializableKmsConnectionConfig {
416 kms_instance_id: String,
417 kms_instance_url: String,
418 key_access_token: String,
419 custom_kms_conf: BTreeMap<String, String>,
420 }
421
422 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
423 #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
424 #[cfg_attr(
425 feature = "dsl-schema",
426 schemars(rename = "KmsEncryptionConfiguration")
427 )]
428 struct SerializableEncryptionConfiguration {
429 footer_key_id: String,
430 column_key_ids: BTreeMap<String, Vec<String>>,
431 plaintext_footer: bool,
432 double_wrapping: bool,
433 cache_lifetime: Option<Duration>,
434 internal_key_material: bool,
435 data_key_length_bits: u32,
436 }
437
438 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
439 #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
440 #[cfg_attr(
441 feature = "dsl-schema",
442 schemars(rename = "KmsDecryptionConfiguration")
443 )]
444 struct SerializableDecryptionConfiguration {
445 cache_lifetime: Option<Duration>,
446 read_kms_url: bool,
447 }
448
449 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
450 #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
451 #[cfg_attr(feature = "dsl-schema", schemars(rename = "PythonCryptoFactory"))]
452 struct SerializablePythonCryptoFactory {
453 id: UniqueId,
454 #[cfg_attr(
455 feature = "serde",
456 serde(
457 serialize_with = "PythonObject::serialize_with_pyversion",
458 deserialize_with = "PythonObject::deserialize_with_pyversion"
459 )
460 )]
461 kms_client_factory: Arc<PythonObject>,
462 }
463
464 impl PythonCryptoFactory {
465 fn to_serializable(&self) -> SerializablePythonCryptoFactory {
466 SerializablePythonCryptoFactory {
467 id: self.id,
468 kms_client_factory: Arc::clone(&self.kms_client_factory),
469 }
470 }
471
472 #[cfg(feature = "serde")]
473 fn from_serializable(serializable: SerializablePythonCryptoFactory) -> Self {
474 Self::from_python_object(serializable.id, serializable.kms_client_factory)
475 }
476 }
477
478 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
479 #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
480 #[cfg_attr(feature = "dsl-schema", schemars(rename = "KmsEncryption"))]
481 struct SerializableKmsEncryption {
482 crypto_factory: SerializablePythonCryptoFactory,
483 kms_connection_config: SerializableKmsConnectionConfig,
484 encryption_configuration: SerializableEncryptionConfiguration,
485 }
486
487 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
488 #[cfg_attr(feature = "dsl-schema", derive(schemars::JsonSchema))]
489 #[cfg_attr(feature = "dsl-schema", schemars(rename = "KmsDecryption"))]
490 struct SerializableKmsDecryption {
491 crypto_factory: SerializablePythonCryptoFactory,
492 kms_connection_config: SerializableKmsConnectionConfig,
493 decryption_configuration: SerializableDecryptionConfiguration,
494 }
495
496 impl SerializableKmsConnectionConfig {
497 fn new(config: &KmsConnectionConfig) -> Self {
498 Self {
499 kms_instance_id: config.kms_instance_id().to_string(),
500 kms_instance_url: config.kms_instance_url().to_string(),
501 key_access_token: config.key_access_token(),
502 custom_kms_conf: config
503 .custom_kms_conf()
504 .iter()
505 .map(|(key, value)| (key.clone(), value.clone()))
506 .collect(),
507 }
508 }
509
510 fn into_config(self) -> Arc<KmsConnectionConfig> {
511 Arc::new(
512 KmsConnectionConfig::builder()
513 .set_kms_instance_id(self.kms_instance_id)
514 .set_kms_instance_url(self.kms_instance_url)
515 .set_key_access_token(self.key_access_token)
516 .set_custom_kms_conf(self.custom_kms_conf.into_iter().collect())
517 .build(),
518 )
519 }
520 }
521
522 impl SerializableEncryptionConfiguration {
523 fn new(config: &EncryptionConfiguration) -> Self {
524 Self {
525 footer_key_id: config.footer_key_id().to_string(),
526 column_key_ids: config
527 .column_key_ids()
528 .iter()
529 .map(|(key_id, columns)| (key_id.clone(), columns.clone()))
530 .collect(),
531 plaintext_footer: config.plaintext_footer(),
532 double_wrapping: config.double_wrapping(),
533 cache_lifetime: config.cache_lifetime(),
534 internal_key_material: config.internal_key_material(),
535 data_key_length_bits: config.data_key_length_bits(),
536 }
537 }
538
539 fn into_config(self) -> parquet_key_management::errors::Result<EncryptionConfiguration> {
540 let mut builder = EncryptionConfiguration::builder(self.footer_key_id)
541 .set_plaintext_footer(self.plaintext_footer)
542 .set_double_wrapping(self.double_wrapping)
543 .set_cache_lifetime(self.cache_lifetime);
544 for (key_id, columns) in self.column_key_ids {
545 builder = builder.add_column_key(key_id, columns);
546 }
547 let config = builder.build()?;
548 if config.internal_key_material() != self.internal_key_material
551 || config.data_key_length_bits() != self.data_key_length_bits
552 {
553 return Err(KmsError::General(format!(
554 "cannot deserialize a KMS encryption configuration with \
555 internal_key_material={} and data_key_length_bits={}",
556 self.internal_key_material, self.data_key_length_bits
557 )));
558 }
559 Ok(config)
560 }
561 }
562
563 impl SerializableDecryptionConfiguration {
564 fn new(config: &DecryptionConfiguration) -> Self {
565 Self {
566 cache_lifetime: config.cache_lifetime(),
567 read_kms_url: config.read_kms_url(),
568 }
569 }
570
571 fn into_config(self) -> DecryptionConfiguration {
572 DecryptionConfiguration::builder()
573 .set_cache_lifetime(self.cache_lifetime)
574 .set_read_kms_url(self.read_kms_url)
575 .build()
576 }
577 }
578
579 #[cfg(feature = "serde")]
580 impl serde::Serialize for KmsEncryption {
581 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
582 where
583 S: serde::Serializer,
584 {
585 SerializableKmsEncryption {
586 crypto_factory: self.crypto_factory.to_serializable(),
587 kms_connection_config: SerializableKmsConnectionConfig::new(
588 &self.kms_connection_config,
589 ),
590 encryption_configuration: SerializableEncryptionConfiguration::new(
591 &self.encryption_configuration,
592 ),
593 }
594 .serialize(serializer)
595 }
596 }
597
598 #[cfg(feature = "serde")]
599 impl<'de> serde::Deserialize<'de> for KmsEncryption {
600 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
601 where
602 D: serde::Deserializer<'de>,
603 {
604 use serde::de::Error;
605
606 let encryption = SerializableKmsEncryption::deserialize(deserializer)?;
607 Ok(Self::new(
608 PythonCryptoFactory::from_serializable(encryption.crypto_factory),
609 encryption.kms_connection_config.into_config(),
610 encryption
611 .encryption_configuration
612 .into_config()
613 .map_err(D::Error::custom)?,
614 ))
615 }
616 }
617
618 #[cfg(feature = "serde")]
619 impl serde::Serialize for KmsDecryption {
620 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
621 where
622 S: serde::Serializer,
623 {
624 SerializableKmsDecryption {
625 crypto_factory: self.crypto_factory.to_serializable(),
626 kms_connection_config: SerializableKmsConnectionConfig::new(
627 &self.kms_connection_config,
628 ),
629 decryption_configuration: SerializableDecryptionConfiguration::new(
630 &self.decryption_configuration,
631 ),
632 }
633 .serialize(serializer)
634 }
635 }
636
637 #[cfg(feature = "serde")]
638 impl<'de> serde::Deserialize<'de> for KmsDecryption {
639 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
640 where
641 D: serde::Deserializer<'de>,
642 {
643 let decryption = SerializableKmsDecryption::deserialize(deserializer)?;
644 Ok(Self::new(
645 PythonCryptoFactory::from_serializable(decryption.crypto_factory),
646 decryption.kms_connection_config.into_config(),
647 decryption.decryption_configuration.into_config(),
648 ))
649 }
650 }
651
652 #[cfg(feature = "dsl-schema")]
653 impl schemars::JsonSchema for KmsEncryption {
654 fn schema_name() -> std::borrow::Cow<'static, str> {
655 SerializableKmsEncryption::schema_name()
656 }
657
658 fn schema_id() -> std::borrow::Cow<'static, str> {
659 SerializableKmsEncryption::schema_id()
660 }
661
662 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
663 SerializableKmsEncryption::json_schema(generator)
664 }
665 }
666
667 #[cfg(feature = "dsl-schema")]
668 impl schemars::JsonSchema for KmsDecryption {
669 fn schema_name() -> std::borrow::Cow<'static, str> {
670 SerializableKmsDecryption::schema_name()
671 }
672
673 fn schema_id() -> std::borrow::Cow<'static, str> {
674 SerializableKmsDecryption::schema_id()
675 }
676
677 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
678 SerializableKmsDecryption::json_schema(generator)
679 }
680 }
681}