alien-core 3.3.70

Deploy software into your customers' cloud accounts and keep it fully managed
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
use crate::permissions::{ManagementPermissions, PermissionProfile, PermissionsConfig};
use crate::{
    Platform, Resource, ResourceLifecycle, ResourceRef, ResourceType, StackInputDefinition,
};
use bon::Builder;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::BTreeMap;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct ResourceEntry {
    /// Optional human-readable name. The stable resource ID is the display fallback.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub display_name: Option<String>,
    /// Authored purpose, displayed as plain text. Does not affect resource configuration.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Resource configuration (can be any type of resource)
    pub config: Resource,
    /// Lifecycle management configuration for this resource
    pub lifecycle: ResourceLifecycle,
    /// Additional dependencies for this resource beyond those defined in the resource itself.
    /// The total dependencies are: resource.get_dependencies() + this list
    pub dependencies: Vec<ResourceRef>,
    /// Enable remote bindings for this resource (BYOB use case).
    /// When true, binding params are synced to StackState's `remote_binding_params`.
    /// Default: false (prevents sensitive data in synced state).
    #[serde(default)]
    pub remote_access: bool,
    /// Id of the boolean stack input that decides whether this resource is
    /// created at all. `None` means always create it.
    ///
    /// Set by `.enabled(input)` in the SDK. Setup emitters render the resource
    /// conditionally on the matching template variable, so a deployer who says no
    /// never gets the resource, its outputs, or anything derived from it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enabled_when: Option<String>,
}

impl ResourceEntry {
    /// Creates a resource entry with no presentation metadata.
    pub fn new<T: crate::ResourceDefinition>(resource: T, lifecycle: ResourceLifecycle) -> Self {
        StackBuilder::entry(resource, lifecycle)
    }

    /// Sets the human-readable name without changing the stable resource ID.
    pub fn display_name(mut self, name: impl Into<String>) -> Self {
        self.display_name = Some(name.into());
        self
    }

    /// Describes this resource's purpose without changing its runtime configuration.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    pub fn display_name_or_id(&self) -> &str {
        self.display_name
            .as_deref()
            .unwrap_or_else(|| self.config.id())
    }

    /// Returns intrinsic and stack-authored dependencies in planner order.
    pub fn combined_dependencies(&self) -> Vec<ResourceRef> {
        let mut dependencies = self.config.get_dependencies();
        dependencies.extend(self.dependencies.clone());
        dependencies
    }

    /// Returns whether this resource is published through Remote Bindings.
    ///
    /// Provider emitters use this generic signal to create the stack-level
    /// Remote Bindings identity. Each resource emitter remains responsible for
    /// granting that identity only the resource's declared data-plane access.
    pub fn has_remote_bindings(&self) -> bool {
        crate::remote_bindings::remote_binding_for_entry(self).is_some()
    }

    /// Whether the controller's non-secret binding locator must be synchronized
    /// into stack state. Reserved vault locators support secret sync and metadata
    /// checks, without exposing either vault through the Remote Bindings API.
    pub fn publishes_binding_params(&self) -> bool {
        self.remote_access
            || self
                .config
                .downcast_ref::<crate::Vault>()
                .is_some_and(|vault| {
                    matches!(
                        vault.id.as_str(),
                        crate::SECRETS_VAULT_ID | crate::DEPLOYER_SECRETS_VAULT_ID
                    )
                })
    }
}

/// A bag of resources, unaware of any cloud.
#[derive(Builder, Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
#[builder(start_fn = new)]
pub struct Stack {
    /// Unique identifier for the stack
    #[builder(start_fn)]
    pub id: String,
    /// Map of resource IDs to their configurations and lifecycle settings
    #[builder(field)]
    pub resources: IndexMap<String, ResourceEntry>,
    /// Combined permissions configuration containing both profiles and management
    #[builder(field)]
    #[serde(default)]
    pub permissions: PermissionsConfig,
    /// Which platforms this stack supports. When None, all platforms are supported.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub supported_platforms: Option<Vec<Platform>>,
    /// Input definitions required before setup or deployment can proceed.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub inputs: Vec<StackInputDefinition>,
    /// Exact image repositories approved for containers created after installation.
    /// The runtime API also requires an immutable SHA-256 digest.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dynamic_container_repositories: Vec<String>,
    /// Released Container resources whose image repositories are approved for
    /// containers created after installation.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub dynamic_container_image_resources: Vec<String>,
    /// Operations this stack's deployments run: the plugins, their settings, and
    /// which operations run without approval. Changing them takes a new release.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub operations: Option<crate::OperationsConfig>,
    /// Set by `alien build` for a Kubernetes stack: the CPU architectures of the image
    /// built for each Container, Daemon and Worker, by resource id (more than one means a
    /// multi-architecture image). Pods of a single-architecture image are placed on
    /// matching nodes. A resource with no entry was not recorded (a prebuilt image or an
    /// older release), so no architecture is selected. Build output replaces any value
    /// written in the stack definition.
    ///
    /// Kept on the stack, not on the resources: older managers and Operators read every
    /// resource strictly and refuse a field they do not know, but ignore an unknown
    /// stack-level field.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub built_architectures: BTreeMap<String, Vec<crate::instance_catalog::Architecture>>,
    /// Extensions whose resource types this stack may use, in the order the stack lists them.
    #[builder(field)]
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub extensions: Vec<crate::ExtensionManifest>,
}

impl Stack {
    /// The architectures `alien build` recorded for a workload's image. Empty when none
    /// were recorded.
    pub fn built_architectures_of(
        &self,
        resource_id: &str,
    ) -> &[crate::instance_catalog::Architecture] {
        self.built_architectures
            .get(resource_id)
            .map(Vec::as_slice)
            .unwrap_or_default()
    }

    /// The ids of the stack's own vaults: those the application reads and writes, not the
    /// reserved ones the framework keeps its secrets in.
    pub fn application_vault_ids(&self) -> Vec<String> {
        self.resources()
            .filter(|(_, entry)| entry.config.resource_type() == crate::Vault::RESOURCE_TYPE)
            .map(|(id, _)| id.clone())
            .filter(|id| id != crate::SECRETS_VAULT_ID && id != crate::DEPLOYER_SECRETS_VAULT_ID)
            .collect()
    }
    /// SQS visibility derived from all consumers, including a batch collection window.
    pub fn queue_visibility_timeout_seconds(&self, queue_id: &str) -> u32 {
        self.resources
            .values()
            .filter_map(|entry| {
                let worker = entry.config.downcast_ref::<crate::Worker>()?;
                worker
                    .triggers
                    .iter()
                    .filter_map(|trigger| match trigger {
                        crate::WorkerTrigger::Queue { queue, batch } if queue.id == queue_id => {
                            Some(worker.timeout_seconds.saturating_mul(6).saturating_add(
                                batch.as_ref().map_or(0, |batch| batch.max_window_seconds),
                            ))
                        }
                        _ => None,
                    })
                    .max()
            })
            .max()
            .unwrap_or(30)
            .clamp(30, 43_200)
    }

