use crate::rules::encryption::kms_driver::KmsDriver;
use crate::serdes::serde::SerdeError;
use lazy_static::lazy_static;
use std::sync::{Arc, RwLock};
use tink_core::TinkError;
use tink_core::registry::KmsClient;
#[cfg(feature = "rules-encryption-awskms")]
pub mod awskms;
#[cfg(feature = "rules-encryption-azurekms")]
pub mod azurekms;
#[cfg(feature = "rules-encryption-tink")]
pub mod encrypt_executor;
#[cfg(feature = "rules-encryption-gcpkms")]
pub mod gcpkms;
#[cfg(feature = "rules-encryption-hcvault")]
pub mod hcvault;
pub mod kms_driver;
#[cfg(feature = "rules-encryption-localkms")]
pub mod localkms;
lazy_static! {
static ref KMS_DRIVERS: RwLock<Vec<Arc<dyn KmsDriver>>> = RwLock::new(Vec::new());
static ref KMS_CLIENTS: RwLock<Vec<Arc<dyn KmsClient>>> = RwLock::new(Vec::new());
}
const DERR: &str = "global KMS_DRIVERS lock poisoned";
const CERR: &str = "global KMS_CLIENTS lock poisoned";
pub fn register_kms_driver<T>(k: T)
where
T: 'static + KmsDriver,
{
let mut kms_drivers = KMS_DRIVERS.write().expect(DERR); kms_drivers.push(Arc::new(k));
}
pub fn clear_kms_drivers() {
let mut kms_drivers = KMS_DRIVERS.write().expect(DERR); kms_drivers.clear();
}
pub fn get_kms_driver(key_uri: &str) -> Result<Arc<dyn KmsDriver>, SerdeError> {
let kms_drivers = KMS_DRIVERS.read().expect(CERR); for k in kms_drivers.iter() {
if key_uri.starts_with(k.get_key_url_prefix()) {
return Ok(k.clone());
}
}
Err(SerdeError::Tink(TinkError::new(&format!(
"kms driver supporting {key_uri} not found"
))))
}
pub fn register_kms_client(k: Arc<dyn KmsClient>) {
let mut kms_clients = KMS_CLIENTS.write().expect(CERR); kms_clients.push(k);
}
pub fn clear_kms_clients() {
let mut kms_clients = KMS_CLIENTS.write().expect(CERR); kms_clients.clear();
}
pub fn get_kms_client(key_uri: &str) -> Result<Arc<dyn KmsClient>, TinkError> {
let kms_clients = KMS_CLIENTS.read().expect(CERR); for k in kms_clients.iter() {
if k.supported(key_uri) {
return Ok(k.clone());
}
}
Err(format!("KMS client supporting {key_uri} not found").into())
}