Skip to main content

alien_core/resources/
artifact_registry.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 an artifact registry for storing container images and other build artifacts.
10/// This is a high-level wrapper resource that provides a cloud-agnostic interface over
11/// AWS ECR, GCP Artifact Registry, and Azure Container Registry.
12///
13/// # Platform Mapping
14/// - **AWS**: Implicitly exists as the AWS account and region
15/// - **GCP**: Explicitly configured per project and location (Artifact Registry API enabled)
16/// - **Azure**: Explicitly provisioned Azure Container Registry instance
17///
18/// The actual repository management and permissions are handled through the bindings API.
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
20#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
21#[serde(rename_all = "camelCase", deny_unknown_fields)]
22#[builder(start_fn = new)]
23pub struct ArtifactRegistry {
24    /// Identifier for the artifact registry. Must contain only alphanumeric characters, hyphens, and underscores ([A-Za-z0-9-_]).
25    /// Maximum 64 characters.
26    #[builder(start_fn)]
27    pub id: String,
28
29    /// AWS-only: regions to replicate container images to.
30    /// ECR private image replication ensures images pushed in the registry's home region
31    /// are automatically available in these additional regions (required when Lambda or
32    /// other compute runs in a different region from the registry).
33    #[serde(default, skip_serializing_if = "Vec::is_empty")]
34    #[builder(default)]
35    pub replication_regions: Vec<String>,
36
37    /// AWS-only: id of a deployer-provided string-list stack input that names the
38    /// regions to replicate to. CloudFormation reads the list at deploy time, so
39    /// the template reserves a fixed number of region slots. Empty answers write
40    /// no replication configuration, so existing installs render unchanged.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub replication_regions_input: Option<String>,
43}
44
45impl ArtifactRegistry {
46    /// The resource type identifier for ArtifactRegistry
47    pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("artifact-registry");
48
49    /// Account-wide ECR configuration must have one infrastructure owner. A deployment
50    /// cannot safely merge its rules with other deployments or external account writers.
51    pub fn validate_aws_replication(&self) -> Result<()> {
52        if !self.replication_regions.is_empty() {
53            tracing::warn!(resource_id = %self.id, "Per-deployment ECR replicationRegions is ignored; configure replication through the registry account's infrastructure. Existing account replication rules remain unchanged.");
54        }
55        Ok(())
56    }
57
58    /// Returns the artifact registry's unique identifier.
59    pub fn id(&self) -> &str {
60        &self.id
61    }
62}
63
64// Implementation of ResourceDefinition trait for ArtifactRegistry
65impl ResourceDefinition for ArtifactRegistry {
66    fn get_resource_type(&self) -> ResourceType {
67        Self::RESOURCE_TYPE
68    }
69
70    fn id(&self) -> &str {
71        &self.id
72    }
73
74    fn replace_after_failed_create_is_safe(&self) -> bool {
75        // A create adopts an existing repository with the same name, and deleting it deletes every
76        // image in it, including images this deployment never pushed.
77        false
78    }
79
80    fn get_dependencies(&self) -> Vec<ResourceRef> {
81        Vec::new()
82    }
83
84    fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
85        // Downcast to ArtifactRegistry type to use the existing validate_update method
86        let new_registry = new_config
87            .as_any()
88            .downcast_ref::<ArtifactRegistry>()
89            .ok_or_else(|| {
90                AlienError::new(ErrorData::UnexpectedResourceType {
91                    resource_id: self.id.clone(),
92                    expected: Self::RESOURCE_TYPE,
93                    actual: new_config.get_resource_type(),
94                })
95            })?;
96
97        if self.id != new_registry.id {
98            return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
99                resource_id: self.id.clone(),
100                reason: "the 'id' field is immutable".to_string(),
101            }));
102        }
103        Ok(())
104    }
105
106    fn as_any(&self) -> &dyn Any {
107        self
108    }
109
110    fn as_any_mut(&mut self) -> &mut dyn Any {
111        self
112    }
113
114    fn box_clone(&self) -> Box<dyn ResourceDefinition> {
115        Box::new(self.clone())
116    }
117
118    fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
119        other.as_any().downcast_ref::<ArtifactRegistry>() == Some(self)
120    }
121
122    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
123        serde_json::to_value(self)
124    }
125
126    fn with_empty_input_references_removed(
127        &self,
128        inputs: &crate::InputAnswers<'_>,
129    ) -> Option<Box<dyn ResourceDefinition>> {
130        // Only a declared input answered with no regions resolves to nothing. An undeclared
131        // input or a listed region is a real difference from a config without the reference.
132        let input = self.replication_regions_input.as_deref()?;
133        if !inputs.string_list(input)?.is_empty() {
134            return None;
135        }
136        let mut config = self.clone();
137        config.replication_regions_input = None;
138        Some(Box::new(config))
139    }
140
141    fn input_references(&self) -> Vec<(&'static str, String)> {
142        self.replication_regions_input
143            .iter()
144            .map(|input| ("replicationRegionsInput", input.clone()))
145            .collect()
146    }
147}
148
149/// Outputs generated by a successfully provisioned ArtifactRegistry.
150#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
151#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
152#[serde(rename_all = "camelCase")]
153pub struct ArtifactRegistryOutputs {
154    /// The platform-specific registry identifier.
155    /// - AWS: Account and region (e.g., "123456789012:us-west-2")
156    /// - GCP: Full registry name (e.g., "projects/my-project/locations/us-central1")
157    /// - Azure: Registry resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ContainerRegistry/registries/myregistry")
158    pub registry_id: String,
159
160    /// The registry endpoint for docker operations.
161    /// - AWS: ECR registry URL (e.g., "123456789012.dkr.ecr.us-west-2.amazonaws.com")
162    /// - GCP: Artifact Registry URL (e.g., "us-central1-docker.pkg.dev/my-project")
163    /// - Azure: Container registry login server (e.g., "myregistry.azurecr.io")
164    pub registry_endpoint: String,
165
166    /// Role/principal identifier for pull-only access.
167    /// - AWS: IAM role ARN (e.g., "arn:aws:iam::123456789012:role/my-stack-my-registry-pull")
168    /// - GCP: Service account email (e.g., "my-stack-my-registry-pull@my-project.iam.gserviceaccount.com")
169    /// - Azure: Managed identity resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-registry-pull")
170    #[serde(skip_serializing_if = "Option::is_none")]
171    pub pull_role: Option<String>,
172
173    /// Role/principal identifier for push and pull access.
174    /// - AWS: IAM role ARN (e.g., "arn:aws:iam::123456789012:role/my-stack-my-registry-push")
175    /// - GCP: Service account email (e.g., "my-stack-my-registry-push@my-project.iam.gserviceaccount.com")
176    /// - Azure: Managed identity resource ID (e.g., "/subscriptions/.../resourceGroups/.../providers/Microsoft.ManagedIdentity/userAssignedIdentities/my-registry-push")
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub push_role: Option<String>,
179}
180
181/// Whose rules the registry's replication configuration holds. The configuration is one
182/// per account and region, and writing it replaces every rule. The setup that writes ours
183/// reads the rules when it writes and keeps every rule that is not ours unchanged, so this
184/// report is informational: it tells the operator which other rules the account has.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
187#[serde(rename_all = "camelCase")]
188pub enum RegistryReplicationOwner {
189    /// No rules.
190    None,
191    /// Exactly the one rule this registry's setup writes.
192    Ours,
193    /// At least one rule this registry did not write; setup keeps it unchanged.
194    Foreign,
195}
196
197/// The replication rules a registry reported, without anything beyond rule shapes.
198#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
199#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
200#[serde(rename_all = "camelCase")]
201pub struct RegistryReplicationReport {
202    pub owner: RegistryReplicationOwner,
203    /// One short line per rule that is not ours: destination regions and repository filters.
204    #[serde(default, skip_serializing_if = "Vec::is_empty")]
205    pub foreign_rules: Vec<String>,
206}
207
208impl ResourceOutputsDefinition for ArtifactRegistryOutputs {
209    fn get_resource_type(&self) -> ResourceType {
210        ArtifactRegistry::RESOURCE_TYPE.clone()
211    }
212
213    fn as_any(&self) -> &dyn Any {
214        self
215    }
216
217    fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
218        Box::new(self.clone())
219    }
220
221    fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
222        other.as_any().downcast_ref::<ArtifactRegistryOutputs>() == Some(self)
223    }
224
225    fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
226        serde_json::to_value(self)
227    }
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn test_artifact_registry_creation() {
236        let registry = ArtifactRegistry::new("my-registry".to_string()).build();
237        assert_eq!(registry.id, "my-registry");
238    }
239
240    #[test]
241    fn aws_registry_does_not_promise_per_deployment_replication() {
242        let mut registry = ArtifactRegistry::new("images".to_string()).build();
243        assert!(registry.validate_aws_replication().is_ok());
244        registry.replication_regions = vec!["us-west-2".to_string()];
245        assert!(registry.validate_aws_replication().is_ok());
246    }
247
248    #[test]
249    fn test_artifact_registry_dependencies() {
250        let registry = ArtifactRegistry::new("my-registry".to_string()).build();
251        let dependencies = registry.get_dependencies();
252        assert!(dependencies.is_empty());
253    }
254}