    /// Explicit consumers whose links grant access to every port on a container.
    /// Cluster-wide reach is separate and remains the backend's existing behavior.
    pub fn container_linkers(&self, container_id: &str) -> Vec<ResourceRef> {
        self.linkers(&ResourceRef::new(
            crate::Container::RESOURCE_TYPE,
            container_id,
        ))
    }

    /// Workloads whose links name `target`, which are the ones that use it at runtime.
    pub fn linkers(&self, target: &ResourceRef) -> Vec<ResourceRef> {
        self.resources
            .iter()
            .filter_map(|(id, entry)| {
                let links = if let Some(resource) = entry.config.downcast_ref::<crate::Worker>() {
                    &resource.links
                } else if let Some(resource) = entry.config.downcast_ref::<crate::Container>() {
                    &resource.links
                } else if let Some(resource) = entry.config.downcast_ref::<crate::Daemon>() {
                    &resource.links
                } else if let Some(resource) = entry.config.downcast_ref::<crate::Build>() {
                    &resource.links
                } else if let Some(resource) = entry.config.downcast_ref::<crate::Sandbox>() {
                    &resource.links
                } else {
                    return None;
                };
                links
                    .contains(target)
                    .then(|| ResourceRef::new(entry.config.resource_type(), id.clone()))
            })
            .collect()
    }

    /// Digest of what setup owns: every Frozen entry plus each Live sandbox's setup inputs. Without
    /// a Live sandbox the bytes equal the Frozen-only projection. Declined gated entries must be
    /// stripped by the caller.
    pub fn setup_owned_digest(&self) -> String {
        let (resources, live_sandbox_inputs) = self.setup_owned_projection();
        let encoded = if live_sandbox_inputs.is_empty() {
            serde_json::to_vec(&resources)
        } else {
            serde_json::to_vec(&(&resources, &live_sandbox_inputs))
        }
        .expect("canonical setup-owned projection always serializes");
        format!("{:x}", Sha256::digest(encoded))
    }

    /// Per-entry digests of the projection `setup_owned_digest` hashes, keyed by resource ID.
    /// A Live sandbox's setup inputs are keyed `<id>#setupInputs`. Two stacks with equal
    /// `setup_owned_digest` have equal maps; comparing the maps names the entries that differ
    /// without exposing their contents.
    pub fn setup_owned_entry_digests(&self) -> BTreeMap<String, String> {
        let (resources, live_sandbox_inputs) = self.setup_owned_projection();
        resources
            .iter()
            .map(|(id, value)| {
                let encoded = serde_json::to_vec(value).expect("canonical entry always serializes");
                ((*id).clone(), format!("{:x}", Sha256::digest(encoded)))
            })
            .chain(live_sandbox_inputs.iter().map(|(id, inputs)| {
                let encoded =
                    serde_json::to_vec(inputs).expect("canonical inputs always serialize");
                (
                    format!("{id}#setupInputs"),
                    format!("{:x}", Sha256::digest(encoded)),
                )
            }))
            .collect()
    }

    fn setup_owned_projection(
        &self,
    ) -> (
        Vec<(&String, serde_json::Value)>,
        Vec<(&String, Vec<(&'static str, serde_json::Value)>)>,
    ) {
        let mut resources = self
            .resources
            .iter()
            .filter(|(_, entry)| entry.lifecycle == ResourceLifecycle::Frozen)
            .map(|(id, entry)| {
                let mut value =
                    serde_json::to_value(entry).expect("resource entries always serialize to JSON");
                let object = value.as_object_mut().expect("resource entry is an object");
                object.remove("displayName");
                object.remove("description");
                if let Some(sandbox) = entry.config.downcast_ref::<crate::Sandbox>() {
                    value["config"]["egress"] = sandbox.setup_digest_value();
                    value["config"]
                        .as_object_mut()
                        .expect("resource config is an object")
                        .remove("defaultPolicy");
                }
                if entry
                    .config
                    .downcast_ref::<crate::AzureStorageAccount>()
                    .is_some()
                {
                    if let Some(settings) = crate::AzureStorageAccount::setup_settings_digest(self)
                    {
                        value["azureStorageSettings"] = settings.into();
                    }
                }
                canonicalize_json(&mut value);
                // Bind setup approval to derived queue settings too. Preserve old digests
                // for stacks without explicit batching.
                if entry.config.downcast_ref::<crate::Queue>().is_some()
                    && self.resources.values().any(|consumer| {
                        consumer
                            .config
                            .downcast_ref::<crate::Worker>()
                            .is_some_and(|worker| worker.queue_batch_config(id).is_some())
                    })
                {
                    value["queueBatchVisibilityTimeout"] =
                        self.queue_visibility_timeout_seconds(id).into();
                }
                // A setup-owned dead-letter queue triggered by a Live Worker needs a
                // project-level grant that only setup can write. Adding or removing such a
                // trigger must therefore ask for setup. The digest does not know the platform,
                // so the field also appears for such a queue on other platforms, where nothing
                // asks for setup because of it (only GCP's compatibility check compares it).
                // It is absent for every stack without a Frozen dead-letter queue that has a
                // Live Worker trigger, so those stacks keep their digests.
                if crate::queue_needs_project_push_subscriber(self, id) {
                    value["queueProjectPushSubscriber"] = true.into();
                }
                (id, value)
            })
            .collect::<Vec<_>>();
        resources.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));

        let mut live_sandbox_inputs = self
            .resources
            .iter()
            .filter(|(_, entry)| entry.lifecycle == ResourceLifecycle::Live)
            .filter_map(|(id, entry)| {
                let sandbox = entry.config.downcast_ref::<crate::Sandbox>()?;
                let mut inputs = crate::sandbox_setup_inputs::comparable_aws_sandbox_setup_inputs(
                    self,
                    sandbox,
                    entry.lifecycle,
                );
                for (_, value) in &mut inputs {
                    canonicalize_json(value);
                }
                Some((id, inputs))
            })
            .collect::<Vec<_>>();
        live_sandbox_inputs.sort_unstable_by_key(|(id, _)| *id);
        (resources, live_sandbox_inputs)
    }

