use crate::{
error::{ErrorData, Result},
resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType},
};
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct Key {
#[builder(start_fn)]
pub id: String,
}
pub fn key_description(key_id: &str) -> String {
format!("Encryption key '{key_id}'")
}
impl Key {
pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("key");
pub fn id(&self) -> &str {
&self.id
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(tag = "provider", rename_all = "lowercase", deny_unknown_fields)]
pub enum KeyFingerprint {
Aws { key_arn: String },
Gcp { crypto_key_name: String },
Azure {
vault_resource_id: String,
key_name: String,
lineage_version_id: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct KeyOutputs {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub available: Option<bool>,
pub fingerprint: KeyFingerprint,
pub wrapping_key_id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub disk_encryption_set_id: Option<String>,
}
impl ResourceDefinition for Key {
fn get_resource_type(&self) -> ResourceType {
Self::RESOURCE_TYPE
}
fn id(&self) -> &str {
&self.id
}
fn replace_after_failed_create_is_safe(&self) -> bool {
false
}
fn get_dependencies(&self) -> Vec<ResourceRef> {
Vec::new()
}
fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
let Some(new_key) = new_config.as_any().downcast_ref::<Self>() else {
return Err(AlienError::new(ErrorData::UnexpectedResourceType {
resource_id: self.id.clone(),
expected: Self::RESOURCE_TYPE,
actual: new_config.get_resource_type(),
}));
};
if self.id != new_key.id {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'id' field is immutable".to_string(),
}));
}
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceDefinition> {
Box::new(self.clone())
}
fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
other.as_any().downcast_ref::<Self>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
impl ResourceOutputsDefinition for KeyOutputs {
fn is_available(&self) -> bool {
self.available.unwrap_or(true)
}
fn get_resource_type(&self) -> ResourceType {
Key::RESOURCE_TYPE
}
fn as_any(&self) -> &dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
Box::new(self.clone())
}
fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
other.as_any().downcast_ref::<Self>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn provider_rotation_preserves_the_key_family_fingerprint() {
let fingerprint = KeyFingerprint::Gcp {
crypto_key_name: "projects/example/locations/us/keyRings/data/cryptoKeys/customer"
.to_string(),
};
let before = KeyOutputs {
available: None,
fingerprint: fingerprint.clone(),
wrapping_key_id: "projects/example/locations/us/keyRings/data/cryptoKeys/customer/cryptoKeyVersions/1".to_string(),
disk_encryption_set_id: None,
};
let after = KeyOutputs {
available: None,
fingerprint,
wrapping_key_id: "projects/example/locations/us/keyRings/data/cryptoKeys/customer/cryptoKeyVersions/2".to_string(),
disk_encryption_set_id: None,
};
assert_eq!(before.fingerprint, after.fingerprint);
assert_ne!(before.wrapping_key_id, after.wrapping_key_id);
}
#[test]
fn outputs_written_before_the_disk_encryption_set_existed_still_read() {
let old = serde_json::json!({
"fingerprint": {
"provider": "azure",
"vault_resource_id": "/subscriptions/s/resourceGroups/g/providers/Microsoft.KeyVault/vaults/v",
"key_name": "key",
"lineage_version_id": "https://v.vault.azure.net/keys/key/1",
},
"wrappingKeyId": "https://v.vault.azure.net/keys/key/1",
});
let outputs: KeyOutputs = serde_json::from_value(old.clone()).unwrap();
assert_eq!(outputs.disk_encryption_set_id, None);
assert_eq!(serde_json::to_value(&outputs).unwrap(), old);
let with_set = KeyOutputs {
disk_encryption_set_id: Some("/subscriptions/s/resourceGroups/g/providers/Microsoft.Compute/diskEncryptionSets/d".into()),
..outputs
};
let round_trip: KeyOutputs =
serde_json::from_value(serde_json::to_value(&with_set).unwrap()).unwrap();
assert_eq!(round_trip, with_set);
}
}