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