    /// Binds a setup update to both its resources and installed permissions.
    /// Runtime code changes remain outside this authorization.
    pub fn setup_update_digest(&self) -> String {
        let mut permissions = serde_json::to_value(&self.permissions)
            .expect("permission profiles always serialize to JSON");
        canonicalize_json(&mut permissions);
        let encoded = serde_json::to_vec(&(self.setup_owned_digest(), permissions))
            .expect("setup update projection always serializes");
        format!("{:x}", Sha256::digest(encoded))
    }

    /// Returns an iterator over the resources in the stack, including their lifecycle state.
    pub fn resources(&self) -> impl Iterator<Item = (&String, &ResourceEntry)> {
        self.resources.iter()
    }

    /// Returns a mutable iterator over the resources in the stack, including their lifecycle state.
    pub fn resources_mut(&mut self) -> impl Iterator<Item = (&String, &mut ResourceEntry)> {
        self.resources.iter_mut()
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    /// Create a reference to the current stack
    pub fn current() -> StackRef {
        StackRef::Current
    }

    /// Returns the permissions configuration for the stack.
    pub fn permissions(&self) -> &PermissionsConfig {
        &self.permissions
    }

    /// Returns the permission profiles for the stack.
    pub fn permission_profiles(&self) -> &IndexMap<String, PermissionProfile> {
        &self.permissions.profiles
    }

    /// Returns the management permissions configuration for the stack.
    pub fn management(&self) -> &ManagementPermissions {
        &self.permissions.management
    }

    /// Returns the supported platforms, or None if all platforms are supported.
    pub fn supported_platforms(&self) -> Option<&[Platform]> {
        self.supported_platforms.as_deref()
    }

    /// Returns stack input definitions.
    pub fn inputs(&self) -> &[StackInputDefinition] {
        &self.inputs
    }

    /// Returns true if the given platform is supported by this stack.
    /// When supported_platforms is None, all platforms are supported.
    pub fn supports_platform(&self, platform: &Platform) -> bool {
        match &self.supported_platforms {
            Some(platforms) => platforms.contains(platform),
            None => true,
        }
    }

    /// The descriptor of a resource type an extension in this stack defines. `None` for a
    /// built-in type, even when a manifest lists it, for a type listed only by an extension whose
    /// name is not the type's prefix, and for a type no extension defines.
    pub fn descriptor(
        &self,
        resource_type: &ResourceType,
    ) -> Option<&crate::ResourceTypeDescriptor> {
        self.defining_extension(resource_type)
            .and_then(|extension| extension.resource_types.get(resource_type))
    }

    /// The extension in this stack that defines `resource_type`.
    fn defining_extension(
        &self,
        resource_type: &ResourceType,
    ) -> Option<&crate::ExtensionManifest> {
        if !crate::custom_resource::is_custom_resource_type(resource_type.as_ref()) {
            return None;
        }
        self.extensions.iter().find(|extension| {
            extension.owns(resource_type) && extension.resource_types.contains_key(resource_type)
        })
    }

    /// Refuses to set up resource `resource_id` with `format` on `platform` when its type comes
    /// from an extension that has no part for that format and platform. A setup path a custom
    /// resource lacks is off for every stack that uses it, and the error says why. Alien's own
    /// types pass.
    pub fn check_setup_format(
        &self,
        resource_id: &str,
        resource_type: &ResourceType,
        format: crate::SetupFormat,
        platform: Platform,
    ) -> crate::Result<()> {
        let Some(extension) = self.defining_extension(resource_type) else {
            return Ok(());
        };
        if extension.resource_types[resource_type]
            .setup
            .platforms(format)
            .contains(&platform)
        {
            return Ok(());
        }
        Err(alien_error::AlienError::new(
            crate::ErrorData::OperationNotSupported {
                operation: format!("{format} setup"),
                reason: format!(
                    "resource '{resource_id}' has type {resource_type} from extension '{}', which has no {format} emitter for it on {platform}, so {format} setup is off for every stack that uses it",
                    extension.name
                ),
            },
        ))
    }
}

fn canonicalize_json(value: &mut serde_json::Value) {
    match value {
        serde_json::Value::Array(values) => {
            for value in values {
                canonicalize_json(value);
            }
        }
        serde_json::Value::Object(object) => {
            let mut entries = std::mem::take(object).into_iter().collect::<Vec<_>>();
            entries.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));
            for (key, mut value) in entries {
                canonicalize_json(&mut value);
                object.insert(key, value);
            }
        }
        _ => {}
    }
}

impl StackBuilder {
    /// Adds an entry with authored presentation metadata and lifecycle settings.
    pub fn add_entry(self, entry: ResourceEntry) -> Self {
        self.insert(entry)
    }

    /// Adds a resource to the stack with its lifecycle state.
    /// The resource's intrinsic dependencies (from resource.get_dependencies()) are automatically included.
    /// Use add_with_dependencies() if you need to specify additional dependencies.
    pub fn add<T: crate::ResourceDefinition>(
        self,
        resource: T,
        lifecycle: ResourceLifecycle,
    ) -> Self {
        self.add_with_dependencies(resource, lifecycle, vec![])
    }

    /// Adds a resource to the stack with its lifecycle state and additional dependencies.
    /// The total dependencies will be: resource.get_dependencies() + additional_dependencies
    pub fn add_with_dependencies<T: crate::ResourceDefinition>(
        self,
        resource: T,
        lifecycle: ResourceLifecycle,
        additional_dependencies: Vec<ResourceRef>,
    ) -> Self {
        let mut entry = Self::entry(resource, lifecycle);
        entry.dependencies = additional_dependencies;
        self.insert(entry)
    }

    /// Adds a resource whose creation follows a boolean stack input.
    /// The deployer's answer decides whether it is provisioned at all.
    ///
    /// Stacks are authored through the TypeScript SDK's `.enabled(input)`, which
    /// sets the field on the resource; this is the Rust-side seam the generator
    /// and preflight tests build gated stacks with.
    #[doc(hidden)]
    pub fn add_enabled_when<T: crate::ResourceDefinition>(
        self,
        resource: T,
        lifecycle: ResourceLifecycle,
        input_id: impl Into<String>,
    ) -> Self {
        let mut entry = Self::entry(resource, lifecycle);
        entry.enabled_when = Some(input_id.into());
        self.insert(entry)
    }

    /// Adds a resource with remote access enabled.
    /// When remote_access is true, binding params are synced to StackState for external access.
    pub fn add_with_remote_access<T: crate::ResourceDefinition>(
        self,
        resource: T,
        lifecycle: ResourceLifecycle,
    ) -> Self {
        let mut entry = Self::entry(resource, lifecycle);
        entry.remote_access = true;
        self.insert(entry)
    }

