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
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
// SPDX-License-Identifier: Apache-2.0
//! Launch, the launch wait, the lifecycle calls, and the proxy token (TRAP-5, TRAP-8).
//!
//! # TRAP-5: the payload ceiling is 4096 bytes, inclusive
//!
//! [`RunHookPayload`] cannot hold an over-ceiling value, so the check happens when the
//! payload is *made* rather than when the request is sent — which means every path into
//! `RunMicrovm` is closed by one guard instead of each needing its own.
//!
//! The number is worth stating precisely because the project got it wrong in the dangerous
//! direction. `docs/STRATEGY.md` and `docs/TRUST.md` claimed 16 KB — and so does the
//! service model's own **documentation** string for `runHookPayload`, which reads "Maximum:
//! 16,384 bytes" while its shape `RunMicrovmRequestRunHookPayloadString` says `max: 4096`.
//! So a reader who checks the docs rather than the shape reproduces the bug. 4x wrong in
//! the direction that tells a caller four times as much secret material fits as actually
//! does. Bracketed 2026-08-07 by calling `RunMicrovm` with a deliberately bogus
//! `imageIdentifier` so nothing could be created or billed: **4096 passes, 4097 fails.**
//!
//! Measured in UTF-8 **bytes**, not characters. A payload counted by character length
//! passes while the same value with one multi-byte character in it does not.
//!
//! # TRAP-5's other half: why the payload at all
//!
//! It is the only per-VM secret channel the platform offers, and it is what keeps the agent
//! token out of the shared image snapshot. That is safe because the platform forwards no
//! external traffic until the run hook returns 200, so a per-VM secret delivered at launch
//! wins the first-writer race through the endpoint.
//!
//! The daemon reads it one JSON parse deeper than expected: the platform **wraps** the
//! string, so the hook body is `{"runHookPayload": "{\"agent_token\": \"...\"}"}`.
//!
//! # TRAP-8: a terminal state before RUNNING
//!
//! A VM that reaches a terminal state before RUNNING died during startup, and for a
//! hook-serving daemon that almost always means a lifecycle hook failed. Polling through it
//! wastes minutes and then reports a connection error that hides the cause — and by then
//! the VM is gone, so `stateReason` is the only evidence left. [`ControlPlane::wait_for_running`]
//! fails fast and attaches both the state and the reason.
//!
//! # TRAP-11, again: the shell mint is a separate surface, not a sibling of exec's
//!
//! [`ControlPlane::mint_auth_token`] calls `CreateMicrovmAuthToken` and is what the exec
//! path uses. [`ControlPlane::mint_shell_auth_token`] calls `CreateMicrovmShellAuthToken`
//! and exists for exactly one caller: `microvm shell`, the interactive PTY (issue #69).
//! Nothing on the exec or session path reaches it — the lifecycle test below drives
//! everything exec can do and asserts zero shell calls were emitted. See [`super`].
use super::transport::{Call, paths};
use super::{ControlPlane, RunMicrovmRequest, WaitOpts, ops, timed_out, token};
use crate::error::{Error, ErrorKind};
/// The proxy token's auth header, which is also the key in the `authToken` map.
pub const PROXY_AUTH_HEADER: &str = "X-aws-proxy-auth";
/// The proxy port header.
///
/// Sent on **every** endpoint request alongside the auth header: `X-aws-proxy-auth` without
/// `X-aws-proxy-port` is rejected in a way that reads like a bad token, which is a long
/// detour for a missing header.
pub const PROXY_PORT_HEADER: &str = "X-aws-proxy-port";
/// The service ceiling on a proxy token's life, in minutes.
pub const MAX_TOKEN_MINUTES: u32 = 60;
/// A `runHookPayload` that is known to fit the service ceiling.
///
/// The type is the guard: there is no way to build one over 4096 bytes, so no call site has
/// to remember to check. See the module docs for the measurement and for why the service
/// model's own documentation string disagrees with its shape.
#[derive(Clone, Eq, PartialEq)]
pub struct RunHookPayload(String);
/// Prints the size and nothing else.
///
/// The payload is the platform's only per-VM secret channel — its whole purpose is to carry
/// the agent token — so a derived `Debug` would print that token into every log line that
/// formats one, and into every line that formats the [`RunMicrovmRequest`] holding it.
/// [`RunMicrovmRequest`] keeps its derive: with this impl in place, the derived one prints
/// `RunHookPayload(<N bytes>)` for that field, so the safety is inherited rather than
/// restated. The length is kept because it is the number every TRAP-5 diagnosis needs.
impl std::fmt::Debug for RunHookPayload {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "RunHookPayload(<{} bytes>)", self.0.len())
}
}
impl RunHookPayload {
/// The payload carrying an agent token, as the daemon expects to find it.
///
/// `{"agent_token": "<token>"}` — and the platform wraps *this whole string* as the
/// value of `runHookPayload`, which is the extra parse the daemon does.
///
/// Checked even though this function builds the JSON itself, because the token is
/// caller-supplied: someone passing a JWT or a signed blob rather than a bearer token is
/// exactly who this catches.
pub fn for_agent_token(agent_token: &str) -> Result<Self, Error> {
Self::for_launch(agent_token, &std::collections::HashMap::new())
}
/// The payload carrying an agent token and a launch environment.
///
/// `{"agent_token": "<token>", "env": {...}}`, and the platform wraps that whole
/// string as the value of `runHookPayload` — the extra parse the daemon does.
/// The daemon applies `env` as the base environment of every subsequent exec,
/// under the per-request `env`.
///
/// **This is where the 4096-byte refusal fires for a launch env.** The check is
/// on the serialized payload rather than on the map, because the ceiling is on
/// the string: JSON escaping, the key names, and the punctuation all count, so a
/// caller who measured their own values would measure the wrong thing. And it is
/// local rather than left to the service for the same reason
/// [`super::super::control::image`]'s `require_workdir` and
/// `require_matching_from` are local: the service's answer arrives as a
/// `ValidationException` on a member the caller did not know they were filling,
/// after the call, and botocore does not enforce it client-side at all (measured;
/// `docs/PLATFORM.md`). `env` is what makes this reachable in practice — one
/// bearer token has always fit with room to spare, and a map of credentials does
/// not.
///
/// The env is omitted from the JSON entirely when it is empty, so a caller who
/// passes no launch env produces byte-for-byte the payload
/// [`RunHookPayload::for_agent_token`] always produced. A pinned daemon that has
/// never heard of `env` therefore sees no change, and the two constructors do not
/// have two different budgets.
pub fn for_launch(
agent_token: &str,
env: &std::collections::HashMap<String, String>,
) -> Result<Self, Error> {
Self::for_launch_with_identity(agent_token, env, None)
}
/// [`RunHookPayload::for_launch`], optionally carrying the tunnel identity material.
///
/// The two identity fields are the VM's own seed and the launching host's public key,
/// under the keys `protocol::identity` declares — the daemon pins one and derives from
/// the other, which lets `microvm tunnel --verify-identity` prove possession of the
/// launch-pinned key under `protocol::identity`'s trust assumptions. `None` produces byte-for-byte the
/// payload the other constructors always built, so a caller who never asks for identity
/// cannot be affected by the field existing (the same compatibility rule `env` follows).
///
/// The material costs [`protocol::identity::IDENTITY_PAYLOAD_BYTES`] of the shared
/// 4096-byte budget — two 44-character base64 values plus JSON framing — and the ceiling
/// check below covers it like everything else in the payload.
pub fn for_launch_with_identity(
agent_token: &str,
env: &std::collections::HashMap<String, String>,
identity: Option<&crate::identity::LaunchIdentity>,
) -> Result<Self, Error> {
let mut payload = if env.is_empty() {
serde_json::json!({ "agent_token": agent_token })
} else {
serde_json::json!({ "agent_token": agent_token, "env": env })
};
if let Some(identity) = identity {
let object = payload
.as_object_mut()
.expect("the payload is built as an object two lines up");
object.insert(
protocol::identity::SEED_KEY.to_string(),
serde_json::Value::String(identity.seed_field()),
);
object.insert(
protocol::identity::HOST_PUBLIC_KEY_KEY.to_string(),
serde_json::Value::String(identity.host_public_field()),
);
}
let text = serde_json::to_string(&payload).map_err(|error| {
Error::new(
ErrorKind::Unexpected,
format!("could not serialize the run-hook payload: {error}"),
)
})?;
// The length is read before the value moves into `new`, so the refusal below can
// account for it without rebuilding the payload.
let total = text.len();
Self::new(text).map_err(|error| {
if env.is_empty() {
return error;
}
// The generic message names the byte count and the ceiling, which is the
// whole diagnosis for a token. For a launch env it is half of one: the
// caller wants to know how much of the budget their env is, because the
// fix is to move a value out of it rather than to shorten the token.
Error::invalid_arg(format!(
"{error} The launch env contributed {} of those bytes across {} variable(s); \
the payload's other {} are the token and the JSON framing. A launch env is \
for small values a workload needs at startup — move credential-scale \
material to PUT /v1/fs/file after bootstrap, or to a role the workload \
assumes.",
env_contribution(agent_token, env),
env.len(),
total.saturating_sub(env_contribution(agent_token, env)),
))
})
}
/// An arbitrary payload, if it fits.
///
/// Public because the run-hook body is the caller's channel and this crate does not own
/// what goes in it; the ceiling is the only thing it enforces.
pub fn new(payload: impl Into<String>) -> Result<Self, Error> {
let payload = payload.into();
// Bytes, not characters: the ceiling is on the serialized string, so a payload
// measured by character count passes while the same value with one multi-byte
// character in it does not.
let size = payload.len();
if size <= crate::constants::MAX_RUN_HOOK_PAYLOAD_BYTES {
return Ok(Self(payload));
}
Err(Error::invalid_arg(format!(
"runHookPayload is {size} bytes, over the ceiling of {} (service model {}, measured \
inclusive 2026-08-07: 4096 passes and 4097 fails). This is the only per-VM secret \
channel the platform offers — one bearer token fits, a cloud credential set does \
not. Note that docs/STRATEGY.md, docs/TRUST.md, and the service model's own \
documentation string for this member all claim 16 KB, which is wrong by 4x in the \
dangerous direction; the shape RunMicrovmRequestRunHookPayloadString is the \
authority and it states max 4096.",
crate::constants::MAX_RUN_HOOK_PAYLOAD_BYTES,
crate::constants::MODEL_API_VERSION,
)))
}
/// The payload's bytes as the wire will carry them.
pub fn as_str(&self) -> &str {
&self.0
}
/// The size in bytes, which is what the ceiling measures.
pub fn len(&self) -> usize {
self.0.len()
}
/// Whether the payload is empty. The model's minimum is 0, so an empty payload is legal.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
/// How many of a launch payload's bytes the env accounts for.
///
/// Measured by difference against the token-only payload rather than by summing key and
/// value lengths, because the ceiling is on the *serialized* string: the `"env":{}`
/// wrapper, the quotes, the commas, and every backslash JSON escaping adds all count
/// against the budget, and a figure that summed the raw values would understate exactly
/// the payloads that are near the limit.
///
/// Only ever called on the refusal path, where the payload has already been built once.
fn env_contribution(agent_token: &str, env: &std::collections::HashMap<String, String>) -> usize {
let with = serde_json::json!({ "agent_token": agent_token, "env": env }).to_string();
let without = serde_json::json!({ "agent_token": agent_token }).to_string();
with.len().saturating_sub(without.len())
}
/// A launched MicroVM, as the service last described it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Microvm {
pub id: String,
pub state: String,
/// The proxy endpoint. Present from the launch response onward.
pub endpoint: String,
pub image_arn: String,
pub image_version: String,
/// Why the VM is in this state, when the service said. The absence is information —
/// TRAP-8's message distinguishes "no stateReason" from an empty one.
pub state_reason: Option<String>,
/// The idle policy the service reports the VM is running under.
///
/// Carried rather than dropped because it is the platform's own account of the window
/// that will suspend and then terminate this VM, and it was measured coming back on a
/// real `GetMicrovm` — see [`ops::IdlePolicy`], which used to claim it does not. The
/// client's request is what *asked* for a window; this is what the service says it got,
/// and a caller diagnosing a VM that vanished earlier than expected needs the second.
///
/// `Option` because the model does not mark the member required on either response
/// shape, so an absent one must parse rather than fail.
pub idle_policy: Option<ops::IdlePolicy>,
/// `maximumDurationInSeconds` as the service reports it.
pub maximum_duration_seconds: Option<u32>,
/// When the VM first started (`startedAt`). Absent on a launch reply.
pub started_at: Option<std::time::SystemTime>,
/// When the VM terminated (`terminatedAt`), once it has.
pub terminated_at: Option<std::time::SystemTime>,
}
/// Epoch seconds from a `Timestamp` member, or `None` for an absent or unrepresentable one.
///
/// The checked conversion refuses a negative, NaN, infinite or too-large figure. The unchecked
/// one, behind a filter for the first three, panicked on a figure past what a `Duration` holds
/// before `checked_add` could refuse it (#335).
fn epoch(seconds: Option<f64>) -> Option<std::time::SystemTime> {
let since = std::time::Duration::try_from_secs_f64(seconds?).ok()?;
std::time::UNIX_EPOCH.checked_add(since)
}
/// The optional filters `ListMicrovms` accepts.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MicrovmFilter {
/// Only VMs running this image (ARN or ID).
pub image_identifier: Option<String>,
/// Only VMs running this image version.
pub image_version: Option<String>,
}
impl Microvm {
/// The reason the service gave, or a phrase saying it gave none.
///
/// A phrase rather than an empty string, because "the service said nothing" and "the
/// service said nothing useful" are different diagnoses and a caller reading a message
/// has to be able to tell them apart.
pub(crate) fn reason(&self) -> &str {
self.state_reason.as_deref().unwrap_or("no stateReason")
}
}
impl From<ops::MicrovmResponseWire> for Microvm {
fn from(wire: ops::MicrovmResponseWire) -> Self {
Self {
id: wire.microvm_id,
state: wire.state,
endpoint: wire.endpoint,
image_arn: wire.image_arn,
image_version: wire.image_version,
state_reason: wire.state_reason,
idle_policy: wire.idle_policy,
maximum_duration_seconds: wire.maximum_duration_in_seconds,
started_at: epoch(wire.started_at),
terminated_at: epoch(wire.terminated_at),
}
}
}
/// The minted proxy token, as a header map (TRAP-7).
///
/// # Why a map rather than a string
///
/// Because that is what the service answers: `authToken` is a `TokenParts` map, and the
/// value at `X-aws-proxy-auth` is the header value. A client that treated the response as a
/// string would send a stringified map and get a rejection that reads like a bad token.
///
/// [`ProxyToken::headers`] always emits **both** headers, which is the other half of the
/// same trap: `X-aws-proxy-auth` without `X-aws-proxy-port` is rejected the same
/// indistinguishable way.
#[derive(Clone, Eq, PartialEq)]
pub struct ProxyToken {
value: String,
port: u16,
}
/// Names the headers and the port, never the token value.
///
/// A minted proxy token is a credential, and a derived `Debug` would print it into every
/// log line that formats a [`ProxyToken`], a [`RunMicrovmRequest`] holding one, or an error
/// chain containing either. The sibling type in [`crate::session::proxy`] made this choice
/// first; this is the same rule on the control-plane side of the conversion.
impl std::fmt::Debug for ProxyToken {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProxyToken")
.field("headers", &[PROXY_AUTH_HEADER, PROXY_PORT_HEADER])
.field("port", &self.port)
.finish()
}
}
impl ProxyToken {
/// Reads the token out of the service's `authToken` map.
///
/// A missing `X-aws-proxy-auth` key is [`ErrorKind::Retryable`] via
/// [`crate::error::WireKind::AuthTokenMint`]: minting is inside the request retry path
/// (TRAP-9), and a throttle at minute 30 of a long run must not kill a trial that is
/// otherwise healthy.
pub fn from_map(
map: &std::collections::BTreeMap<String, String>,
port: u16,
) -> Result<Self, Error> {
Self::from_operation_map("CreateMicrovmAuthToken", map, port)
}
/// [`ProxyToken::from_map`], naming the operation whose response the map came from.
///
/// The shell mint reads the same `TokenParts` shape out of
/// `CreateMicrovmShellAuthToken`, and a missing-key failure that blamed the ordinary
/// mint would send the reader to the wrong operation's response.
pub fn from_operation_map(
operation: &str,
map: &std::collections::BTreeMap<String, String>,
port: u16,
) -> Result<Self, Error> {
let value = map.get(PROXY_AUTH_HEADER).ok_or_else(|| {
Error::wire(
crate::error::WireKind::AuthTokenMint,
format!(
"the {operation} response carried no {PROXY_AUTH_HEADER} key. The \
authToken member is a map, not a string, and that key is the header value \
(keys present: {:?}).",
map.keys().collect::<Vec<_>>()
),
)
})?;
Ok(Self {
value: value.clone(),
port,
})
}
/// Both headers every endpoint request needs.
///
/// Both, always. See the type docs: sending only the auth header is rejected in a way
/// that reads like a bad token.
pub fn headers(&self) -> [(&'static str, String); 2] {
[
(PROXY_AUTH_HEADER, self.value.clone()),
(PROXY_PORT_HEADER, self.port.to_string()),
]
}
/// The raw token value.
pub fn value(&self) -> &str {
&self.value
}
/// The port the token was minted for.
pub fn port(&self) -> u16 {
self.port
}
}
impl ControlPlane {
/// Launches a MicroVM.
///
/// TRAP-5 is already closed by [`RunHookPayload`]'s type; the duration range is checked
/// here, and the connectors are derived from intents (TRAP-4). The `clientToken` is
/// minted from a label (TRAP-1).
pub async fn run_microvm(&self, request: RunMicrovmRequest) -> Result<Microvm, Error> {
self.run_microvm_reported(request, None)
.await
.map(|(vm, _)| vm)
}
pub(crate) async fn run_microvm_reported(
&self,
request: RunMicrovmRequest,
cancellation: Option<&super::transport::RetryCancellation>,
) -> Result<(Microvm, super::transport::RetryDetails), Error> {
let (ingress, egress) = self.launch_connectors(&request)?;
let wire = ops::RunMicrovmWire {
image_identifier: request.image_identifier.clone(),
image_version: request.image_version.clone(),
execution_role_arn: request.execution_role_arn.clone(),
ingress_network_connectors: ingress,
// Absent rather than empty: omitting egress omits the connector from the request.
// Measured 2026-09-11 and 2026-09-12 the platform still gave such a VM outbound
// network (`docs/PLATFORM.md`, "A VM launched without the egress connector still
// has outbound network").
egress_network_connectors: (!egress.is_empty()).then_some(egress),
idle_policy: ops::IdlePolicy {
max_idle_duration_seconds: request.max_idle_sec,
suspended_duration_seconds: request.suspended_sec,
auto_resume_enabled: request.auto_resume,
},
maximum_duration_in_seconds: request.max_duration_sec,
run_hook_payload: request.run_hook_payload.as_str().to_string(),
logging: request.logging.clone(),
client_token: match request.client_token {
Some(token) => token,
None => token::run_token_with(
request
.token_scope
.as_deref()
.unwrap_or(&request.image_identifier),
self.entropy(),
)?,
},
};
let call = Call::post_json("RunMicrovm", paths::microvms(), &wire)?;
let (reply, details) = super::transport::send_cancellable(
self.transport(),
call,
&[],
self.retry,
self.clock.as_ref(),
cancellation,
)
.await?;
let reply = super::ReportedReply { reply, details };
let launched: ops::MicrovmResponseWire = reply.json("RunMicrovm")?;
Ok((launched.into(), details))
}
/// Every local refusal [`Self::run_microvm`] makes, then the ingress and egress connector
/// ARNs the launch carries. Local; zero calls.
///
/// Separate so [`crate::sandbox::Sandbox::run`] can ask it before it resolves an image
/// name: that listing is a call, and a launch this client refuses anyway should cost none.
pub(crate) fn launch_connectors(
&self,
request: &RunMicrovmRequest,
) -> Result<(Vec<String>, Vec<String>), Error> {
if let Some(token) = request.client_token.as_deref() {
super::token::require_run_token(token)?;
}
super::require_valid_identifier("imageIdentifier", &request.image_identifier)?;
super::require_duration_in_range(request.max_duration_sec)?;
// `min: 60` on `IdlePolicyMaxIdleDurationSecondsInteger`. There used to be no guard for
// this on the grounds that botocore enforces `min` locally — true of the deleted Python
// client and never of this one. See `super::require_idle_duration`.
super::require_idle_duration(request.max_idle_sec)?;
// Checked before the wire because a pinned launch is what a rollback does, and a
// `ValidationException` on the member rather than on the version is the least useful
// failure available at that moment. See `super::require_valid_version`.
if let Some(version) = request.image_version.as_deref() {
super::require_valid_version("imageVersion", version)?;
}
// `RoleArn` — optional in the model, and every real launch has one. A malformed value
// here is a `ValidationException` on a member the caller may not know is being filled
// from their infra config, so the refusal names it.
if let Some(role) = request.execution_role_arn.as_deref() {
super::require_valid_role_arn("executionRoleArn", role)?;
}
if let Some(ops::Logging::CloudWatch { cloud_watch }) = &request.logging {
let Some(group) = cloud_watch.log_group.as_deref() else {
return Err(Error::invalid_arg(
"per-VM CloudWatch logging needs a logGroup; pass a group name or disable logging",
));
};
super::require_valid_log_group(group)?;
if let Some(stream) = cloud_watch.log_stream.as_deref() {
super::require_valid_log_stream(stream)?;
}
}
// `ALL_INGRESS` cannot be combined with any other ingress connector, and the
// platform says so only at token-mint time: `RunMicrovm` accepts the invalid
// set, the VM reaches RUNNING, and it bills until something asks for a shell
// token (`docs/PLATFORM.md`, measured 2026-08-15). Refused here instead, before
// anything launches or bills. The pair that works is `[HTTP_INGRESS,
// SHELL_INGRESS]`.
let has_all_ingress = request
.connectors
.contains(&super::ConnectorIntent::AllIngress);
let has_finer_ingress = request.connectors.iter().any(|intent| {
matches!(
intent,
super::ConnectorIntent::HttpIngress | super::ConnectorIntent::ShellIngress
)
});
if has_all_ingress && has_finer_ingress {
return Err(Error::invalid_arg(
"ALL_INGRESS cannot be combined with other ingress connectors; use \
HTTP_INGRESS and/or SHELL_INGRESS instead. The platform accepts the \
combination at launch and rejects it only when a shell token is minted, \
after the VM has launched and billed — so it is refused here.",
));
}
// The other half of the same measured constraint: the pair that launches and
// mints a shell token is `[HTTP_INGRESS, SHELL_INGRESS]`. A shell-only ingress
// set has no measured success path, and the platform accepts an invalid set at
// launch — so it too is refused here, before anything launches or bills.
let has_shell_ingress = request
.connectors
.contains(&super::ConnectorIntent::ShellIngress);
let has_http_ingress = request
.connectors
.contains(&super::ConnectorIntent::HttpIngress);
if has_shell_ingress && !has_http_ingress {
return Err(Error::invalid_arg(
"SHELL_INGRESS was requested without HTTP_INGRESS. The measured pair that \
launches and mints a shell token is [HTTP_INGRESS, SHELL_INGRESS] \
(docs/PLATFORM.md); the platform accepts an invalid ingress set at launch \
and the VM runs and bills before any failure appears — so it is refused \
here.",
));
}
// Ingress and egress go in separate members, so they are split by intent rather
// than concatenated into one list.
let ingress: Vec<String> = request
.connectors
.iter()
.filter(|intent| {
matches!(
intent,
super::ConnectorIntent::AllIngress
| super::ConnectorIntent::HttpIngress
| super::ConnectorIntent::ShellIngress
)
})
.map(|intent| intent.arn(&self.region))
.collect();
let mut egress: Vec<String> = request
.connectors
.iter()
.filter(|intent| matches!(intent, super::ConnectorIntent::Egress))
.map(|intent| intent.arn(&self.region))
.collect();
// The same refusals, in the same order and words, as `egress_posture_for`, which
// `Sandbox::run` asks first; these stand for a caller of `run_microvm` directly.
if !egress.is_empty() && !request.egress_network_connectors.is_empty() {
return Err(super::connector::egress_with_connectors());
}
for arn in &request.egress_network_connectors {
super::connector::require_egress_connector_arn(arn, &self.region)?;
egress.push(arn.clone());
}
// Each request member is a NetworkConnectorList with its own limit.
for (member, count) in [
("ingressNetworkConnectors", ingress.len()),
("egressNetworkConnectors", egress.len()),
] {
if let Some(refusal) = super::connector::over_connector_ceiling(member, count) {
return Err(refusal);
}
}
Ok((ingress, egress))
}
/// Polls to RUNNING, failing fast on a terminal state (TRAP-8).
///
/// The fast failure is the whole value. A VM that reaches a terminal state before
/// RUNNING died during startup; polling through it wastes minutes and then reports a
/// connection error that hides the cause, and by then the VM is gone so `stateReason` is
/// the only evidence left.
pub async fn wait_for_running(&self, id: &str, opts: WaitOpts) -> Result<Microvm, Error> {
self.wait_for_state(id, &["RUNNING"], &crate::constants::TERMINAL_STATES, opts)
.await
}
/// Polls a launch that may have **adopted** an existing VM through its client token.
///
/// A repeated `clientToken` makes `RunMicrovm` answer with the VM the first attempt
/// launched, and that VM may have idle-suspended since (#195). [`Self::wait_for_running`]
/// would read that SUSPENDED as a death during startup (TRAP-8) and report LaunchDied
/// for a healthy VM. Here SUSPENDING is waited through, SUSPENDED is resumed once, and
/// only the dead states fail fast. A genuine startup death still ends in a dead state,
/// so it still fails with `stateReason`.
pub async fn wait_for_launch(&self, id: &str, opts: WaitOpts) -> Result<Microvm, Error> {
self.wait_for_launch_inner(id, opts, true, false).await
}
/// Sandbox launches poll quickly while a typical launch is becoming ready. Public
/// control-plane waits keep the caller's fixed polling interval.
pub(crate) async fn wait_for_sandbox_launch(
&self,
id: &str,
opts: WaitOpts,
adoptable: bool,
) -> Result<Microvm, Error> {
self.wait_for_launch_inner(id, opts, adoptable, true).await
}
async fn wait_for_launch_inner(
&self,
id: &str,
opts: WaitOpts,
adoptable: bool,
fast_start: bool,
) -> Result<Microvm, Error> {
let started = self.clock().elapsed();
let mut resumed = false;
let mut fast_polls_remaining = 3;
let fail_on = if adoptable {
&crate::constants::DEAD_STATES[..]
} else {
&crate::constants::TERMINAL_STATES[..]
};
loop {
let got = self.get_microvm(id).await?;
match got.state.as_str() {
"RUNNING" => return Ok(got),
state if fail_on.contains(&state) => {
return Err(self.reached_terminal_state(&got, &["RUNNING"]));
}
// `GetMicrovm` is eventually consistent, so SUSPENDED can still be read
// just after the resume was accepted; one resume is enough.
"SUSPENDED" if adoptable && !resumed => {
self.resume(id).await?;
resumed = true;
continue;
}
_ => {}
}
let elapsed = self.clock().elapsed().saturating_sub(started);
if elapsed >= opts.timeout {
return Err(timed_out(
&format!(
"microvm {id} never reached [\"RUNNING\"] (last state {})",
got.state
),
elapsed,
));
}
// Poll promptly during startup, then use the lifecycle interval to bound
// repeated requests during a slower launch.
let interval = if fast_start && fast_polls_remaining > 0 {
fast_polls_remaining -= 1;
opts.poll_interval.min(std::time::Duration::from_secs(1))
} else {
opts.poll_interval
};
self.clock().sleep(interval).await;
}
}
/// Polls until the VM reaches one of `wanted`, failing fast on any of `fail_on`.
///
/// # Why `fail_on` is a parameter rather than always the terminal set
///
/// Because `suspend` **wants** SUSPENDED and tolerates TERMINATED: a VM that dies while
/// suspending is a state to report, not an exception to raise out of the middle of a
/// teardown. The resume path passes the *dead* states instead, because a VM the idle
/// policy terminated during suspension never reaches RUNNING — and waiting only for
/// RUNNING there burns the full timeout and then reports "never reached RUNNING", a
/// timeout message hiding a cause the service had already stated.
pub async fn wait_for_state(
&self,
id: &str,
wanted: &[&str],
fail_on: &[&str],
opts: WaitOpts,
) -> Result<Microvm, Error> {
let started = self.clock().elapsed();
loop {
let got = self.get_microvm(id).await?;
if wanted.contains(&got.state.as_str()) {
return Ok(got);
}
if fail_on.contains(&got.state.as_str()) {
return Err(self.reached_terminal_state(&got, wanted));
}
let elapsed = self.clock().elapsed().saturating_sub(started);
if elapsed >= opts.timeout {
return Err(timed_out(
&format!(
"microvm {id} never reached {wanted:?} (last state {})",
got.state
),
elapsed,
));
}
self.clock().sleep(opts.poll_interval).await;
}
}
/// TRAP-8's error: the state **and** the reason, both in the message.
///
/// Both because either alone is unactionable. The state says the VM is gone; the reason
/// says why, and it is the only evidence that survives the VM.
fn reached_terminal_state(&self, got: &Microvm, wanted: &[&str]) -> Error {
Error::new(
ErrorKind::LaunchDied,
format!(
"microvm {} reached {} before {wanted:?}: {}. A VM that reaches a terminal state \
before RUNNING died during startup, and for a hook-serving daemon that almost \
always means a lifecycle hook failed — the stateReason above is the only evidence \
left, because the VM is gone (docs/PLATFORM.md, 'MicroVM states, and terminal \
states reached before RUNNING').",
got.id,
got.state,
got.reason(),
),
)
}
/// `GetMicrovm`.
///
/// `microvmIdentifier` is a URI parameter, so an empty one collapses the path onto the
/// listing and asks a different question — see [`super::require_valid_identifier`]. This is
/// the read every wait loop makes, so the check also covers
/// [`Self::wait_for_state`] and everything built on it.
pub async fn get_microvm(&self, id: &str) -> Result<Microvm, Error> {
super::require_valid_identifier("microvmIdentifier", id)?;
let call = Call::get("GetMicrovm", paths::microvm(id));
let reply = self.send(call).await?;
let got: ops::MicrovmResponseWire = reply.json("GetMicrovm")?;
Ok(got.into())
}
/// `ListMicrovms`, read to its last page.
///
/// # Why every page
///
/// `maxResults` caps at 50, so a fleet above 50 VMs read from one page is a
/// **confidently wrong** answer rather than a missing one: the caller gets a list that
/// looks complete, and a VM absent from it is a VM nothing here will terminate. That is
/// the same argument [`ops::ListImagesResponseWire`] makes for the image listing, and a
/// fleet listing is the one a teardown reads.
///
/// Each VM is listed once (#280): a VM the service returns on two pages keeps the place it
/// was first listed and the entry read last, the newer reading of its state.
pub async fn list_microvms(&self) -> Result<Vec<ops::MicrovmItemWire>, Error> {
self.list_microvms_matching(&MicrovmFilter::default()).await
}
/// [`Self::list_microvms`], narrowed by the service's image and version filters.
pub async fn list_microvms_matching(
&self,
filter: &MicrovmFilter,
) -> Result<Vec<ops::MicrovmItemWire>, Error> {
Ok(self
.list_microvm_summaries(filter)
.await?
.into_iter()
.map(Into::into)
.collect())
}
/// The paginated listing with optional `started_at` metadata. This adds metadata without
/// changing the exhaustively constructible item returned by the original listing methods.
pub async fn list_microvm_summaries(
&self,
filter: &MicrovmFilter,
) -> Result<Vec<ops::MicrovmSummaryWire>, Error> {
if let Some(image) = filter.image_identifier.as_deref() {
super::require_valid_identifier("imageIdentifier", image)?;
}
if let Some(version) = filter.image_version.as_deref() {
super::require_valid_version("imageVersion", version)?;
}
let mut items: Vec<ops::MicrovmSummaryWire> = Vec::new();
// Where each id sits in `items`. The service can return one VM on two pages while VMs
// change state (docs/PLATFORM.md, "A paginated `ListMicrovms` can return one VM on two
// of its pages"), so a repeat replaces the earlier entry, the older reading, in place.
let mut position: std::collections::HashMap<String, usize> =
std::collections::HashMap::new();
let mut next_token: Option<String> = None;
loop {
let call = Call::get(
"ListMicrovms",
paths::microvms_list_matching(
filter.image_identifier.as_deref(),
filter.image_version.as_deref(),
next_token.as_deref(),
),
);
let reply = self.send(call).await?;
let page: ops::ListMicrovmSummariesResponseWire = reply.json("ListMicrovms")?;
for item in page.items {
match position.get(&item.microvm_id) {
Some(&at) => items[at] = item,
None => {
position.insert(item.microvm_id.clone(), items.len());
items.push(item);
}
}
}
match page.next_token {
Some(token) => next_token = Some(token),
None => return Ok(items),
}
}
}
/// `SuspendMicrovm`. Freezes the VM; the caller waits for SUSPENDED.
pub async fn suspend(&self, id: &str) -> Result<(), Error> {
super::require_valid_identifier("microvmIdentifier", id)?;
let call = Call::post_empty("SuspendMicrovm", paths::suspend(id));
self.send(call).await?;
Ok(())
}
/// `ResumeMicrovm`. Thaws the VM; no token re-delivery and no re-bootstrap.
///
/// # A VM that ended before the resume is `WindowClosed` (STATE-12)
///
/// Nothing is checked against the suspended window before the call, because the service
/// decides whether a suspended VM can still resume. It terminates a VM the idle policy
/// suspended once `suspendedDurationSeconds` passes, and it doesn't hold an explicit
/// `SuspendMicrovm` to that window: measured 2026-10-12 in us-east-1, an explicitly
/// suspended VM resumed 1283 s into a 60 s window (#597). A resume of a VM that has
/// terminated is refused with a `ValidationException` ("The MicroVM <id> has been
/// terminated and its state cannot be changed."), the same status as any refused value,
/// and it was the same refusal for a VM the service ended and one `TerminateMicrovm`
/// ended (measured 2026-10-12, us-east-1). So a refusal reads the VM's state rather than
/// the message, and a VM that's TERMINATING or TERMINATED is [`ErrorKind::WindowClosed`]
/// with its state and `stateReason`, carrying the refusal as its source. The error names
/// no cause, because the client doesn't know which of the suspended window, the maximum
/// duration, or a terminate ended the VM; the `stateReason` is the service's word on it.
/// Every other refusal comes back as the service gave it.
pub async fn resume(&self, id: &str) -> Result<(), Error> {
super::require_valid_identifier("microvmIdentifier", id)?;
let call = Call::post_empty("ResumeMicrovm", paths::resume(id));
match self.send(call).await {
Ok(_) => Ok(()),
Err(refused) if refused.kind() == ErrorKind::Platform => {
Err(self.ended_before_resume(id, refused).await)
}
Err(error) => Err(error),
}
}
/// The error a refused resume reports: [`ErrorKind::WindowClosed`] with `refused` as its
/// source when `GetMicrovm` reports the VM dead, and `refused` otherwise, including when
/// that read fails.
async fn ended_before_resume(&self, id: &str, refused: Error) -> Error {
let Ok(vm) = self.get_microvm(id).await else {
return refused;
};
if !crate::constants::DEAD_STATES.contains(&vm.state.as_str()) {
return refused;
}
Error::new(
ErrorKind::WindowClosed,
format!(
"microvm {id} can't be resumed: the service refused ResumeMicrovm, and \
GetMicrovm reports the VM {} ({}). A VM that has ended doesn't come back; \
launch a new one.",
vm.state,
vm.reason(),
),
)
.with_source(refused)
}
/// `TerminateMicrovm`.
///
/// The identifier check matters most on this one, and for a reason the others do not share:
/// the path is `DELETE /microvms/{microvmIdentifier}`, so an empty identifier is a `DELETE`
/// addressed at the **collection**. There is no operation on that path and the service
/// refuses it, but "send a delete at the fleet and rely on the service to refuse" is not a
/// thing to leave to the service.
pub async fn terminate(&self, id: &str) -> Result<(), Error> {
super::require_valid_identifier("microvmIdentifier", id)?;
let call = Call::delete("TerminateMicrovm", paths::microvm(id));
self.send(call).await?;
Ok(())
}
/// Mints a proxy token for the agent port (TRAP-7, TRAP-9).
///
/// `expirationInMinutes` is capped at [`MAX_TOKEN_MINUTES`] here rather than passed
/// through, because over-asking is rejected and the rejection reads like a bad request
/// rather than like a ceiling. The *refresh* interval — half the ceiling — belongs to
/// the endpoint client that holds the token (T-W2-5), not here.
///
/// Scoped to the agent port alone, which is right for every request this client makes on
/// its own behalf and **wrong for a caller reaching another port on the same VM**. That
/// caller wants [`Self::mint_auth_token_for`]; see [`ops::PortSpecification`] for the
/// measurement that made the distinction necessary.
pub async fn mint_auth_token(&self, id: &str) -> Result<ProxyToken, Error> {
self.mint_auth_token_for(id, &[ops::PortSpecification::port(self.port())])
.await
}
/// Mints a proxy token scoped to `ports`, whatever they are.
///
/// The agent port is **not** added for you. A caller naming ports is answering the
/// question the token asks, and silently widening the scope would hand back a
/// credential broader than the one requested — the opposite of the mistake this exists
/// to fix, and a worse one, since it is invisible. A caller that needs both the agent
/// port and a workload port names both, which is what [`ProxyAuth`] does.
///
/// The returned token still records the agent port as its *default* header port, because
/// that is the port a request carries when nobody names one.
///
/// [`ProxyAuth`]: crate::session::ProxyAuth
pub async fn mint_auth_token_for(
&self,
id: &str,
ports: &[ops::PortSpecification],
) -> Result<ProxyToken, Error> {
super::require_valid_identifier("microvmIdentifier", id)?;
if ports.is_empty() {
// The model declares `min: 1` on `allowedPorts`, so an empty list is a
// round-trip that comes back as a validation error naming a member the caller
// did not know it was sending. Refused here, with the reason.
return Err(Error::new(
ErrorKind::Precondition,
"a proxy token must allow at least one port ('allowedPorts' declares min: 1). \
Name the ports this token is for — the agent port plus any workload port \
reached through the endpoint.",
));
}
// `PortNumber` is `min: 1`, and the value that reaches here as a 0 is not a typo — it is
// a caller who took `ControlPlane::with_port(0)`'s default port, or who passed a
// `SocketAddr`'s port before binding. A token minted for port 0 authorizes nothing, and
// the proxy's refusal is `403 Access to port denied`, which reads like the token being
// wrong rather than its scope being empty (measured 2026-08-15, see
// `ops::PortSpecification`). Both ends of a range are checked, because `PortRange`'s two
// members name the same shape and a range starting at 0 is the same defect.
for spec in ports {
match spec {
ops::PortSpecification::One { port } => {
super::require_valid_port("allowedPorts[].port", *port)?;
}
ops::PortSpecification::Range { range } => {
super::require_valid_port("allowedPorts[].range.startPort", range.start_port)?;
super::require_valid_port("allowedPorts[].range.endPort", range.end_port)?;
}
// `allPorts` names no number, so there is nothing to bound.
ops::PortSpecification::All { .. } => {}
}
}
let wire = ops::CreateAuthTokenWire {
expiration_in_minutes: MAX_TOKEN_MINUTES,
allowed_ports: ports.to_vec(),
};
let call = Call::post_json("CreateMicrovmAuthToken", paths::auth_token(id), &wire)?;
let reply = self.send(call).await?;
let minted: ops::CreateAuthTokenResponseWire = reply.json("CreateMicrovmAuthToken")?;
ProxyToken::from_map(&minted.auth_token, self.port()).map_err(|error| reply.error(error))
}
/// Mints a shell token: the credential `microvm shell` opens the PTY WebSocket with.
///
/// `CreateMicrovmShellAuthToken`, which the VM must have been launched with
/// `SHELL_INGRESS` to answer — a VM launched without it gets a `ValidationException`
/// naming the connector, and `RunMicrovmRequest::with_shell` is how a launch requests
/// the measured pair. The request takes only the expiration; there is no
/// `allowedPorts`, because the shell is not a port (`docs/PLATFORM.md`, 2026-08-15).
///
/// # This is `microvm shell`'s method, not exec's (TRAP-11)
///
/// One interactive session is not programmatic exec — no exec ids, no idempotency,
/// no separated stdout/stderr, no exit codes — so nothing on the exec or session
/// path calls this, and the lifecycle test asserts that absence. A caller holding
/// the returned token has a real root PTY on the VM; treat it like the credential
/// it is.
///
/// The expiration is pinned at [`MAX_TOKEN_MINUTES`] for the reason
/// [`Self::mint_auth_token`] gives: over-asking is rejected in a way that reads like
/// a bad request rather than like a ceiling. A shell session held past the ceiling
/// keeps its already-open WebSocket — the expiry gates the *handshake*, not an
/// established session.
pub async fn mint_shell_auth_token(&self, id: &str) -> Result<ProxyToken, Error> {
super::require_valid_identifier("microvmIdentifier", id)?;
let wire = ops::CreateShellAuthTokenWire {
expiration_in_minutes: MAX_TOKEN_MINUTES,
};
let call = Call::post_json(
"CreateMicrovmShellAuthToken",
paths::shell_auth_token(id),
&wire,
)?;
let reply = self.send(call).await?;
let minted: ops::CreateShellAuthTokenResponseWire =
reply.json("CreateMicrovmShellAuthToken")?;
ProxyToken::from_operation_map(
"CreateMicrovmShellAuthToken",
&minted.auth_token,
self.port(),
)
.map_err(|error| reply.error(error))
}
}
/// The states a suspend may end in.
///
/// TERMINATED is *wanted* rather than a failure: a VM that dies while suspending is a state
/// to report, not an exception to raise out of the middle of a teardown.
pub const SUSPEND_WANTED: [&str; 2] = ["SUSPENDED", "TERMINATED"];
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::super::fake::{self as fake, Answer, FakeControlPlane, TestClock};
use super::*;
use crate::region::Region;
/// A suspend waits for these, so each has to be a state the service can report. The rest
/// of the polling loops' sets are checked beside the enum in `constants`; this one lives
/// here, so its check does too.
#[test]
fn every_state_a_suspend_waits_for_is_in_the_models_enum() {
for state in SUSPEND_WANTED {
assert!(
crate::constants::MICROVM_STATES.contains(&state),
"SUSPEND_WANTED has {state}, which is not a MicrovmState: a suspend would wait \
for a state the service can't report and time out"
);
}
}
fn planted() -> (ControlPlane, Arc<FakeControlPlane>, Arc<TestClock>) {
let fake = Arc::new(FakeControlPlane::new());
let clock = Arc::new(TestClock::new());
let plane = crate::testing::control_plane(fake.clone(), Region::UsEast1, clock.clone());
(plane, fake, clock)
}
#[tokio::test]
async fn post_response_failures_keep_request_retry_details() {
let (plane, fake, _) = planted();
fake.answer("GetMicrovm", Answer::throttled_as_400())
.answer("GetMicrovm", Answer::ok("{}"));
let malformed = plane.get_microvm("mvm-one").await.unwrap_err();
assert_eq!(malformed.kind(), ErrorKind::Platform);
assert_eq!(malformed.attempt_count(), 2);
assert!(!malformed.backoff().is_zero());
assert!(!malformed.throttled());
let (plane, fake, _) = planted();
fake.answer("ResumeMicrovm", Answer::throttled_as_400())
.answer("ResumeMicrovm", terminated_refusal())
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("TERMINATED", None)),
);
let ended = plane.resume("mvm-one").await.unwrap_err();
assert_eq!(ended.kind(), ErrorKind::WindowClosed);
assert_eq!(ended.attempt_count(), 2);
assert!(!ended.backoff().is_zero());
assert!(!ended.throttled());
}
/// **TRAP-5, the boundary.** 4096 bytes passes, 4097 is rejected — inclusive, as
/// measured 2026-08-07.
///
/// **Falsification** — change the comparison to `<` and the 4096 case fails; change the
/// ceiling to 16384 (the number the docs and the model's own documentation string claim)
/// and the 4097 case fails.
#[test]
fn the_payload_ceiling_is_four_thousand_ninety_six_bytes_inclusive() {
let at_ceiling = "a".repeat(4096);
let payload = RunHookPayload::new(at_ceiling.clone()).expect("4096 bytes fits");
assert_eq!(payload.len(), 4096);
assert_eq!(payload.as_str(), at_ceiling);
let over = "a".repeat(4097);
let error = RunHookPayload::new(over).expect_err("4097 bytes does not fit");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
let message = error.to_string();
assert!(message.contains("4097 bytes"), "{message}");
assert!(
message.contains("ceiling of 4096"),
"the message must name the service-model ceiling: {message}"
);
assert!(message.contains("2025-09-09"), "{message}");
assert!(
message.contains("wrong by 4x"),
"the 16 KB claim has to be named as wrong: {message}"
);
}
/// **TRAP-5, the local-refusal half.** An over-ceiling payload means the fake records
/// **zero** calls: the launch is refused before any control-plane call.
#[tokio::test]
async fn an_over_ceiling_payload_reaches_no_control_plane_call() {
let (plane, fake, _) = planted();
// The payload type refuses first, so there is no way to even build the request.
let refused = RunHookPayload::new("a".repeat(4097));
assert!(refused.is_err());
assert_eq!(fake.calls().len(), 0);
// And the at-ceiling one does launch, so the guard is not simply refusing
// everything.
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::new("a".repeat(4096)).expect("fits");
plane
.run_microvm(RunMicrovmRequest::new("arn:image", payload))
.await
.expect("launches");
assert_eq!(fake.call_count("RunMicrovm"), 1);
}
/// The ceiling is measured in **bytes**, not characters. A payload of 2049 two-byte
/// characters is 4098 bytes and must be refused even though it is 2049 characters.
#[test]
fn the_ceiling_counts_utf8_bytes_rather_than_characters() {
let two_byte_chars = "é".repeat(2049);
assert_eq!(
two_byte_chars.chars().count(),
2049,
"well under 4096 chars"
);
assert_eq!(two_byte_chars.len(), 4098, "but over 4096 bytes");
let error = RunHookPayload::new(two_byte_chars).expect_err("bytes are what count");
assert!(error.to_string().contains("4098 bytes"), "{error}");
// 2048 of them is exactly 4096 bytes, which fits.
let exact = "é".repeat(2048);
assert_eq!(exact.len(), 4096);
RunHookPayload::new(exact).expect("exactly at the ceiling");
}
/// The identity material costs exactly its declared budget, and a launch without it is
/// byte-for-byte what the older constructors built.
///
/// Measured by difference rather than trusted from the constant's comment, the same
/// discipline `env_contribution` applies: the ceiling is on the serialized string, so
/// only the serialized string can say what the material costs. The compatibility half
/// matters just as much — a pinned daemon that has never heard of identity must see no
/// change from a client that did not ask for it.
#[test]
fn the_identity_material_costs_its_declared_budget_and_absence_costs_nothing() {
let env = std::collections::HashMap::new();
let without = RunHookPayload::for_launch("tok", &env).expect("fits");
let none_asked = RunHookPayload::for_launch_with_identity("tok", &env, None).expect("fits");
assert_eq!(
without.as_str(),
none_asked.as_str(),
"no identity must produce byte-for-byte the payload this client always sent"
);
let identity = crate::identity::LaunchIdentity::from_seeds([7_u8; 32], [9_u8; 32])
.expect("valid seeds");
let with =
RunHookPayload::for_launch_with_identity("tok", &env, Some(&identity)).expect("fits");
assert_eq!(
with.len() - without.len(),
protocol::identity::IDENTITY_PAYLOAD_BYTES,
"the budget constant must equal what the material really costs on the wire"
);
// And the payload parses as the daemon parses it, with both halves present.
let parsed = protocol::hook::RunHook::parse(with.as_str()).expect("the daemon can read it");
assert_eq!(
parsed.identity_seed.as_deref(),
Some(identity.seed_field().as_str())
);
assert_eq!(
parsed.identity_host_public_key.as_deref(),
Some(identity.host_public_field().as_str())
);
}
/// The agent-token payload is the shape the daemon parses, and an oversized token is
/// caught even though the client builds the JSON — because the token is caller-supplied.
#[test]
fn the_agent_token_payload_is_checked_even_though_the_client_builds_it() {
let payload = RunHookPayload::for_agent_token("bearer-token-value").expect("fits");
assert_eq!(payload.as_str(), r#"{"agent_token":"bearer-token-value"}"#);
// A caller passing a credential bundle rather than a bearer token is who this
// catches.
let huge = "x".repeat(4096);
let error = RunHookPayload::for_agent_token(&huge)
.expect_err("the JSON wrapper pushes it over the ceiling");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
assert!(
error.to_string().contains("one bearer token fits"),
"{error}"
);
}
/// An empty launch env produces byte-for-byte the payload the token-only
/// constructor always produced, so a caller who never passes one is unaffected by
/// the field existing — and a daemon baked into an older image sees no new key.
///
/// **Falsification** — always emit `"env"` and this fails on both assertions.
#[test]
fn an_empty_launch_env_emits_the_payload_the_token_only_constructor_did() {
let with_empty = RunHookPayload::for_launch("tok", &std::collections::HashMap::new())
.expect("an empty env fits");
let token_only = RunHookPayload::for_agent_token("tok").expect("fits");
assert_eq!(with_empty.as_str(), token_only.as_str());
assert_eq!(with_empty.as_str(), r#"{"agent_token":"tok"}"#);
assert!(
!with_empty.as_str().contains("env"),
"an empty env must not appear on the wire at all: {}",
with_empty.as_str()
);
}
/// A launch env is carried in the payload the daemon parses.
#[test]
fn a_launch_env_rides_in_the_payload_the_daemon_parses() {
let mut env = std::collections::HashMap::new();
env.insert("ANTHROPIC_BASE_URL".to_string(), "https://x".to_string());
let payload = RunHookPayload::for_launch("tok", &env).expect("fits");
// Parsed rather than string-compared, since a HashMap has no key order.
let value: serde_json::Value =
serde_json::from_str(payload.as_str()).expect("the payload is JSON");
assert_eq!(value["agent_token"], "tok");
assert_eq!(value["env"]["ANTHROPIC_BASE_URL"], "https://x");
}
/// **The local 4096-byte refusal for a launch env.**
///
/// The reason this is the case worth its own test rather than a repeat of the
/// ceiling test above: one bearer token has always fit with room to spare, so
/// before `env` existed the ceiling was effectively unreachable through the typed
/// constructor. A launch env is what makes it reachable, and botocore does not
/// enforce it client-side — the oversized request goes to the wire and comes back
/// as a `ValidationException` on a member the caller did not know they were
/// filling (`docs/PLATFORM.md`). So this refusal is the only local signal there is.
///
/// The message must carry the byte count, the ceiling, and the env's share of it.
/// Without the share, a caller reading "4128 bytes, ceiling 4096" cannot tell
/// whether to shorten the token or drop a variable.
///
/// **Falsification** — return `Ok` from `for_launch` without calling `new`, or drop
/// the byte-count clause from the message, and this goes red on the specific
/// assertion.
#[test]
fn an_over_ceiling_launch_env_is_refused_locally_with_the_byte_count() {
let mut env = std::collections::HashMap::new();
// Comfortably over on its own, the way a set of session credentials is.
env.insert("CREDENTIALS".to_string(), "c".repeat(4096));
// The expected figure is derived from the same serialization the constructor
// does rather than written as a literal, because a literal here asserts my
// arithmetic about JSON framing and the point is the *count*, not the framing.
let expected = serde_json::json!({ "agent_token": "tok", "env": &env })
.to_string()
.len();
assert!(
expected > 4096,
"the fixture must actually be over: {expected}"
);
let error = RunHookPayload::for_launch("tok", &env)
.expect_err("a credential-scale launch env does not fit");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
let message = error.to_string();
assert!(
message.contains("ceiling of 4096"),
"the ceiling has to be named: {message}"
);
assert!(
message.contains(&format!("{expected} bytes")),
"the actual byte count has to be named: {message}"
);
assert!(
message.contains("launch env contributed"),
"the env's share of the budget is the actionable half: {message}"
);
assert!(
message.contains("1 variable(s)"),
"the variable count has to be named: {message}"
);
}
/// The refusal fires on the *serialized* payload, so a caller who measured their own
/// values would be measuring the wrong thing.
///
/// Two variables whose raw bytes sum to 4060 — under the ceiling — go over it once
/// the JSON framing, the key names, and the quotes are counted. A check on the map
/// rather than on the string would accept this and the launch would fail at AWS.
#[test]
fn the_launch_env_ceiling_counts_the_serialized_payload_and_not_the_raw_values() {
let mut env = std::collections::HashMap::new();
env.insert("A".to_string(), "a".repeat(2030));
env.insert("B".to_string(), "b".repeat(2030));
let raw: usize = env.values().map(String::len).sum();
assert_eq!(raw, 4060, "the raw values are under the ceiling");
assert!(
raw <= crate::constants::MAX_RUN_HOOK_PAYLOAD_BYTES,
"the fixture only means something if the raw sum fits: {raw}"
);
let error = RunHookPayload::for_launch("tok", &env)
.expect_err("the serialized payload is over even though the raw values are not");
assert!(error.to_string().contains("2 variable(s)"), "{error}");
// And the boundary is still inclusive with an env in play: trimmed to fit, the
// same shape succeeds — so the refusal is a ceiling and not a blanket ban.
let mut fits = std::collections::HashMap::new();
fits.insert("A".to_string(), "a".repeat(2000));
fits.insert("B".to_string(), "b".repeat(2000));
let payload = RunHookPayload::for_launch("tok", &fits).expect("4000-odd bytes fits");
assert!(payload.len() <= 4096, "{}", payload.len());
}
/// An empty payload is legal: the model's minimum is 0.
#[test]
fn an_empty_payload_is_legal() {
let payload = RunHookPayload::new("").expect("min is 0");
assert!(payload.is_empty());
assert_eq!(payload.len(), 0);
}
/// The launch request lands on the model's path with the model's member names, and the
/// connectors are derived ARNs split across the two members (TRAP-4).
#[tokio::test]
async fn the_launch_emits_derived_connector_arns_in_the_right_members() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let request = RunMicrovmRequest::new("arn:image", payload).with_egress();
plane.run_microvm(request).await.expect("launches");
let calls = fake.calls();
assert_eq!(calls[0].path, "/2025-09-09/microvms");
assert_eq!(calls[0].method, super::super::transport::Method::Post);
let body = fake.first_body("RunMicrovm");
assert_eq!(
body["ingressNetworkConnectors"],
serde_json::json!([
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:ALL_INGRESS"
])
);
assert_eq!(
body["egressNetworkConnectors"],
serde_json::json!([
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS"
])
);
assert_eq!(body["runHookPayload"], r#"{"agent_token":"token"}"#);
assert_eq!(body["maximumDurationInSeconds"], 3600);
}
/// Without egress, the member is **absent** — the request names no connector. What
/// the platform does with that omission is a measurement, not this test's claim:
/// `docs/PLATFORM.md`, "A VM launched without the egress connector still has
/// outbound network" (2026-09-11 and 2026-09-12).
#[tokio::test]
async fn a_launch_without_egress_omits_the_member_entirely() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
plane
.run_microvm(RunMicrovmRequest::new("arn:image", payload))
.await
.expect("launches");
let body = fake.first_body("RunMicrovm");
assert!(
body.get("egressNetworkConnectors").is_none(),
"omitting egress is the whole mechanism: {body}"
);
assert!(body.get("ingressNetworkConnectors").is_some());
}
#[tokio::test]
async fn customer_vpc_connector_arns_reach_the_egress_member_unchanged() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
let arns: Vec<String> = (0..10)
.map(|id| format!("arn:aws:lambda:us-east-1:123456789012:network-connector:vpc-{id}:1"))
.collect();
request.egress_network_connectors = arns.clone();
plane
.run_microvm(request)
.await
.expect("ten egress connectors plus ingress fits");
let body = fake.first_body("RunMicrovm");
assert_eq!(body["egressNetworkConnectors"], serde_json::json!(arns));
assert_eq!(
body["ingressNetworkConnectors"].as_array().unwrap().len(),
1
);
}
#[tokio::test]
async fn invalid_customer_egress_connectors_are_refused_before_launch() {
let valid = "arn:aws:lambda:us-east-1:123456789012:network-connector:vpc-test";
let invalid = [
"VPC_EGRESS",
"arn:aws:lambda:us-west-2:123456789012:network-connector:vpc-test",
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS",
"arn:aws:lambda:us-east-1:123456789012:network-connector:",
"arn:aws:lambda:us-east-1:123456789012:network-connector:vpc-test:0",
"arn:aws:lambda:us-east-1:123456789012:network-connector:vpc-test/other",
];
for arn in invalid {
let (plane, fake, _) = planted();
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let error = plane
.run_microvm(
RunMicrovmRequest::new("arn:image", payload).with_egress_network_connector(arn),
)
.await
.expect_err(arn);
assert_eq!(error.kind(), ErrorKind::InvalidArg);
assert!(
error.to_string().contains("egressNetworkConnectors"),
"{error}"
);
assert!(fake.calls().is_empty());
}
for (internet, count) in [(true, 1), (false, 11)] {
let (plane, fake, _) = planted();
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request.egress_network_connectors = vec![valid.to_string(); count];
if internet {
request = request.with_egress();
}
let error = plane
.run_microvm(request)
.await
.expect_err("invalid routing request");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
assert!(fake.calls().is_empty());
}
}
/// **A pinned `imageVersion` reaches the wire, and an unpinned launch omits the member.**
///
/// The absence half is the one that matters for compatibility: an unpinned launch has to
/// emit byte-for-byte what this client always sent, so a `"imageVersion": null` on every
/// launch would be a new member on a request that has worked for months. The presence half
/// is what makes a canary a canary — the launch goes against the version named rather than
/// against whatever became latest while it was starting.
///
/// **Falsification** — run 2026-08-16. Drop the `image_version` assignment in
/// `run_microvm` and the pinned assertion goes red with the member absent; remove
/// `skip_serializing_if` from the wire field and the absence assertion goes red with a
/// `null`.
#[tokio::test]
async fn a_pinned_launch_version_reaches_the_wire_and_an_unpinned_one_omits_the_member() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
plane
.run_microvm(RunMicrovmRequest::new("arn:image", payload).with_image_version("2.0"))
.await
.expect("launches");
let body = fake.first_body("RunMicrovm");
assert_eq!(body["imageVersion"], "2.0");
assert_eq!(
body["imageIdentifier"], "arn:image",
"pinning a version does not replace the identifier; both are sent"
);
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
plane
.run_microvm(RunMicrovmRequest::new("arn:image", payload))
.await
.expect("launches");
assert!(
fake.first_body("RunMicrovm").get("imageVersion").is_none(),
"an unpinned launch must send what this client always sent: {}",
fake.first_body("RunMicrovm")
);
}
/// An invalid `imageVersion` is refused before any call — including on the launch path,
/// which is where a rollback happens.
///
/// A `ValidationException` about the request rather than about the version, arriving at the
/// moment someone is re-pinning away from a bad build, is the least useful failure
/// available. So the `Version` shape's three constraints are checked here.
///
/// **Falsification** — run 2026-08-16. Delete the `require_valid_version` call from
/// `run_microvm` and the zero-call assertion goes red.
#[tokio::test]
async fn an_invalid_launch_version_reaches_no_control_plane_call() {
for bad in ["", "2.0\n", "a b"] {
let (plane, fake, _) = planted();
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let error = plane
.run_microvm(RunMicrovmRequest::new("arn:image", payload).with_image_version(bad))
.await
.expect_err(&format!("{bad:?} is not a legal Version"));
assert_eq!(error.kind(), ErrorKind::InvalidArg, "{bad:?}");
assert!(
error.to_string().contains("imageVersion"),
"{bad:?}: {error}"
);
assert_eq!(fake.calls().len(), 0, "{bad:?} must not reach the wire");
}
}
/// The connectors reaching the wire are ARNs, never bare names — a bare name is rejected
/// with "Malformed network connector ARN", and it is the value that reads most natural
/// to write.
#[tokio::test]
async fn no_bare_connector_name_reaches_the_wire() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
plane
.run_microvm(RunMicrovmRequest::new("arn:image", payload).with_egress())
.await
.expect("launches");
let body = fake.first_body("RunMicrovm");
for member in ["ingressNetworkConnectors", "egressNetworkConnectors"] {
for value in body[member].as_array().expect("a list") {
let text = value.as_str().expect("a string");
assert!(text.starts_with("arn:aws:lambda:"), "{member}: {text}");
assert_ne!(text, "ALL_INGRESS");
assert_ne!(text, "INTERNET_EGRESS");
}
}
}
/// An out-of-range duration is refused before any call.
#[tokio::test]
async fn an_out_of_range_duration_reaches_no_control_plane_call() {
let (plane, fake, _) = planted();
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request.max_duration_sec = 28_801;
let error = plane
.run_microvm(request)
.await
.expect_err("over the ceiling");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
assert_eq!(fake.calls().len(), 0);
}
/// **TRAP-8.** A VM that reaches a terminal state before RUNNING is rejected with the
/// state **and** the `stateReason` in the message.
///
/// The message is asserted rather than merely the error, because a timeout also produces
/// an error — so "an error occurred" would pass against the exact defect this closes.
///
/// **Falsification** — remove the `fail_on` branch from `wait_for_state` and this test
/// fails with an `ErrorKind::Timeout` whose message names neither the state nor the
/// reason. Verified; see the packet's guard proofs.
#[tokio::test]
async fn a_terminal_state_before_running_carries_both_the_state_and_the_reason() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response(
"TERMINATED",
Some("run hook returned 500"),
)),
);
let error = plane
.wait_for_running("mvm-abc123", WaitOpts::for_launch())
.await
.expect_err("a dead VM must not be waited out");
assert_eq!(error.kind(), ErrorKind::LaunchDied);
assert_eq!(error.code(), "ERR_LAUNCH_DIED");
let message = error.to_string();
assert!(
message.contains("TERMINATED"),
"the state must be attached: {message}"
);
assert!(
message.contains("run hook returned 500"),
"the stateReason must be attached: {message}"
);
assert!(
message.contains("lifecycle hook failed"),
"the likely cause is worth naming: {message}"
);
assert!(
fake.call_count("GetMicrovm") == 1,
"it fails fast rather than polling to the deadline"
);
}
/// Every terminal state fails the launch fast, not just TERMINATED. SUSPENDED reached
/// before RUNNING is also a death — the VM never came up.
///
/// The states are read from `constants::TERMINAL_STATES` rather than listed, so a state
/// added there is covered here without a second edit — and the count is asserted so the
/// loop cannot silently become empty.
#[tokio::test]
async fn every_terminal_state_fails_a_launch_fast() {
assert_eq!(crate::constants::TERMINAL_STATES.len(), 4);
for state in crate::constants::TERMINAL_STATES {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response(state, Some("hook timeout"))),
);
let error = plane
.wait_for_running("mvm-abc123", WaitOpts::for_launch())
.await
.expect_err(&format!("{state} before RUNNING is a death"));
assert_eq!(error.kind(), ErrorKind::LaunchDied, "{state}");
assert!(error.to_string().contains(state), "{state}: {error}");
assert!(
error.to_string().contains("hook timeout"),
"{state}: {error}"
);
assert_eq!(
fake.call_count("GetMicrovm"),
1,
"{state} must fail fast rather than polling to the deadline"
);
}
}
/// A terminal state with **no** `stateReason` says so rather than printing an empty
/// string: "the service said nothing" is a different diagnosis from "the service said
/// nothing useful".
#[tokio::test]
async fn a_missing_state_reason_is_named_rather_than_printed_empty() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("TERMINATED", None)),
);
let error = plane
.wait_for_running("mvm-abc123", WaitOpts::for_launch())
.await
.expect_err("still a death");
let message = error.to_string();
assert!(message.contains("no stateReason"), "{message}");
// The failure this guards against is an absent reason rendering as an empty string,
// which reads as the service having answered with nothing rather than not having
// answered. `: .` is what that looks like in this message's shape.
assert!(
!message.contains(r#"["RUNNING"]: ."#),
"an absent reason must not render as an empty string: {message}"
);
assert_eq!(error.kind(), ErrorKind::LaunchDied);
}
/// The wait returns on RUNNING, having polled through PENDING.
#[tokio::test]
async fn the_launch_wait_polls_through_pending_and_returns_on_running() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
);
let vm = plane
.wait_for_running("mvm-abc123", WaitOpts::for_launch())
.await
.expect("reaches RUNNING");
assert_eq!(vm.state, "RUNNING");
assert_eq!(
vm.endpoint,
"https://mvm-abc123.microvm.us-east-1.amazonaws.com"
);
assert_eq!(fake.call_count("GetMicrovm"), 2);
}
/// A launch that never comes up ends at its deadline with a `Timeout` — which is a
/// *different* error from TRAP-8's, and the distinction is the whole reason the TRAP-8
/// test asserts on the message.
#[tokio::test]
async fn a_launch_that_never_comes_up_times_out_rather_than_reporting_a_death() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let error = plane
.wait_for_running("mvm-abc123", WaitOpts::for_launch())
.await
.expect_err("the deadline elapses");
assert_eq!(error.kind(), ErrorKind::Timeout);
assert_ne!(
error.kind(),
ErrorKind::LaunchDied,
"a timeout is not a death, and conflating them is what hid the cause"
);
assert!(error.to_string().contains("PENDING"), "{error}");
}
/// The resume path fails fast on the **dead** states and waits through SUSPENDED —
/// which is the state a resume is called from, so failing on it would fail every resume.
#[tokio::test]
async fn the_resume_wait_tolerates_suspended_and_fails_on_terminated() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("SUSPENDED", None)),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
);
let vm = plane
.wait_for_state(
"mvm-abc123",
&["RUNNING"],
&crate::constants::DEAD_STATES,
WaitOpts::for_launch(),
)
.await
.expect("SUSPENDED is a waypoint on the resume path");
assert_eq!(vm.state, "RUNNING");
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response(
"TERMINATED",
Some("suspended window elapsed"),
)),
);
let error = plane
.wait_for_state(
"mvm-abc123",
&["RUNNING"],
&crate::constants::DEAD_STATES,
WaitOpts::for_launch(),
)
.await
.expect_err("a terminated VM never reaches RUNNING");
assert_eq!(error.kind(), ErrorKind::LaunchDied);
assert!(
error.to_string().contains("suspended window elapsed"),
"{error}"
);
}
/// A suspend **wants** TERMINATED as well as SUSPENDED: a VM that dies while suspending
/// is a state to report, not an exception out of a teardown.
#[tokio::test]
async fn a_suspend_treats_terminated_as_a_state_to_report() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("TERMINATED", None)),
);
let vm = plane
.wait_for_state("mvm-abc123", &SUSPEND_WANTED, &[], WaitOpts::for_launch())
.await
.expect("a suspend reports the state it reached");
assert_eq!(vm.state, "TERMINATED");
}
/// The lifecycle calls land on the model's paths and methods. `POST` for suspend and
/// resume, `DELETE` for terminate — transcribed from each operation's `http` trait.
#[tokio::test]
async fn the_lifecycle_calls_use_the_models_paths_and_methods() {
let (plane, fake, _) = planted();
fake.answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
.answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
.answer("TerminateMicrovm", Answer::ok(fake::empty_response()));
plane.suspend("mvm-1").await.expect("suspends");
plane.resume("mvm-1").await.expect("resumes");
plane.terminate("mvm-1").await.expect("terminates");
let calls = fake.calls();
use super::super::transport::Method;
assert_eq!(
calls
.iter()
.map(|call| (call.operation, call.method, call.path.as_str()))
.collect::<Vec<_>>(),
[
(
"SuspendMicrovm",
Method::Post,
"/2025-09-09/microvms/mvm-1/suspend"
),
(
"ResumeMicrovm",
Method::Post,
"/2025-09-09/microvms/mvm-1/resume"
),
(
"TerminateMicrovm",
Method::Delete,
"/2025-09-09/microvms/mvm-1"
),
]
);
}
/// `ResumeMicrovm`'s refusal of a VM the service terminated, as it answered on 2026-10-12
/// in us-east-1 (#597): a 400 whose error type is `ValidationException`.
fn terminated_refusal() -> Answer {
Answer {
status: 400,
body: r#"{"message": "The MicroVM mvm-abc123 has been terminated and its state cannot be changed."}"#
.to_string(),
error_type: Some("ValidationException".to_string()),
}
}
/// **STATE-12 at the control plane.** A resume the service refuses for a VM `GetMicrovm`
/// reports in either dead state is `WindowClosed`, naming the state and its `stateReason`.
/// The CLI's `resume`, both bindings' `ControlPlane.resume` and `Sandbox::resume` call
/// this, so every resume that reaches the service reports an ended VM the same way. A
/// `Sandbox` whose VM the idle policy suspended still holds it as RUNNING, and its resume
/// is refused from RUNNING before any call: that suspend reaches a caller only through
/// `Sandbox::adopt`, which reads the state from the service, or `ControlPlane::resume`,
/// which holds no lifecycle to refuse from.
#[tokio::test]
async fn a_resume_refused_for_a_vm_that_terminated_while_suspended_is_window_closed() {
for state in crate::constants::DEAD_STATES {
let (plane, fake, _) = planted();
fake.answer("ResumeMicrovm", terminated_refusal()).answer(
"GetMicrovm",
Answer::ok(fake::microvm_response(
state,
Some("MicroVM exceeded maximum lifetime."),
)),
);
let error = plane
.resume("mvm-abc123")
.await
.expect_err("the VM is gone");
assert_eq!(error.kind(), ErrorKind::WindowClosed, "{state}: {error}");
let message = error.to_string();
assert!(message.contains(state), "{state}: {message}");
assert!(
message.contains("MicroVM exceeded maximum lifetime."),
"{state}: the stateReason: {message}"
);
assert_eq!(
fake.operations(),
["ResumeMicrovm", "GetMicrovm"],
"{state}: one refused resume, then one read"
);
}
}
/// **STATE-12 for a VM a terminate ended.** On 2026-10-12 in us-east-1, `GetMicrovm` on a
/// VM `microvm terminate` ended answered TERMINATED with `stateReason` `Success.` about
/// 4 h later, and `ResumeMicrovm` refused it with the same `ValidationException` as a VM
/// the service ended. The error states what the client knows, the state, the
/// `stateReason` and the refusal, and names no suspended window it can't know about. The
/// refusal is the error's source, and the `stateReason`'s own period isn't doubled.
#[tokio::test]
async fn a_resume_refused_for_a_vm_a_terminate_ended_names_no_cause_and_keeps_the_refusal() {
let (plane, fake, _) = planted();
fake.answer("ResumeMicrovm", terminated_refusal()).answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("TERMINATED", Some("Success."))),
);
let error = plane
.resume("mvm-abc123")
.await
.expect_err("the VM is gone");
assert_eq!(error.kind(), ErrorKind::WindowClosed, "{error}");
let message = error.to_string();
assert_eq!(
message,
"microvm mvm-abc123 can't be resumed: the service refused ResumeMicrovm, and \
GetMicrovm reports the VM TERMINATED (Success.). A VM that has ended doesn't come \
back; launch a new one."
);
assert!(!message.contains(".."), "{message}");
assert!(
!message.contains("suspended"),
"no cause it can't know: {message}"
);
let source = std::error::Error::source(&error).expect("the refusal is the source");
let refused = source
.downcast_ref::<Error>()
.expect("the source is the service's refusal");
assert_eq!(refused.kind(), ErrorKind::Platform);
assert!(
refused
.to_string()
.contains("has been terminated and its state cannot be changed"),
"the service's own text: {refused}"
);
}
/// A refused resume of a VM `GetMicrovm` reports alive, or whose state that read can't
/// get, comes back as the service's refusal: only a VM reported dead is `WindowClosed`.
#[tokio::test]
async fn a_resume_refused_for_a_live_or_unreadable_vm_keeps_the_services_answer() {
let (plane, fake, _) = planted();
fake.answer(
"ResumeMicrovm",
Answer::failure(409, "The MicroVM is changing state."),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("SUSPENDED", None)),
);
let error = plane
.resume("mvm-abc123")
.await
.expect_err("the service refused");
assert_eq!(error.kind(), ErrorKind::Platform, "{error}");
assert!(error.to_string().contains("ConflictException"), "{error}");
let (plane, fake, _) = planted();
fake.answer("ResumeMicrovm", terminated_refusal())
.answer("GetMicrovm", Answer::failure(404, "not found"));
let error = plane
.resume("mvm-abc123")
.await
.expect_err("the service refused");
assert_eq!(error.kind(), ErrorKind::Platform, "{error}");
let message = error.to_string();
assert!(
message.contains("ResumeMicrovm failed") && !message.contains("GetMicrovm"),
"the resume's refusal rather than the read's: {message}"
);
}
/// A resume denied for its credentials is not the service's word on the VM, so no state
/// is read and the denial comes back as it was.
#[tokio::test]
async fn a_resume_denied_for_its_credentials_reads_no_state() {
let (plane, fake, _) = planted();
fake.answer(
"ResumeMicrovm",
Answer::failure(403, "User is not authorized to perform ResumeMicrovm"),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("TERMINATED", None)),
);
let error = plane.resume("mvm-abc123").await.expect_err("denied");
assert_eq!(error.kind(), ErrorKind::Credentials, "{error}");
assert_eq!(fake.call_count("GetMicrovm"), 0);
}
/// **TRAP-7.** The minted token is read out of the `authToken` **map**, and
/// [`ProxyToken::headers`] emits both headers.
#[tokio::test]
async fn the_minted_token_comes_from_the_map_and_carries_both_headers() {
let (plane, fake, _) = planted();
fake.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("opaque-proxy-token")),
);
let token = plane.mint_auth_token("mvm-1").await.expect("mints");
assert_eq!(token.value(), "opaque-proxy-token");
assert_eq!(token.port(), 9000);
let headers = token.headers();
assert_eq!(
headers[0],
("X-aws-proxy-auth", "opaque-proxy-token".to_string())
);
assert_eq!(
headers[1],
("X-aws-proxy-port", "9000".to_string()),
"the auth header without the port header is rejected in a way that reads like a \
bad token"
);
let body = fake.first_body("CreateMicrovmAuthToken");
assert_eq!(body["expirationInMinutes"], 60);
assert_eq!(body["allowedPorts"][0]["port"], 9000);
}
/// The shell mint posts to the model's `shell-auth-token` route with **only** the
/// expiration in its body, and reads the credential out of the `authToken` map —
/// the same `TokenParts` discipline as TRAP-7.
///
/// The `allowedPorts` absence is asserted rather than assumed, because it is the
/// measured heart of the operation: `CreateMicrovmShellAuthToken` takes no ports at
/// all — the shell is not a port — and a client that sent them would be sending a
/// member the model does not declare (`docs/PLATFORM.md`, 2026-08-15).
///
/// **Falsification** — watched fail 2026-08-31: pointing the call at
/// `paths::auth_token` fails the path assertion at the `assert_eq!` on `calls[0].path`.
#[tokio::test]
async fn the_shell_mint_names_its_own_route_and_sends_no_ports() {
let (plane, fake, _) = planted();
fake.answer(
"CreateMicrovmShellAuthToken",
Answer::ok(fake::auth_token_response("opaque-shell-jwe")),
);
let token = plane
.mint_shell_auth_token("mvm-1")
.await
.expect("mints a shell token");
assert_eq!(token.value(), "opaque-shell-jwe");
let calls = fake.calls();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].operation, "CreateMicrovmShellAuthToken");
assert_eq!(calls[0].path, "/2025-09-09/microvms/mvm-1/shell-auth-token");
let body = fake.first_body("CreateMicrovmShellAuthToken");
assert_eq!(body["expirationInMinutes"], 60);
assert_eq!(
body.get("allowedPorts"),
None,
"the shell is not a port: the request declares no allowedPorts member"
);
assert_eq!(
body.as_object().map(serde_json::Map::len),
Some(1),
"expirationInMinutes is the body's only member: {body}"
);
}
/// The shell mint refuses an empty identifier locally, like every other
/// identifier-in-the-URI operation: an empty segment would address a route the model
/// does not declare.
#[tokio::test]
async fn the_shell_mint_refuses_an_empty_identifier_before_the_wire() {
let (plane, fake, _) = planted();
let error = plane
.mint_shell_auth_token("")
.await
.expect_err("an empty identifier is refused");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
assert_eq!(fake.calls().len(), 0, "nothing may reach the wire");
}
/// A launch request's `Debug` does not print the agent token.
///
/// Asserted on the whole [`RunMicrovmRequest`] rather than on the payload alone,
/// because that is the type a caller actually logs — and it keeps its derived `Debug`,
/// so what is pinned here is that the derive inherits [`RunHookPayload`]'s hand-written
/// one. **Falsification** — restore `#[derive(Debug)]` on [`RunHookPayload`] and the
/// `SECRETTOKEN` assertion fails through the derived request `Debug`.
#[test]
fn a_launch_requests_debug_does_not_print_the_agent_token() {
let payload = RunHookPayload::for_agent_token("SECRETTOKEN").expect("fits");
let rendered = format!("{payload:?}");
assert!(
!rendered.contains("SECRETTOKEN"),
"the agent token reached a Debug string: {rendered}"
);
assert!(
rendered.contains(&format!("{} bytes", payload.len())),
"the size is what a TRAP-5 diagnosis needs: {rendered}"
);
let request = RunMicrovmRequest::new("arn:image", payload);
let rendered = format!("{request:?}");
assert!(rendered.contains("arn:image"), "{rendered}");
assert!(
!rendered.contains("SECRETTOKEN"),
"the agent token reached a Debug string through the request: {rendered}"
);
}
/// A minted token's `Debug` names its headers and never its value, so a logged
/// launch does not log a credential.
///
/// The mirror of `session::proxy`'s `a_proxy_token_debug_does_not_print_the_credential`,
/// on the control-plane side of the conversion. **Falsification** — restore
/// `#[derive(Debug)]` on [`ProxyToken`] and this fails on the `secret` assertion.
#[test]
fn a_proxy_token_debug_does_not_print_the_credential() {
let mut map = std::collections::BTreeMap::new();
map.insert(
PROXY_AUTH_HEADER.to_string(),
"eyJhbGciOi-secret".to_string(),
);
let token = ProxyToken::from_map(&map, 9000).expect("the map has the auth key");
let rendered = format!("{token:?}");
assert!(rendered.contains(PROXY_AUTH_HEADER), "{rendered}");
assert!(rendered.contains("9000"), "{rendered}");
assert!(
!rendered.contains("secret"),
"the token value reached a Debug string: {rendered}"
);
}
/// A response whose map lacks the auth key is **retryable**, because minting happens
/// inside the request retry path and a throttle mid-run must not kill a healthy trial.
#[test]
fn a_map_missing_the_auth_key_is_a_retryable_mint_failure() {
let mut map = std::collections::BTreeMap::new();
map.insert("SomeOtherKey".to_string(), "value".to_string());
let error = ProxyToken::from_map(&map, 9000).expect_err("no auth key");
assert_eq!(
error.wire_kind(),
Some(crate::error::WireKind::AuthTokenMint)
);
assert!(error.retryable(), "minting is inside the retry path");
assert!(
error.to_string().contains("is a map, not a string"),
"{error}"
);
}
/// The token is minted for the configured port, not always 9000.
#[tokio::test]
async fn the_token_is_minted_for_the_configured_port() {
let fake = Arc::new(FakeControlPlane::new());
let plane = crate::testing::control_plane(
fake.clone(),
Region::UsEast1,
Arc::new(TestClock::new()),
)
.with_port(8080)
.expect("8080 is a legal port");
fake.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("t")),
);
let token = plane.mint_auth_token("mvm-1").await.expect("mints");
assert_eq!(token.port(), 8080);
assert_eq!(
fake.first_body("CreateMicrovmAuthToken")["allowedPorts"][0]["port"],
8080
);
}
/// **TRAP-11, revised, across a full lifecycle.** Drive create, wait, launch, wait,
/// mint, suspend, resume, terminate, delete — and then assert the recorder saw
/// **zero** shell-auth calls, and that the launch request carried **exactly the
/// connectors the caller asked for**, nothing added and nothing dropped.
///
/// The body scan used to assert zero `SHELL_INGRESS` anywhere, standing on the claim
/// that no intent could name it. `ConnectorIntent::ShellIngress` exists now — the
/// measured ground is that one interactive session is not programmatic exec, not
/// that the connector is unspeakable (`docs/PLATFORM.md`, 2026-08-15) — so the
/// honest assertion is set-equality against the request: a caller that asked for
/// `[ALL_INGRESS]` plus egress gets that set on the wire and no other.
///
/// The shell-auth scans stay as counts, and their ground moved once more:
/// `mint_shell_auth_token` exists now (issue #69, `microvm shell`'s method), so the
/// absence being pinned is no longer the method's but the **exec path's** — a
/// lifecycle that asked for no shell drives everything exec can do and emits zero
/// shell operations. Nothing here calls the shell mint, and that is the assertion.
///
/// **Falsification** — make any lifecycle step (`run_microvm`, `mint_auth_token`,
/// suspend/resume/terminate) also touch the shell route, or call
/// `mint_shell_auth_token` from this lifecycle: the operation scan and the path scan
/// both fail. Make `run_microvm` inject a connector the request did not carry: the
/// set-equality assertions fail.
#[tokio::test]
async fn a_full_lifecycle_never_calls_shell_auth_and_requests_only_what_was_asked() {
let (plane, fake, _) = planted();
fake.answer(
"CreateMicrovmImage",
Answer::created(fake::create_image_response("img")),
)
.answer(
"GetMicrovmImage",
Answer::ok(fake::get_image_response("img", "CREATED")),
)
.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
)
.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("proxy-token")),
)
.answer("SuspendMicrovm", Answer::ok(fake::empty_response()))
.answer("ResumeMicrovm", Answer::ok(fake::empty_response()))
.answer("TerminateMicrovm", Answer::ok(fake::empty_response()))
.answer(
"ListMicrovmImageVersions",
Answer::ok(fake::list_versions_response("1")),
)
.answer(
"DeleteMicrovmImage",
Answer::ok(fake::delete_image_response()),
);
// Everything this client can do, in the order a real run does it.
let request = super::super::CreateImageRequest::new(
"img",
crate::testing::aarch64_daemon(b"binary"),
"s3://bucket/img.zip",
"arn:aws:iam::123456789012:role/build",
);
let image = plane.create_image(request).await.expect("creates");
plane
.wait_for_image(&image.identifier, image.size, WaitOpts::default())
.await
.expect("becomes usable");
let payload = RunHookPayload::for_agent_token("agent-token").expect("fits");
let vm = plane
.run_microvm(
super::super::RunMicrovmRequest::new(&image.identifier, payload).with_egress(),
)
.await
.expect("launches");
plane
.wait_for_running(&vm.id, WaitOpts::for_launch())
.await
.expect("reaches RUNNING");
plane.mint_auth_token(&vm.id).await.expect("mints");
plane.suspend(&vm.id).await.expect("suspends");
plane.resume(&vm.id).await.expect("resumes");
plane.terminate(&vm.id).await.expect("terminates");
plane
.delete_image(&image.identifier, 1, std::time::Duration::from_secs(1))
.await;
// The lifecycle really ran, so the zero counts below are about absence rather than
// about nothing having happened.
let operations = fake.operations();
assert!(
operations.len() >= 10,
"the lifecycle must actually have run: {operations:?}"
);
assert!(operations.contains(&"CreateMicrovmAuthToken"));
assert_eq!(
fake.call_count("CreateMicrovmShellAuthToken"),
0,
"the shell mint exists for `microvm shell` alone, and a lifecycle that asked \
for no shell must mint no shell token: {operations:?}"
);
for operation in &operations {
assert!(
!operation.contains("Shell"),
"no operation may be a shell one: {operation}"
);
}
for path in fake.paths() {
assert!(
!path.contains("shell"),
"no request may reach a shell route: {path}"
);
}
// The launch carried exactly the connector set the caller asked for —
// `ALL_INGRESS` from the default plus the egress `with_egress` added — and this
// client injected nothing of its own. Set-equality cuts both ways: a connector
// the caller never named (the shell, or anything else) fails it, and so does a
// dropped one.
let launch = fake.first_body("RunMicrovm");
assert_eq!(
launch["ingressNetworkConnectors"],
serde_json::json!([
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:ALL_INGRESS"
]),
"ingress is exactly what the caller asked for"
);
assert_eq!(
launch["egressNetworkConnectors"],
serde_json::json!([
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:INTERNET_EGRESS"
]),
"egress is exactly what the caller asked for"
);
}
/// The measured pair `[HTTP_INGRESS, SHELL_INGRESS]` reaches the wire intact — the
/// combination `docs/PLATFORM.md` (2026-08-15) records as launching and minting a
/// shell token successfully. Both are ingress connectors, so both must land in
/// `ingressNetworkConnectors`; a split that only recognized `ALL_INGRESS` as ingress
/// would silently drop them, and this is the test that catches that.
#[tokio::test]
async fn http_plus_shell_ingress_is_the_pair_that_reaches_the_wire() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("agent-token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request.connectors = vec![
super::super::ConnectorIntent::HttpIngress,
super::super::ConnectorIntent::ShellIngress,
];
plane.run_microvm(request).await.expect("launches");
let launch = fake.first_body("RunMicrovm");
assert_eq!(
launch["ingressNetworkConnectors"],
serde_json::json!([
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:HTTP_INGRESS",
"arn:aws:lambda:us-east-1:aws:network-connector:aws-network-connector:SHELL_INGRESS"
]),
"both fine-grained ingress connectors reach the wire, in the order asked"
);
assert_eq!(
launch.get("egressNetworkConnectors"),
None,
"no egress was asked for, so the member is absent rather than empty"
);
}
/// `ALL_INGRESS` combined with the shell connector is refused **before the wire**.
/// The platform accepts the invalid set at launch — the VM reaches RUNNING and bills
/// — and rejects it only when a shell token is minted (`docs/PLATFORM.md`,
/// 2026-08-15). A local refusal is the only one that costs nothing.
///
/// **Falsification** — run 2026-08-31: with the combination guard in
/// [`ControlPlane::run_microvm`] disabled, this failed on the error assertion.
/// Restored.
#[tokio::test]
async fn all_ingress_combined_with_shell_ingress_is_refused_before_the_wire() {
let (plane, fake, _) = planted();
let payload = RunHookPayload::for_agent_token("agent-token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request
.connectors
.push(super::super::ConnectorIntent::ShellIngress);
let error = plane
.run_microvm(request)
.await
.expect_err("the invalid combination is refused locally");
assert!(
error
.to_string()
.contains("HTTP_INGRESS and/or SHELL_INGRESS"),
"the refusal names the pair that works: {error}"
);
assert_eq!(
fake.call_count("RunMicrovm"),
0,
"nothing launched, so nothing billed"
);
}
/// **W1, measured constraint 1, second half.** `SHELL_INGRESS` without `HTTP_INGRESS`
/// is the same launches-bills-fails-late shape as `ALL_INGRESS` plus a finer connector:
/// the measured pair that launches and mints a shell token is `[HTTP_INGRESS,
/// SHELL_INGRESS]` (`docs/PLATFORM.md`), no measurement says a shell-only ingress set
/// even mints, and the platform accepts an invalid set at launch — the VM reaches
/// RUNNING and bills before any refusal appears. Refused here instead, before the wire.
///
/// **Falsification** — run 2026-08-31. This test was written before the guard clause
/// existed and failed on both assertions (`run_microvm` reached the wire and launched);
/// adding the shell-without-HTTP refusal in `run_microvm` turned it green.
#[tokio::test]
async fn shell_ingress_without_http_ingress_is_refused_before_the_wire() {
let (plane, fake, _) = planted();
let payload = RunHookPayload::for_agent_token("agent-token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request.connectors = vec![
super::super::ConnectorIntent::ShellIngress,
super::super::ConnectorIntent::Egress,
];
let error = plane
.run_microvm(request)
.await
.expect_err("shell ingress without HTTP ingress is refused locally");
assert!(
error.to_string().contains("HTTP_INGRESS"),
"the refusal names the missing connector: {error}"
);
assert_eq!(
fake.call_count("RunMicrovm"),
0,
"nothing launched, so nothing billed"
);
}
/// A page the service throttles is retried, not the end of the listing. The service
/// sent that throttle as HTTP 400 named only by the `x-amzn-ErrorType` header
/// (docs/PLATFORM.md, 2026-10-02), and a fleet of 140 VMs, fourteen pages read back to
/// back, met it on most listings, each of which then failed as a validation refusal.
///
/// **Falsification** — run 2026-10-02. Guard the classifier's header arm with `false` and
/// the listing stops at the throttled page with the 400 as its error, so `expect` panics
/// (`guards:fire -- --only control-listing-stops-at-a-throttled-page`). Restored.
#[tokio::test]
async fn the_fleet_listing_retries_a_page_the_service_throttled_as_400() {
let (plane, fake, _) = planted();
fake.answer(
"ListMicrovms",
Answer::ok(fake::list_microvms_page(
&["mvm-page1-a"],
Some("fleet-page-2"),
)),
)
.answer("ListMicrovms", Answer::throttled_as_400())
.answer(
"ListMicrovms",
Answer::ok(fake::list_microvms_page(&["mvm-page2-a"], None)),
);
let fleet = plane
.list_microvms()
.await
.expect("lists past the throttle");
let ids: Vec<&str> = fleet.iter().map(|vm| vm.microvm_id.as_str()).collect();
assert_eq!(ids, ["mvm-page1-a", "mvm-page2-a"]);
assert_eq!(
fake.call_count("ListMicrovms"),
3,
"page two was asked for again after the throttle"
);
let paths = fake.paths();
assert_eq!(paths[1], paths[2], "the retry is the identical request");
}
/// **Issue #23.** The fleet listing follows `nextToken`, so a fleet larger than one page
/// is not silently truncated.
///
/// One page is a **confidently wrong** answer rather than a missing one: the caller gets a
/// list that looks complete, and a VM absent from it is a VM nothing here will terminate.
///
/// The assertion is the fleet **length** and the presence of the page-two ids, which is
/// what a test against the single-page code cannot satisfy.
///
/// **Falsification** — run 2026-08-15. Replace the `Some(token)` arm with
/// `Some(_) => return Ok(items)` and this fails with 2 VMs instead of 3, and both
/// page-two `contains` assertions go red. Restored.
#[tokio::test]
async fn the_fleet_listing_follows_next_token_to_the_vms_on_page_two() {
let (plane, fake, _) = planted();
fake.answer(
"ListMicrovms",
Answer::ok(fake::list_microvms_page(
&["mvm-page1-a", "mvm-page1-b"],
Some("fleet-page-2"),
)),
)
.answer(
"ListMicrovms",
Answer::ok(fake::list_microvms_page(&["mvm-page2-a"], None)),
);
let fleet = plane.list_microvms().await.expect("lists");
assert_eq!(
fleet.len(),
3,
"a fleet spanning two pages is three VMs, not two"
);
let ids: Vec<&str> = fleet.iter().map(|vm| vm.microvm_id.as_str()).collect();
assert!(ids.contains(&"mvm-page2-a"), "page two is missing: {ids:?}");
assert!(ids.contains(&"mvm-page1-a"), "{ids:?}");
assert_eq!(fake.call_count("ListMicrovms"), 2, "both pages were read");
let paths = fake.paths();
assert!(
paths[1].contains("nextToken=fleet-page-2"),
"the second request must carry the first page's token: {}",
paths[1]
);
assert!(
!paths[0].contains('?'),
"the first request carries no cursor: {}",
paths[0]
);
}
/// **A VM the service lists on two pages is listed once (#280).**
///
/// Measured 2026-10-01 (docs/PLATFORM.md, "A paginated `ListMicrovms` can return one VM on
/// two of its pages"): while VMs change state, a `nextToken` walk can meet one VM twice.
/// A listing that concatenated the pages counted it twice, so `ls --remote` listed it
/// twice and a teardown would terminate it twice. The later page's entry is the newer
/// reading, so it is the one kept, at the place the VM was first listed.
#[tokio::test]
async fn a_vm_the_fleet_listing_meets_on_two_pages_is_listed_once() {
let (plane, fake, _) = planted();
fake.answer(
"ListMicrovms",
Answer::ok(fake::list_microvms_page(
&["mvm-a", "mvm-moved"],
Some("fleet-page-2"),
)),
)
.answer(
"ListMicrovms",
Answer::ok(
fake::list_microvms_page(&["mvm-moved", "mvm-b"], None).replacen(
"RUNNING",
"SUSPENDED",
1,
),
),
);
let fleet = plane.list_microvms().await.expect("lists");
let ids: Vec<&str> = fleet.iter().map(|vm| vm.microvm_id.as_str()).collect();
assert_eq!(
ids,
["mvm-a", "mvm-moved", "mvm-b"],
"each VM once, in the order first listed"
);
assert_eq!(
fleet[1].state, "SUSPENDED",
"the page read later is the newer reading of the VM"
);
assert_eq!(fleet[0].state, "RUNNING");
assert_eq!(fake.call_count("ListMicrovms"), 2, "both pages were read");
}
/// **Issue #25.** The `idlePolicy` the service reports is carried rather than dropped.
///
/// The comment on [`ops::IdlePolicy`] used to claim `suspendedDurationSeconds` "exists
/// only in the request". A live `GetMicrovm` on a RUNNING VM disagrees, which is what the
/// fake's body now reflects — so this test is over a response shape that was measured
/// rather than assumed.
///
/// **Falsification** — drop `idle_policy` from the `From<MicrovmResponseWire>` impl and
/// this does not compile; set it to `None` there and every field assertion goes red.
#[tokio::test]
async fn the_reported_idle_policy_is_carried_rather_than_dropped() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
);
let vm = plane.get_microvm("mvm-1").await.expect("reads");
let policy = vm
.idle_policy
.expect("GetMicrovm returns an idlePolicy, measured 2026-08-15");
assert_eq!(policy.max_idle_duration_seconds, 1800);
assert_eq!(
policy.suspended_duration_seconds, 600,
"the member the comment claimed was request-only"
);
assert!(!policy.auto_resume_enabled);
}
/// A response with no `idlePolicy` still parses, and the absence is `None` rather than a
/// default. The model does not mark the member required on either response shape, so an
/// invented `0` would be a window nobody configured.
#[tokio::test]
async fn an_absent_idle_policy_is_none_rather_than_a_zero_window() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(
r#"{
"microvmId": "mvm-1",
"state": "RUNNING",
"endpoint": "https://e",
"imageArn": "arn:aws:lambda:us-east-1:123456789012:microvm-image:img",
"imageVersion": "1"
}"#,
),
);
let vm = plane.get_microvm("mvm-1").await.expect("parses");
assert_eq!(vm.idle_policy, None);
}
/// A transport failure is retried and then succeeds, so a connection reset on the way to
/// a launch is not a failed launch.
#[tokio::test]
async fn a_transport_failure_is_retried_rather_than_reported() {
let (plane, fake, _) = planted();
fake.fail_transport("GetMicrovm", 2).answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
);
let vm = plane
.get_microvm("mvm-1")
.await
.expect("the retry succeeds");
assert_eq!(vm.state, "RUNNING");
assert_eq!(
fake.call_count("GetMicrovm"),
3,
"two failures then a success"
);
}
// ── issue #24's guards on the launch and lifecycle paths ─────────────────
/// **`max_idle_sec: 59` no longer reaches the wire.**
///
/// The measurement issue #24 made, turned into a test. The exemption it replaces was not a
/// wrong number — it was a correct fact about botocore's `VALIDATED_METADATA_ATTRS` applied to
/// a client that does not use botocore, so `IdlePolicy.maxIdleDurationSeconds` was the one
/// constraint in the model with a *reason* for having no guard rather than an oversight.
///
/// The fake has `RunMicrovm` answered, so a missing guard shows as a launch that **succeeded**
/// with 59 on the wire rather than as some other failure. That is what makes the zero-call
/// assertion the load-bearing one.
///
/// **Guard proof** — run 2026-08-16. Delete `require_idle_duration` from `run_microvm` and
/// this fails on `expect_err`, with the fake recording `RunMicrovm` once and
/// `idlePolicy.maxIdleDurationSeconds: 59` in its body.
#[tokio::test]
async fn an_under_minimum_idle_duration_reaches_no_control_plane_call() {
for under in [0, 1, 59] {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request.max_idle_sec = under;
let error = plane
.run_microvm(request)
.await
.expect_err("the model's min is 60");
assert_eq!(error.kind(), ErrorKind::InvalidArg);
let message = error.to_string();
assert!(message.contains("maxIdleDurationSeconds"), "{message}");
assert!(message.contains(&under.to_string()), "{message}");
assert_eq!(
fake.calls().len(),
0,
"{under} was refused locally; before this guard it was serialized and sent"
);
}
// 60 exactly does launch, so the boundary is inclusive and the guard is not refusing
// every idle window.
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
request.max_idle_sec = 60;
plane.run_microvm(request).await.expect("60 is the minimum");
assert_eq!(
fake.first_body("RunMicrovm")["idlePolicy"]["maxIdleDurationSeconds"],
60
);
}
/// **The launch's `executionRoleArn` and `imageIdentifier`, refused before the call.**
///
/// `executionRoleArn` is filled from an infra config on every real launch — the CLI reads it
/// out of `MICROVM_EXECUTION_ROLE_ARN` — so a malformed one is a `ValidationException` about a
/// member the caller never typed. Naming it locally is the whole difference.
///
/// **Guard proof** — run 2026-08-16. Delete `require_valid_role_arn("executionRoleArn", …)`
/// and the role rows launch successfully with the bad ARN on the wire; delete
/// `require_valid_identifier` and the identifier rows do.
#[tokio::test]
async fn a_malformed_launch_role_or_identifier_reaches_no_control_plane_call() {
/// What to break, aliased for the reason clippy's `type_complexity` gives — and the same
/// alias `image.rs`'s create-path table uses, so the two read alike.
type Mutate = fn(&mut RunMicrovmRequest);
let rows: [(&str, Mutate, &str); 6] = [
(
"an execution role that is a bare name",
|request| {
request.execution_role_arn = Some("execution-role".to_string());
},
"role *name*",
),
(
"an execution role with eleven account digits",
|request| {
request.execution_role_arn =
Some("arn:aws:iam::12345678901:role/exec".to_string());
},
"exactly twelve digits",
),
(
"an execution role that is a function ARN",
|request| {
request.execution_role_arn =
Some("arn:aws:lambda:us-east-1:123456789012:function:h".to_string());
},
"RoleArn pattern",
),
(
"an empty image identifier",
|request| {
request.image_identifier = String::new();
},
"collapses the path",
),
(
"a 257-character image identifier",
|request| {
request.image_identifier = "a".repeat(257);
},
"MicrovmImageArn permits 2048",
),
(
"an image version with a newline",
|request| {
request.image_version = Some("2.0\n".to_string());
},
"contains whitespace",
),
];
for (label, mutate, expected) in rows {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload);
mutate(&mut request);
let error = plane
.run_microvm(request)
.await
.expect_err(&format!("{label} must be refused"));
assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
assert!(
error.to_string().contains(expected),
"{label}: wanted {expected:?}, got {error}"
);
assert_eq!(fake.calls().len(), 0, "{label}");
}
// The control case: a launch carrying a real execution role, a pinned version, and the
// account's actual ARN shape goes through.
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = RunHookPayload::for_agent_token("token").expect("fits");
let mut request = RunMicrovmRequest::new(
"arn:aws:lambda:us-east-1:392583147479:microvm-image:agentd-conformance",
payload,
);
request.execution_role_arn =
Some("arn:aws:iam::392583147479:role/bonk-sandbox-microvm-execution".to_string());
request.image_version = Some("1.0".to_string());
plane
.run_microvm(request)
.await
.expect("a realistic pinned launch with a real execution role");
assert_eq!(fake.call_count("RunMicrovm"), 1);
}
/// **The `microvmIdentifier` guard on every lifecycle operation, proved by the call count.**
///
/// `TerminateMicrovm` is the one worth reading twice. Its path is
/// `DELETE /microvms/{microvmIdentifier}`, so an empty identifier is a `DELETE` addressed at
/// the fleet collection. The service has no operation there and refuses it, but "send a delete
/// at the collection and trust the service" is not a thing to leave to the service.
///
/// **Guard proof** — run 2026-08-16. Delete `require_valid_identifier` from any one of the
/// five and its assertion goes red with `calls: 1`.
#[tokio::test]
async fn no_lifecycle_operation_sends_an_empty_or_over_long_microvm_identifier() {
for bad in ["", &"a".repeat(257)] {
let (plane, fake, _) = planted();
// Every operation answered, so a missing guard is a *successful* call rather than a
// different failure.
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
);
fake.answer("SuspendMicrovm", Answer::ok("{}"));
fake.answer("ResumeMicrovm", Answer::ok("{}"));
fake.answer("TerminateMicrovm", Answer::ok("{}"));
fake.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("t")),
);
plane.get_microvm(bad).await.expect_err("GetMicrovm");
plane.suspend(bad).await.expect_err("SuspendMicrovm");
plane.resume(bad).await.expect_err("ResumeMicrovm");
plane.terminate(bad).await.expect_err("TerminateMicrovm");
plane
.mint_auth_token(bad)
.await
.expect_err("CreateMicrovmAuthToken");
plane
.wait_for_running(bad, WaitOpts::for_launch())
.await
.expect_err("GetMicrovm, in a loop");
assert_eq!(
fake.calls().len(),
0,
"six operations refused {bad:?} locally. An empty identifier on the terminate \
path is a DELETE addressed at the collection."
);
}
}
/// **Issue #24's `PortNumber` half: a token is never minted for port 0.**
///
/// The measurement that makes this worth a guard rather than a comment is in
/// [`ops::PortSpecification`]: a token whose `allowedPorts` does not cover the port a request
/// names is refused with **403 `Access to port denied`**, and on the WebSocket path it is close
/// code 1006 with no reason. So a token minted for port 0 authorizes nothing and fails in a
/// way that reads like a bad credential rather than like an empty scope.
///
/// Both ends of a range are checked as well as the single-port form, because `PortRange`'s two
/// members name the same shape and a range starting at 0 is the same defect.
///
/// **Guard proof** — run 2026-08-16. Delete the `for spec in ports` loop from
/// `mint_auth_token_for` and all three rows mint successfully with `{"port": 0}` or
/// `{"range": {"startPort": 0, …}}` on the wire.
#[tokio::test]
async fn no_proxy_token_is_minted_for_port_zero() {
let rows: [(&str, ops::PortSpecification, &str); 3] = [
(
"a single port of 0",
ops::PortSpecification::port(0),
"allowedPorts[].port",
),
(
"a range starting at 0",
ops::PortSpecification::range(0, 9000),
"allowedPorts[].range.startPort",
),
(
"a range ending at 0",
ops::PortSpecification::range(0, 0),
"allowedPorts[].range.startPort",
),
];
for (label, spec, member) in rows {
let (plane, fake, _) = planted();
fake.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("t")),
);
let error = plane
.mint_auth_token_for("mvm-1", &[spec])
.await
.expect_err(&format!("{label} must be refused"));
assert_eq!(error.kind(), ErrorKind::InvalidArg, "{label}");
let message = error.to_string();
assert!(message.contains(member), "{label}: {message}");
assert!(
message.contains("authorizes nothing"),
"{label}: the 403 consequence has to be in the message: {message}"
);
assert_eq!(fake.calls().len(), 0, "{label}");
}
// A zero port among legal ones is still refused: the check is per-entry, not on the
// first. A token minted with `[{port: 9000}, {port: 0}]` would look scoped correctly and
// carry a member the service refuses the whole request over.
let (plane, fake, _) = planted();
fake.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("t")),
);
plane
.mint_auth_token_for(
"mvm-1",
&[
ops::PortSpecification::port(9000),
ops::PortSpecification::port(0),
],
)
.await
.expect_err("every entry is checked, not the first");
assert_eq!(fake.calls().len(), 0);
// And the three legal forms mint, including `allPorts` — which names no number, so there
// is nothing to bound and the guard must not refuse it.
for legal in [
ops::PortSpecification::port(1),
ops::PortSpecification::port(65_535),
ops::PortSpecification::range(1, 65_535),
ops::PortSpecification::all(),
] {
let (plane, fake, _) = planted();
fake.answer(
"CreateMicrovmAuthToken",
Answer::ok(fake::auth_token_response("t")),
);
plane
.mint_auth_token_for("mvm-1", &[legal])
.await
.expect("a legal port specification mints");
assert_eq!(fake.call_count("CreateMicrovmAuthToken"), 1);
}
}
/// **#195.** A launch whose client token adopted a VM that idle-suspended since the
/// first attempt resumes it and returns RUNNING, rather than reporting LaunchDied.
///
/// **Falsification** — route `wait_for_launch` through `TERMINAL_STATES` (the fresh
/// launch's fail set) and this reports LaunchDied on the first SUSPENDED poll.
#[tokio::test]
async fn an_adopted_launch_that_finds_its_vm_suspended_resumes_it() {
for first in ["SUSPENDING", "SUSPENDED"] {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response(first, None)),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("SUSPENDED", None)),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("SUSPENDED", None)),
)
.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
)
.answer("ResumeMicrovm", Answer::ok(fake::empty_response()));
let running = plane
.wait_for_launch("mvm-abc123", WaitOpts::for_launch())
.await
.unwrap_or_else(|error| panic!("{first}: {error}"));
assert_eq!(running.state, "RUNNING", "{first}");
assert_eq!(
fake.call_count("ResumeMicrovm"),
1,
"{first}: one resume, even though GetMicrovm still read SUSPENDED after it"
);
}
}
/// The adopted-launch wait still fails fast, with `stateReason`, on a dead state.
#[tokio::test]
async fn an_adopted_launch_still_fails_fast_on_a_dead_state() {
for state in crate::constants::DEAD_STATES {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response(state, Some("hook timeout"))),
);
let error = plane
.wait_for_launch("mvm-abc123", WaitOpts::for_launch())
.await
.expect_err(&format!("{state} is a death"));
assert_eq!(error.kind(), ErrorKind::LaunchDied, "{state}");
assert!(
error.to_string().contains("hook timeout"),
"{state}: {error}"
);
assert_eq!(fake.call_count("GetMicrovm"), 1, "{state}");
assert_eq!(fake.call_count("ResumeMicrovm"), 0, "{state}");
}
}
/// `startedAt`, `terminatedAt`, and `maximumDurationInSeconds` reach [`Microvm`].
#[tokio::test]
async fn get_microvm_carries_the_lifetime_members() {
let (plane, fake, _) = planted();
fake.answer(
"GetMicrovm",
Answer::ok(fake::microvm_response("RUNNING", None)),
);
let vm = plane.get_microvm("mvm-abc123").await.expect("parses");
assert_eq!(vm.maximum_duration_seconds, Some(3600));
assert_eq!(
vm.started_at,
Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_754_524_800))
);
assert_eq!(vm.terminated_at, None);
}
/// A timestamp past what a `Duration` holds reads as absent, as a negative one does, and
/// the rest of the reply still parses. The conversion ran before the checked add, so such
/// a reply panicked the parser instead (#335). The negative figure is last, so the fault
/// below panics on an out-of-range one first.
///
/// **Falsification**: `verify/guards/faults/seconds-flags.toml` entry
/// `app-epoch-past-a-duration-panics` restores `Duration::from_secs_f64` in `epoch`, and
/// the `1e300` reply panics.
#[tokio::test]
async fn an_out_of_range_timestamp_reads_as_absent() {
for seconds in ["2e19", "1e300", "1.7976931348623157e308", "-1"] {
let (plane, fake, _) = planted();
let body = fake::microvm_response("TERMINATED", None).replace(
r#""startedAt": 1754524800"#,
&format!(r#""startedAt": {seconds}, "terminatedAt": {seconds}"#),
);
fake.answer("GetMicrovm", Answer::ok(body));
let vm = plane
.get_microvm("mvm-abc123")
.await
.unwrap_or_else(|error| panic!("{seconds}: {error}"));
assert_eq!(vm.state, "TERMINATED", "{seconds}");
assert_eq!(vm.maximum_duration_seconds, Some(3600), "{seconds}");
assert_eq!(vm.started_at, None, "{seconds}");
assert_eq!(vm.terminated_at, None, "{seconds}");
}
}
/// The list filters reach the query string in SigV4's sorted order, ARN colons escaped.
#[tokio::test]
async fn list_filters_reach_the_query_string() {
let (plane, fake, _) = planted();
fake.answer(
"ListMicrovms",
Answer::ok(fake::list_microvms_page(&["mvm-1"], None)),
);
let filter = MicrovmFilter {
image_identifier: Some(
"arn:aws:lambda:us-east-1:123456789012:microvm-image:img".into(),
),
image_version: Some("1.0".into()),
};
let items = plane.list_microvms_matching(&filter).await.expect("lists");
assert_eq!(items.len(), 1);
let path = fake.paths().pop().expect("one call");
assert!(
path.ends_with(
"/microvms?imageIdentifier=arn%3Aaws%3Alambda%3Aus-east-1%3A123456789012%3Amicrovm-image%3Aimg&imageVersion=1.0"
),
"{path}"
);
plane.list_microvms().await.expect("unfiltered");
assert!(fake.paths().pop().expect("second").ends_with("/microvms"));
}
/// Per-VM logging reaches the wire, and a malformed group is refused before any call.
#[tokio::test]
async fn per_vm_logging_is_sent_and_checked_locally() {
let (plane, fake, _) = planted();
fake.answer(
"RunMicrovm",
Answer::ok(fake::microvm_response("PENDING", None)),
);
let payload = || RunHookPayload::for_agent_token("t").expect("fits");
let mut request = RunMicrovmRequest::new("arn:image", payload());
request.logging = Some(ops::Logging::cloud_watch("/team/agents", None));
plane.run_microvm(request).await.expect("launches");
assert_eq!(
fake.first_body("RunMicrovm")["logging"],
serde_json::json!({"cloudWatch": {"logGroup": "/team/agents"}})
);
let mut disabled = RunMicrovmRequest::new("arn:image", payload());
disabled.logging = Some(ops::Logging::disabled());
plane.run_microvm(disabled).await.expect("launches");
assert_eq!(
fake.body_of("RunMicrovm", 1)["logging"],
serde_json::json!({"disabled": {}})
);
let plain = RunMicrovmRequest::new("arn:image", payload());
plane.run_microvm(plain).await.expect("launches");
assert!(fake.body_of("RunMicrovm", 2).get("logging").is_none());
for bad in [
ops::Logging::cloud_watch("bad group!", None),
ops::Logging::CloudWatch {
cloud_watch: ops::CloudWatchLogging {
log_group: None,
log_stream: Some("s".into()),
},
},
] {
let mut request = RunMicrovmRequest::new("arn:image", payload());
request.logging = Some(bad);
let error = plane.run_microvm(request).await.expect_err("refused");
assert_eq!(error.kind(), ErrorKind::InvalidArg, "{error}");
}
assert_eq!(
fake.call_count("RunMicrovm"),
3,
"the refusals cost no call"
);
}
}