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
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
//! Sandbox resource for running untrusted code in an isolated environment.
//!
//! A Sandbox is a session-oriented resource: the declaration provisions a durable parent, and
//! the application creates and destroys individual sessions through its binding at runtime.
//!
//! The capability set differs per platform and is published rather than assumed. Calling an
//! unsupported capability is a typed error naming both the platform and the capability, so a
//! portable application can branch on `SandboxCapabilities` before it calls.
use crate::error::{ErrorData, Result};
use crate::resource::{ResourceDefinition, ResourceOutputsDefinition, ResourceRef, ResourceType};
use crate::resources::ToolchainConfig;
use crate::Platform;
use alien_error::AlienError;
use bon::Builder;
use serde::{Deserialize, Serialize};
use std::any::Any;
use std::fmt::Debug;
/// Specifies where the sandbox's root filesystem comes from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "type")]
pub enum SandboxCode {
/// A prebuilt container image used as the sandbox root filesystem.
#[serde(rename_all = "camelCase")]
Image {
/// Image reference (e.g. `ubuntu:24.04`, `ghcr.io/myorg/sandbox:latest`).
///
/// Two backends narrow it in opposite directions: AWS wants an `s3://` bundle, Azure a
/// bare catalog name such as `ubuntu`. Each refuses the other's shape while planning.
image: String,
},
/// Source built into a sandbox image at deploy time.
#[serde(rename_all = "camelCase")]
Source {
/// The source directory to build from
src: String,
/// Toolchain configuration with type-safe options
toolchain: ToolchainConfig,
},
}
/// Hard ceilings enforced on a sandbox session.
///
/// These are limits, not scheduling requests. Untrusted code does not respect a hint, so every
/// field is enforced by the platform and a platform that cannot enforce one is rejected at plan
/// time rather than silently ignoring it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxLimits {
/// CPU ceiling in cores or millicores (e.g. `"1"`, `"500m"`)
pub cpu: String,
/// Memory ceiling (e.g. `"2Gi"`, `"512Mi"`)
pub memory: String,
/// Disk ceiling (e.g. `"20Gi"`)
pub disk: String,
/// Maximum number of processes, which bounds fork bombs.
///
/// Optional because only a container runtime has the primitive: Kubernetes sets a pid ceiling
/// per node, not per pod, and neither AWS MicroVMs nor Azure sandboxes expose one. Declaring
/// it on a platform that cannot apply it is refused at plan time.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_processes: Option<u32>,
}
/// One of the five sizes a Lambda MicroVM can be built at.
///
/// AWS has no ceiling knob: `minimumMemoryInMiB` sets a *baseline* and a running MicroVM bursts
/// vertically to four times it with no way to opt out. A declared ceiling is therefore honoured by
/// picking the tier whose **peak** stays inside it, not the tier whose baseline matches it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MicrovmTier {
/// What `minimumMemoryInMiB` is set to.
pub baseline_memory_mib: i64,
/// The most memory the MicroVM can reach, in MiB.
pub peak_memory_mib: i64,
/// The most vCPU the MicroVM can reach.
pub peak_vcpu: u32,
/// The most disk the MicroVM can use, in MiB.
pub max_disk_mib: i64,
}
/// The published sizes, smallest first. Baseline memory to vCPU is 2 GB per vCPU, peak is four
/// times baseline, and disk is fixed per tier rather than independently selectable.
/// Longest life AWS will run a MicroVM for, from `RunMicrovm`'s `maximumDurationInSeconds`.
const AWS_MAX_SESSION_LIFETIME_SECONDS: u32 = 28_800;
const MICROVM_TIERS: &[MicrovmTier] = &[
MicrovmTier {
baseline_memory_mib: 512,
peak_memory_mib: 2048,
peak_vcpu: 1,
max_disk_mib: 8192,
},
MicrovmTier {
baseline_memory_mib: 1024,
peak_memory_mib: 4096,
peak_vcpu: 2,
max_disk_mib: 8192,
},
MicrovmTier {
baseline_memory_mib: 2048,
peak_memory_mib: 8192,
peak_vcpu: 4,
max_disk_mib: 8192,
},
MicrovmTier {
baseline_memory_mib: 4096,
peak_memory_mib: 16384,
peak_vcpu: 8,
max_disk_mib: 16384,
},
MicrovmTier {
baseline_memory_mib: 8192,
peak_memory_mib: 32768,
peak_vcpu: 16,
max_disk_mib: 32768,
},
];
/// Outbound network policy for a sandbox.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", tag = "mode")]
pub enum SandboxEgress {
/// No outbound network access.
///
/// Routed traffic only. Link-local is not outbound and no backend's egress control reaches
/// it, so this is not a boundary against instance metadata.
Deny,
/// Unrestricted outbound access to the public internet, and none to private ranges or the
/// deployment's own network.
///
/// Link-local carries the same exception as `Deny`. AWS and Kubernetes deliver both halves.
/// Azure and GCP deliver the first only: one matches host patterns and the other is a single
/// switch, so neither can name an address range to exclude.
Allow,
/// Outbound access only to the listed hostnames.
///
/// Azure alone expresses it: its egress proxy matches on host pattern. The others filter by
/// CIDR or carry a single switch, and both would approximate the list rather than keep it.
#[serde(rename_all = "camelCase")]
AllowDomains {
/// Hostnames the sandbox may reach
domains: Vec<String>,
},
}
impl SandboxEgress {
/// The single outbound switch for a backend that has no host matcher, or `None` for a mode a
/// boolean cannot carry.
///
/// `AllowDomains` needs a host list, so it maps to nothing and each caller refuses it in its
/// own error naming the sandbox. One source for what a mode means, so a template and a session
/// cannot disagree on it.
pub fn internet_access_switch(&self) -> Option<bool> {
match self {
SandboxEgress::Allow => Some(true),
SandboxEgress::Deny => Some(false),
SandboxEgress::AllowDomains { .. } => None,
}
}
}
/// How long a session may live and when it is suspended.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxSessionPolicy {
/// Wall-clock ceiling on a single session, after which the platform terminates it.
///
/// Optional because not every backend has the primitive: Kubernetes has
/// `activeDeadlineSeconds` and AWS `maximumDurationInSeconds`, while neither Azure nor Local
/// expose one, so declaring a ceiling there is refused at plan time rather than accepted and
/// never applied. AWS caps it at 8 hours.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub max_lifetime_seconds: Option<u32>,
/// Idle period after which the session is suspended, where the platform supports it
#[serde(skip_serializing_if = "Option::is_none")]
pub idle_suspend_seconds: Option<u32>,
}
/// What a platform's sandbox backend can actually do.
///
/// Published so portable code can branch before calling rather than discovering a gap through
/// an error. Every field here corresponds to a capability that at least one platform lacks;
/// create, exec and terminate are the guaranteed floor and are therefore not listed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SandboxCapabilities {
/// Files can be moved in and out of a session
pub files: bool,
/// A later call can reach a session created by an earlier one
pub reconnect: bool,
/// An authenticated, port-scoped capability to reach a service inside the sandbox
pub preview: bool,
/// Session state can be suspended and resumed
pub suspend_resume: bool,
/// A session's full state can be captured and used to create another
pub snapshot: bool,
/// Egress can be restricted to a hostname allowlist
pub domain_egress_rules: bool,
/// Whether a declared `deny` is actually enforced, rather than accepted and dropped
pub egress_deny: bool,
/// The platform enforces the declared cpu, memory and disk ceilings
pub enforced_limits: bool,
/// The platform can cap how many processes a session runs
pub process_limit: bool,
/// The platform terminates a session at a declared wall-clock deadline
pub session_lifetime: bool,
/// A command runs in its own PID namespace and cannot see or signal the agent's processes.
///
/// Only where an agent runs as root. Creating the namespace needs `CAP_SYS_ADMIN`, and the
/// Kubernetes sandbox pod drops every capability — which is also what denies `ptrace` by
/// construction, so granting it there would remove a lock to add one.
pub supervisor_pid_namespace: bool,
/// The process supervising a command is a different identity from the command.
///
/// False where a command runs as the agent's own user: it can then read the supervisor's
/// environment and signal it. Separate from `supervisorPidNamespace`, which is about
/// visibility rather than identity — a backend can have one without the other.
pub supervisor_isolation: bool,
}
impl SandboxCapabilities {
/// Returns what the given platform's sandbox backend supports.
///
/// Errors for platforms with no sandbox backend, rather than returning an all-false set —
/// "every capability is missing" and "this platform has no sandboxes" are different
/// conditions and an application should not have to tell them apart by inspection.
pub fn for_platform(platform: Platform) -> Result<Self> {
match platform {
Platform::Aws => Ok(Self {
files: true,
reconnect: true,
preview: true,
suspend_resume: true,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: true,
// Nothing in the API bounds process count.
process_limit: false,
// `maximumDurationInSeconds` on `RunMicrovm`, which Lambda enforces by
// terminating the MicroVM. Capped at 8 hours by the service.
session_lifetime: true,
// Measured, not assumed: the agent inside a Lambda MicroVM runs as uid 0 with
// `CapEff: 00000000a80425fb`, the standard container default set, which excludes
// `CAP_SYS_ADMIN`. It can drop privilege (`CAP_SETUID`/`CAP_SETGID` are held) and
// it cannot create a namespace. No backend offers this today.
supervisor_pid_namespace: false,
// The agent runs as uid 0 and `setuid`s the command to uid 60000, so the command
// runs under a different identity than the process supervising it.
supervisor_isolation: true,
}),
Platform::Azure => Ok(Self {
files: true,
reconnect: true,
// A sandbox port carries a URL and an auth config, and the auth config offers two
// things: anonymous, or Entra ID with an allowlist of human email addresses.
// Neither is a credential scoped to a port for a fixed time, which is what a
// preview capability is. Returning the anonymous URL would publish the port.
preview: false,
suspend_resume: true,
// The one cloud of the five that could offer this, and the blocker is ours:
// `snapshot()` returns an id and `CreateSessionRequest` has no field to consume
// one, so no backend can complete the round trip. Nothing in the resource model
// owns such an artifact either, and Microsoft states snapshots are not garbage
// collected — an id with no owner is a bill that grows.
snapshot: false,
domain_egress_rules: true,
egress_deny: true,
enforced_limits: false,
process_limit: false,
// Auto-suspend and auto-delete exist; a wall-clock ceiling does not. Accepting
// `maxLifetimeSeconds` here would be the silent no-op the capability set exists
// to prevent, so this is a decision rather than a gap.
session_lifetime: false,
// No Alien process inside an Azure sandbox, so there is no supervisor to isolate.
supervisor_pid_namespace: false,
// No Alien process runs the command at all — the platform's own data plane does,
// so there is no separate supervisor identity to speak of.
supervisor_isolation: false,
}),
Platform::Gcp => Ok(Self::gcp_agent_platform()),
// Preview needs a gateway that validates a session-and-port capability, and that
// gateway does not exist yet.
Platform::Kubernetes => Ok(Self {
files: true,
reconnect: true,
preview: false,
suspend_resume: false,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: true,
// A pid ceiling is a kubelet setting per node, not a pod field.
process_limit: false,
// `activeDeadlineSeconds` on the pod, which the kubelet enforces.
session_lifetime: true,
// The pod drops every capability, including the `CAP_SYS_ADMIN` the agent would
// need to unshare. That is also what denies `ptrace`, so this stays false rather
// than the pod being weakened to make it true.
supervisor_pid_namespace: false,
// The pod pins one uid (`run_as_user: 65534` on both pod and container) with
// `capabilities.drop: [ALL]` and `allow_privilege_escalation: false`, so no
// process can setuid to split the command off from a supervisor. No uid split is
// possible, so none exists.
supervisor_isolation: false,
}),
Platform::Local => Ok(Self {
files: true,
reconnect: true,
preview: true,
suspend_resume: false,
snapshot: false,
domain_egress_rules: false,
egress_deny: true,
enforced_limits: true,
// Docker's `--pids-limit`.
process_limit: true,
session_lifetime: false,
// Local has no in-sandbox agent: the manager drives Docker from outside, so
// there is no supervisor inside the sandbox to isolate from.
supervisor_pid_namespace: false,
// The supervisor is the manager on the host, outside the container entirely, and
// `docker exec` runs the command as the workload uid — a different identity by
// construction.
supervisor_isolation: true,
}),
Platform::Machines | Platform::Test => {
Err(AlienError::new(ErrorData::SandboxPlatformUnsupported {
platform: platform.to_string(),
}))
}
}
}
/// What the GCP Agent Platform sandbox backend supports; the body of the `Platform::Gcp` arm.
pub fn gcp_agent_platform() -> Self {
Self {
// Agent file operations move over the session envelope.
files: true,
// Reaching a session across processes is safe because `generation` is derived from the
// container boot id read through the agent's health op, so a caller detects a container
// replaced under a stable session name rather than reconnecting to a blank one.
reconnect: true,
// No method mints a port-scoped ingress capability; the only ingress is `:execute`.
preview: false,
// `:pause` and `:resume` preserve the running container.
suspend_resume: true,
// A session's state can be captured and used to create another.
snapshot: true,
// Egress is shaped by VPC and DNS peering, which is not a hostname allowlist.
domain_egress_rules: false,
// A declared `deny` blocks both routed egress and DNS.
egress_deny: true,
// The declared ceilings are enforced, but by terminating the session on breach rather
// than by refusing the allocation — a caller reading `true` should expect the session
// to die, not a clean error at the point of the request.
enforced_limits: true,
// No ceiling on process count is observed.
process_limit: false,
// `ttl` maps to a session `expireTime` the platform terminates at.
session_lifetime: true,
// No PID-namespace isolation between the command and anything supervising it.
supervisor_pid_namespace: false,
// No separate supervisor identity: the command is not run under a different identity
// than the process supervising it.
supervisor_isolation: false,
}
}
/// Returns a typed error if the named capability is absent on this platform.
pub fn require(&self, capability: SandboxCapability, platform: Platform) -> Result<()> {
let available = match capability {
SandboxCapability::Files => self.files,
SandboxCapability::Reconnect => self.reconnect,
SandboxCapability::Preview => self.preview,
SandboxCapability::SuspendResume => self.suspend_resume,
SandboxCapability::Snapshot => self.snapshot,
SandboxCapability::DomainEgressRules => self.domain_egress_rules,
SandboxCapability::EgressDeny => self.egress_deny,
SandboxCapability::EnforcedLimits => self.enforced_limits,
SandboxCapability::ProcessLimit => self.process_limit,
SandboxCapability::SessionLifetime => self.session_lifetime,
SandboxCapability::SupervisorPidNamespace => self.supervisor_pid_namespace,
SandboxCapability::SupervisorIsolation => self.supervisor_isolation,
};
if available {
return Ok(());
}
Err(AlienError::new(ErrorData::SandboxCapabilityUnsupported {
capability: capability.as_str().to_string(),
platform: platform.to_string(),
}))
}
}
/// Names a single sandbox capability, so an unsupported call can report which one it needed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub enum SandboxCapability {
/// Moving files in and out of a session
Files,
/// Reaching a session created by an earlier call
Reconnect,
/// An authenticated, port-scoped ingress capability
Preview,
/// Suspending and resuming session state
SuspendResume,
/// Capturing full session state
Snapshot,
/// Restricting egress to a hostname allowlist
DomainEgressRules,
/// Refusing outbound access when a sandbox declares none
EgressDeny,
/// Platform-enforced resource ceilings
EnforcedLimits,
/// A ceiling on the number of processes a session may run
ProcessLimit,
/// A wall-clock ceiling on a session, applied by the platform rather than by a caller
SessionLifetime,
/// A command runs in its own PID namespace, isolated from the agent supervising it
SupervisorPidNamespace,
/// A command runs under a different identity than the process supervising it
SupervisorIsolation,
}
impl SandboxCapability {
/// Returns the stable identifier used in errors and capability queries.
pub fn as_str(&self) -> &'static str {
match self {
Self::Files => "files",
Self::Reconnect => "reconnect",
Self::Preview => "preview",
Self::SuspendResume => "suspendResume",
Self::Snapshot => "snapshot",
Self::DomainEgressRules => "domainEgressRules",
Self::EgressDeny => "egressDeny",
Self::EnforcedLimits => "enforcedLimits",
Self::ProcessLimit => "processLimit",
Self::SessionLifetime => "sessionLifetime",
Self::SupervisorPidNamespace => "supervisorPidNamespace",
Self::SupervisorIsolation => "supervisorIsolation",
}
}
}
/// An isolated environment for running untrusted code, created per session at runtime.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Builder)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
#[builder(start_fn = new)]
pub struct Sandbox {
/// Identifier for the sandbox. Must contain only alphanumeric characters, hyphens, and
/// underscores ([A-Za-z0-9-_]). Maximum 64 characters.
#[builder(start_fn)]
pub id: String,
/// Where the sandbox's root filesystem comes from
pub code: SandboxCode,
/// Enforced resource ceilings.
///
/// Optional because not every platform can enforce them, and a declaration that names none
/// takes the platform's own defaults. Naming them on a platform that cannot enforce them is
/// rejected at plan time rather than silently ignored.
#[serde(skip_serializing_if = "Option::is_none")]
pub limits: Option<SandboxLimits>,
/// Outbound network policy
pub egress: SandboxEgress,
/// Session lifetime and idle behaviour
pub session: SandboxSessionPolicy,
/// Ports eligible for a preview capability. A port not listed here can never be exposed,
/// so an application cannot widen its own ingress at runtime.
#[builder(default)]
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub preview_ports: Vec<u16>,
}
/// Whether the artifact being rendered restricts which network modes it accepts.
///
/// A sandbox is not emitted on a Kubernetes target, so nothing there routes egress through a
/// connector and the default network stays a working answer. Every site that withholds the mode,
/// explains the restriction, or renders a branch for it has to ask this one question — asking the
/// stack directly is how they came to disagree.
pub fn restricts_network_mode(stack: &crate::Stack, targets_kubernetes: bool) -> bool {
!targets_kubernetes && stack_needs_named_subnets_at_setup(stack)
}
/// Whether any sandbox in the stack forces setup to name subnets.
///
/// A restricted sandbox routes session egress through a VPC connector, and neither generator can
/// enumerate the account default VPC's subnets, so that mode leaves the connector without any and
/// it fails at create. Callers that render an artifact want [`restricts_network_mode`] instead:
/// this one answers for the declaration, which on a Kubernetes target is not what gets emitted.
pub fn stack_needs_named_subnets_at_setup(stack: &crate::Stack) -> bool {
stack.resources().any(|(_resource_id, resource)| {
resource
.config
.downcast_ref::<Sandbox>()
.is_some_and(|sandbox| !matches!(sandbox.egress, SandboxEgress::Allow))
})
}
impl Sandbox {
/// The resource type identifier for Sandbox
pub const RESOURCE_TYPE: ResourceType = ResourceType::from_static("sandbox");
/// Returns the sandbox's unique identifier.
pub fn id(&self) -> &str {
&self.id
}
/// The declared ceilings, or the defaults a platform applies when none were named.
///
/// Backends want a concrete set: a sandbox with no declared ceilings still runs inside
/// whatever the platform gives it, and a backend that had to branch on `None` would end up
/// inventing its own default anyway.
pub fn resolved_limits(&self) -> SandboxLimits {
self.limits.clone().unwrap_or_else(default_limits)
}
/// Validates the declaration against what the target platform can enforce.
///
/// Runs at plan time so an unenforceable limit or an unsupported egress mode fails before
/// anything is provisioned, rather than at the first exec.
pub fn validate_for_platform(&self, platform: Platform) -> Result<()> {
let capabilities = SandboxCapabilities::for_platform(platform)?;
// No backend builds a sandbox image from source: an empty image string schedules a pod
// that can never run, the silent no-op the capability contract forbids — the failure
// has to land here instead.
if let SandboxCode::Source { .. } = &self.code {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "code".to_string(),
value: "source".to_string(),
reason: "no sandbox backend builds an image from source yet; give code.image a \
prebuilt reference"
.to_string(),
}));
}
// Read before the limits, because the image is declared whether or not any are.
if platform == Platform::Azure {
self.azure_catalog_image()?;
}
let Some(limits) = self.limits.as_ref() else {
// Nothing declared, so nothing to enforce and nothing to reject.
return self.validate_capabilities(&capabilities, platform);
};
validate_quantity(&self.id, "cpu", &limits.cpu)?;
validate_quantity(&self.id, "memory", &limits.memory)?;
validate_quantity(&self.id, "disk", &limits.disk)?;
if let Some(max_processes) = limits.max_processes {
if max_processes == 0 {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "maxProcesses".to_string(),
value: "0".to_string(),
reason: "a sandbox that may run no processes cannot run code".to_string(),
}));
}
capabilities.require(SandboxCapability::ProcessLimit, platform)?;
}
// Declaring limits a platform ignores is worse than not declaring them: the stack reads
// as bounded while the sandbox is not.
capabilities.require(SandboxCapability::EnforcedLimits, platform)?;
if platform == Platform::Aws {
// Refused here rather than at emit so a customer sees it while planning, and so both
// package formats inherit the same answer.
self.microvm_tier()?;
// The ceiling is Lambda's, and it rejects the run rather than clamping — so a value
// outside it would pass planning, render into the package, and fail at the first
// session. Kubernetes takes the same field with no such bound, which is why this
// sits under the AWS gate rather than on the type.
if let Some(seconds) = self.session.max_lifetime_seconds {
if !(1..=AWS_MAX_SESSION_LIFETIME_SECONDS).contains(&seconds) {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "maxLifetimeSeconds".to_string(),
value: seconds.to_string(),
reason: format!(
"AWS runs a MicroVM for between 1 and \
{AWS_MAX_SESSION_LIFETIME_SECONDS} seconds"
),
}));
}
}
}
self.validate_capabilities(&capabilities, platform)
}
/// The catalog disk image Azure creates a session from.
///
/// Azure names a public catalog entry rather than pulling a reference, so a registry path,
/// tag or digest has nowhere to go. An allowlist, because the answer to "what else could be
/// in there" is a name the data plane rejects at the first session, long after the apply.
pub fn azure_catalog_image(&self) -> Result<&str> {
let refused = |value: &str, reason: &str| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "code.image".to_string(),
value: value.to_string(),
reason: reason.to_string(),
})
};
let SandboxCode::Image { image } = &self.code else {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "code".to_string(),
value: "source".to_string(),
reason: "no sandbox backend builds an image from source yet".to_string(),
}));
};
let image = image.trim();
if image.is_empty() {
return Err(refused(image, "a sandbox has to name an image"));
}
if !image
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
{
return Err(refused(
image,
"Azure creates a session from a public catalog disk image, so code.image must be \
a bare catalog name such as 'ubuntu'",
));
}
Ok(image)
}
/// The MicroVM size that keeps every declared ceiling, or why none does.
///
/// AWS sizes are discrete and a running MicroVM bursts to four times its baseline, so the
/// only tier that honours a ceiling is one whose peak fits inside it. A declaration no tier
/// satisfies is refused: shipping the nearest size would give the customer a sandbox that
/// exceeds the bound they wrote down.
pub fn microvm_tier(&self) -> Result<MicrovmTier> {
let Some(limits) = self.limits.as_ref() else {
// Nothing declared: AWS's own default baseline, which is also `default_limits`.
return Ok(MICROVM_TIERS[2]);
};
let memory_mib = quantity_mib(&limits.memory).ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "memory".to_string(),
value: limits.memory.clone(),
reason: "AWS sizes a MicroVM in whole MiB".to_string(),
})
})?;
let disk_mib = quantity_mib(&limits.disk).ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "disk".to_string(),
value: limits.disk.clone(),
reason: "AWS sizes a MicroVM's disk in whole MiB".to_string(),
})
})?;
let cpu_millicores = millicores(&limits.cpu).ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "cpu".to_string(),
value: limits.cpu.clone(),
reason: "expected cores or millicores".to_string(),
})
})?;
// Memory and disk choose the size; cpu is then checked rather than used to choose.
// AWS couples cpu to memory at 2 GB per vCPU, so letting a low cpu ceiling select the
// size too would quietly hand back a machine four times smaller than the memory ceiling
// asked for, with nothing to indicate it.
let sized = |tier: &&MicrovmTier| {
tier.peak_memory_mib <= memory_mib && tier.max_disk_mib <= disk_mib
};
let tier = MICROVM_TIERS
.iter()
.rev()
.find(sized)
.copied()
.ok_or_else(|| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "memory".to_string(),
value: limits.memory.clone(),
reason: format!(
"a Lambda MicroVM bursts to four times its baseline, so the smallest \
ceiling AWS can hold is 2Gi memory with 8Gi disk; '{}' memory and '{}' \
disk fit no size",
limits.memory, limits.disk
),
})
})?;
let required_millicores = i64::from(tier.peak_vcpu) * 1000;
if cpu_millicores < required_millicores {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "cpu".to_string(),
value: limits.cpu.clone(),
reason: format!(
"AWS allocates one vCPU per 2GB, so a MicroVM sized to a '{}' memory ceiling \
reaches {} vCPU; declare cpu '{}' or lower the memory ceiling",
limits.memory, tier.peak_vcpu, tier.peak_vcpu
),
}));
}
Ok(tier)
}
/// The capability checks that do not depend on declared limits.
fn validate_capabilities(
&self,
capabilities: &SandboxCapabilities,
platform: Platform,
) -> Result<()> {
if matches!(self.egress, SandboxEgress::AllowDomains { .. }) {
capabilities.require(SandboxCapability::DomainEgressRules, platform)?;
}
// `allow` asks for no restriction, so a backend that ignores it fails loudly on the first
// blocked connection. `deny` asks for one, and a backend that ignores it puts untrusted
// code on the internet with nothing to notice — so only this direction is gated.
// An empty list is not a restriction anyone wrote down: it renders as a deny-all wearing
// an allowlist's label, which reads at a glance as the opposite of what it does.
if let SandboxEgress::AllowDomains { domains } = &self.egress {
if domains.is_empty() {
return Err(AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: self.id.clone(),
field: "egress.domains".to_string(),
value: "[]".to_string(),
reason: "an allowlist naming no domain denies everything; declare \
egress: deny if that is what was meant"
.to_string(),
}));
}
}
if matches!(self.egress, SandboxEgress::Deny) {
capabilities.require(SandboxCapability::EgressDeny, platform)?;
}
if !self.preview_ports.is_empty() {
capabilities.require(SandboxCapability::Preview, platform)?;
}
if self.session.idle_suspend_seconds.is_some() {
capabilities.require(SandboxCapability::SuspendResume, platform)?;
}
if self.session.max_lifetime_seconds.is_some() {
capabilities.require(SandboxCapability::SessionLifetime, platform)?;
}
Ok(())
}
}
/// Ceilings applied when a declaration names none.
///
/// Modest on purpose: an undeclared sandbox is one whose author did not think about sizing, and
/// the safe reading of that is a small box rather than a generous one.
fn default_limits() -> SandboxLimits {
SandboxLimits {
cpu: "1".to_string(),
memory: "2Gi".to_string(),
disk: "8Gi".to_string(),
max_processes: None,
}
}
/// Validates a Kubernetes-style resource quantity such as `500m`, `2Gi` or `1`.
fn validate_quantity(resource_id: &str, field: &str, value: &str) -> Result<()> {
let invalid = |reason: &str| {
AlienError::new(ErrorData::SandboxLimitInvalid {
resource_id: resource_id.to_string(),
field: field.to_string(),
value: value.to_string(),
reason: reason.to_string(),
})
};
let digits_end = value
.find(|c: char| !c.is_ascii_digit() && c != '.')
.unwrap_or(value.len());
let (number, suffix) = value.split_at(digits_end);
let parsed: f64 = number
.parse()
.map_err(|_| invalid("expected a number, optionally followed by a unit suffix"))?;
if parsed <= 0.0 {
return Err(invalid("must be greater than zero"));
}
const SUFFIXES: &[&str] = &["", "m", "k", "M", "G", "T", "Ki", "Mi", "Gi", "Ti"];
if !SUFFIXES.contains(&suffix) {
return Err(invalid(
"unit must be one of m, k, M, G, T, Ki, Mi, Gi, Ti, or absent",
));
}
Ok(())
}
/// Splits a quantity into its number and unit suffix.
fn split_quantity(value: &str) -> Option<(f64, &str)> {
let trimmed = value.trim();
let digits_end = trimmed
.find(|c: char| !c.is_ascii_digit() && c != '.')
.unwrap_or(trimmed.len());
let (number, suffix) = trimmed.split_at(digits_end);
number.parse().ok().map(|number| (number, suffix))
}
/// A memory or disk quantity in whole MiB, rounded down.
///
/// Every suffix `validate_quantity` accepts is handled here. Reading only `Gi` and `Mi` and
/// falling back for the rest would turn a declared `4G` into a different size than the customer
/// asked for, which for a ceiling means a sandbox larger than its bound.
pub fn quantity_mib(value: &str) -> Option<i64> {
let (number, suffix) = split_quantity(value)?;
let bytes = match suffix {
"" => number,
"k" => number * 1e3,
"M" => number * 1e6,
"G" => number * 1e9,
"T" => number * 1e12,
"Ki" => number * 1024.0,
"Mi" => number * 1024.0 * 1024.0,
"Gi" => number * 1024.0 * 1024.0 * 1024.0,
"Ti" => number * 1024.0 * 1024.0 * 1024.0 * 1024.0,
// `m` is a millicore suffix; memory has no use for it.
_ => return None,
};
Some((bytes / (1024.0 * 1024.0)) as i64)
}
/// A CPU quantity in millicores.
pub fn millicores(value: &str) -> Option<i64> {
let (number, suffix) = split_quantity(value)?;
match suffix {
"" => Some((number * 1000.0) as i64),
"m" => Some(number as i64),
_ => None,
}
}
/// Outputs generated by a successfully provisioned Sandbox parent.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
#[serde(rename_all = "camelCase")]
pub struct SandboxOutputs {
/// Name of the durable parent that sessions are created inside
pub parent_name: String,
/// Platform-specific identifier for the parent (image ARN, sandbox group id, namespace)
#[serde(skip_serializing_if = "Option::is_none")]
pub identifier: Option<String>,
/// Data-plane endpoint sessions are created through, where the platform has one
#[serde(skip_serializing_if = "Option::is_none")]
pub endpoint: Option<String>,
}
impl ResourceOutputsDefinition for SandboxOutputs {
fn get_resource_type(&self) -> ResourceType {
Sandbox::RESOURCE_TYPE
}
fn as_any(&self) -> &dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceOutputsDefinition> {
Box::new(self.clone())
}
fn outputs_eq(&self, other: &dyn ResourceOutputsDefinition) -> bool {
other.as_any().downcast_ref::<SandboxOutputs>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
impl ResourceDefinition for Sandbox {
fn get_resource_type(&self) -> ResourceType {
Self::RESOURCE_TYPE
}
fn id(&self) -> &str {
&self.id
}
fn get_dependencies(&self) -> Vec<ResourceRef> {
Vec::new()
}
fn validate_update(&self, new_config: &dyn ResourceDefinition) -> Result<()> {
let new_sandbox = new_config
.as_any()
.downcast_ref::<Sandbox>()
.ok_or_else(|| {
AlienError::new(ErrorData::UnexpectedResourceType {
resource_id: self.id.clone(),
expected: Self::RESOURCE_TYPE,
actual: new_config.get_resource_type(),
})
})?;
if self.id != new_sandbox.id {
return Err(AlienError::new(ErrorData::InvalidResourceUpdate {
resource_id: self.id.clone(),
reason: "the 'id' field is immutable".to_string(),
}));
}
Ok(())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn box_clone(&self) -> Box<dyn ResourceDefinition> {
Box::new(self.clone())
}
fn resource_eq(&self, other: &dyn ResourceDefinition) -> bool {
other.as_any().downcast_ref::<Sandbox>() == Some(self)
}
fn to_json_value(&self) -> serde_json::Result<serde_json::Value> {
serde_json::to_value(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sandbox_with(egress: SandboxEgress, preview_ports: Vec<u16>) -> Sandbox {
Sandbox::new("agent-sbx".to_string())
.code(SandboxCode::Image {
image: "ubuntu".to_string(),
})
.limits(SandboxLimits {
cpu: "1".to_string(),
memory: "2Gi".to_string(),
disk: "20Gi".to_string(),
max_processes: None,
})
.egress(egress)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.preview_ports(preview_ports)
.build()
}
#[test]
fn resource_type_is_stable() {
assert_eq!(Sandbox::RESOURCE_TYPE.as_ref(), "sandbox");
}
#[test]
fn capability_sets_are_per_platform() {
let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
assert!(
gcp.reconnect,
"generation from the container boot id makes a session reachable across processes"
);
assert!(!gcp.preview);
assert!(gcp.enforced_limits);
let azure = SandboxCapabilities::for_platform(Platform::Azure).expect("azure is supported");
assert!(azure.files, "every backend moves files");
assert!(gcp.files);
// Azure is the only backend whose egress policy matches on host pattern, and the only
// one where `deny` and a hostname list are the same object.
assert!(azure.domain_egress_rules);
assert!(azure.egress_deny);
// The data plane takes no ceiling, so a declaration of one is refused rather than
// accepted and dropped.
assert!(!azure.enforced_limits);
assert!(azure.suspend_resume);
// Both stay false for reasons that are not "unbuilt": a snapshot id has nothing to
// consume it on any backend, and an Azure port's auth is anonymous or a human allowlist,
// neither of which is a port-scoped credential.
assert!(!azure.snapshot);
assert!(!azure.preview);
let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
assert!(!aws.snapshot, "AWS has no user-callable session snapshot");
assert!(aws.suspend_resume);
let k8s =
SandboxCapabilities::for_platform(Platform::Kubernetes).expect("k8s is supported");
assert!(
!k8s.preview,
"the session-scoped ingress gateway does not exist yet"
);
}
/// Whether the process supervising a command is a separate identity from the command.
///
/// Values are measured, not inferred. AWS: the agent runs as uid 0 with
/// `CapEff: 00000000a80425fb` and `setuid`s the command to uid 60000, so the two differ.
/// Kubernetes: the sandbox pod pins `run_as_user: 65534` on both pod and container with
/// `capabilities.drop: [ALL]` and `allow_privilege_escalation: false`, so no uid split is
/// possible (`kubernetes_spec.rs`). Local: `docker exec` runs as the workload uid while the
/// manager supervises from the host. Azure and Agent Platform have no in-sandbox supervisor.
#[test]
fn supervisor_isolation_is_per_platform() {
let value = |platform| {
SandboxCapabilities::for_platform(platform)
.expect("supported")
.supervisor_isolation
};
assert!(
value(Platform::Aws),
"root agent setuids the command to 60000"
);
assert!(
value(Platform::Local),
"the supervisor is on the host, outside the container"
);
assert!(
!value(Platform::Kubernetes),
"a single pinned uid cannot be split"
);
assert!(!value(Platform::Azure), "no Alien process runs the command");
assert!(
!value(Platform::Gcp),
"no separate supervisor identity runs the command"
);
}
/// The point of the field: AWS and GCP report the *same* `supervisor_pid_namespace` (neither
/// has `CAP_SYS_ADMIN`), so that axis alone reads them as equivalent. They are not — AWS
/// separates the command's identity from the supervisor's and Agent Platform does not.
#[test]
fn supervisor_isolation_separates_aws_from_a_subprocess_backend() {
let aws = SandboxCapabilities::for_platform(Platform::Aws).expect("aws is supported");
let gcp = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
assert_eq!(
aws.supervisor_pid_namespace, gcp.supervisor_pid_namespace,
"the older axis cannot tell them apart"
);
assert!(
aws.supervisor_isolation,
"AWS setuids the command off the supervisor"
);
assert!(
!gcp.supervisor_isolation,
"the command runs under no separate supervisor identity"
);
}
/// The Agent Platform row, each value against the behaviour it was measured from. `reconnect`
/// is the tripwire: it is `true` only because `generation` is derived from the container boot
/// id read through the agent's health op, so a caller detects a replaced container instead of
/// reconnecting to a blank one. It is also the body of the `Platform::Gcp` arm, asserted below.
#[test]
fn gcp_agent_platform_row_matches_measured_backend() {
let row = SandboxCapabilities::gcp_agent_platform();
assert!(row.files, "agent file ops move over the session envelope");
assert!(
row.reconnect,
"generation is derived from the container boot id, so a session is reachable across \
processes"
);
assert!(
!row.preview,
"the only ingress is :execute; no port-scoped capability"
);
assert!(
row.suspend_resume,
":pause and :resume preserve the container"
);
assert!(
row.snapshot,
"session state can be captured and restored into a new session"
);
assert!(
!row.domain_egress_rules,
"VPC and DNS peering is not a hostname allowlist"
);
assert!(
row.egress_deny,
"a declared deny blocks both egress and DNS"
);
assert!(
row.enforced_limits,
"ceilings are enforced, by terminating the session on breach"
);
assert!(!row.process_limit, "no process-count ceiling is observed");
assert!(row.session_lifetime, "ttl maps to a session expireTime");
assert!(!row.supervisor_pid_namespace, "no PID-namespace isolation");
assert!(
!row.supervisor_isolation,
"the command is not run under a separate supervisor identity"
);
// Agent Platform is the registered GCP backend, so the arm returns exactly this row.
let live = SandboxCapabilities::for_platform(Platform::Gcp).expect("gcp is supported");
assert_eq!(
live, row,
"the Platform::Gcp arm is the Agent Platform capability row"
);
}
#[test]
fn platforms_without_a_backend_are_an_error_not_an_empty_set() {
let error = SandboxCapabilities::for_platform(Platform::Machines)
.expect_err("Machines has no sandbox backend");
assert_eq!(error.code, "SANDBOX_PLATFORM_UNSUPPORTED");
}
#[test]
fn unsupported_capability_names_platform_and_capability() {
let capabilities = SandboxCapabilities::for_platform(Platform::Gcp).expect("supported");
let error = capabilities
.require(SandboxCapability::Preview, Platform::Gcp)
.expect_err("GCP has no preview");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
let rendered = error.to_string();
assert!(
rendered.contains("preview"),
"names the capability: {rendered}"
);
assert!(rendered.contains("gcp"), "names the platform: {rendered}");
}
/// Azure matches on hostname; AWS and Kubernetes match CIDRs, and Local and GCP have a
/// switch rather than a filter. Accepting a hostname list on those four would leave a stack
/// reading as restricted while the sandbox reaches the whole internet.
#[test]
fn a_hostname_allowlist_is_refused_everywhere_it_would_be_approximated() {
let sandbox = sandbox_with(
SandboxEgress::AllowDomains {
domains: vec!["example.com".to_string()],
},
vec![],
);
for platform in [
Platform::Aws,
Platform::Gcp,
Platform::Kubernetes,
Platform::Local,
] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("only Azure expresses a hostname allowlist");
assert_eq!(
error.code, "SANDBOX_CAPABILITY_UNSUPPORTED",
"on {platform:?}"
);
}
assert!(
SandboxCapabilities::for_platform(Platform::Azure)
.expect("supported")
.domain_egress_rules,
"Azure's egress policy matches on host pattern"
);
}
/// `deny` is the declaration that carries a security promise, so a backend that cannot keep
/// it has to refuse rather than accept it and run the code with open egress.
#[test]
fn a_denied_egress_is_refused_where_it_would_not_be_enforced() {
let sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
// GCP is asserted at the capability rather than through validation: this sandbox declares
// ceilings GCP cannot enforce, so it is refused for a reason unrelated to egress.
assert!(
SandboxCapabilities::for_platform(Platform::Gcp)
.expect("supported")
.egress_deny
);
for platform in [Platform::Aws, Platform::Kubernetes, Platform::Local] {
sandbox
.validate_for_platform(platform)
.expect("deny is enforced here");
}
// Declares no ceilings, which Azure refuses for its own reason, so this isolates egress.
let egress_only = Sandbox::new("sbx".to_string())
.code(SandboxCode::Image {
image: "alpine".to_string(),
})
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
egress_only
.validate_for_platform(Platform::Azure)
.expect("Azure creates the sandbox under a Deny policy with full inspection");
}
/// Ceilings are rejected per-platform where unsupported — rejected when *declared*. With
/// limits mandatory that would read as "GCP sandboxes cannot exist", contradicting the
/// create, exec, files and terminate GCP does support.
#[test]
fn a_platform_that_cannot_enforce_limits_still_takes_a_sandbox_without_them() {
let declared = sandbox_with(SandboxEgress::Deny, Vec::new());
declared
.validate_for_platform(Platform::Azure)
.expect_err("declaring ceilings Azure cannot enforce is rejected");
let undeclared = Sandbox::new("sbx".to_string())
.code(SandboxCode::Image {
image: "alpine".to_string(),
})
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
undeclared
.validate_for_platform(Platform::Azure)
.expect("a sandbox naming no ceilings takes the platform's own");
// A backend still gets a concrete set, so nothing downstream has to invent one.
assert_eq!(undeclared.resolved_limits().cpu, "1");
}
#[test]
fn preview_ports_require_the_preview_capability() {
let sandbox = sandbox_with(SandboxEgress::Deny, vec![8080]);
sandbox
.validate_for_platform(Platform::Aws)
.expect("AWS mints a port-scoped JWE");
let error = sandbox
.validate_for_platform(Platform::Kubernetes)
.expect_err("Kubernetes preview is deferred");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
#[test]
fn gcp_accepts_a_sandbox_declaring_enforced_limits() {
let sandbox = sandbox_with(SandboxEgress::Allow, vec![]);
sandbox
.validate_for_platform(Platform::Gcp)
.expect("Agent Platform enforces declared ceilings, by terminating on breach");
}
#[test]
fn invalid_quantities_are_rejected_with_the_offending_field() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.memory = "2Gb".to_string();
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("Gb is not a valid suffix");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(error.to_string().contains("memory"));
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.memory = "2Gi".to_string();
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.cpu = "0".to_string();
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("zero cpu is not a ceiling");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
}
#[test]
fn zero_max_processes_is_rejected() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.max_processes = Some(0);
let error = sandbox
.validate_for_platform(Platform::Local)
.expect_err("a sandbox must be able to run at least one process");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(error.to_string().contains("maxProcesses"));
}
/// A process ceiling needs a container runtime. Kubernetes sets one per node rather than per
/// pod, and neither MicroVMs nor Azure sandboxes expose one, so accepting the declaration
/// anywhere else would mean carrying a bound nothing applies.
#[test]
fn a_process_ceiling_is_accepted_only_where_a_runtime_can_apply_it() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.max_processes = Some(256);
sandbox
.validate_for_platform(Platform::Local)
.expect("Docker takes a pids limit");
for platform in [Platform::Aws, Platform::Azure, Platform::Kubernetes] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("a process ceiling nothing applies must be refused");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
}
/// Lambda rejects a run outside 1–28,800 rather than clamping it, so a value beyond that
/// would pass planning, render into the package, and fail at the first session. Kubernetes
/// takes the same field with no such bound, so the check is AWS's alone.
#[test]
fn a_lifetime_aws_would_reject_is_refused_while_planning() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
for seconds in [0, 28_801, 100_000] {
sandbox.session.max_lifetime_seconds = Some(seconds);
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("a lifetime outside what AWS runs is refused");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "{seconds}s");
// Kubernetes has no such ceiling, so the same declaration is fine there.
sandbox
.validate_for_platform(Platform::Kubernetes)
.expect("the kubelet takes any activeDeadlineSeconds");
}
sandbox.session.max_lifetime_seconds = Some(28_800);
sandbox
.validate_for_platform(Platform::Aws)
.expect("the ceiling itself is allowed");
}
/// An image reference Azure cannot honour is refused while planning, not at the first session.
///
/// `code.image`'s own documentation gives a tag and a registry path as examples — exactly
/// what Azure cannot take, so this is the shape a customer is most likely to declare.
#[test]
fn an_image_azure_cannot_pull_is_refused_while_planning() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
// Azure enforces no declared ceiling, so a sandbox carrying limits is refused before the
// image is ever read.
sandbox.limits = None;
for image in [
"ubuntu:24.04",
"ghcr.io/myorg/sandbox:latest",
"ubuntu@sha256:abc",
"",
" ",
"ubuntu latest",
"ubuntu?x",
] {
sandbox.code = SandboxCode::Image {
image: image.to_string(),
};
let error = sandbox
.validate_for_platform(Platform::Azure)
.expect_err("an image Azure has nowhere to put is refused");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID", "image '{image}'");
// The same declaration is ordinary everywhere that pulls a reference.
sandbox
.validate_for_platform(Platform::Kubernetes)
.expect("a registry reference is what every other backend takes");
}
for image in ["ubuntu", "ubuntu-22.04", "debian_slim"] {
sandbox.code = SandboxCode::Image {
image: image.to_string(),
};
sandbox
.validate_for_platform(Platform::Azure)
.unwrap_or_else(|error| panic!("'{image}' is a catalog name: {error}"));
}
// Surrounding space is trimmed rather than carried into the create body.
sandbox.code = SandboxCode::Image {
image: " ubuntu ".to_string(),
};
assert_eq!(
sandbox
.azure_catalog_image()
.expect("a padded name is still a name"),
"ubuntu"
);
}
/// A deadline is accepted only where the platform itself terminates on it — the kubelet's
/// `activeDeadlineSeconds` and Lambda's `maximumDurationInSeconds`. Everywhere else it would
/// need a reaper that does not exist, so it is refused rather than accepted and dropped.
#[test]
fn a_session_deadline_is_accepted_only_where_the_platform_applies_it() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox.session.max_lifetime_seconds = Some(3600);
sandbox
.validate_for_platform(Platform::Kubernetes)
.expect("the kubelet enforces activeDeadlineSeconds");
sandbox
.validate_for_platform(Platform::Aws)
.expect("Lambda terminates the MicroVM at maximumDurationInSeconds");
for platform in [Platform::Azure, Platform::Local] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("a deadline nothing applies must be refused");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
}
}
/// A MicroVM bursts to four times its baseline with no way to opt out, so a ceiling is kept
/// by choosing the size whose *peak* fits inside it. Sizing by baseline would hand back a
/// sandbox that can reach four times what the customer declared.
#[test]
fn an_aws_size_is_chosen_so_its_peak_stays_inside_the_declared_ceiling() {
let sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
let tier = sandbox
.microvm_tier()
.expect("2Gi/1cpu/20Gi is satisfiable");
assert_eq!(
tier.peak_memory_mib, 2048,
"the peak is the declared ceiling"
);
assert_eq!(
tier.baseline_memory_mib, 512,
"which is a quarter of it as the baseline"
);
assert!(tier.max_disk_mib <= 20 * 1024);
}
/// AWS allocates one vCPU per 2GB, so a cpu ceiling below what the memory ceiling implies
/// cannot be honoured together with it. Letting cpu choose the size instead would hand back a
/// machine four times smaller than the memory asked for, with nothing to indicate it.
#[test]
fn a_cpu_ceiling_below_what_the_memory_implies_is_refused_not_quietly_downsized() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
{
let limits = sandbox
.limits
.as_mut()
.expect("the fixture declares limits");
limits.cpu = "1".to_string();
limits.memory = "8Gi".to_string();
}
let error = sandbox
.microvm_tier()
.expect_err("1 cpu and 8Gi cannot both be ceilings on AWS");
assert!(
error.to_string().contains("4 vCPU"),
"the refusal must say what the memory ceiling implies: {error}"
);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.cpu = "4".to_string();
let tier = sandbox.microvm_tier().expect("4 cpu matches 8Gi");
assert_eq!(tier.peak_memory_mib, 8192);
}
/// Below AWS's smallest peak there is no size that holds the ceiling, and rounding up to the
/// nearest one would silently exceed it.
#[test]
fn an_aws_ceiling_smaller_than_any_size_is_refused_rather_than_rounded() {
let mut sandbox = sandbox_with(SandboxEgress::Deny, vec![]);
sandbox
.limits
.as_mut()
.expect("the fixture declares limits")
.memory = "1Gi".to_string();
let error = sandbox
.validate_for_platform(Platform::Aws)
.expect_err("no MicroVM size peaks at or below 1Gi");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(
error.to_string().contains("2Gi"),
"the refusal must say what the smallest holdable ceiling is: {error}"
);
}
/// `Source` is a public part of the type that no backend builds: an empty image string
/// schedules a pod that can never run, so the refusal has to happen at plan time and on
/// every platform, not in one emitter.
#[test]
fn source_code_is_refused_everywhere_rather_than_producing_a_broken_manifest() {
let sandbox = Sandbox::new("agent".to_string())
.code(SandboxCode::Source {
src: "./sandbox".to_string(),
toolchain: ToolchainConfig::Docker {
dockerfile: None,
build_args: None,
target: None,
},
})
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
for platform in [
Platform::Aws,
Platform::Azure,
Platform::Gcp,
Platform::Kubernetes,
Platform::Local,
] {
let error = sandbox
.validate_for_platform(platform)
.expect_err("no backend builds a sandbox image from source");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
assert!(
error.to_string().contains("code.image"),
"the refusal must say what to write instead: {error}"
);
}
}
/// `validate_quantity` accepts nine suffixes. Reading only `Gi` and `Mi` would size a
/// declared `4G` as though it were `4Gi`, which for a ceiling means exceeding it.
#[test]
fn every_accepted_unit_converts_rather_than_falling_back() {
assert_eq!(quantity_mib("2Gi"), Some(2048));
assert_eq!(quantity_mib("512Mi"), Some(512));
assert_eq!(quantity_mib("4G"), Some(3814));
assert_eq!(quantity_mib("1Ti"), Some(1024 * 1024));
assert_eq!(millicores("1"), Some(1000));
assert_eq!(millicores("500m"), Some(500));
}
#[test]
fn unknown_fields_are_rejected() {
let json = r#"{
"id": "sbx",
"code": {"type": "image", "image": "ubuntu:24.04"},
"limits": {"cpu": "1", "memory": "2Gi", "disk": "20Gi"},
"egress": {"mode": "deny"},
"session": {},
"unexpected": true
}"#;
serde_json::from_str::<Sandbox>(json).expect_err("deny_unknown_fields must reject");
}
#[test]
fn serialization_roundtrips() {
let sandbox = sandbox_with(
SandboxEgress::AllowDomains {
domains: vec!["example.com".to_string()],
},
vec![8080, 9090],
);
let json = serde_json::to_string(&sandbox).expect("serializes");
let restored: Sandbox = serde_json::from_str(&json).expect("deserializes");
assert_eq!(sandbox, restored);
}
#[test]
fn id_is_immutable_across_updates() {
let original = sandbox_with(SandboxEgress::Deny, vec![]);
let renamed = Sandbox::new("other".to_string())
.code(SandboxCode::Image {
image: "ubuntu".to_string(),
})
.limits(
original
.limits
.clone()
.expect("the fixture declares limits"),
)
.egress(SandboxEgress::Deny)
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build();
original
.validate_update(&original.clone())
.expect("an unchanged config is a valid update");
original
.validate_update(&renamed)
.expect_err("renaming a sandbox is not an update");
}
/// Azure declares an idle-suspend policy but not a wall-clock ceiling.
///
/// The two travel together in `SandboxSessionPolicy` and are gated separately on purpose:
/// Azure suspends on idle and has no maximum lifetime, so accepting one and refusing the
/// other is the honest split rather than an inconsistency.
#[test]
fn azure_takes_an_idle_policy_and_still_refuses_a_lifetime_ceiling() {
let with_policy = |session: SandboxSessionPolicy| {
Sandbox::new("sbx".to_string())
.code(SandboxCode::Image {
image: "ubuntu".to_string(),
})
.egress(SandboxEgress::Allow)
.session(session)
.build()
.validate_for_platform(Platform::Azure)
};
with_policy(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: Some(900),
})
.expect("Azure suspends a session on idle");
let error = with_policy(SandboxSessionPolicy {
max_lifetime_seconds: Some(3600),
idle_suspend_seconds: None,
})
.expect_err("Azure has no wall-clock ceiling to enforce one with");
assert_eq!(error.code, "SANDBOX_CAPABILITY_UNSUPPORTED");
assert!(
error.message.contains("sessionLifetime"),
"names the capability: {}",
error.message
);
}
/// An allowlist naming nothing is a deny-all wearing an allowlist's label.
///
/// It renders as a `Deny` default with no rules — the shape the Azure provider adds a
/// catch-all to avoid — and a reader scanning the declaration sees "allowDomains" and reads
/// the opposite of what it does.
#[test]
fn an_allowlist_with_no_domains_is_refused() {
let declared = |domains: Vec<String>| {
Sandbox::new("sbx".to_string())
.code(SandboxCode::Image {
image: "ubuntu".to_string(),
})
.egress(SandboxEgress::AllowDomains { domains })
.session(SandboxSessionPolicy {
max_lifetime_seconds: None,
idle_suspend_seconds: None,
})
.build()
.validate_for_platform(Platform::Azure)
};
let error = declared(vec![]).expect_err("an empty allowlist must be refused");
assert_eq!(error.code, "SANDBOX_LIMIT_INVALID");
declared(vec!["api.example.com".to_string()])
.expect("a named domain is what an allowlist is for");
}
/// The two expressible modes map to the boolean; a host list maps to nothing so the caller has
/// to refuse rather than silently pick a side.
#[test]
fn internet_access_switch_maps_only_the_two_expressible_modes() {
assert_eq!(SandboxEgress::Allow.internet_access_switch(), Some(true));
assert_eq!(SandboxEgress::Deny.internet_access_switch(), Some(false));
assert_eq!(
SandboxEgress::AllowDomains {
domains: vec!["api.example.com".to_string()]
}
.internet_access_switch(),
None,
"a host list has no boolean and must not be approximated"
);
}
}