    /// The only place a `ResourceEntry` is spelled out. Each public `add_*`
    /// varies one field of it, so a new per-entry field costs one edit here
    /// instead of one per method.
    fn entry<T: crate::ResourceDefinition>(
        resource: T,
        lifecycle: ResourceLifecycle,
    ) -> ResourceEntry {
        ResourceEntry {
            config: Resource::new(resource),
            lifecycle,
            dependencies: Vec::new(),
            display_name: None,
            description: None,
            remote_access: false,
            enabled_when: None,
        }
    }

    fn insert(mut self, entry: ResourceEntry) -> Self {
        self.resources.insert(entry.config.id().to_string(), entry);
        self
    }

    /// Sets the permissions configuration for the stack.
    /// This defines access control for compute services in the stack.
    pub fn permissions(mut self, permissions: PermissionsConfig) -> Self {
        self.permissions = permissions;
        self
    }

    /// Add a single permission profile to the stack - allows fluent chaining
    ///
    /// # Example
    /// ```rust
    /// # use alien_core::{Stack, permissions::PermissionProfile};
    /// Stack::new("my-stack".to_string())
    ///     .permission("execution", PermissionProfile::new().global(["storage/data-read"]))
    ///     .permission("management", PermissionProfile::new().global(["storage/management"]))
    ///     .build()
    /// # ;
    /// ```
    pub fn permission(mut self, name: impl Into<String>, profile: PermissionProfile) -> Self {
        self.permissions.profiles.insert(name.into(), profile);
        self
    }

    /// Sets the supported platforms for this stack.
    pub fn platforms(mut self, platforms: Vec<Platform>) -> Self {
        self.supported_platforms = Some(platforms);
        self
    }

    /// Sets stack input definitions.
    pub fn inputs(mut self, inputs: Vec<StackInputDefinition>) -> Self {
        self.inputs = inputs;
        self
    }

    /// Declares the operations this stack's deployments run.
    pub fn operations(mut self, operations: crate::OperationsConfig) -> Self {
        self.operations = Some(operations);
        self
    }

    /// Sets the management permissions configuration for the stack.
    /// This defines how management permissions are derived and configured.
    ///
    /// # Examples
    /// ```rust
    /// # use alien_core::{Stack, permissions::{ManagementPermissions, PermissionProfile}};
    /// // Auto-derived management permissions (default)
    /// Stack::new("my-stack".to_string())
    ///     .management(ManagementPermissions::auto())
    ///     .build();
    ///
    /// // Extend auto-derived permissions
    /// Stack::new("my-stack".to_string())
    ///     .management(ManagementPermissions::extend(
    ///         PermissionProfile::new().global(["vault/data-write"])
    ///     ))
    ///     .build();
    ///
    /// // Override auto-derived permissions entirely
    /// Stack::new("my-stack".to_string())
    ///     .management(ManagementPermissions::override_(
    ///         PermissionProfile::new().global(["storage/heartbeat", "worker/provision"])
    ///     ))
    ///     .build();
    /// ```
    pub fn management(mut self, management: ManagementPermissions) -> Self {
        self.permissions.management = management;
        self
    }
}

/// Reference to a stack for management permissions
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum StackRef {
    /// Reference to the current stack being built
    Current,
    /// Reference to another stack by ID
    External(String),
}

impl StackRef {
    /// Create a StackRef from a stack reference
    pub fn from_stack(stack: &Stack) -> Self {
        StackRef::External(stack.id().to_string())
    }
}

