Skip to main content

alien_core/resources/
vault.rs

1use crate::error::{ErrorData, Result};
2use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
3use alien_error::AlienError;
4use bon::Builder;
5use serde::{Deserialize, Serialize};
6use std::any::Any;
7use std::fmt::Debug;
8
9/// Represents a secure vault for storing secrets.
10/// This resource provides a platform-agnostic interface over cloud-native secret management services:
11/// - AWS: AWS Secrets Manager with prefixed secret names
12/// - GCP: Secret Manager with prefixed secret names
13/// - Azure: Key Vault resource
14///
15/// The vault acts as a namespace for secrets and controls access permissions for workers and services.
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
17#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
18#[serde(rename_all = "camelCase", deny_unknown_fields)]
19#[builder(start_fn = new)]
20pub struct Vault {
21    /// Unique identifier for the vault. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
22    /// Maximum 64 characters.
23    #[builder(start_fn)]
24    pub id: String,
25}
26
27impl Vault {
28    /// The resource type identifier for Vault
29    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("vault");
30
31    /// Returns the vault's unique identifier.
32    pub fn id(&self) -> &str {
33        &self.id
34    }
35}
36
37/// Outputs generated by a successfully provisioned Vault.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
40#[serde(rename_all = "camelCase")]
41pub struct VaultOutputs {
42    /// Platform-specific vault identifier.
43    /// - AWS: Account and region (e.g., "123456789012:us-west-2") - implicit reference to Secrets Manager
44    /// - GCP: Project and location (e.g., "projects/my-project/locations/us-central1") - implicit reference to Secret Manager
45    /// - Azure: Key Vault resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.KeyVault/vaults/my-vault")
46    pub vault_id: String,
47}
48
49impl ResourceOutputsDefinition for VaultOutputs {
50    fn get_resource_type(&self) -> ResourceType {
51        Vault::RESOURCE_TYPE.clone()
52    }
53
54    fn as_any(&self) -> &dyn Any {
55        self
56    }
57
58    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
59        Box::new(self.clone())
60    }
61
62    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
63        other.as_any().downcast_ref::<VaultOutputs>() == Some(self)
64    }
65
66    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
67        serde_json::to_value(self)
68    }
69}
70
71// Implementation of ResourceDefinition trait for Vault
72impl ResourceDefinition for Vault {
73    fn get_resource_type(&self) -> ResourceType {
74        Self::RESOURCE_TYPE
75    }
76
77    fn id(&self) -> &str {
78        &self.id
79    }
80
81    fn replace_after_failed_create_is_safe(&self) -> bool {
82        // Deleting it destroys the stored secrets.
83        false
84    }
85
86    fn get_dependencies(&self) -> Vec<ResourceRef> {
87        Vec::new()
88    }
89
90    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
91        // Downcast to Vault type to use the existing validate_update method
92        let new_vault = new_config.as_any().downcast_ref::<Vault>().ok_or_else(|| {
93            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_vault.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        Ok(())
107    }
108
109    fn as_any(&self) -> &dyn Any {
110        self
111    }
112
113    fn as_any_mut(&mut self) -> &mut dyn Any {
114        self
115    }
116
117    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
118        Box::new(self.clone())
119    }
120
121    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
122        other.as_any().downcast_ref::<Vault>() == Some(self)
123    }
124
125    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
126        serde_json::to_value(self)
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn test_vault_creation() {
136        let vault = Vault::new("my-vault".to_string()).build();
137        assert_eq!(vault.id, "my-vault");
138    }
139
140    #[test]
141    fn test_vault_dependencies() {
142        let vault = Vault::new("my-vault".to_string()).build();
143        let dependencies = vault.get_dependencies();
144        assert!(dependencies.is_empty());
145    }
146
147    #[test]
148    fn test_vault_outputs_equality() {
149        let outputs1 = VaultOutputs {
150            vault_id: "test-vault".to_string(),
151        };
152
153        let outputs2 = VaultOutputs {
154            vault_id: "test-vault".to_string(),
155        };
156
157        let outputs3 = VaultOutputs {
158            vault_id: "different-vault".to_string(),
159        };
160
161        assert!(outputs1.outputs_eq(&outputs2));
162        assert!(!outputs1.outputs_eq(&outputs3));
163    }
164}