Skip to main content

alien_core/
stack.rs

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