impl From<&Stack> for StackRef {
    fn from(stack: &Stack) -> Self {
        StackRef::External(stack.id().to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resource::ResourceLifecycle;
    use crate::{
        Container, ContainerCode, Daemon, DaemonCode, PermissionSetReference, ResourceSpec,
        Storage, Worker, WorkerCode,
    };
    use insta::assert_json_snapshot;

    fn resource_entry<T: crate::ResourceDefinition>(
        resource: T,
        lifecycle: ResourceLifecycle,
        remote_access: bool,
    ) -> ResourceEntry {
        ResourceEntry {
            config: Resource::new(resource),
            lifecycle,
            dependencies: Vec::new(),
            display_name: None,
            description: None,
            remote_access,
            enabled_when: None,
        }
    }

    /// The grant is rendered by setup, so a resource setup renders nothing for — a Live bucket —
    /// cannot be published, while a Live sandbox can: setup still installs its scaffolding.
    #[test]
    fn remote_bindings_require_a_setup_rendered_resource_and_opt_in() {
        assert!(resource_entry(
            Storage::new("archive".to_string()).build(),
            ResourceLifecycle::Frozen,
            true,
        )
        .has_remote_bindings());
        assert!(!resource_entry(
            Storage::new("archive".to_string()).build(),
            ResourceLifecycle::Frozen,
            false,
        )
        .has_remote_bindings());
        assert!(!resource_entry(
            Storage::new("archive".to_string()).build(),
            ResourceLifecycle::Live,
            true,
        )
        .has_remote_bindings());
        let sandbox = crate::Sandbox::new("agents".to_string())
            .code(crate::SandboxCode::Image {
                image: "s3://alien-bundles/sandbox/bundle.zip".to_string(),
                bundled_from: None,
            })
            .egress(crate::SandboxEgress::Allow)
            .lifecycle(crate::SandboxLifecyclePolicy {
                max_lifetime_seconds: None,
                idle_pause_seconds: None,
                ..Default::default()
            })
            .build();
        assert!(resource_entry(sandbox, ResourceLifecycle::Live, true).has_remote_bindings());
        assert!(!resource_entry(
            Worker::new("worker".to_string())
                .code(WorkerCode::Image {
                    image: "example.com/worker:latest".to_string(),
                })
                .permissions("worker-execution".to_string())
                .build(),
            ResourceLifecycle::Frozen,
            true,
        )
        .has_remote_bindings());
    }

    #[test]
    fn test_stack_serialization() {
        use crate::WorkerCode;

        let storage = Storage::new("my-bucket".to_string())
            .public_read(true)
            .build();

        let worker = Worker::new("my-worker".to_string())
            .code(WorkerCode::Image {
                image: "rust:latest".to_string(),
            })
            .permissions("execution".to_string())
            .link(&storage)
            .build();

        // Create permission profiles for the new system
        let mut permissions = IndexMap::new();
        let mut execution_profile = PermissionProfile::new();
        execution_profile.0.insert(
            "*".to_string(),
            vec![
                PermissionSetReference::from_name("storage/data-read"),
                PermissionSetReference::from_name("storage/data-write"),
            ],
        );
        permissions.insert("execution".to_string(), execution_profile);

        let stack_builder = Stack::new("test-stack".to_string())
            .add(storage, ResourceLifecycle::Frozen)
            .add(worker.clone(), ResourceLifecycle::Live);

        let stack = stack_builder
            .permissions(PermissionsConfig {
                profiles: permissions,
                management: ManagementPermissions::Auto,
            })
            .build();

        // Serialize and Deserialize
        let serialized_stack =
            serde_json::to_string_pretty(&stack).expect("Failed to serialize stack");
        let deserialized_stack: Stack =
            serde_json::from_str(&serialized_stack).expect("Failed to deserialize stack");

        // Assert equality
        assert_eq!(
            stack, deserialized_stack,
            "Original and deserialized stacks do not match."
        );

        // Verify snapshot (sort maps to be deterministic across Rust versions)
        let mut settings = insta::Settings::clone_current();
        settings.set_sort_maps(true);
        settings.bind(|| {
            assert_json_snapshot!("stack_serialization_account_managed", stack);
        });
    }

    #[test]
    fn test_empty_stack_serialization() {
        let stack_builder = Stack::new("empty-test-stack".to_string());

        let stack = stack_builder
            .permissions(PermissionsConfig::new()) // Empty permissions for existing tests
            .build();

        // Serialize and Deserialize
        let serialized_stack =
            serde_json::to_string_pretty(&stack).expect("Failed to serialize empty stack");
        let deserialized_stack: Stack =
            serde_json::from_str(&serialized_stack).expect("Failed to deserialize empty stack");

        // Assert equality
        assert_eq!(
            stack, deserialized_stack,
            "Original and deserialized empty stacks do not match."
        );

        // Verify snapshot (sort maps to be deterministic across Rust versions)
        let mut settings = insta::Settings::clone_current();
        settings.set_sort_maps(true);
        settings.bind(|| {
            assert_json_snapshot!("empty_stack_serialization_account", stack);
        });
    }

    #[test]
    fn stack_deserializes_resources_without_public_endpoints() {
        let container = Container::new("api".to_string())
            .code(ContainerCode::Image {
                image: "example.com/api:latest".to_string(),
            })
            .cpu(ResourceSpec {
                min: "0.5".to_string(),
                desired: "1".to_string(),
            })
            .memory(ResourceSpec {
                min: "512Mi".to_string(),
                desired: "1Gi".to_string(),
            })
            .port(8080)
            .permissions("container-execution".to_string())
            .build();
        let daemon = Daemon::new("agent".to_string())
            .code(DaemonCode::Image {
                image: "example.com/agent:latest".to_string(),
            })
            .permissions("daemon-execution".to_string())
            .build();
        let worker = Worker::new("worker".to_string())
            .code(WorkerCode::Image {
                image: "example.com/worker:latest".to_string(),
            })
            .permissions("worker-execution".to_string())
            .build();
        let stack = Stack::new("legacy-stack".to_string())
            .add(container, ResourceLifecycle::Live)
            .add(daemon, ResourceLifecycle::Live)
            .add(worker, ResourceLifecycle::Live)
            .build();

        let mut legacy_json = serde_json::to_value(stack).expect("stack should serialize");
        for resource_id in ["api", "agent", "worker"] {
            legacy_json
                .pointer_mut(&format!("/resources/{resource_id}/config"))
                .and_then(serde_json::Value::as_object_mut)
                .expect("resource config should be an object")
                .remove("publicEndpoints");
        }

        let stack: Stack =
            serde_json::from_value(legacy_json).expect("legacy stack should deserialize");

        let container = stack
            .resources
            .get("api")
            .and_then(|entry| entry.config.downcast_ref::<Container>())
            .expect("api should be a container");
        assert!(container.public_endpoints.is_empty());

        let daemon = stack
            .resources
            .get("agent")
            .and_then(|entry| entry.config.downcast_ref::<Daemon>())
            .expect("agent should be a daemon");
        assert!(daemon.public_endpoints.is_empty());

        let worker = stack
            .resources
            .get("worker")
            .and_then(|entry| entry.config.downcast_ref::<Worker>())
            .expect("worker should be a worker");
        assert!(worker.public_endpoints.is_empty());
    }

    #[test]
    fn test_stack_with_permissions() {
        use crate::permissions::PermissionProfile;
        use indexmap::IndexMap;

        // Create a simple stack with permissions
        let storage = Storage::new("test-storage".to_string()).build();

        // Create a permission profile
        let mut permission_profile = PermissionProfile::new();
        permission_profile.0.insert(
            "*".to_string(),
            vec![PermissionSetReference::from_name("storage/data-read")],
        );

        let mut permissions = IndexMap::new();
        permissions.insert("reader".to_string(), permission_profile);

        let stack = Stack::new("test-permissions-stack".to_string())
            .add(storage, ResourceLifecycle::Frozen)
            .permissions(PermissionsConfig {
                profiles: permissions,
                management: ManagementPermissions::Auto,
            })
            .build();

        // Verify permissions are accessible
        assert_eq!(stack.permission_profiles().len(), 1);
        assert!(stack.permission_profiles().contains_key("reader"));

        let reader_profile = stack.permission_profiles().get("reader").unwrap();
        assert_eq!(reader_profile.0.len(), 1);
        assert!(reader_profile.0.contains_key("*"));

        let global_permissions = reader_profile.0.get("*").unwrap();
        assert_eq!(
            global_permissions,
            &vec![PermissionSetReference::from_name("storage/data-read")]
        );

        // Test serialization/deserialization
        let serialized = serde_json::to_string_pretty(&stack).expect("Failed to serialize");
        let deserialized: Stack = serde_json::from_str(&serialized).expect("Failed to deserialize");
        assert_eq!(stack, deserialized);
    }

    #[test]
    fn test_stack_with_management_permissions() {
        use crate::permissions::{ManagementPermissions, PermissionProfile};

        // Create a simple stack with management permissions
        let storage = Storage::new("test-storage".to_string()).build();

        // Create a permission profile for management
        let mut management_profile = PermissionProfile::new();
        management_profile.0.insert(
            "*".to_string(),
            vec![PermissionSetReference::from_name("vault/data-write")],
        );

        // Test auto management permissions (default)
        let stack_auto = Stack::new("test-auto-management-stack".to_string())
            .add(storage.clone(), ResourceLifecycle::Frozen)
            .management(ManagementPermissions::auto())
            .build();

        assert!(stack_auto.management().is_auto());
        assert!(stack_auto.management().profile().is_none());

        // Test extend management permissions
        let stack_extend = Stack::new("test-extend-management-stack".to_string())
            .add(storage.clone(), ResourceLifecycle::Frozen)
            .management(ManagementPermissions::extend(management_profile.clone()))
            .build();

        assert!(stack_extend.management().is_extend());
        assert_eq!(
            stack_extend.management().profile().unwrap(),
            &management_profile
        );

        // Test override management permissions
        let stack_override = Stack::new("test-override-management-stack".to_string())
            .add(storage.clone(), ResourceLifecycle::Frozen)
            .management(ManagementPermissions::override_(management_profile.clone()))
            .build();

        assert!(stack_override.management().is_override());
        assert_eq!(
            stack_override.management().profile().unwrap(),
            &management_profile
        );

        // Test default management permissions
        let stack_default = Stack::new("test-default-management-stack".to_string())
            .add(storage, ResourceLifecycle::Frozen)
            .build();

        assert!(stack_default.management().is_auto());

        // Test serialization/deserialization with management
        let serialized = serde_json::to_string_pretty(&stack_extend).expect("Failed to serialize");
        let deserialized: Stack = serde_json::from_str(&serialized).expect("Failed to deserialize");
        assert_eq!(stack_extend, deserialized);
    }

    fn dead_letter_stack(with_worker: bool, worker_lifecycle: ResourceLifecycle) -> Stack {
        use crate::{Queue, QueueDeadLetter, Worker, WorkerCode, WorkerTrigger};
        let failed = Queue::new("failed".to_string()).build();
        let tasks = Queue::new("tasks".to_string())
            .dead_letter(
                QueueDeadLetter::builder()
                    .queue(ResourceRef::new(Queue::RESOURCE_TYPE, "failed"))
                    .build(),
            )
            .build();
        let mut stack = Stack::new("dlq".to_string())
            .add(failed, ResourceLifecycle::Frozen)
            .add(tasks.clone(), ResourceLifecycle::Frozen);
        if with_worker {
            stack = stack.add(
                Worker::new("consumer".to_string())
                    .code(WorkerCode::Image {
                        image: "img".to_string(),
                    })
                    .permissions("execution".to_string())
                    .trigger(WorkerTrigger::queue(&tasks))
                    .build(),
                worker_lifecycle,
            );
        }
        stack.build()
    }

    #[test]
    fn a_live_worker_trigger_on_a_frozen_dead_letter_queue_changes_the_setup_digest() {
        let without = dead_letter_stack(false, ResourceLifecycle::Live);
        let with = dead_letter_stack(true, ResourceLifecycle::Live);
        // The Worker is not setup-owned, so only the derived queue field can differ.
        assert_ne!(without.setup_update_digest(), with.setup_update_digest());
        assert_ne!(without.setup_owned_digest(), with.setup_owned_digest());
    }

    #[test]
    fn the_dead_letter_queue_digest_is_unchanged_when_no_project_grant_is_needed() {
        // Without a Worker trigger, or with a setup-owned Worker (setup grants on its
        // subscription directly), the digest field must stay absent.
        let plain_stack = dead_letter_stack(false, ResourceLifecycle::Live);
        let (plain, _) = plain_stack.setup_owned_projection();
        assert!(plain
            .iter()
            .all(|(_, v)| v.get("queueProjectPushSubscriber").is_none()));
        let frozen_stack = dead_letter_stack(true, ResourceLifecycle::Frozen);
        let (frozen_worker, _) = frozen_stack.setup_owned_projection();
        assert!(frozen_worker
            .iter()
            .all(|(_, v)| v.get("queueProjectPushSubscriber").is_none()));
        let live_stack = dead_letter_stack(true, ResourceLifecycle::Live);
        let (live_worker, _) = live_stack.setup_owned_projection();
        assert!(live_worker
            .iter()
            .any(|(id, v)| *id == "tasks" && v["queueProjectPushSubscriber"] == true));
        assert!(live_worker
            .iter()
            .filter(|(id, _)| *id != "tasks")
            .all(|(_, v)| v.get("queueProjectPushSubscriber").is_none()));
    }

    #[test]
    fn presentation_metadata_preserves_setup_fingerprints_and_old_entries() {
        let original = Stack::new("metadata".to_string())
            .add(
                Storage::new("documents".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .build();
        let mut documented = original.clone();
        let entry = documented.resources.get_mut("documents").unwrap();
        entry.display_name = Some("Document storage".to_string());
        entry.description = Some("Uploaded documents and processed results.".to_string());
        assert_eq!(
            original.setup_owned_digest(),
            documented.setup_owned_digest()
        );
        assert_eq!(
            original.setup_update_digest(),
            documented.setup_update_digest()
        );
        assert_eq!(
            original.resources["documents"].config,
            documented.resources["documents"].config
        );
        let old_json = serde_json::to_value(&original).unwrap();
        assert!(old_json["resources"]["documents"]
            .get("displayName")
            .is_none());
        let loaded: Stack = serde_json::from_value(old_json).unwrap();
        assert_eq!(
            loaded.resources["documents"].display_name_or_id(),
            "documents"
        );
        assert!(loaded.resources["documents"].description.is_none());
        let round_trip: Stack =
            serde_json::from_value(serde_json::to_value(&documented).unwrap()).unwrap();
        assert_eq!(round_trip, documented);
    }

    fn digest_sandbox(id: &str, image: &str, private_base_image: Option<&str>) -> crate::Sandbox {
        crate::Sandbox::new(id.to_string())
            .code(crate::SandboxCode::Image {
                image: image.to_string(),
                bundled_from: None,
            })
            .maybe_private_base_image(private_base_image.map(str::to_string))
            .egress(crate::SandboxEgress::None)
            .lifecycle(crate::SandboxLifecyclePolicy {
                max_lifetime_seconds: None,
                idle_pause_seconds: None,
                ..Default::default()
            })
            .build()
    }

    /// Stored setup authorizations carry this digest, so its bytes must not move for any stack
    /// without a Live sandbox.
    #[test]
    fn setup_owned_digest_is_stable_without_a_live_sandbox() {
        let stack = Stack::new("golden".to_string())
            .add(
                Storage::new("ledger".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                digest_sandbox(
                    "frozen-agents",
                    "s3://bucket/frozen.zip",
                    Some("123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base:1"),
                ),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("scratch".to_string()).build(),
                ResourceLifecycle::Live,
            )
            .build();

        assert_eq!(
            stack.setup_owned_digest(),
            "aacf34583a0bb9e3d48dd08be0bdd1da0f1d1e3666f93b844ecb0e1506ca537e"
        );
    }

    struct LiveSandbox {
        image: &'static str,
        private_base_image: Option<&'static str>,
        egress: crate::SandboxEgress,
        network_id: &'static str,
        remote_access: bool,
    }

    const BASE_A: &str = "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-a:1";

    impl LiveSandbox {
        fn installed() -> Self {
            Self {
                image: "s3://bucket/sandbox-bundle/v1/bundle.zip",
                private_base_image: Some(BASE_A),
                egress: crate::SandboxEgress::Allow,
                network_id: "net-a",
                remote_access: false,
            }
        }

        fn digest(self) -> String {
            let mut sandbox = digest_sandbox("agents", self.image, self.private_base_image);
            sandbox.egress = self.egress;
            let mut stack = Stack::new("stack".to_string())
                .add(
                    crate::Network::new(self.network_id.to_string())
                        .settings(crate::NetworkSettings::Create {
                            cidr: Some("10.0.0.0/16".to_string()),
                            availability_zones: 2,
                        })
                        .build(),
                    ResourceLifecycle::Frozen,
                )
                .add(sandbox, ResourceLifecycle::Live)
                .build();
            stack
                .resources
                .get_mut("agents")
                .expect("sandbox")
                .remote_access = self.remote_access;
            let entry = &stack.resources["agents"];
            crate::sandbox_setup_inputs::aws_sandbox_setup_inputs(
                &stack,
                entry.config.downcast_ref().expect("sandbox"),
                entry.lifecycle,
                crate::sandbox_setup_inputs::SETUP_INPUTS_COMPARISON_ACCOUNT,
            )
            .expect("the inputs resolve, so no case is compared by its whole configuration");
            stack.setup_owned_digest()
        }
    }

    #[test]
    fn setup_owned_digest_follows_a_live_sandboxs_setup_inputs_but_not_its_image() {
        let installed = LiveSandbox::installed().digest();

        for (unchanged, why) in [
            (
                LiveSandbox {
                    image: "s3://bucket/sandbox-bundle/v2/bundle.zip",
                    ..LiveSandbox::installed()
                },
                "a new bundle under the same prefix",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-a:2",
                    ),
                    ..LiveSandbox::installed()
                },
                "a new tag",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-a@sha256:abc",
                    ),
                    ..LiveSandbox::installed()
                },
                "a digest",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/team/base-b:1",
                    ),
                    ..LiveSandbox::installed()
                },
                "another repository",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "210987654321.dkr.ecr.us-east-1.amazonaws.com/team/base-a:1",
                    ),
                    ..LiveSandbox::installed()
                },
                "another account",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "123456789012.dkr.ecr.{region}.amazonaws.com/team/base-a:1",
                    ),
                    ..LiveSandbox::installed()
                },
                "the deployment's region",
            ),
            (
                LiveSandbox {
                    image: "s3://other-bucket/sandbox-bundle/v1/bundle.zip",
                    ..LiveSandbox::installed()
                },
                "another bundle bucket",
            ),
        ] {
            assert_eq!(
                installed,
                unchanged.digest(),
                "{why} is the runtime's to roll: a Live sandbox builds from the store and repository its setup granted"
            );
        }

        for (changed, what) in [
            (
                LiveSandbox {
                    private_base_image: None,
                    ..LiveSandbox::installed()
                },
                "a dropped private base",
            ),
            (
                LiveSandbox {
                    egress: crate::SandboxEgress::None,
                    ..LiveSandbox::installed()
                },
                "egress allow to deny",
            ),
            (
                LiveSandbox {
                    image: "s3://bucket/other-prefix/v1/bundle.zip",
                    ..LiveSandbox::installed()
                },
                "another bundle prefix",
            ),
            (
                LiveSandbox {
                    remote_access: true,
                    ..LiveSandbox::installed()
                },
                "a remote grant",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/cache/team/base-a:1",
                    ),
                    ..LiveSandbox::installed()
                },
                "a base repository in another namespace",
            ),
            (
                LiveSandbox {
                    private_base_image: Some(
                        "123456789012.dkr.ecr.us-east-1.amazonaws.com/base-a:1",
                    ),
                    ..LiveSandbox::installed()
                },
                "a base repository with no namespace",
            ),
        ] {
            assert_ne!(installed, changed.digest(), "{what} is setup-owned");
        }

        let deny = |network_id| {
            LiveSandbox {
                egress: crate::SandboxEgress::None,
                network_id,
                ..LiveSandbox::installed()
            }
            .digest()
        };
        assert_ne!(
            deny("net-a"),
            deny("net-b"),
            "the connector's network is setup-owned"
        );
    }

    #[test]
    fn setup_owned_digest_is_order_independent() {
        let first = Stack::new("first".to_string())
            .add(
                Storage::new("alpha".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("beta".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("live-one".to_string()).build(),
                ResourceLifecycle::Live,
            )
            .build();
        let second = Stack::new("second".to_string())
            .add(
                Storage::new("beta".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("alpha".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("live-two".to_string()).build(),
                ResourceLifecycle::Live,
            )
            .build();

        assert_eq!(first.setup_owned_digest(), second.setup_owned_digest());
        assert_eq!(
            first.setup_owned_entry_digests(),
            second.setup_owned_entry_digests()
        );
    }

    #[test]
    fn setup_owned_entry_digests_name_only_the_changed_entries() {
        let installed = Stack::new("stack".to_string())
            .add(
                Storage::new("alpha".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("beta".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("live".to_string()).build(),
                ResourceLifecycle::Live,
            )
            .build();
        let target = Stack::new("stack".to_string())
            .add(
                Storage::new("alpha".to_string()).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("beta".to_string()).versioning(true).build(),
                ResourceLifecycle::Frozen,
            )
            .add(
                Storage::new("live".to_string()).versioning(true).build(),
                ResourceLifecycle::Live,
            )
            .build();

        let installed_entries = installed.setup_owned_entry_digests();
        let target_entries = target.setup_owned_entry_digests();
        assert_ne!(installed.setup_owned_digest(), target.setup_owned_digest());
        assert_eq!(
            installed_entries.keys().collect::<Vec<_>>(),
            vec!["alpha", "beta"]
        );
        assert_eq!(
            installed_entries.keys().collect::<Vec<_>>(),
            target_entries.keys().collect::<Vec<_>>()
        );
        assert_eq!(installed_entries["alpha"], target_entries["alpha"]);
        assert_ne!(installed_entries["beta"], target_entries["beta"]);
        assert!(installed_entries
            .values()
            .chain(target_entries.values())
            .all(|digest| digest.len() == 64));
    }

    /// The manifest `alien extensions build` writes for the docs' DNS zone, in its wire shape.
    fn acme_manifest() -> serde_json::Value {
        serde_json::json!({
            "name": "acme",
            "version": "0.1.0",
            "digest": "sha256:4ff931a2",
            "resourceTypes": {
                "acme/dns-zone": {
                    "lifecycles": ["frozen", "live"],
                    "holdsData": false,
                    "setup": {
                        "cloudformation": ["aws"],
                        "terraform": ["aws", "gcp", "azure"],
                        "helm": ["kubernetes"],
                        "importers": ["aws", "gcp", "azure"]
                    },
                    "controllerPlatforms": ["aws", "gcp", "azure"],
                    "permissionSets": [{
                        "id": "acme/dns-zone/provision",
                        "description": "Create, read and delete the zone",
                        "platforms": {
                            "aws": [{
                                "grant": { "actions": ["route53:CreateHostedZone"] },
                                "binding": {
                                    "stack": { "resources": ["*"] },
                                    "resource": { "resources": ["*"] }
                                }
                            }]
                        }
                    }],
                    "link": { "permissionSets": ["acme/dns-zone/records-write"] },
                    "schemas": {
                        "config": { "type": "object", "required": ["id", "domain"] },
                        "outputs": { "type": "object", "required": ["zoneId"] }
                    }
                }
            }
        })
    }

    fn dns_zone() -> crate::CustomResource {
        crate::CustomResource::from_untagged(
            "acme/dns-zone",
            serde_json::json!({ "id": "zone", "domain": "internal.acme.dev" }),
        )
        .unwrap()
    }

    #[test]
    fn a_stack_without_extensions_writes_no_extensions_field() {
        let stack = Stack::new("app".to_string())
            .add(dns_zone(), ResourceLifecycle::Frozen)
            .build();

        let json = serde_json::to_value(&stack).unwrap();
        assert!(json.get("extensions").is_none(), "{json}");
        assert_eq!(serde_json::from_value::<Stack>(json).unwrap(), stack);
    }

    #[test]
    fn a_stack_carries_its_extensions_and_finds_the_types_they_define() {
        let mut stack = Stack::new("app".to_string())
            .add(dns_zone(), ResourceLifecycle::Frozen)
            .build();
        stack.extensions = vec![serde_json::from_value(acme_manifest()).unwrap()];

        let json = serde_json::to_value(&stack).unwrap();
        assert_eq!(json["extensions"], serde_json::json!([acme_manifest()]));
        let stack: Stack = serde_json::from_value(json).unwrap();

        let descriptor = stack
            .descriptor(&ResourceType::from("acme/dns-zone"))
            .expect("acme declares acme/dns-zone");
        assert!(!descriptor.holds_data);
        assert_eq!(
            descriptor.lifecycles,
            [ResourceLifecycle::Frozen, ResourceLifecycle::Live]
        );
        assert_eq!(
            descriptor.link.permission_sets,
            ["acme/dns-zone/records-write"]
        );
        assert!(stack
            .descriptor(&ResourceType::from("acme/record"))
            .is_none());
    }

    #[test]
    fn a_descriptor_writes_services_and_the_network_only_when_the_type_asks_for_them() {
        let descriptor: crate::ResourceTypeDescriptor =
            serde_json::from_value(acme_manifest()["resourceTypes"]["acme/dns-zone"].clone())
                .unwrap();
        assert!(descriptor.services.is_empty());
        assert!(!descriptor.requires_network);
        let json = serde_json::to_value(&descriptor).unwrap();
        assert_eq!(json, acme_manifest()["resourceTypes"]["acme/dns-zone"]);

        let mut asking = json;
        asking["services"] = serde_json::json!({
            "gcp": ["dns.googleapis.com"],
            "azure": ["Microsoft.Network"]
        });
        asking["requiresNetwork"] = true.into();
        let descriptor: crate::ResourceTypeDescriptor =
            serde_json::from_value(asking.clone()).unwrap();
        assert_eq!(
            descriptor.services[&crate::Platform::Gcp],
            ["dns.googleapis.com"]
        );
        assert!(descriptor.requires_network);
        assert_eq!(serde_json::to_value(&descriptor).unwrap(), asking);
    }

    /// A type whose descriptor asks for the network keeps one on Kubernetes, as a cloud
    /// database does.
    #[test]
    fn a_type_that_requires_the_network_keeps_one_like_a_database() {
        let zone = crate::CustomResource::from_untagged(
            "acme/dns-zone",
            serde_json::json!({ "id": "zone", "domain": "internal.acme.dev" }),
        )
        .unwrap();
        let mut stack = Stack::new("app".to_string())
            .add(zone, ResourceLifecycle::Frozen)
            .build();
        let keeps = |stack: &Stack| {
            stack
                .resources()
                .any(|(_, entry)| crate::keeps_cloud_network(stack, entry))
        };
        let mut manifest = acme_manifest();
        stack.extensions = vec![serde_json::from_value(manifest.clone()).unwrap()];
        assert!(!keeps(&stack));

        manifest["resourceTypes"]["acme/dns-zone"]["requiresNetwork"] = true.into();
        stack.extensions = vec![serde_json::from_value(manifest).unwrap()];
        assert!(keeps(&stack));
    }

    /// An extension cannot redefine a built-in type: its descriptor for one is never returned.
    #[test]
    fn a_manifest_that_lists_a_built_in_type_does_not_describe_it() {
        let mut manifest = acme_manifest();
        let zone = manifest["resourceTypes"]["acme/dns-zone"].clone();
        manifest["resourceTypes"]["storage"] = zone;
        let mut stack = Stack::new("app".to_string()).build();
        stack.extensions = vec![serde_json::from_value(manifest).unwrap()];

        assert!(stack.descriptor(&Storage::RESOURCE_TYPE).is_none());
    }

    /// Only `acme` can define `acme/dns-zone`, wherever another extension sits in the list.
    #[test]
    fn a_type_listed_by_an_extension_of_another_name_has_no_descriptor() {
        let mut evil = acme_manifest();
        evil["name"] = "evil".into();
        let mut stack = Stack::new("app".to_string()).build();
        stack.extensions = vec![serde_json::from_value(evil).unwrap()];
        let zone = ResourceType::from("acme/dns-zone");
        assert!(stack.descriptor(&zone).is_none());

        stack
            .extensions
            .push(serde_json::from_value(acme_manifest()).unwrap());
        assert!(std::ptr::eq(
            stack.descriptor(&zone).unwrap(),
            &stack.extensions[1].resource_types[&zone]
        ));
    }
}