alien_core/resources/
key.rs1use crate::{
2 error::{ErrorData, Result},
3 resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType},
4};
5use alien_error::AlienError;
6use bon::Builder;
7use serde::{Deserialize, Serialize};
8use std::any::Any;
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[serde(rename_all = "camelCase", deny_unknown_fields)]
14#[builder(start_fn = new)]
15pub struct Key {
16 #[builder(start_fn)]
18 pub id: String,
19}
20
21pub fn key_description(key_id: &str) -> String {
23 format!("Encryption key '{key_id}'")
24}
25
26impl Key {
27 pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("key");
28
29 pub fn id(&self) -> &str {
30 &self.id
31 }
32}
33
34#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
40#[serde(tag = "provider", rename_all = "lowercase", deny_unknown_fields)]
41pub enum KeyFingerprint {
42 Aws { key_arn: String },
44 Gcp { crypto_key_name: String },
46 Azure {
48 vault_resource_id: String,
49 key_name: String,
50 lineage_version_id: String,
51 },
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
56#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
57#[serde(rename_all = "camelCase")]
58pub struct KeyOutputs {
59 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub available: Option<bool>,
63 pub fingerprint: KeyFingerprint,
65 pub wrapping_key_id: String,
67 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub disk_encryption_set_id: Option<String>,
71}
72
73impl ResourceDefinition for Key {
74 fn get_resource_type(&self) -> ResourceType {
75 Self::RESOURCE_TYPE
76 }
77
78 fn id(&self) -> &str {
79 &self.id
80 }
81
82 fn replace_after_failed_create_is_safe(&self) -> bool {
83 false
85 }
86
87 fn get_dependencies(&self) -> Vec<ResourceRef> {
88 Vec::new()
89 }
90
91 fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
92 let Some(new_key) = new_config.as_any().downcast_ref::<Self>() else {
93 return Err(AlienError::new(ErrorData::UnexpectedResourceType {
94 resource_id: self.id.clone(),
95 expected: Self::RESOURCE_TYPE,
96 actual: new_config.get_resource_type(),
97 }));
98 };
99
100 if self.id != new_key.id {
101 return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
102 resource_id: self.id.clone(),
103 reason: "the 'id' field is immutable".to_string(),
104 }));
105 }
106
107 Ok(())
108 }
109
110 fn as_any(&self) -> &dyn Any {
111 self
112 }
113
114 fn as_any_mut(&mut self) -> &mut dyn Any {
115 self
116 }
117
118 fn box_clone(&self) -> Box<dyn ResourceDefinition> {
119 Box::new(self.clone())
120 }
121
122 fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
123 other.as_any().downcast_ref::<Self>() == Some(self)
124 }
125
126 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
127 serde_json::to_value(self)
128 }
129}
130
131impl ResourceOutputsDefinition for KeyOutputs {
132 fn is_available(&self) -> bool {
133 self.available.unwrap_or(true)
134 }
135
136 fn get_resource_type(&self) -> ResourceType {
137 Key::RESOURCE_TYPE
138 }
139
140 fn as_any(&self) -> &dyn Any {
141 self
142 }
143
144 fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
145 Box::new(self.clone())
146 }
147
148 fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
149 other.as_any().downcast_ref::<Self>() == Some(self)
150 }
151
152 fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
153 serde_json::to_value(self)
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use super::*;
160
161 #[test]
162 fn provider_rotation_preserves_the_key_family_fingerprint() {
163 let fingerprint = KeyFingerprint::Gcp {
164 crypto_key_name: "projects/example/locations/us/keyRings/data/cryptoKeys/customer"
165 .to_string(),
166 };
167 let before = KeyOutputs {
168 available: None,
169 fingerprint: fingerprint.clone(),
170 wrapping_key_id: "projects/example/locations/us/keyRings/data/cryptoKeys/customer/cryptoKeyVersions/1".to_string(),
171 disk_encryption_set_id: None,
172 };
173 let after = KeyOutputs {
174 available: None,
175 fingerprint,
176 wrapping_key_id: "projects/example/locations/us/keyRings/data/cryptoKeys/customer/cryptoKeyVersions/2".to_string(),
177 disk_encryption_set_id: None,
178 };
179
180 assert_eq!(before.fingerprint, after.fingerprint);
181 assert_ne!(before.wrapping_key_id, after.wrapping_key_id);
182 }
183
184 #[test]
185 fn outputs_written_before_the_disk_encryption_set_existed_still_read() {
186 let old = serde_json::json!({
187 "fingerprint": {
188 "provider": "azure",
189 "vault_resource_id": "/subscriptions/s/resourceGroups/g/providers/Microsoft.KeyVault/vaults/v",
190 "key_name": "key",
191 "lineage_version_id": "https://v.vault.azure.net/keys/key/1",
192 },
193 "wrappingKeyId": "https://v.vault.azure.net/keys/key/1",
194 });
195 let outputs: KeyOutputs = serde_json::from_value(old.clone()).unwrap();
196 assert_eq!(outputs.disk_encryption_set_id, None);
197 assert_eq!(serde_json::to_value(&outputs).unwrap(), old);
199
200 let with_set = KeyOutputs {
201 disk_encryption_set_id: Some("/subscriptions/s/resourceGroups/g/providers/Microsoft.Compute/diskEncryptionSets/d".into()),
202 ..outputs
203 };
204 let round_trip: KeyOutputs =
205 serde_json::from_value(serde_json::to_value(&with_set).unwrap()).unwrap();
206 assert_eq!(round_trip, with_set);
207 }
208}