Skip to main content

alien_core/
stack.rs

1use crate::permissions::{ManagementPermissions, PermissionProfile, PermissionsConfig};
2use crate::{
3    Platform, Resource, ResourceLifecycle, ResourceRef, ResourceType, StackInputDefinition,
4};
5use bon::Builder;
6use indexmap::IndexMap;
7use serde::{Deserialize, Serialize};
8use sha2::{Digest, Sha256};
9use std::collections::BTreeMap;
10
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
13#[serde(rename_all = "camelCase")]
14pub struct ResourceEntry {
15    /// Optional human-readable name. The stable resource ID is the display fallback.
16    #[serde(default, skip_serializing_if = "Option::is_none")]
17    pub display_name: Option<String>,
18    /// Authored purpose, displayed as plain text. Does not affect resource configuration.
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub description: Option<String>,
21    /// Resource configuration (can be any type of resource)
22    pub config: Resource,
23    /// Lifecycle management configuration for this resource
24    pub lifecycle: ResourceLifecycle,
25    /// Additional dependencies for this resource beyond those defined in the resource itself.
26    /// The total dependencies are: resource.get_dependencies() + this list
27    pub dependencies: Vec<ResourceRef>,
28    /// Enable remote bindings for this resource (BYOB use case).
29    /// When true, binding params are synced to StackState's `remote_binding_params`.
30    /// Default: false (prevents sensitive data in synced state).
31    #[serde(default)]
32    pub remote_access: bool,
33    /// Id of the boolean stack input that decides whether this resource is
34    /// created at all. `None` means always create it.
35    ///
36    /// Set by `.enabled(input)` in the SDK. Setup emitters render the resource
37    /// conditionally on the matching template variable, so a deployer who says no
38    /// never gets the resource, its outputs, or anything derived from it.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub enabled_when: Option<String>,
41}
42
43impl ResourceEntry {
44    /// Creates a resource entry with no presentation metadata.
45    pub fn new<T: crate::ResourceDefinition>(resource: T, lifecycle: ResourceLifecycle) -> Self {
46        StackBuilder::entry(resource, lifecycle)
47    }
48
49    /// Sets the human-readable name without changing the stable resource ID.
50    pub fn display_name(mut self, name: impl Into<String>) -> Self {
51        self.display_name = Some(name.into());
52        self
53    }
54
55    /// Describes this resource's purpose without changing its runtime configuration.
56    pub fn description(mut self, description: impl Into<String>) -> Self {
57        self.description = Some(description.into());
58        self
59    }
60
61    pub fn display_name_or_id(&self) -> &str {
62        self.display_name
63            .as_deref()
64            .unwrap_or_else(|| self.config.id())
65    }
66
67    /// Returns intrinsic and stack-authored dependencies in planner order.
68    pub fn combined_dependencies(&self) -> Vec<ResourceRef> {
69        let mut dependencies = self.config.get_dependencies();
70        dependencies.extend(self.dependencies.clone());
71        dependencies
72    }
73
74    /// Returns whether this resource is published through Remote Bindings.
75    ///
76    /// Provider emitters use this generic signal to create the stack-level
77    /// Remote Bindings identity. Each resource emitter remains responsible for
78    /// granting that identity only the resource's declared data-plane access.
79    pub fn has_remote_bindings(&self) -> bool {
80        crate::remote_bindings::remote_binding_for_entry(self).is_some()
81    }
82
83    /// Whether the controller's non-secret binding locator must be synchronized
84    /// into stack state. Reserved vault locators support secret sync and metadata
85    /// checks, without exposing either vault through the Remote Bindings API.
86    pub fn publishes_binding_params(&self) -> bool {
87        self.remote_access
88            || self
89                .config
90                .downcast_ref::<crate::Vault>()
91                .is_some_and(|vault| {
92                    matches!(
93                        vault.id.as_str(),
94                        crate::SECRETS_VAULT_ID | crate::DEPLOYER_SECRETS_VAULT_ID
95                    )
96                })
97    }
98}
99
100/// A bag of resources, unaware of any cloud.
101#[derive(Builder, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
102#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
103#[serde(rename_all = "camelCase")]
104#[builder(start_fn = new)]
105pub struct Stack {
106    /// Unique identifier for the stack
107    #[builder(start_fn)]
108    pub id: String,
109    /// Map of resource IDs to their configurations and lifecycle settings
110    #[builder(field)]
111    pub resources: IndexMap<String, ResourceEntry>,
112    /// Combined permissions configuration containing both profiles and management
113    #[builder(field)]
114    #[serde(default)]
115    pub permissions: PermissionsConfig,
116    /// Which platforms this stack supports. When None, all platforms are supported.
117    #[builder(field)]
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub supported_platforms: Option<Vec<Platform>>,
120    /// Input definitions required before setup or deployment can proceed.
121    #[builder(field)]
122    #[serde(default, skip_serializing_if = "Vec::is_empty")]
123    pub inputs: Vec<StackInputDefinition>,
124    /// Exact image repositories approved for containers created after installation.
125    /// The runtime API also requires an immutable SHA-256 digest.
126    #[builder(field)]
127    #[serde(default, skip_serializing_if = "Vec::is_empty")]
128    pub dynamic_container_repositories: Vec<String>,
129    /// Released Container resources whose image repositories are approved for
130    /// containers created after installation.
131    #[builder(field)]
132    #[serde(default, skip_serializing_if = "Vec::is_empty")]
133    pub dynamic_container_image_resources: Vec<String>,
134    /// Operations this stack's deployments run: the plugins, their settings, and
135    /// which operations run without approval. Changing them takes a new release.
136    #[builder(field)]
137    #[serde(default, skip_serializing_if = "Option::is_none")]
138    pub operations: Option<crate::OperationsConfig>,
139    /// Set by `alien build` for a Kubernetes stack: the CPU architectures of the image
140    /// built for each Container, Daemon and Worker, by resource id (more than one means a
141    /// multi-architecture image). Pods of a single-architecture image are placed on
142    /// matching nodes. A resource with no entry was not recorded (a prebuilt image or an
143    /// older release), so no architecture is selected. Build output replaces any value
144    /// written in the stack definition.
145    ///
146    /// Kept on the stack, not on the resources: older managers and Operators read every
147    /// resource strictly and refuse a field they do not know, but ignore an unknown
148    /// stack-level field.
149    #[builder(field)]
150    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
151    pub built_architectures: BTreeMap<String, Vec<crate::instance_catalog::Architecture>>,
152    /// Extensions whose resource types this stack may use, in the order the stack lists them.
153    #[builder(field)]
154    #[serde(default, skip_serializing_if = "Vec::is_empty")]
155    pub extensions: Vec<crate::ExtensionManifest>,
156}
157
158impl Stack {
159    /// The architectures `alien build` recorded for a workload's image. Empty when none
160    /// were recorded.
161    pub fn built_architectures_of(
162        &self,
163        resource_id: &str,
164    ) -> &[crate::instance_catalog::Architecture] {
165        self.built_architectures
166            .get(resource_id)
167            .map(Vec::as_slice)
168            .unwrap_or_default()
169    }
170
171    /// The ids of the stack's own vaults: those the application reads and writes, not the
172    /// reserved ones the framework keeps its secrets in.
173    pub fn application_vault_ids(&self) -> Vec<String> {
174        self.resources()
175            .filter(|(_, entry)| entry.config.resource_type() == crate::Vault::RESOURCE_TYPE)
176            .map(|(id, _)| id.clone())
177            .filter(|id| id != crate::SECRETS_VAULT_ID && id != crate::DEPLOYER_SECRETS_VAULT_ID)
178            .collect()
179    }
180    /// SQS visibility derived from all consumers, including a batch collection window.
181    pub fn queue_visibility_timeout_seconds(&self, queue_id: &str) -> u32 {
182        self.resources
183            .values()
184            .filter_map(|entry| {
185                let worker = entry.config.downcast_ref::<crate::Worker>()?;
186                worker
187                    .triggers
188                    .iter()
189                    .filter_map(|trigger| match trigger {
190                        crate::WorkerTrigger::Queue { queue, batch } if queue.id == queue_id => {
191                            Some(worker.timeout_seconds.saturating_mul(6).saturating_add(
192                                batch.as_ref().map_or(0, |batch| batch.max_window_seconds),
193                            ))
194                        }
195                        _ => None,
196                    })
197                    .max()
198            })
199            .max()
200            .unwrap_or(30)
201            .clamp(30, 43_200)
202    }
203
204    /// Explicit consumers whose links grant access to every port on a container.
205    /// Cluster-wide reach is separate and remains the backend's existing behavior.
206    pub fn container_linkers(&self, container_id: &str) -> Vec<ResourceRef> {
207        self.linkers(&ResourceRef::new(
208            crate::Container::RESOURCE_TYPE,
209            container_id,
210        ))
211    }
212
213    /// Workloads whose links name `target`, which are the ones that use it at runtime.
214    pub fn linkers(&self, target: &ResourceRef) -> Vec<ResourceRef> {
215        self.resources
216            .iter()
217            .filter_map(|(id, entry)| {
218                let links = if let Some(resource) = entry.config.downcast_ref::<crate::Worker>() {
219                    &resource.links
220                } else if let Some(resource) = entry.config.downcast_ref::<crate::Container>() {
221                    &resource.links
222                } else if let Some(resource) = entry.config.downcast_ref::<crate::Daemon>() {
223                    &resource.links
224                } else if let Some(resource) = entry.config.downcast_ref::<crate::Build>() {
225                    &resource.links
226                } else if let Some(resource) = entry.config.downcast_ref::<crate::Sandbox>() {
227                    &resource.links
228                } else {
229                    return None;
230                };
231                links
232                    .contains(target)
233                    .then(|| ResourceRef::new(entry.config.resource_type(), id.clone()))
234            })
235            .collect()
236    }
237
238    /// Digest of what setup owns: every Frozen entry plus each Live sandbox's setup inputs. Without
239    /// a Live sandbox the bytes equal the Frozen-only projection. Declined gated entries must be
240    /// stripped by the caller.
241    pub fn setup_owned_digest(&self) -> String {
242        let (resources, live_sandbox_inputs) = self.setup_owned_projection();
243        let encoded = if live_sandbox_inputs.is_empty() {
244            serde_json::to_vec(&resources)
245        } else {
246            serde_json::to_vec(&(&resources, &live_sandbox_inputs))
247        }
248        .expect("canonical setup-owned projection always serializes");
249        format!("{:x}", Sha256::digest(encoded))
250    }
251
252    /// Per-entry digests of the projection `setup_owned_digest` hashes, keyed by resource ID.
253    /// A Live sandbox's setup inputs are keyed `<id>#setupInputs`. Two stacks with equal
254    /// `setup_owned_digest` have equal maps; comparing the maps names the entries that differ
255    /// without exposing their contents.
256    pub fn setup_owned_entry_digests(&self) -> BTreeMap<String, String> {
257        let (resources, live_sandbox_inputs) = self.setup_owned_projection();
258        resources
259            .iter()
260            .map(|(id, value)| {
261                let encoded = serde_json::to_vec(value).expect("canonical entry always serializes");
262                ((*id).clone(), format!("{:x}", Sha256::digest(encoded)))
263            })
264            .chain(live_sandbox_inputs.iter().map(|(id, inputs)| {
265                let encoded =
266                    serde_json::to_vec(inputs).expect("canonical inputs always serialize");
267                (
268                    format!("{id}#setupInputs"),
269                    format!("{:x}", Sha256::digest(encoded)),
270                )
271            }))
272            .collect()
273    }
274
275    fn setup_owned_projection(
276        &self,
277    ) -> (
278        Vec<(&String, serde_json::Value)>,
279        Vec<(&String, Vec<(&'static str, serde_json::Value)>)>,
280    ) {
281        let mut resources = self
282            .resources
283            .iter()
284            .filter(|(_, entry)| entry.lifecycle == ResourceLifecycle::Frozen)
285            .map(|(id, entry)| {
286                let mut value =
287                    serde_json::to_value(entry).expect("resource entries always serialize to JSON");
288                let object = value.as_object_mut().expect("resource entry is an object");
289                object.remove("displayName");
290                object.remove("description");
291                if let Some(sandbox) = entry.config.downcast_ref::<crate::Sandbox>() {
292                    value["config"]["egress"] = sandbox.setup_digest_value();
293                    value["config"]
294                        .as_object_mut()
295                        .expect("resource config is an object")
296                        .remove("defaultPolicy");
297                }
298                if entry
299                    .config
300                    .downcast_ref::<crate::AzureStorageAccount>()
301                    .is_some()
302                {
303                    if let Some(settings) = crate::AzureStorageAccount::setup_settings_digest(self)
304                    {
305                        value["azureStorageSettings"] = settings.into();
306                    }
307                }
308                canonicalize_json(&mut value);
309                // Bind setup approval to derived queue settings too. Preserve old digests
310                // for stacks without explicit batching.
311                if entry.config.downcast_ref::<crate::Queue>().is_some()
312                    && self.resources.values().any(|consumer| {
313                        consumer
314                            .config
315                            .downcast_ref::<crate::Worker>()
316                            .is_some_and(|worker| worker.queue_batch_config(id).is_some())
317                    })
318                {
319                    value["queueBatchVisibilityTimeout"] =
320                        self.queue_visibility_timeout_seconds(id).into();
321                }
322                // A setup-owned dead-letter queue triggered by a Live Worker needs a
323                // project-level grant that only setup can write. Adding or removing such a
324                // trigger must therefore ask for setup. The digest does not know the platform,
325                // so the field also appears for such a queue on other platforms, where nothing
326                // asks for setup because of it (only GCP's compatibility check compares it).
327                // It is absent for every stack without a Frozen dead-letter queue that has a
328                // Live Worker trigger, so those stacks keep their digests.
329                if crate::queue_needs_project_push_subscriber(self, id) {
330                    value["queueProjectPushSubscriber"] = true.into();
331                }
332                (id, value)
333            })
334            .collect::<Vec<_>>();
335        resources.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
336
337        let mut live_sandbox_inputs = self
338            .resources
339            .iter()
340            .filter(|(_, entry)| entry.lifecycle == ResourceLifecycle::Live)
341            .filter_map(|(id, entry)| {
342                let sandbox = entry.config.downcast_ref::<crate::Sandbox>()?;
343                let mut inputs = crate::sandbox_setup_inputs::comparable_aws_sandbox_setup_inputs(
344                    self,
345                    sandbox,
346                    entry.lifecycle,
347                );
348                for (_, value) in &mut inputs {
349                    canonicalize_json(value);
350                }
351                Some((id, inputs))
352            })
353            .collect::<Vec<_>>();
354        live_sandbox_inputs.sort_unstable_by_key(|(id, _)| *id);
355        (resources, live_sandbox_inputs)
356    }
357
358    /// Binds a setup update to both its resources and installed permissions.
359    /// Runtime code changes remain outside this authorization.
360    pub fn setup_update_digest(&self) -> String {
361        let mut permissions = serde_json::to_value(&self.permissions)
362            .expect("permission profiles always serialize to JSON");
363        canonicalize_json(&mut permissions);
364        let encoded = serde_json::to_vec(&(self.setup_owned_digest(), permissions))
365            .expect("setup update projection always serializes");
366        format!("{:x}", Sha256::digest(encoded))
367    }
368
369    /// Returns an iterator over the resources in the stack, including their lifecycle state.
370    pub fn resources(&self) -> impl Iterator<Item = (&String, &ResourceEntry)> {
371        self.resources.iter()
372    }
373
374    /// Returns a mutable iterator over the resources in the stack, including their lifecycle state.
375    pub fn resources_mut(&mut self) -> impl Iterator<Item = (&String, &mut ResourceEntry)> {
376        self.resources.iter_mut()
377    }
378
379    pub fn id(&self) -> &str {
380        &self.id
381    }
382
383    /// Create a reference to the current stack
384    pub fn current() -> StackRef {
385        StackRef::Current
386    }
387
388    /// Returns the permissions configuration for the stack.
389    pub fn permissions(&self) -> &PermissionsConfig {
390        &self.permissions
391    }
392
393    /// Returns the permission profiles for the stack.
394    pub fn permission_profiles(&self) -> &IndexMap<String, PermissionProfile> {
395        &self.permissions.profiles
396    }
397
398    /// Returns the management permissions configuration for the stack.
399    pub fn management(&self) -> &ManagementPermissions {
400        &self.permissions.management
401    }
402
403    /// Returns the supported platforms, or None if all platforms are supported.
404    pub fn supported_platforms(&self) -> Option<&[Platform]> {
405        self.supported_platforms.as_deref()
406    }
407
408    /// Returns stack input definitions.
409    pub fn inputs(&self) -> &[StackInputDefinition] {
410        &self.inputs
411    }
412
413    /// Returns true if the given platform is supported by this stack.
414    /// When supported_platforms is None, all platforms are supported.
415    pub fn supports_platform(&self, platform: &Platform) -> bool {
416        match &self.supported_platforms {
417            Some(platforms) => platforms.contains(platform),
418            None => true,
419        }
420    }
421
422    /// The descriptor of a resource type an extension in this stack defines. `None` for a
423    /// built-in type, even when a manifest lists it, for a type listed only by an extension whose
424    /// name is not the type's prefix, and for a type no extension defines.
425    pub fn descriptor(
426        &self,
427        resource_type: &ResourceType,
428    ) -> Option<&crate::ResourceTypeDescriptor> {
429        self.defining_extension(resource_type)
430            .and_then(|extension| extension.resource_types.get(resource_type))
431    }
432
433    /// The extension in this stack that defines `resource_type`.
434    fn defining_extension(
435        &self,
436        resource_type: &ResourceType,
437    ) -> Option<&crate::ExtensionManifest> {
438        if !crate::custom_resource::is_custom_resource_type(resource_type.as_ref()) {
439            return None;
440        }
441        self.extensions.iter().find(|extension| {
442            extension.owns(resource_type) && extension.resource_types.contains_key(resource_type)
443        })
444    }
445
446    /// Refuses to set up resource `resource_id` with `format` on `platform` when its type comes
447    /// from an extension that has no part for that format and platform. A setup path a custom
448    /// resource lacks is off for every stack that uses it, and the error says why. Alien's own
449    /// types pass.
450    pub fn check_setup_format(
451        &self,
452        resource_id: &str,
453        resource_type: &ResourceType,
454        format: crate::SetupFormat,
455        platform: Platform,
456    ) -> crate::Result<()> {
457        let Some(extension) = self.defining_extension(resource_type) else {
458            return Ok(());
459        };
460        if extension.resource_types[resource_type]
461            .setup
462            .platforms(format)
463            .contains(&platform)
464        {
465            return Ok(());
466        }
467        Err(alien_error::AlienError::new(
468            crate::ErrorData::OperationNotSupported {
469                operation: format!("{format} setup"),
470                reason: format!(
471                    "resource '{resource_id}' has type {resource_type} from extension '{}', which has no {format} emitter for it on {platform}, so {format} setup is off for every stack that uses it",
472                    extension.name
473                ),
474            },
475        ))
476    }
477}
478
479fn canonicalize_json(value: &mut serde_json::Value) {
480    match value {
481        serde_json::Value::Array(values) => {
482            for value in values {
483                canonicalize_json(value);
484            }
485        }
486        serde_json::Value::Object(object) => {
487            let mut entries = std::mem::take(object).into_iter().collect::<Vec<_>>();
488            entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
489            for (key, mut value) in entries {
490                canonicalize_json(&mut value);
491                object.insert(key, value);
492            }
493        }
494        _ => {}
495    }
496}
497
498impl StackBuilder {
499    /// Adds an entry with authored presentation metadata and lifecycle settings.
500    pub fn add_entry(self, entry: ResourceEntry) -> Self {
501        self.insert(entry)
502    }
503
504    /// Adds a resource to the stack with its lifecycle state.
505    /// The resource's intrinsic dependencies (from resource.get_dependencies()) are automatically included.
506    /// Use add_with_dependencies() if you need to specify additional dependencies.
507    pub fn add<T: crate::ResourceDefinition>(
508        self,
509        resource: T,
510        lifecycle: ResourceLifecycle,
511    ) -> Self {
512        self.add_with_dependencies(resource, lifecycle, vec![])
513    }
514
515    /// Adds a resource to the stack with its lifecycle state and additional dependencies.
516    /// The total dependencies will be: resource.get_dependencies() + additional_dependencies
517    pub fn add_with_dependencies<T: crate::ResourceDefinition>(
518        self,
519        resource: T,
520        lifecycle: ResourceLifecycle,
521        additional_dependencies: Vec<ResourceRef>,
522    ) -> Self {
523        let mut entry = Self::entry(resource, lifecycle);
524        entry.dependencies = additional_dependencies;
525        self.insert(entry)
526    }
527
528    /// Adds a resource whose creation follows a boolean stack input.
529    /// The deployer's answer decides whether it is provisioned at all.
530    ///
531    /// Stacks are authored through the TypeScript SDK's `.enabled(input)`, which
532    /// sets the field on the resource; this is the Rust-side seam the generator
533    /// and preflight tests build gated stacks with.
534    #[doc(hidden)]
535    pub fn add_enabled_when<T: crate::ResourceDefinition>(
536        self,
537        resource: T,
538        lifecycle: ResourceLifecycle,
539        input_id: impl Into<String>,
540    ) -> Self {
541        let mut entry = Self::entry(resource, lifecycle);
542        entry.enabled_when = Some(input_id.into());
543        self.insert(entry)
544    }
545
546    /// Adds a resource with remote access enabled.
547    /// When remote_access is true, binding params are synced to StackState for external access.
548    pub fn add_with_remote_access<T: crate::ResourceDefinition>(
549        self,
550        resource: T,
551        lifecycle: ResourceLifecycle,
552    ) -> Self {
553        let mut entry = Self::entry(resource, lifecycle);
554        entry.remote_access = true;
555        self.insert(entry)
556    }
557
558    /// The only place a `ResourceEntry` is spelled out. Each public `add_*`
559    /// varies one field of it, so a new per-entry field costs one edit here
560    /// instead of one per method.
561    fn entry<T: crate::ResourceDefinition>(
562        resource: T,
563        lifecycle: ResourceLifecycle,
564    ) -> ResourceEntry {
565        ResourceEntry {
566            config: Resource::new(resource),
567            lifecycle,
568            dependencies: Vec::new(),
569            display_name: None,
570            description: None,
571            remote_access: false,
572            enabled_when: None,
573        }
574    }
575
576    fn insert(mut self, entry: ResourceEntry) -> Self {
577        self.resources.insert(entry.config.id().to_string(), entry);
578        self
579    }
580
581    /// Sets the permissions configuration for the stack.
582    /// This defines access control for compute services in the stack.
583    pub fn permissions(mut self, permissions: PermissionsConfig) -> Self {
584        self.permissions = permissions;
585        self
586    }
587
588    /// Add a single permission profile to the stack - allows fluent chaining
589    ///
590    /// # Example
591    /// ```rust
592    /// # use alien_core::{Stack, permissions::PermissionProfile};
593    /// Stack::new("my-stack".to_string())
594    ///     .permission("execution", PermissionProfile::new().global(["storage/data-read"]))
595    ///     .permission("management", PermissionProfile::new().global(["storage/management"]))
596    ///     .build()
597    /// # ;
598    /// ```
599    pub fn permission(mut self, name: impl Into<String>, profile: PermissionProfile) -> Self {
600        self.permissions.profiles.insert(name.into(), profile);
601        self
602    }
603
604    /// Sets the supported platforms for this stack.
605    pub fn platforms(mut self, platforms: Vec<Platform>) -> Self {
606        self.supported_platforms = Some(platforms);
607        self
608    }
609
610    /// Sets stack input definitions.
611    pub fn inputs(mut self, inputs: Vec<StackInputDefinition>) -> Self {
612        self.inputs = inputs;
613        self
614    }
615
616    /// Declares the operations this stack's deployments run.
617    pub fn operations(mut self, operations: crate::OperationsConfig) -> Self {
618        self.operations = Some(operations);
619        self
620    }
621
622    /// Sets the management permissions configuration for the stack.
623    /// This defines how management permissions are derived and configured.
624    ///
625    /// # Examples
626    /// ```rust
627    /// # use alien_core::{Stack, permissions::{ManagementPermissions, PermissionProfile}};
628    /// // Auto-derived management permissions (default)
629    /// Stack::new("my-stack".to_string())
630    ///     .management(ManagementPermissions::auto())
631    ///     .build();
632    ///
633    /// // Extend auto-derived permissions
634    /// Stack::new("my-stack".to_string())
635    ///     .management(ManagementPermissions::extend(
636    ///         PermissionProfile::new().global(["vault/data-write"])
637    ///     ))
638    ///     .build();
639    ///
640    /// // Override auto-derived permissions entirely
641    /// Stack::new("my-stack".to_string())
642    ///     .management(ManagementPermissions::override_(
643    ///         PermissionProfile::new().global(["storage/heartbeat", "worker/provision"])
644    ///     ))
645    ///     .build();
646    /// ```
647    pub fn management(mut self, management: ManagementPermissions) -> Self {
648        self.permissions.management = management;
649        self
650    }
651}
652
653/// Reference to a stack for management permissions
654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
655#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
656#[serde(rename_all = "camelCase")]
657pub enum StackRef {
658    /// Reference to the current stack being built
659    Current,
660    /// Reference to another stack by ID
661    External(String),
662}
663
664impl StackRef {
665    /// Create a StackRef from a stack reference
666    pub fn from_stack(stack: &Stack) -> Self {
667        StackRef::External(stack.id().to_string())
668    }
669}
670
671impl From<&Stack> for StackRef {
672    fn from(stack: &Stack) -> Self {
673        StackRef::External(stack.id().to_string())
674    }
675}
676
677#[cfg(test)]
678mod tests {
679    use super::*;
680    use crate::resource::ResourceLifecycle;
681    use crate::{
682        Container, ContainerCode, Daemon, DaemonCode, PermissionSetReference, ResourceSpec,
683        Storage, Worker, WorkerCode,
684    };
685    use insta::assert_json_snapshot;
686
687    fn resource_entry<T: crate::ResourceDefinition>(
688        resource: T,
689        lifecycle: ResourceLifecycle,
690        remote_access: bool,
691    ) -> ResourceEntry {
692        ResourceEntry {
693            config: Resource::new(resource),
694            lifecycle,
695            dependencies: Vec::new(),
696            display_name: None,
697            description: None,
698            remote_access,
699            enabled_when: None,
700        }
701    }
702
703    /// The grant is rendered by setup, so a resource setup renders nothing for — a Live bucket —
704    /// cannot be published, while a Live sandbox can: setup still installs its scaffolding.
705    #[test]
706    fn remote_bindings_require_a_setup_rendered_resource_and_opt_in() {
707        assert!(resource_entry(
708            Storage::new("archive".to_string()).build(),
709            ResourceLifecycle::Frozen,
710            true,
711        )
712        .has_remote_bindings());
713        assert!(!resource_entry(
714            Storage::new("archive".to_string()).build(),
715            ResourceLifecycle::Frozen,
716            false,
717        )
718        .has_remote_bindings());
719        assert!(!resource_entry(
720            Storage::new("archive".to_string()).build(),
721            ResourceLifecycle::Live,
722            true,
723        )
724        .has_remote_bindings());
725        let sandbox = crate::Sandbox::new("agents".to_string())
726            .code(crate::SandboxCode::Image {
727                image: "s3://alien-bundles/sandbox/bundle.zip".to_string(),
728                bundled_from: None,
729            })
730            .egress(crate::SandboxEgress::Allow)
731            .lifecycle(crate::SandboxLifecyclePolicy {
732                max_lifetime_seconds: None,
733                idle_pause_seconds: None,
734                ..Default::default()
735            })
736            .build();
737        assert!(resource_entry(sandbox, ResourceLifecycle::Live, true).has_remote_bindings());
738        assert!(!resource_entry(
739            Worker::new("worker".to_string())
740                .code(WorkerCode::Image {
741                    image: "example.com/worker:latest".to_string(),
742                })
743                .permissions("worker-execution".to_string())
744                .build(),
745            ResourceLifecycle::Frozen,
746            true,
747        )
748        .has_remote_bindings());
749    }
750
751    #[test]
752    fn test_stack_serialization() {
753        use crate::WorkerCode;
754
755        let storage = Storage::new("my-bucket".to_string())
756            .public_read(true)
757            .build();
758
759        let worker = Worker::new("my-worker".to_string())
760            .code(WorkerCode::Image {
761                image: "rust:latest".to_string(),
762            })
763            .permissions("execution".to_string())
764            .link(&storage)
765            .build();
766
767        // Create permission profiles for the new system
768        let mut permissions = IndexMap::new();
769        let mut execution_profile = PermissionProfile::new();
770        execution_profile.0.insert(
771            "*".to_string(),
772            vec![
773                PermissionSetReference::from_name("storage/data-read"),
774                PermissionSetReference::from_name("storage/data-write"),
775            ],
776        );
777        permissions.insert("execution".to_string(), execution_profile);
778
779        let stack_builder = Stack::new("test-stack".to_string())
780            .add(storage, ResourceLifecycle::Frozen)
781            .add(worker.clone(), ResourceLifecycle::Live);
782
783        let stack = stack_builder
784            .permissions(PermissionsConfig {
785                profiles: permissions,
786                management: ManagementPermissions::Auto,
787            })
788            .build();
789
790        // Serialize and Deserialize
791        let serialized_stack =
792            serde_json::to_string_pretty(&stack).expect("Failed to serialize stack");
793        let deserialized_stack: Stack =
794            serde_json::from_str(&serialized_stack).expect("Failed to deserialize stack");
795
796        // Assert equality
797        assert_eq!(
798            stack, deserialized_stack,
799            "Original and deserialized stacks do not match."
800        );
801
802        // Verify snapshot (sort maps to be deterministic across Rust versions)
803        let mut settings = insta::Settings::clone_current();
804        settings.set_sort_maps(true);
805        settings.bind(|| {
806            assert_json_snapshot!("stack_serialization_account_managed", stack);
807        });
808    }
809
810    #[test]
811    fn test_empty_stack_serialization() {
812        let stack_builder = Stack::new("empty-test-stack".to_string());
813
814        let stack = stack_builder
815            .permissions(PermissionsConfig::new()) // Empty permissions for existing tests
816            .build();
817
818        // Serialize and Deserialize
819        let serialized_stack =
820            serde_json::to_string_pretty(&stack).expect("Failed to serialize empty stack");
821        let deserialized_stack: Stack =
822            serde_json::from_str(&serialized_stack).expect("Failed to deserialize empty stack");
823
824        // Assert equality
825        assert_eq!(
826            stack, deserialized_stack,
827            "Original and deserialized empty stacks do not match."
828        );
829
830        // Verify snapshot (sort maps to be deterministic across Rust versions)
831        let mut settings = insta::Settings::clone_current();
832        settings.set_sort_maps(true);
833        settings.bind(|| {
834            assert_json_snapshot!("empty_stack_serialization_account", stack);
835        });
836    }
837
838    #[test]
839    fn stack_deserializes_resources_without_public_endpoints() {
840        let container = Container::new("api".to_string())
841            .code(ContainerCode::Image {
842                image: "example.com/api:latest".to_string(),
843            })
844            .cpu(ResourceSpec {
845                min: "0.5".to_string(),
846                desired: "1".to_string(),
847            })
848            .memory(ResourceSpec {
849                min: "512Mi".to_string(),
850                desired: "1Gi".to_string(),
851            })
852            .port(8080)
853            .permissions("container-execution".to_string())
854            .build();
855        let daemon = Daemon::new("agent".to_string())
856            .code(DaemonCode::Image {
857                image: "example.com/agent:latest".to_string(),
858            })
859            .permissions("daemon-execution".to_string())
860            .build();
861        let worker = Worker::new("worker".to_string())
862            .code(WorkerCode::Image {
863                image: "example.com/worker:latest".to_string(),
864            })
865            .permissions("worker-execution".to_string())
866            .build();
867        let stack = Stack::new("legacy-stack".to_string())
868            .add(container, ResourceLifecycle::Live)
869            .add(daemon, ResourceLifecycle::Live)
870            .add(worker, ResourceLifecycle::Live)
871            .build();
872
873        let mut legacy_json = serde_json::to_value(stack).expect("stack should serialize");
874        for resource_id in ["api", "agent", "worker"] {
875            legacy_json
876                .pointer_mut(&format!("/resources/{resource_id}/config"))
877                .and_then(serde_json::Value::as_object_mut)
878                .expect("resource config should be an object")
879                .remove("publicEndpoints");
880        }
881
882        let stack: Stack =
883            serde_json::from_value(legacy_json).expect("legacy stack should deserialize");
884
885        let container = stack
886            .resources
887            .get("api")
888            .and_then(|entry| entry.config.downcast_ref::<Container>())
889            .expect("api should be a container");
890        assert!(container.public_endpoints.is_empty());
891
892        let daemon = stack
893            .resources
894            .get("agent")
895            .and_then(|entry| entry.config.downcast_ref::<Daemon>())
896            .expect("agent should be a daemon");
897        assert!(daemon.public_endpoints.is_empty());
898
899        let worker = stack
900            .resources
901            .get("worker")
902            .and_then(|entry| entry.config.downcast_ref::<Worker>())
903            .expect("worker should be a worker");
904        assert!(worker.public_endpoints.is_empty());
905    }
906
907    #[test]
908    fn test_stack_with_permissions() {
909        use crate::permissions::PermissionProfile;
910        use indexmap::IndexMap;
911
912        // Create a simple stack with permissions
913        let storage = Storage::new("test-storage".to_string()).build();
914
915        // Create a permission profile
916        let mut permission_profile = PermissionProfile::new();
917        permission_profile.0.insert(
918            "*".to_string(),
919            vec![PermissionSetReference::from_name("storage/data-read")],
920        );
921
922        let mut permissions = IndexMap::new();
923        permissions.insert("reader".to_string(), permission_profile);
924
925        let stack = Stack::new("test-permissions-stack".to_string())
926            .add(storage, ResourceLifecycle::Frozen)
927            .permissions(PermissionsConfig {
928                profiles: permissions,
929                management: ManagementPermissions::Auto,
930            })
931            .build();
932
933        // Verify permissions are accessible
934        assert_eq!(stack.permission_profiles().len(), 1);
935        assert!(stack.permission_profiles().contains_key("reader"));
936
937        let reader_profile = stack.permission_profiles().get("reader").unwrap();
938        assert_eq!(reader_profile.0.len(), 1);
939        assert!(reader_profile.0.contains_key("*"));
940
941        let global_permissions = reader_profile.0.get("*").unwrap();
942        assert_eq!(
943            global_permissions,
944            &vec![PermissionSetReference::from_name("storage/data-read")]
945        );
946
947        // Test serialization/deserialization
948        let serialized = serde_json::to_string_pretty(&stack).expect("Failed to serialize");
949        let deserialized: Stack = serde_json::from_str(&serialized).expect("Failed to deserialize");
950        assert_eq!(stack, deserialized);
951    }
952
953    #[test]
954    fn test_stack_with_management_permissions() {
955        use crate::permissions::{ManagementPermissions, PermissionProfile};
956
957        // Create a simple stack with management permissions
958        let storage = Storage::new("test-storage".to_string()).build();
959
960        // Create a permission profile for management
961        let mut management_profile = PermissionProfile::new();
962        management_profile.0.insert(
963            "*".to_string(),
964            vec![PermissionSetReference::from_name("vault/data-write")],
965        );
966
967        // Test auto management permissions (default)
968        let stack_auto = Stack::new("test-auto-management-stack".to_string())
969            .add(storage.clone(), ResourceLifecycle::Frozen)
970            .management(ManagementPermissions::auto())
971            .build();
972
973        assert!(stack_auto.management().is_auto());
974        assert!(stack_auto.management().profile().is_none());
975
976        // Test extend management permissions
977        let stack_extend = Stack::new("test-extend-management-stack".to_string())
978            .add(storage.clone(), ResourceLifecycle::Frozen)
979            .management(ManagementPermissions::extend(management_profile.clone()))
980            .build();
981
982        assert!(stack_extend.management().is_extend());
983        assert_eq!(
984            stack_extend.management().profile().unwrap(),
985            &management_profile
986        );
987
988        // Test override management permissions
989        let stack_override = Stack::new("test-override-management-stack".to_string())
990            .add(storage.clone(), ResourceLifecycle::Frozen)
991            .management(ManagementPermissions::override_(management_profile.clone()))
992            .build();
993
994        assert!(stack_override.management().is_override());
995        assert_eq!(
996            stack_override.management().profile().unwrap(),
997            &management_profile
998        );
999
1000        // Test default management permissions
1001        let stack_default = Stack::new("test-default-management-stack".to_string())
1002            .add(storage, ResourceLifecycle::Frozen)
1003            .build();
1004
1005        assert!(stack_default.management().is_auto());
1006
1007        // Test serialization/deserialization with management
1008        let serialized = serde_json::to_string_pretty(&stack_extend).expect("Failed to serialize");
1009        let deserialized: Stack = serde_json::from_str(&serialized).expect("Failed to deserialize");
1010        assert_eq!(stack_extend, deserialized);
1011    }
1012
1013    fn dead_letter_stack(with_worker: bool, worker_lifecycle: ResourceLifecycle) -> Stack {
1014        use crate::{Queue, QueueDeadLetter, Worker, WorkerCode, WorkerTrigger};
1015        let failed = Queue::new("failed".to_string()).build();
1016        let tasks = Queue::new("tasks".to_string())
1017            .dead_letter(
1018                QueueDeadLetter::builder()
1019                    .queue(ResourceRef::new(Queue::RESOURCE_TYPE, "failed"))
1020                    .build(),
1021            )
1022            .build();
1023        let mut stack = Stack::new("dlq".to_string())
1024            .add(failed, ResourceLifecycle::Frozen)
1025            .add(tasks.clone(), ResourceLifecycle::Frozen);
1026        if with_worker {
1027            stack = stack.add(
1028                Worker::new("consumer".to_string())
1029                    .code(WorkerCode::Image {
1030                        image: "img".to_string(),
1031                    })
1032                    .permissions("execution".to_string())
1033                    .trigger(WorkerTrigger::queue(&tasks))
1034                    .build(),
1035                worker_lifecycle,
1036            );
1037        }
1038        stack.build()
1039    }
1040
1041    #[test]
1042    fn a_live_worker_trigger_on_a_frozen_dead_letter_queue_changes_the_setup_digest() {
1043        let without = dead_letter_stack(false, ResourceLifecycle::Live);
1044        let with = dead_letter_stack(true, ResourceLifecycle::Live);
1045        // The Worker is not setup-owned, so only the derived queue field can differ.
1046        assert_ne!(without.setup_update_digest(), with.setup_update_digest());
1047        assert_ne!(without.setup_owned_digest(), with.setup_owned_digest());
1048    }
1049
1050    #[test]
1051    fn the_dead_letter_queue_digest_is_unchanged_when_no_project_grant_is_needed() {
1052        // Without a Worker trigger, or with a setup-owned Worker (setup grants on its
1053        // subscription directly), the digest field must stay absent.
1054        let plain_stack = dead_letter_stack(false, ResourceLifecycle::Live);
1055        let (plain, _) = plain_stack.setup_owned_projection();
1056        assert!(plain
1057            .iter()
1058            .all(|(_, v)| v.get("queueProjectPushSubscriber").is_none()));
1059        let frozen_stack = dead_letter_stack(true, ResourceLifecycle::Frozen);
1060        let (frozen_worker, _) = frozen_stack.setup_owned_projection();
1061        assert!(frozen_worker
1062            .iter()
1063            .all(|(_, v)| v.get("queueProjectPushSubscriber").is_none()));
1064        let live_stack = dead_letter_stack(true, ResourceLifecycle::Live);
1065        let (live_worker, _) = live_stack.setup_owned_projection();
1066        assert!(live_worker
1067            .iter()
1068            .any(|(id, v)| *id == "tasks" && v["queueProjectPushSubscriber"] == true));
1069        assert!(live_worker
1070            .iter()
1071            .filter(|(id, _)| *id != "tasks")
1072            .all(|(_, v)| v.get("queueProjectPushSubscriber").is_none()));
1073    }
1074
1075    #[test]
1076    fn presentation_metadata_preserves_setup_fingerprints_and_old_entries() {
1077        let original = Stack::new("metadata".to_string())
1078            .add(
1079                Storage::new("documents".to_string()).build(),
1080                ResourceLifecycle::Frozen,
1081            )
1082            .build();
1083        let mut documented = original.clone();
1084        let entry = documented.resources.get_mut("documents").unwrap();
1085        entry.display_name = Some("Document storage".to_string());
1086        entry.description = Some("Uploaded documents and processed results.".to_string());
1087        assert_eq!(
1088            original.setup_owned_digest(),
1089            documented.setup_owned_digest()
1090        );
1091        assert_eq!(
1092            original.setup_update_digest(),
1093            documented.setup_update_digest()
1094        );
1095        assert_eq!(
1096            original.resources["documents"].config,
1097            documented.resources["documents"].config
1098        );
1099        let old_json = serde_json::to_value(&original).unwrap();
1100        assert!(old_json["resources"]["documents"]
1101            .get("displayName")
1102            .is_none());
1103        let loaded: Stack = serde_json::from_value(old_json).unwrap();
1104        assert_eq!(
1105            loaded.resources["documents"].display_name_or_id(),
1106            "documents"
1107        );
1108        assert!(loaded.resources["documents"].description.is_none());
1109        let round_trip: Stack =
1110            serde_json::from_value(serde_json::to_value(&documented).unwrap()).unwrap();
1111        assert_eq!(round_trip, documented);
1112    }
1113
1114    fn digest_sandbox(id: &str, image: &str, private_base_image: Option<&str>) -> crate::Sandbox {
1115        crate::Sandbox::new(id.to_string())
1116            .code(crate::SandboxCode::Image {
1117                image: image.to_string(),
1118                bundled_from: None,
1119            })
1120            .maybe_private_base_image(private_base_image.map(str::to_string))
1121            .egress(crate::SandboxEgress::None)
1122            .lifecycle(crate::SandboxLifecyclePolicy {
1123                max_lifetime_seconds: None,
1124                idle_pause_seconds: None,
1125                ..Default::default()
1126            })
1127            .build()
1128    }
1129
1130    /// Stored setup authorizations carry this digest, so its bytes must not move for any stack
1131    /// without a Live sandbox.
1132    #[test]
1133    fn setup_owned_digest_is_stable_without_a_live_sandbox() {
1134        let stack = Stack::new("golden".to_string())
1135            .add(
1136                Storage::new("ledger".to_string()).build(),
1137                ResourceLifecycle::Frozen,
1138            )
1139            .add(
1140                digest_sandbox(
1141                    "frozen-agents",
1142                    "s3://bucket/frozen.zip",
1143                    Some("123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base:1"),
1144                ),
1145                ResourceLifecycle::Frozen,
1146            )
1147            .add(
1148                Storage::new("scratch".to_string()).build(),
1149                ResourceLifecycle::Live,
1150            )
1151            .build();
1152
1153        assert_eq!(
1154            stack.setup_owned_digest(),
1155            "aacf34583a0bb9e3d48dd08be0bdd1da0f1d1e3666f93b844ecb0e1506ca537e"
1156        );
1157    }
1158
1159    struct LiveSandbox {
1160        image: &'static str,
1161        private_base_image: Option<&'static str>,
1162        egress: crate::SandboxEgress,
1163        network_id: &'static str,
1164        remote_access: bool,
1165    }
1166
1167    const BASE_A: &str = "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-a:1";
1168
1169    impl LiveSandbox {
1170        fn installed() -> Self {
1171            Self {
1172                image: "s3://bucket/sandbox-bundle/v1/bundle.zip",
1173                private_base_image: Some(BASE_A),
1174                egress: crate::SandboxEgress::Allow,
1175                network_id: "net-a",
1176                remote_access: false,
1177            }
1178        }
1179
1180        fn digest(self) -> String {
1181            let mut sandbox = digest_sandbox("agents", self.image, self.private_base_image);
1182            sandbox.egress = self.egress;
1183            let mut stack = Stack::new("stack".to_string())
1184                .add(
1185                    crate::Network::new(self.network_id.to_string())
1186                        .settings(crate::NetworkSettings::Create {
1187                            cidr: Some("10.0.0.0/16".to_string()),
1188                            availability_zones: 2,
1189                        })
1190                        .build(),
1191                    ResourceLifecycle::Frozen,
1192                )
1193                .add(sandbox, ResourceLifecycle::Live)
1194                .build();
1195            stack
1196                .resources
1197                .get_mut("agents")
1198                .expect("sandbox")
1199                .remote_access = self.remote_access;
1200            let entry = &stack.resources["agents"];
1201            crate::sandbox_setup_inputs::aws_sandbox_setup_inputs(
1202                &stack,
1203                entry.config.downcast_ref().expect("sandbox"),
1204                entry.lifecycle,
1205                crate::sandbox_setup_inputs::SETUP_INPUTS_COMPARISON_ACCOUNT,
1206            )
1207            .expect("the inputs resolve, so no case is compared by its whole configuration");
1208            stack.setup_owned_digest()
1209        }
1210    }
1211
1212    #[test]
1213    fn setup_owned_digest_follows_a_live_sandboxs_setup_inputs_but_not_its_image() {
1214        let installed = LiveSandbox::installed().digest();
1215
1216        for (unchanged, why) in [
1217            (
1218                LiveSandbox {
1219                    image: "s3://bucket/sandbox-bundle/v2/bundle.zip",
1220                    ..LiveSandbox::installed()
1221                },
1222                "a new bundle under the same prefix",
1223            ),
1224            (
1225                LiveSandbox {
1226                    private_base_image: Some(
1227                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-a:2",
1228                    ),
1229                    ..LiveSandbox::installed()
1230                },
1231                "a new tag",
1232            ),
1233            (
1234                LiveSandbox {
1235                    private_base_image: Some(
1236                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-a@sha256:abc",
1237                    ),
1238                    ..LiveSandbox::installed()
1239                },
1240                "a digest",
1241            ),
1242            (
1243                LiveSandbox {
1244                    private_base_image: Some(
1245                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-b:1",
1246                    ),
1247                    ..LiveSandbox::installed()
1248                },
1249                "another repository",
1250            ),
1251            (
1252                LiveSandbox {
1253                    private_base_image: Some(
1254                        "210987654321.dkr.ecr.us-east-1.amazonaws.com/team/base-a:1",
1255                    ),
1256                    ..LiveSandbox::installed()
1257                },
1258                "another account",
1259            ),
1260            (
1261                LiveSandbox {
1262                    private_base_image: Some(
1263                        "123456789012.dkr.ecr.{region}.amazonaws.com/team/base-a:1",
1264                    ),
1265                    ..LiveSandbox::installed()
1266                },
1267                "the deployment's region",
1268            ),
1269            (
1270                LiveSandbox {
1271                    image: "s3://other-bucket/sandbox-bundle/v1/bundle.zip",
1272                    ..LiveSandbox::installed()
1273                },
1274                "another bundle bucket",
1275            ),
1276        ] {
1277            assert_eq!(
1278                installed,
1279                unchanged.digest(),
1280                "{why} is the runtime's to roll: a Live sandbox builds from the store and repository its setup granted"
1281            );
1282        }
1283
1284        for (changed, what) in [
1285            (
1286                LiveSandbox {
1287                    private_base_image: None,
1288                    ..LiveSandbox::installed()
1289                },
1290                "a dropped private base",
1291            ),
1292            (
1293                LiveSandbox {
1294                    egress: crate::SandboxEgress::None,
1295                    ..LiveSandbox::installed()
1296                },
1297                "egress allow to deny",
1298            ),
1299            (
1300                LiveSandbox {
1301                    image: "s3://bucket/other-prefix/v1/bundle.zip",
1302                    ..LiveSandbox::installed()
1303                },
1304                "another bundle prefix",
1305            ),
1306            (
1307                LiveSandbox {
1308                    remote_access: true,
1309                    ..LiveSandbox::installed()
1310                },
1311                "a remote grant",
1312            ),
1313            (
1314                LiveSandbox {
1315                    private_base_image: Some(
1316                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/cache/team/base-a:1",
1317                    ),
1318                    ..LiveSandbox::installed()
1319                },
1320                "a base repository in another namespace",
1321            ),
1322            (
1323                LiveSandbox {
1324                    private_base_image: Some(
1325                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/base-a:1",
1326                    ),
1327                    ..LiveSandbox::installed()
1328                },
1329                "a base repository with no namespace",
1330            ),
1331        ] {
1332            assert_ne!(installed, changed.digest(), "{what} is setup-owned");
1333        }
1334
1335        let deny = |network_id| {
1336            LiveSandbox {
1337                egress: crate::SandboxEgress::None,
1338                network_id,
1339                ..LiveSandbox::installed()
1340            }
1341            .digest()
1342        };
1343        assert_ne!(
1344            deny("net-a"),
1345            deny("net-b"),
1346            "the connector's network is setup-owned"
1347        );
1348    }
1349
1350    #[test]
1351    fn setup_owned_digest_is_order_independent() {
1352        let first = Stack::new("first".to_string())
1353            .add(
1354                Storage::new("alpha".to_string()).build(),
1355                ResourceLifecycle::Frozen,
1356            )
1357            .add(
1358                Storage::new("beta".to_string()).build(),
1359                ResourceLifecycle::Frozen,
1360            )
1361            .add(
1362                Storage::new("live-one".to_string()).build(),
1363                ResourceLifecycle::Live,
1364            )
1365            .build();
1366        let second = Stack::new("second".to_string())
1367            .add(
1368                Storage::new("beta".to_string()).build(),
1369                ResourceLifecycle::Frozen,
1370            )
1371            .add(
1372                Storage::new("alpha".to_string()).build(),
1373                ResourceLifecycle::Frozen,
1374            )
1375            .add(
1376                Storage::new("live-two".to_string()).build(),
1377                ResourceLifecycle::Live,
1378            )
1379            .build();
1380
1381        assert_eq!(first.setup_owned_digest(), second.setup_owned_digest());
1382        assert_eq!(
1383            first.setup_owned_entry_digests(),
1384            second.setup_owned_entry_digests()
1385        );
1386    }
1387
1388    #[test]
1389    fn setup_owned_entry_digests_name_only_the_changed_entries() {
1390        let installed = Stack::new("stack".to_string())
1391            .add(
1392                Storage::new("alpha".to_string()).build(),
1393                ResourceLifecycle::Frozen,
1394            )
1395            .add(
1396                Storage::new("beta".to_string()).build(),
1397                ResourceLifecycle::Frozen,
1398            )
1399            .add(
1400                Storage::new("live".to_string()).build(),
1401                ResourceLifecycle::Live,
1402            )
1403            .build();
1404        let target = Stack::new("stack".to_string())
1405            .add(
1406                Storage::new("alpha".to_string()).build(),
1407                ResourceLifecycle::Frozen,
1408            )
1409            .add(
1410                Storage::new("beta".to_string()).versioning(true).build(),
1411                ResourceLifecycle::Frozen,
1412            )
1413            .add(
1414                Storage::new("live".to_string()).versioning(true).build(),
1415                ResourceLifecycle::Live,
1416            )
1417            .build();
1418
1419        let installed_entries = installed.setup_owned_entry_digests();
1420        let target_entries = target.setup_owned_entry_digests();
1421        assert_ne!(installed.setup_owned_digest(), target.setup_owned_digest());
1422        assert_eq!(
1423            installed_entries.keys().collect::<Vec<_>>(),
1424            vec!["alpha", "beta"]
1425        );
1426        assert_eq!(
1427            installed_entries.keys().collect::<Vec<_>>(),
1428            target_entries.keys().collect::<Vec<_>>()
1429        );
1430        assert_eq!(installed_entries["alpha"], target_entries["alpha"]);
1431        assert_ne!(installed_entries["beta"], target_entries["beta"]);
1432        assert!(installed_entries
1433            .values()
1434            .chain(target_entries.values())
1435            .all(|digest| digest.len() == 64));
1436    }
1437
1438    /// The manifest `alien extensions build` writes for the docs' DNS zone, in its wire shape.
1439    fn acme_manifest() -> serde_json::Value {
1440        serde_json::json!({
1441            "name": "acme",
1442            "version": "0.1.0",
1443            "digest": "sha256:4ff931a2",
1444            "resourceTypes": {
1445                "acme/dns-zone": {
1446                    "lifecycles": ["frozen", "live"],
1447                    "holdsData": false,
1448                    "setup": {
1449                        "cloudformation": ["aws"],
1450                        "terraform": ["aws", "gcp", "azure"],
1451                        "helm": ["kubernetes"],
1452                        "importers": ["aws", "gcp", "azure"]
1453                    },
1454                    "controllerPlatforms": ["aws", "gcp", "azure"],
1455                    "permissionSets": [{
1456                        "id": "acme/dns-zone/provision",
1457                        "description": "Create, read and delete the zone",
1458                        "platforms": {
1459                            "aws": [{
1460                                "grant": { "actions": ["route53:CreateHostedZone"] },
1461                                "binding": {
1462                                    "stack": { "resources": ["*"] },
1463                                    "resource": { "resources": ["*"] }
1464                                }
1465                            }]
1466                        }
1467                    }],
1468                    "link": { "permissionSets": ["acme/dns-zone/records-write"] },
1469                    "schemas": {
1470                        "config": { "type": "object", "required": ["id", "domain"] },
1471                        "outputs": { "type": "object", "required": ["zoneId"] }
1472                    }
1473                }
1474            }
1475        })
1476    }
1477
1478    fn dns_zone() -> crate::CustomResource {
1479        crate::CustomResource::from_untagged(
1480            "acme/dns-zone",
1481            serde_json::json!({ "id": "zone", "domain": "internal.acme.dev" }),
1482        )
1483        .unwrap()
1484    }
1485
1486    #[test]
1487    fn a_stack_without_extensions_writes_no_extensions_field() {
1488        let stack = Stack::new("app".to_string())
1489            .add(dns_zone(), ResourceLifecycle::Frozen)
1490            .build();
1491
1492        let json = serde_json::to_value(&stack).unwrap();
1493        assert!(json.get("extensions").is_none(), "{json}");
1494        assert_eq!(serde_json::from_value::<Stack>(json).unwrap(), stack);
1495    }
1496
1497    #[test]
1498    fn a_stack_carries_its_extensions_and_finds_the_types_they_define() {
1499        let mut stack = Stack::new("app".to_string())
1500            .add(dns_zone(), ResourceLifecycle::Frozen)
1501            .build();
1502        stack.extensions = vec![serde_json::from_value(acme_manifest()).unwrap()];
1503
1504        let json = serde_json::to_value(&stack).unwrap();
1505        assert_eq!(json["extensions"], serde_json::json!([acme_manifest()]));
1506        let stack: Stack = serde_json::from_value(json).unwrap();
1507
1508        let descriptor = stack
1509            .descriptor(&ResourceType::from("acme/dns-zone"))
1510            .expect("acme declares acme/dns-zone");
1511        assert!(!descriptor.holds_data);
1512        assert_eq!(
1513            descriptor.lifecycles,
1514            [ResourceLifecycle::Frozen, ResourceLifecycle::Live]
1515        );
1516        assert_eq!(
1517            descriptor.link.permission_sets,
1518            ["acme/dns-zone/records-write"]
1519        );
1520        assert!(stack
1521            .descriptor(&ResourceType::from("acme/record"))
1522            .is_none());
1523    }
1524
1525    #[test]
1526    fn a_descriptor_writes_services_and_the_network_only_when_the_type_asks_for_them() {
1527        let descriptor: crate::ResourceTypeDescriptor =
1528            serde_json::from_value(acme_manifest()["resourceTypes"]["acme/dns-zone"].clone())
1529                .unwrap();
1530        assert!(descriptor.services.is_empty());
1531        assert!(!descriptor.requires_network);
1532        let json = serde_json::to_value(&descriptor).unwrap();
1533        assert_eq!(json, acme_manifest()["resourceTypes"]["acme/dns-zone"]);
1534
1535        let mut asking = json;
1536        asking["services"] = serde_json::json!({
1537            "gcp": ["dns.googleapis.com"],
1538            "azure": ["Microsoft.Network"]
1539        });
1540        asking["requiresNetwork"] = true.into();
1541        let descriptor: crate::ResourceTypeDescriptor =
1542            serde_json::from_value(asking.clone()).unwrap();
1543        assert_eq!(
1544            descriptor.services[&crate::Platform::Gcp],
1545            ["dns.googleapis.com"]
1546        );
1547        assert!(descriptor.requires_network);
1548        assert_eq!(serde_json::to_value(&descriptor).unwrap(), asking);
1549    }
1550
1551    /// A type whose descriptor asks for the network keeps one on Kubernetes, as a cloud
1552    /// database does.
1553    #[test]
1554    fn a_type_that_requires_the_network_keeps_one_like_a_database() {
1555        let zone = crate::CustomResource::from_untagged(
1556            "acme/dns-zone",
1557            serde_json::json!({ "id": "zone", "domain": "internal.acme.dev" }),
1558        )
1559        .unwrap();
1560        let mut stack = Stack::new("app".to_string())
1561            .add(zone, ResourceLifecycle::Frozen)
1562            .build();
1563        let keeps = |stack: &Stack| {
1564            stack
1565                .resources()
1566                .any(|(_, entry)| crate::keeps_cloud_network(stack, entry))
1567        };
1568        let mut manifest = acme_manifest();
1569        stack.extensions = vec![serde_json::from_value(manifest.clone()).unwrap()];
1570        assert!(!keeps(&stack));
1571
1572        manifest["resourceTypes"]["acme/dns-zone"]["requiresNetwork"] = true.into();
1573        stack.extensions = vec![serde_json::from_value(manifest).unwrap()];
1574        assert!(keeps(&stack));
1575    }
1576
1577    /// An extension cannot redefine a built-in type: its descriptor for one is never returned.
1578    #[test]
1579    fn a_manifest_that_lists_a_built_in_type_does_not_describe_it() {
1580        let mut manifest = acme_manifest();
1581        let zone = manifest["resourceTypes"]["acme/dns-zone"].clone();
1582        manifest["resourceTypes"]["storage"] = zone;
1583        let mut stack = Stack::new("app".to_string()).build();
1584        stack.extensions = vec![serde_json::from_value(manifest).unwrap()];
1585
1586        assert!(stack.descriptor(&Storage::RESOURCE_TYPE).is_none());
1587    }
1588
1589    /// Only `acme` can define `acme/dns-zone`, wherever another extension sits in the list.
1590    #[test]
1591    fn a_type_listed_by_an_extension_of_another_name_has_no_descriptor() {
1592        let mut evil = acme_manifest();
1593        evil["name"] = "evil".into();
1594        let mut stack = Stack::new("app".to_string()).build();
1595        stack.extensions = vec![serde_json::from_value(evil).unwrap()];
1596        let zone = ResourceType::from("acme/dns-zone");
1597        assert!(stack.descriptor(&zone).is_none());
1598
1599        stack
1600            .extensions
1601            .push(serde_json::from_value(acme_manifest()).unwrap());
1602        assert!(std::ptr::eq(
1603            stack.descriptor(&zone).unwrap(),
1604            &stack.extensions[1].resource_types[&zone]
1605        ));
1606    }
1607}