microsandbox-types 0.6.5

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

use std::collections::BTreeMap;
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::PathBuf;
use std::str::FromStr;

use ipnetwork::{IpNetwork, Ipv4Network, Ipv6Network};
use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;

use crate::modify::SecretSource;

//--------------------------------------------------------------------------------------------------
// Constants
//--------------------------------------------------------------------------------------------------

/// Default number of virtual CPUs in a sandbox specification.
pub const DEFAULT_SANDBOX_VCPUS: u8 = 1;

/// Default guest memory in MiB in a sandbox specification.
pub const DEFAULT_SANDBOX_MEMORY_MIB: u32 = 512;

/// Default metrics sampling interval in milliseconds.
pub const DEFAULT_METRICS_SAMPLE_INTERVAL_MS: u64 = 1000;

//--------------------------------------------------------------------------------------------------
// Types: Root Filesystems
//--------------------------------------------------------------------------------------------------

/// Disk image format for virtio-blk root filesystems and volume mounts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum DiskImageFormat {
    /// QEMU Copy-on-Write v2.
    #[serde(alias = "Qcow2")]
    Qcow2,
    /// Raw disk image.
    #[serde(alias = "Raw")]
    Raw,
    /// VMware Disk (FLAT/ZERO only, no delta links).
    #[serde(alias = "Vmdk")]
    Vmdk,
}

/// Root filesystem source for a sandbox.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum RootfsSource {
    /// Use a host directory directly as the root filesystem.
    #[serde(alias = "Bind")]
    Bind(
        /// Host path to bind mount.
        #[cfg_attr(feature = "ts", ts(type = "string"))]
        PathBuf,
    ),

    /// Use an OCI image reference with an EROFS lower and ext4 overlay upper.
    #[serde(alias = "Oci")]
    Oci(OciRootfsSource),

    /// Use a disk image file as the root filesystem via virtio-blk.
    #[serde(alias = "DiskImage")]
    DiskImage {
        /// Path to the disk image file on the host.
        #[cfg_attr(feature = "ts", ts(type = "string"))]
        path: PathBuf,
        /// Disk image format.
        format: DiskImageFormat,
        /// Inner filesystem type (optional; auto-detected if absent).
        fstype: Option<String>,
    },
}

/// OCI root filesystem source.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct OciRootfsSource {
    /// OCI image reference (e.g. `python`).
    pub reference: String,

    /// Writable overlay upper size in MiB.
    #[serde(
        default,
        alias = "disk_size_mib",
        skip_serializing_if = "Option::is_none"
    )]
    pub upper_size_mib: Option<u32>,
}

/// Controls when an OCI registry is contacted for manifest freshness.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum PullPolicy {
    /// Use cached layers if complete, pull otherwise.
    #[default]
    #[serde(alias = "IfMissing")]
    IfMissing,

    /// Always fetch the manifest from the registry, reusing cached layers whose digests still match.
    #[serde(alias = "Always")]
    Always,

    /// Never contact the registry. Error if the image is not fully cached locally.
    #[serde(alias = "Never")]
    Never,
}

//--------------------------------------------------------------------------------------------------
// Types: Mounts
//--------------------------------------------------------------------------------------------------

/// Stat virtualization policy for a virtiofs-backed volume mount.
///
/// Serializes/deserializes as the lowercase variant name (`"strict"`, `"relaxed"`, `"off"`) so persisted JSON aligns with the CLI grammar (`stat-virt=strict|relaxed|off`) and the NAPI string contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
pub enum StatVirtualization {
    /// Fail-closed: probe the host backing path; require xattr support.
    Strict,
    /// Opportunistic: apply the overlay when present; tolerate missing xattr support.
    Relaxed,
    /// Literal host metadata: do not read or apply the override xattr.
    Off,
}

/// Host permission propagation policy for a virtiofs-backed volume mount.
///
/// Serializes/deserializes as the lowercase variant name (`"private"`, `"mirror"`) to align with the CLI and NAPI spellings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
pub enum HostPermissions {
    /// Guest chmod stays in the metadata overlay only.
    Private,
    /// Mirror ordinary rwx bits for regular files and directories to the host inode.
    Mirror,
}

/// Sandbox-level in-guest security profile.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
pub enum SecurityProfile {
    /// Preserve normal guest-root semantics.
    ///
    /// Exec sessions do not set `no_new_privs` and keep `CAP_SYS_ADMIN`, so workflows such as `sudo`, package managers, and Docker-in-Docker work as they would in a regular VM.
    #[default]
    Default,

    /// Harden guest exec sessions.
    ///
    /// Agentd sets `no_new_privs`, drops `CAP_SYS_ADMIN`, and forces `nosuid,nodev` on user mounts. Workloads that need privilege elevation or guest mount administration, such as `sudo` and Docker-in-Docker, are intentionally incompatible with this profile.
    Restricted,
}

/// Guest mount behavior shared by every volume mount kind.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(default)]
pub struct MountOptions {
    /// Whether the mount is read-only.
    ///
    /// Guest writes fail with the kernel's read-only filesystem behavior. Virtiofs-backed mounts also reject writes on the host-side filesystem server as defense in depth.
    pub readonly: bool,

    /// Whether direct execution from the mount is disabled.
    ///
    /// This prevents `execve` of binaries or scripts located on the mount. Interpreters can still read files from the mount, for example `sh /mnt/script.sh`, because the interpreter itself executes from a different filesystem.
    pub noexec: bool,

    /// Whether setuid and setgid privilege elevation from files on the mount is ignored.
    pub nosuid: bool,

    /// Whether device files on the mount are ignored.
    pub nodev: bool,
}

/// Storage kind for a named volume.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum VolumeKind {
    /// Directory-backed named volume mounted through virtiofs.
    #[serde(alias = "Directory")]
    Directory,

    /// Raw ext4 disk-image named volume mounted through virtio-blk.
    #[serde(alias = "Disk")]
    Disk,
}

/// Configuration for creating a named volume.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct VolumeSpec {
    /// Volume name.
    pub name: String,

    /// Storage kind.
    pub kind: VolumeKind,

    /// Size quota in MiB. `None` means unlimited.
    pub quota_mib: Option<u32>,

    /// Disk capacity in MiB. Required for disk volumes.
    pub capacity_mib: Option<u32>,

    /// Labels for organization.
    pub labels: Vec<(String, String)>,
}

/// Sandbox-time behavior for a named volume mount.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum NamedVolumeMode {
    /// Require the named volume to already exist.
    #[serde(alias = "Existing")]
    Existing,

    /// Create the named volume and fail if it already exists.
    #[serde(alias = "Create")]
    Create,

    /// Ensure the named volume exists, or reuse a compatible existing volume.
    #[serde(alias = "EnsureExists")]
    EnsureExists,
}

/// Creation metadata for sandbox-time named volume provisioning.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct NamedVolumeCreate {
    /// Creation behavior for this named volume mount.
    pub mode: NamedVolumeMode,

    /// Volume name to create or ensure exists.
    pub name: String,

    /// Storage kind to create or ensure exists.
    pub kind: VolumeKind,

    /// Directory quota in MiB, if configured.
    pub quota_mib: Option<u32>,

    /// Disk capacity in MiB, if configured.
    pub capacity_mib: Option<u32>,

    /// Labels to attach to newly-created volumes.
    pub labels: Vec<(String, String)>,
}

/// Default stat-virtualization policy (`Strict`) for a deserialized volume mount.
fn default_strict() -> StatVirtualization {
    StatVirtualization::Strict
}

/// Default host-permission policy (`Private`) for a deserialized volume mount.
fn default_private() -> HostPermissions {
    HostPermissions::Private
}

/// A volume mount specification for a sandbox.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum VolumeMount {
    /// Bind mount a host directory into the guest.
    #[serde(alias = "Bind")]
    Bind {
        /// Host path to bind mount.
        #[cfg_attr(feature = "utoipa", schema(value_type = String))]
        #[cfg_attr(feature = "ts", ts(type = "string"))]
        host: PathBuf,
        /// Guest mount path.
        guest: String,
        /// Guest mount behavior.
        #[serde(default)]
        options: MountOptions,
        /// Guest-visible stat virtualization policy.
        #[serde(default = "default_strict")]
        stat_virtualization: StatVirtualization,
        /// Host permission propagation policy.
        #[serde(default = "default_private")]
        host_permissions: HostPermissions,
        /// Guest-write byte budget in MiB.
        ///
        /// Bounds how much the guest may add beyond the directory's existing
        /// contents. `None` applies the protective default at spawn time; set a
        /// value to override it.
        #[serde(default)]
        quota_mib: Option<u32>,
    },

    /// Mount a named volume into the guest.
    #[serde(alias = "Named")]
    Named {
        /// Volume name.
        name: String,
        /// Guest mount path.
        guest: String,
        /// Creation metadata for sandbox-time named volume provisioning.
        ///
        /// This is transient and intentionally skipped when sandbox configs are persisted; restarting a sandbox mounts the already-created volume.
        #[serde(skip)]
        create: Option<NamedVolumeCreate>,
        /// Guest mount behavior.
        #[serde(default)]
        options: MountOptions,
        /// Guest-visible stat virtualization policy.
        #[serde(default = "default_strict")]
        stat_virtualization: StatVirtualization,
        /// Host permission propagation policy.
        #[serde(default = "default_private")]
        host_permissions: HostPermissions,
    },

    /// Temporary filesystem backed by guest memory.
    #[serde(alias = "Tmpfs")]
    Tmpfs {
        /// Guest mount path.
        guest: String,
        /// Size limit in MiB.
        #[serde(default)]
        size_mib: Option<u32>,
        /// Guest mount behavior.
        #[serde(default)]
        options: MountOptions,
    },

    /// Mount a disk image file as a virtio-blk device at a guest path.
    #[serde(alias = "DiskImage")]
    DiskImage {
        /// Host path to the disk image file.
        #[cfg_attr(feature = "utoipa", schema(value_type = String))]
        #[cfg_attr(feature = "ts", ts(type = "string"))]
        host: PathBuf,
        /// Guest mount path.
        guest: String,
        /// Disk image format.
        format: DiskImageFormat,
        /// Inner filesystem type. When `None`, agentd probes `/proc/filesystems`.
        #[serde(default)]
        fstype: Option<String>,
        /// Guest mount behavior.
        #[serde(default)]
        options: MountOptions,
    },
}

/// Rootfs patch applied before VM startup.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum Patch {
    /// Write text content to a file.
    #[serde(alias = "Text")]
    Text {
        /// Absolute guest path, such as `/etc/app.conf`.
        path: String,
        /// Text content to write.
        content: String,
        /// File permissions, such as `0o644`. `None` uses the default.
        mode: Option<u32>,
        /// Allow replacing a file that already exists in the rootfs.
        replace: bool,
    },

    /// Write raw bytes to a file.
    #[serde(alias = "File")]
    File {
        /// Absolute guest path.
        path: String,
        /// Raw byte content to write.
        content: Vec<u8>,
        /// File permissions, such as `0o644`. `None` uses the default.
        mode: Option<u32>,
        /// Allow replacing a file that already exists in the rootfs.
        replace: bool,
    },

    /// Copy a file from the host into the rootfs.
    #[serde(alias = "CopyFile")]
    CopyFile {
        /// Host path to copy from.
        #[cfg_attr(feature = "utoipa", schema(value_type = String))]
        #[cfg_attr(feature = "ts", ts(type = "string"))]
        src: PathBuf,
        /// Absolute guest destination path.
        dst: String,
        /// File permissions. `None` preserves source permissions.
        mode: Option<u32>,
        /// Allow replacing a file that already exists in the rootfs.
        replace: bool,
    },

    /// Copy a directory from the host into the rootfs.
    #[serde(alias = "CopyDir")]
    CopyDir {
        /// Host directory to copy from.
        #[cfg_attr(feature = "utoipa", schema(value_type = String))]
        #[cfg_attr(feature = "ts", ts(type = "string"))]
        src: PathBuf,
        /// Absolute guest destination path.
        dst: String,
        /// Allow replacing files that already exist in the rootfs.
        replace: bool,
    },

    /// Create a symlink.
    #[serde(alias = "Symlink")]
    Symlink {
        /// Symlink target path.
        target: String,
        /// Absolute guest path where the symlink is created.
        link: String,
        /// Allow replacing a path that already exists in the rootfs.
        replace: bool,
    },

    /// Create a directory.
    #[serde(alias = "Mkdir")]
    Mkdir {
        /// Absolute guest path.
        path: String,
        /// Directory permissions, such as `0o755`. `None` uses the default.
        mode: Option<u32>,
    },

    /// Remove a file or directory.
    #[serde(alias = "Remove")]
    Remove {
        /// Absolute guest path to remove.
        path: String,
    },

    /// Append content to an existing file.
    #[serde(alias = "Append")]
    Append {
        /// Absolute guest path of the file to append to.
        path: String,
        /// Content to append.
        content: String,
    },
}

//--------------------------------------------------------------------------------------------------
// Types: Secret injection
//--------------------------------------------------------------------------------------------------

/// Maximum supported secret placeholder length in bytes.
pub const MAX_SECRET_PLACEHOLDER_BYTES: usize = 1024;

/// Placeholder-based secret injection for a sandbox's TLS-intercepted egress.
///
/// The sandbox only ever sees each secret's `placeholder`; the local network
/// engine substitutes the real `value` into outbound requests bound for an
/// allowed host (and blocks/forwards per [`ViolationAction`] otherwise). Carried
/// in [`NetworkSpec::secrets`](NetworkSpec).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct SecretsConfig {
    /// List of secrets to inject.
    #[serde(default, alias = "secrets")]
    pub entries: Vec<SecretEntry>,

    /// Default action when a placeholder leaks to a disallowed host.
    #[serde(default)]
    pub on_violation: ViolationAction,
}

/// A single secret entry.
///
/// `value` is the sensitive material — it never enters the sandbox and is
/// redacted by the [`Debug`](fmt::Debug) impl.
#[derive(Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct SecretEntry {
    /// Environment variable name exposed to the sandbox (holds the placeholder).
    ///
    /// Must be non-empty and must not contain `=` or NUL. microsandbox does
    /// not require shell-identifier syntax because Linux environment entries
    /// only require a `NAME=value` shape.
    pub env_var: String,

    /// The actual secret value (never enters the sandbox).
    ///
    /// Empty when the entry carries a [`source`](Self::source) reference
    /// instead: reference-model entries resolve the value host-side at spawn
    /// time so the durable sandbox config never stores raw secret material.
    ///
    /// Wrapped in [`Zeroizing`] so the owned plaintext copy is wiped when the
    /// entry drops.
    #[serde(default = "empty_secret_value")]
    #[cfg_attr(feature = "ts", ts(type = "string"))]
    #[cfg_attr(feature = "utoipa", schema(value_type = String))]
    pub value: Zeroizing<String>,

    /// Host-side source reference resolved into [`value`](Self::value) at
    /// spawn time. `None` means `value` already carries the material (the
    /// inline model used by value-based secrets).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<SecretSource>,

    /// Placeholder string the sandbox sees instead of the real value.
    ///
    /// Must be non-empty, no longer than [`MAX_SECRET_PLACEHOLDER_BYTES`], and
    /// must not contain NUL, CR, or LF.
    pub placeholder: String,

    /// Hosts allowed to receive this secret.
    #[serde(default)]
    pub allowed_hosts: Vec<HostPattern>,

    /// Where the secret can be injected.
    #[serde(default)]
    pub injection: SecretInjection,

    /// Action on a violation for this secret (overrides the config default).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub on_violation: Option<ViolationAction>,

    /// Require verified TLS identity before substituting (default: true).
    ///
    /// When true, the secret is only substituted if the connection uses TLS
    /// interception (not bypass) and the SNI matches an allowed host.
    #[serde(default = "default_true")]
    pub require_tls_identity: bool,
}

/// Host pattern for a secret allowlist.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum HostPattern {
    /// Exact hostname match.
    #[serde(alias = "Exact")]
    Exact(String),
    /// Wildcard match (e.g., `*.openai.com`).
    #[serde(alias = "Wildcard")]
    Wildcard(String),
    /// Any host (dangerous — secret can be exfiltrated).
    #[serde(alias = "Any")]
    Any,
}

/// Where in the HTTP request a secret can be injected.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct SecretInjection {
    /// Substitute in HTTP headers (default: true).
    #[serde(default = "default_true")]
    pub headers: bool,

    /// Substitute in HTTP Basic Auth (default: true).
    #[serde(default = "default_true")]
    pub basic_auth: bool,

    /// Substitute in URL query parameters (default: false).
    #[serde(default)]
    pub query_params: bool,

    /// Substitute in request body (default: false).
    ///
    /// Fixed-length HTTP/1 bodies up to 16 MiB update `Content-Length`;
    /// larger fixed-length bodies are blocked. Chunked HTTP/1 bodies are
    /// decoded and re-encoded with fresh chunk sizes. Encoded bodies pass
    /// through unchanged. HTTP/2 DATA-frame body substitution is not
    /// supported; matching body placeholders are blocked.
    #[serde(default)]
    pub body: bool,
}

/// Action when a secret placeholder is detected going to a disallowed host.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum ViolationAction {
    /// Block the request silently.
    #[serde(alias = "Block")]
    Block,
    /// Block and log (default).
    #[default]
    #[serde(alias = "BlockAndLog", alias = "block-and-log")]
    BlockAndLog,
    /// Block and terminate the sandbox.
    #[serde(alias = "BlockAndTerminate", alias = "block-and-terminate")]
    BlockAndTerminate,
    /// Forward the request with the placeholder unchanged for matching hosts.
    #[serde(alias = "Passthrough")]
    Passthrough(Vec<HostPattern>),
}

/// Invalid secret configuration.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SecretConfigError {
    /// The environment variable name is empty.
    #[error("secret #{secret_index}: env_var must not be empty")]
    EmptyEnvVar {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },

    /// The environment variable name contains `=`.
    #[error("secret #{secret_index}: env_var must not contain `=`")]
    EnvVarContainsEquals {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },

    /// The environment variable name contains NUL.
    #[error("secret #{secret_index}: env_var must not contain NUL")]
    EnvVarContainsNul {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },

    /// No allowed hosts were configured for a secret.
    #[error("secret #{secret_index}: at least one allowed host is required")]
    MissingAllowedHosts {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },

    /// The placeholder is empty.
    #[error("secret #{secret_index}: placeholder must not be empty")]
    EmptyPlaceholder {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },

    /// The placeholder exceeds the supported byte length.
    #[error(
        "secret #{secret_index}: placeholder must be at most {max_bytes} bytes, got {actual_bytes}"
    )]
    PlaceholderTooLong {
        /// Index of the invalid secret entry.
        secret_index: usize,
        /// Actual placeholder length in bytes.
        actual_bytes: usize,
        /// Maximum supported placeholder length in bytes.
        max_bytes: usize,
    },

    /// The placeholder contains NUL.
    #[error("secret #{secret_index}: placeholder must not contain NUL")]
    PlaceholderContainsNul {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },

    /// The placeholder contains a line break.
    #[error("secret #{secret_index}: placeholder must not contain CR or LF")]
    PlaceholderContainsLineBreak {
        /// Index of the invalid secret entry.
        secret_index: usize,
    },
}

impl SecretsConfig {
    /// Validate all configured secret entries.
    pub fn validate(&self) -> Result<(), SecretConfigError> {
        for (index, secret) in self.entries.iter().enumerate() {
            secret.validate(index)?;
        }
        Ok(())
    }
}

impl SecretEntry {
    /// Validate this secret entry.
    pub fn validate(&self, secret_index: usize) -> Result<(), SecretConfigError> {
        validate_env_var(&self.env_var, secret_index)?;

        if self.allowed_hosts.is_empty() {
            return Err(SecretConfigError::MissingAllowedHosts { secret_index });
        }

        validate_placeholder(&self.placeholder, secret_index)
    }
}

// The secret value must never reach a log line or an error message.
impl fmt::Debug for SecretEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SecretEntry")
            .field("env_var", &self.env_var)
            .field("value", &"[REDACTED]")
            .field("source", &self.source)
            .field("placeholder", &self.placeholder)
            .field("allowed_hosts", &self.allowed_hosts)
            .field("injection", &self.injection)
            .field("on_violation", &self.on_violation)
            .field("require_tls_identity", &self.require_tls_identity)
            .finish()
    }
}

impl HostPattern {
    /// Parse a user-facing host string: `*` is any host, `*.`-prefixed
    /// strings are wildcards, everything else matches exactly.
    pub fn parse(host: &str) -> Self {
        if host == "*" {
            HostPattern::Any
        } else if host.starts_with("*.") {
            HostPattern::Wildcard(host.to_string())
        } else {
            HostPattern::Exact(host.to_string())
        }
    }

    /// Check if a hostname matches this pattern.
    ///
    /// Uses ASCII case-insensitive comparison to avoid `to_lowercase()`
    /// allocations (DNS hostnames are ASCII per RFC 4343).
    pub fn matches(&self, hostname: &str) -> bool {
        match self {
            HostPattern::Exact(h) => hostname.eq_ignore_ascii_case(h),
            HostPattern::Wildcard(pattern) => {
                if let Some(suffix) = pattern.strip_prefix("*.") {
                    hostname.eq_ignore_ascii_case(suffix)
                        || (hostname.len() > suffix.len() + 1
                            && hostname.as_bytes()[hostname.len() - suffix.len() - 1] == b'.'
                            && hostname[hostname.len() - suffix.len()..]
                                .eq_ignore_ascii_case(suffix))
                } else {
                    hostname.eq_ignore_ascii_case(pattern)
                }
            }
            HostPattern::Any => true,
        }
    }
}

impl Default for SecretInjection {
    fn default() -> Self {
        Self {
            headers: true,
            basic_auth: true,
            query_params: false,
            body: false,
        }
    }
}

fn default_true() -> bool {
    true
}

fn validate_env_var(env_var: &str, secret_index: usize) -> Result<(), SecretConfigError> {
    if env_var.is_empty() {
        return Err(SecretConfigError::EmptyEnvVar { secret_index });
    }
    if env_var.contains('=') {
        return Err(SecretConfigError::EnvVarContainsEquals { secret_index });
    }
    if env_var.contains('\0') {
        return Err(SecretConfigError::EnvVarContainsNul { secret_index });
    }
    Ok(())
}

fn validate_placeholder(placeholder: &str, secret_index: usize) -> Result<(), SecretConfigError> {
    if placeholder.is_empty() {
        return Err(SecretConfigError::EmptyPlaceholder { secret_index });
    }

    let actual_bytes = placeholder.len();
    if actual_bytes > MAX_SECRET_PLACEHOLDER_BYTES {
        return Err(SecretConfigError::PlaceholderTooLong {
            secret_index,
            actual_bytes,
            max_bytes: MAX_SECRET_PLACEHOLDER_BYTES,
        });
    }

    if placeholder.contains('\0') {
        return Err(SecretConfigError::PlaceholderContainsNul { secret_index });
    }
    if placeholder.contains('\r') || placeholder.contains('\n') {
        return Err(SecretConfigError::PlaceholderContainsLineBreak { secret_index });
    }

    Ok(())
}

//--------------------------------------------------------------------------------------------------
// Types: TLS interception
//--------------------------------------------------------------------------------------------------

/// TLS interception configuration. Carried in [`NetworkSpec::tls`](NetworkSpec).
///
/// The local network engine terminates TCP at its in-process stack, so TLS MITM
/// is handled by proxy tasks — these fields configure which ports/domains are
/// intercepted and how the interception CA is sourced.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct TlsConfig {
    /// Whether TLS interception is enabled.
    #[serde(default)]
    pub enabled: bool,

    /// TCP ports subject to TLS interception (default: `[443]`).
    #[serde(default = "default_intercepted_ports")]
    pub intercepted_ports: Vec<u16>,

    /// Domains to bypass (no MITM). Supports exact match and `*.suffix` wildcards.
    #[serde(default)]
    pub bypass: Vec<String>,

    /// Whether to verify the upstream server's TLS certificate.
    #[serde(default = "default_true")]
    pub verify_upstream: bool,

    /// Drop UDP to intercepted ports when TLS interception is active, forcing
    /// QUIC traffic to fall back to TCP/TLS.
    #[serde(default = "default_true")]
    pub block_quic_on_intercept: bool,

    /// CA certificate PEM files to trust for upstream server verification.
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Vec<String>))]
    #[cfg_attr(feature = "ts", ts(type = "Array<string>"))]
    pub upstream_ca_cert: Vec<PathBuf>,

    /// Host-scoped CA certificate PEM files to trust for upstream server verification.
    #[serde(default, alias = "scoped_upstream_ca_certs")]
    pub scoped_upstream_ca_cert: Vec<ScopedUpstreamCaCert>,

    /// Host-scoped upstream verification overrides.
    #[serde(default)]
    pub scoped_verify_upstream: Vec<ScopedVerifyUpstream>,

    /// Interception CA configuration. The TLS proxy uses this CA to sign
    /// per-domain certs it presents to the guest during interception.
    #[serde(default, alias = "ca")]
    pub intercept_ca: InterceptCaConfig,

    /// Per-domain certificate cache configuration.
    #[serde(default)]
    pub cache: CertCacheConfig,
}

/// Certificate authority configuration for TLS interception.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct InterceptCaConfig {
    /// Path to an existing CA certificate PEM file. If `None`, a CA is
    /// auto-generated and persisted.
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    #[cfg_attr(feature = "ts", ts(type = "string | null"))]
    pub cert_path: Option<PathBuf>,

    /// Path to an existing CA private key PEM file. If `None`, a key is
    /// auto-generated and persisted.
    #[serde(default)]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    #[cfg_attr(feature = "ts", ts(type = "string | null"))]
    pub key_path: Option<PathBuf>,
}

/// Per-domain certificate cache configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct CertCacheConfig {
    /// Maximum number of cached certificates. Default: 1000.
    #[serde(default = "default_cache_capacity")]
    pub capacity: usize,

    /// Certificate validity duration in hours. Default: 24.
    #[serde(default = "default_cert_validity_hours")]
    pub validity_hours: u64,
}

/// A CA certificate PEM file trusted only for matching upstream hosts.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct ScopedUpstreamCaCert {
    /// Host pattern this CA applies to. Supports exact hosts and `*.suffix` wildcards.
    pub pattern: String,

    /// Path to the CA certificate PEM file.
    #[cfg_attr(feature = "utoipa", schema(value_type = String))]
    #[cfg_attr(feature = "ts", ts(type = "string"))]
    pub path: PathBuf,
}

/// An upstream certificate verification override for matching hosts.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct ScopedVerifyUpstream {
    /// Host pattern this override applies to. Supports exact hosts and `*.suffix` wildcards.
    pub pattern: String,

    /// Whether to verify matching upstream server certificates.
    pub verify: bool,
}

impl Default for TlsConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            intercepted_ports: default_intercepted_ports(),
            bypass: Vec::new(),
            verify_upstream: true,
            block_quic_on_intercept: true,
            upstream_ca_cert: Vec::new(),
            scoped_upstream_ca_cert: Vec::new(),
            scoped_verify_upstream: Vec::new(),
            intercept_ca: InterceptCaConfig::default(),
            cache: CertCacheConfig::default(),
        }
    }
}

impl Default for CertCacheConfig {
    fn default() -> Self {
        Self {
            capacity: default_cache_capacity(),
            validity_hours: default_cert_validity_hours(),
        }
    }
}

fn default_intercepted_ports() -> Vec<u16> {
    vec![443]
}

fn default_cache_capacity() -> usize {
    1000
}

fn default_cert_validity_hours() -> u64 {
    24
}

//--------------------------------------------------------------------------------------------------
// Types: Networking — policy
//--------------------------------------------------------------------------------------------------

/// Action to take on traffic matched by a [`Rule`] (or a policy default).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "kebab-case")]
pub enum Action {
    /// Allow the traffic.
    Allow,
    /// Silently drop the traffic.
    Deny,
}

/// Direction a [`Rule`] applies to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "kebab-case")]
pub enum Direction {
    /// Outbound: guest → destination.
    Egress,
    /// Inbound: peer → guest.
    Ingress,
    /// Either direction.
    Any,
}

/// Protocol filter for a [`Rule`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "kebab-case")]
pub enum Protocol {
    /// TCP.
    Tcp,
    /// UDP.
    Udp,
    /// ICMPv4.
    Icmpv4,
    /// ICMPv6.
    Icmpv6,
}

/// Pre-defined destination category for a [`Destination::Group`] match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum DestinationGroup {
    /// Public internet — any address not in another category.
    Public,
    /// Loopback addresses (`127.0.0.0/8`, `::1`).
    Loopback,
    /// Private ranges (RFC 1918 / RFC 4193 ULA / CGN).
    Private,
    /// Link-local addresses, excluding the metadata IP.
    #[serde(alias = "link-local")]
    LinkLocal,
    /// Cloud metadata endpoint (`169.254.169.254`).
    Metadata,
    /// Multicast addresses (`224.0.0.0/4`, `ff00::/8`).
    Multicast,
    /// The sandbox host, reachable via the gateway IP.
    Host,
}

/// Traffic destination filter for a [`Rule`].
///
/// The `Cidr`, `Domain`, and `DomainSuffix` leaves carry their canonical
/// string form (e.g. `"10.0.0.0/8"`, `"example.com"`); the local network
/// engine re-parses and validates them into its richer internal types at
/// load time.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "snake_case")]
pub enum Destination {
    /// Match any destination.
    Any,
    /// IP address or CIDR block (e.g. `"1.2.3.4"`, `"10.0.0.0/8"`).
    #[cfg_attr(feature = "utoipa", schema(value_type = String))]
    Cidr(#[cfg_attr(feature = "ts", ts(type = "string"))] IpNetwork),
    /// Exact domain name (e.g. `"example.com"`).
    Domain(String),
    /// Domain suffix — the apex and any subdomain of it.
    #[serde(alias = "domain-suffix")]
    DomainSuffix(String),
    /// A pre-defined destination group.
    Group(DestinationGroup),
}

/// Inclusive guest-side port range for a [`Rule`] match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct PortRange {
    /// Start port (inclusive).
    pub start: u16,
    /// End port (inclusive).
    pub end: u16,
}

/// A single egress/ingress policy rule. Evaluated first-match-wins per
/// direction.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct Rule {
    /// Direction this rule applies to.
    pub direction: Direction,
    /// Destination filter (direction-dependent interpretation).
    pub destination: Destination,
    /// Protocol set; empty matches any protocol.
    #[serde(default)]
    pub protocols: Vec<Protocol>,
    /// Guest-side port-range set; empty matches any port.
    #[serde(default)]
    pub ports: Vec<PortRange>,
    /// Action to take on a match.
    pub action: Action,
}

/// Egress/ingress network policy: an ordered [`Rule`] list plus a
/// per-direction default [`Action`]. Carried in [`NetworkSpec::policy`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct NetworkPolicy {
    /// Default action for egress traffic matching no rule. Default: `Deny`.
    #[serde(default = "action_deny")]
    pub default_egress: Action,
    /// Default action for ingress traffic matching no rule. Default: `Deny`.
    #[serde(default = "action_deny")]
    pub default_ingress: Action,
    /// Ordered rules, evaluated first-match-wins per direction.
    #[serde(default)]
    pub rules: Vec<Rule>,
}

/// Default [`Action`] (`Deny`) for a policy's per-direction defaults, so a
/// partially-specified policy fails closed.
fn action_deny() -> Action {
    Action::Deny
}

//--------------------------------------------------------------------------------------------------
// Types: Networking — DNS & interface
//--------------------------------------------------------------------------------------------------

/// DNS interception and filtering settings. Carried in [`NetworkSpec::dns`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(default)]
pub struct DnsConfig {
    /// Whether DNS-rebinding protection is enabled. Default: true.
    pub rebind_protection: bool,
    /// Upstream nameservers as `IP`, `IP:PORT`, `HOST`, or `HOST:PORT`
    /// strings. Empty falls back to the host's `/etc/resolv.conf`.
    pub nameservers: Vec<String>,
    /// Per-query timeout in milliseconds. Default: 5000.
    pub query_timeout_ms: u64,
}

impl Default for DnsConfig {
    fn default() -> Self {
        Self {
            rebind_protection: true,
            nameservers: Vec::new(),
            query_timeout_ms: 5000,
        }
    }
}

/// Optional guest interface overrides. Unset fields are derived from the
/// sandbox slot by the local network engine. Carried in
/// [`NetworkSpec::interface`].
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(default)]
pub struct InterfaceOverrides {
    /// Guest MAC address as six octets. Default: derived from slot.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mac: Option<[u8; 6]>,
    /// Interface MTU. Default: 1500.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mtu: Option<u16>,
    /// Guest IPv4 address (e.g. `172.16.0.2`). Default: derived from slot.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    #[cfg_attr(feature = "ts", ts(type = "string | null"))]
    pub ipv4_address: Option<Ipv4Addr>,
    /// Guest IPv4 pool CIDR (e.g. `"172.16.0.0/12"`). Default: derived from slot.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    #[cfg_attr(feature = "ts", ts(type = "string | null"))]
    pub ipv4_pool: Option<Ipv4Network>,
    /// Guest IPv6 address. Default: derived from slot.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    #[cfg_attr(feature = "ts", ts(type = "string | null"))]
    pub ipv6_address: Option<Ipv6Addr>,
    /// Guest IPv6 pool CIDR. Default: derived from slot.
    #[serde(skip_serializing_if = "Option::is_none")]
    #[cfg_attr(feature = "utoipa", schema(value_type = Option<String>))]
    #[cfg_attr(feature = "ts", ts(type = "string | null"))]
    pub ipv6_pool: Option<Ipv6Network>,
}

//--------------------------------------------------------------------------------------------------
// Types: Networking — spec
//--------------------------------------------------------------------------------------------------

/// Complete network specification for a sandbox.
///
/// All subdocuments are typed. The local-engine `policy`, `dns`, and
/// `interface` configs are mirrored here as wire types whose leaf values
/// (CIDRs, domain names, nameservers) are carried in their canonical string
/// form; the network engine re-parses these into its richer internal types at
/// load time, which keeps that engine's validation crates out of this shared
/// contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(default)]
pub struct NetworkSpec {
    /// Whether networking is enabled for this sandbox.
    pub enabled: bool,

    /// Guest interface overrides for the local network engine.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interface: Option<InterfaceOverrides>,

    /// Host-to-guest port mappings.
    pub ports: Vec<PublishedPortSpec>,

    /// Egress and ingress policy.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<NetworkPolicy>,

    /// DNS interception and filtering.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dns: Option<DnsConfig>,

    /// TLS-interception subdocument (see [`TlsConfig`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls: Option<TlsConfig>,

    /// Placeholder-based secret-injection subdocument (see [`SecretsConfig`]).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secrets: Option<SecretsConfig>,

    /// Max concurrent guest connections.
    pub max_connections: Option<usize>,

    /// Whether to copy trusted host CAs into the guest at boot.
    pub trust_host_cas: bool,
}

/// A published port mapping between host and guest.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct PublishedPortSpec {
    /// Host-side port to bind.
    pub host_port: u16,

    /// Guest-side port to forward to.
    pub guest_port: u16,

    /// Transport protocol.
    #[serde(default)]
    pub protocol: PortProtocol,

    /// Host address to bind. Defaults to loopback.
    pub host_bind: String,
}

/// Transport protocol for a published port.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub enum PortProtocol {
    /// TCP.
    #[default]
    #[serde(rename = "tcp")]
    Tcp,

    /// UDP.
    #[serde(rename = "udp")]
    Udp,
}

//--------------------------------------------------------------------------------------------------
// Types: Init
//--------------------------------------------------------------------------------------------------

/// Fully-assembled handoff-init specification.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct HandoffInit {
    /// Init binary: absolute path inside the guest rootfs, or the literal `auto`.
    #[cfg_attr(feature = "utoipa", schema(value_type = String))]
    #[cfg_attr(feature = "ts", ts(type = "string"))]
    pub cmd: PathBuf,

    /// Supplemental argv. `argv[0]` is implicitly `cmd`.
    #[serde(default)]
    pub args: Vec<String>,

    /// Extra env vars merged on top of the inherited env.
    #[serde(default)]
    pub env: Vec<(String, String)>,
}

//--------------------------------------------------------------------------------------------------
// Types: Lifecycle
//--------------------------------------------------------------------------------------------------

/// Sandbox lifecycle policy.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct SandboxPolicy {
    /// Whether the sandbox is ephemeral.
    ///
    /// Ephemeral sandboxes are one-off: the host runtime that owns the
    /// process removes the persisted DB row and on-disk state when the VM
    /// reaches a terminal status, and other host runtimes opportunistically
    /// clean up ephemeral leftovers from runtimes that died before they
    /// could self-clean. Defaults to `false` (persistent); named and created
    /// sandboxes stay inspectable and restartable after they stop.
    #[serde(default)]
    pub ephemeral: bool,

    /// Hard cap on total sandbox lifetime in seconds. `None` = run forever.
    // typeshare rejects bare 64-bit ints (JS-unsafe); `U53` is its big-int
    // escape and the Go backend maps it to `uint64` — exact, since this crate's
    // typeshare output targets Go only.
    pub max_duration_secs: Option<u64>,

    /// Idle timeout in seconds. `None` = no idle detection.
    pub idle_timeout_secs: Option<u64>,
}

//--------------------------------------------------------------------------------------------------
// Types: Snapshots
//--------------------------------------------------------------------------------------------------

/// Where to place a new snapshot artifact.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SnapshotDestination {
    /// Bare name resolved under the default snapshots directory.
    #[serde(alias = "Name")]
    Name(String),

    /// Explicit absolute or relative path to the artifact directory.
    #[serde(alias = "Path")]
    Path(
        /// Destination path.
        PathBuf,
    ),
}

/// Inputs to create a snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SnapshotSpec {
    /// Name of the source sandbox. Must be stopped.
    pub source_sandbox: String,

    /// Where to write the artifact.
    pub destination: SnapshotDestination,

    /// User-supplied labels.
    pub labels: Vec<(String, String)>,

    /// Overwrite an existing artifact at the destination.
    pub force: bool,

    /// Compute and record upper-layer content integrity at creation time.
    pub record_integrity: bool,
}

//--------------------------------------------------------------------------------------------------
// Types: Sandbox Specs
//--------------------------------------------------------------------------------------------------

/// Backend-neutral sandbox task description.
///
/// This is the durable contract for fields that are already shared across backends. Local-only execution state such as resolved manifest digests, snapshot upper-layer paths, registry credentials, replace flags, and backend dispatch stays outside this type.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(default)]
pub struct SandboxSpec {
    /// Unique sandbox name.
    pub name: String,

    /// Root filesystem source.
    #[cfg_attr(feature = "utoipa", schema(value_type = Object))]
    pub image: RootfsSource,

    /// CPU and memory resources.
    pub resources: SandboxResources,

    /// Guest runtime options.
    pub runtime: SandboxRuntimeOptions,

    /// Environment variables visible to commands in the sandbox.
    pub env: Vec<EnvVar>,

    /// User-defined labels attached to the sandbox.
    pub labels: BTreeMap<String, String>,

    /// Sandbox-wide resource limits inherited by guest processes.
    pub rlimits: Vec<Rlimit>,

    /// Volume mounts.
    pub mounts: Vec<VolumeMount>,

    /// Rootfs patches applied before VM start.
    pub patches: Vec<Patch>,

    /// Network specification.
    pub network: NetworkSpec,

    /// Hand off PID 1 to a guest init binary after agentd setup.
    pub init: Option<HandoffInit>,

    /// Pull policy for OCI images.
    pub pull_policy: PullPolicy,

    /// In-guest security profile.
    pub security_profile: SecurityProfile,

    /// Sandbox lifecycle policy.
    pub lifecycle: SandboxPolicy,
}

/// CPU and memory resources for a sandbox.
#[derive(Debug, Clone, Copy, Serialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct SandboxResources {
    /// Number of virtual CPUs currently presented to the guest at boot.
    pub vcpus: u8,

    /// Guest memory currently presented to the guest at boot, in MiB.
    pub memory_mib: u32,

    /// Maximum virtual CPUs the sandbox may expose after boot-time hotplug support lands.
    pub max_vcpus: u8,

    /// Maximum guest memory the sandbox may expose after boot-time hotplug support lands, in MiB.
    pub max_memory_mib: u32,
}

/// Guest runtime options for a sandbox.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(default)]
pub struct SandboxRuntimeOptions {
    /// Working directory inside the guest.
    pub workdir: Option<String>,

    /// Default shell for scripts and interactive sessions.
    pub shell: Option<String>,

    /// Named scripts available inside the guest.
    // typeshare doesn't recognize `BTreeMap`; serialize as a map for codegen
    // (identical JSON object shape) → Go `map[string]string`.
    pub scripts: BTreeMap<String, String>,

    /// Image entrypoint override.
    pub entrypoint: Option<Vec<String>>,

    /// Image command override.
    pub cmd: Option<Vec<String>>,

    /// Guest hostname override.
    pub hostname: Option<String>,

    /// Guest user identity override.
    pub user: Option<String>,

    /// Runtime log verbosity.
    pub log_level: Option<SandboxLogLevel>,

    /// Metrics sampling interval in milliseconds. `None` disables sampling.
    pub metrics_sample_interval_ms: Option<u64>,

    /// Force-disable metrics sampling regardless of `metrics_sample_interval_ms`.
    pub disable_metrics_sample: bool,
}

/// Environment variable entry.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct EnvVar {
    /// Environment variable name.
    pub key: String,

    /// Environment variable value.
    pub value: String,
}

/// Runtime log verbosity for sandbox specs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
pub enum SandboxLogLevel {
    /// Emit only error logs.
    Error,

    /// Emit warning and error logs.
    Warn,

    /// Emit info, warning, and error logs.
    Info,

    /// Emit debug and higher-severity logs.
    Debug,

    /// Emit trace and higher-severity logs.
    Trace,
}

//--------------------------------------------------------------------------------------------------
// Types: Exec
//--------------------------------------------------------------------------------------------------

/// POSIX resource limit identifiers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
#[serde(rename_all = "lowercase")]
pub enum RlimitResource {
    /// Max CPU time in seconds (`RLIMIT_CPU`).
    #[serde(alias = "Cpu")]
    Cpu,
    /// Max file size in bytes (`RLIMIT_FSIZE`).
    #[serde(alias = "Fsize")]
    Fsize,
    /// Max data segment size (`RLIMIT_DATA`).
    #[serde(alias = "Data")]
    Data,
    /// Max stack size (`RLIMIT_STACK`).
    #[serde(alias = "Stack")]
    Stack,
    /// Max core file size (`RLIMIT_CORE`).
    #[serde(alias = "Core")]
    Core,
    /// Max resident set size (`RLIMIT_RSS`).
    #[serde(alias = "Rss")]
    Rss,
    /// Max number of processes (`RLIMIT_NPROC`).
    #[serde(alias = "Nproc")]
    Nproc,
    /// Max open file descriptors (`RLIMIT_NOFILE`).
    #[serde(alias = "Nofile")]
    Nofile,
    /// Max locked memory (`RLIMIT_MEMLOCK`).
    #[serde(alias = "Memlock")]
    Memlock,
    /// Max address space size (`RLIMIT_AS`).
    #[serde(alias = "As")]
    As,
    /// Max file locks (`RLIMIT_LOCKS`).
    #[serde(alias = "Locks")]
    Locks,
    /// Max pending signals (`RLIMIT_SIGPENDING`).
    #[serde(alias = "Sigpending")]
    Sigpending,
    /// Max bytes in POSIX message queues (`RLIMIT_MSGQUEUE`).
    #[serde(alias = "Msgqueue")]
    Msgqueue,
    /// Max nice priority (`RLIMIT_NICE`).
    #[serde(alias = "Nice")]
    Nice,
    /// Max real-time priority (`RLIMIT_RTPRIO`).
    #[serde(alias = "Rtprio")]
    Rtprio,
    /// Max real-time timeout (`RLIMIT_RTTIME`).
    #[serde(alias = "Rttime")]
    Rttime,
}

/// A POSIX resource limit.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
pub struct Rlimit {
    /// Resource type.
    pub resource: RlimitResource,

    /// Soft limit (can be raised up to hard limit by the process).
    pub soft: u64,

    /// Hard limit (ceiling, requires privileges to raise).
    pub hard: u64,
}

//--------------------------------------------------------------------------------------------------
// Types: Logs
//--------------------------------------------------------------------------------------------------

/// Source tag on a captured log entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde(rename_all = "lowercase")]
pub enum LogSource {
    /// Captured from a session's stdout (pipe mode).
    Stdout,

    /// Captured from a session's stderr (pipe mode).
    Stderr,

    /// Captured from a session in pty mode (stdout + stderr merged at the kernel level inside the guest arrive as a single stream tagged `output`).
    Output,

    /// Synthetic system entry: lifecycle markers, runtime diagnostics, kernel console output.
    System,
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl DiskImageFormat {
    /// Returns the format as a CLI-safe lowercase string.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Qcow2 => "qcow2",
            Self::Raw => "raw",
            Self::Vmdk => "vmdk",
        }
    }

    /// Parse a disk image format from a file extension.
    ///
    /// Returns `None` if the extension is not a recognized disk image format.
    pub fn from_extension(ext: &str) -> Option<Self> {
        match ext {
            "qcow2" => Some(Self::Qcow2),
            "raw" => Some(Self::Raw),
            "vmdk" => Some(Self::Vmdk),
            _ => None,
        }
    }
}

impl OciRootfsSource {
    /// Create a new OCI rootfs source.
    pub fn new(reference: impl Into<String>) -> Self {
        Self {
            reference: reference.into(),
            upper_size_mib: None,
        }
    }
}

impl RootfsSource {
    /// Create an OCI rootfs source from an image reference.
    pub fn oci(reference: impl Into<String>) -> Self {
        Self::Oci(OciRootfsSource::new(reference))
    }

    /// Return the OCI image reference if this is an OCI rootfs.
    pub fn oci_reference(&self) -> Option<&str> {
        match self {
            Self::Oci(oci) => Some(&oci.reference),
            _ => None,
        }
    }

    /// Return the writable-overlay upper size in MiB for an OCI rootfs, if set.
    pub fn oci_upper_size_mib(&self) -> Option<u32> {
        match self {
            Self::Oci(oci) => oci.upper_size_mib,
            _ => None,
        }
    }
}

impl EnvVar {
    /// Create an environment variable entry.
    pub fn new(key: impl Into<String>, value: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            value: value.into(),
        }
    }

    /// Return this entry as key and value string slices.
    pub fn as_pair(&self) -> (&str, &str) {
        (&self.key, &self.value)
    }
}

impl VolumeKind {
    /// Return the lowercase database and CLI representation.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Directory => "dir",
            Self::Disk => "disk",
        }
    }

    /// Parse a persisted database value, defaulting to directory for unknown values.
    pub fn from_db_value(value: &str) -> Self {
        match value {
            "disk" => Self::Disk,
            _ => Self::Directory,
        }
    }
}

impl VolumeSpec {
    /// Create a directory-backed volume spec with default options.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            kind: VolumeKind::Directory,
            quota_mib: None,
            capacity_mib: None,
            labels: Vec::new(),
        }
    }
}

impl NamedVolumeCreate {
    /// Creation behavior for this named volume mount.
    pub fn mode(&self) -> NamedVolumeMode {
        self.mode
    }

    /// Volume name to create or ensure exists.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Storage kind to create or ensure exists.
    pub fn kind(&self) -> VolumeKind {
        self.kind
    }

    /// Directory quota in MiB, if configured.
    pub fn quota_mib(&self) -> Option<u32> {
        self.quota_mib
    }

    /// Disk capacity in MiB, if configured.
    pub fn capacity_mib(&self) -> Option<u32> {
        self.capacity_mib
    }

    /// Labels to attach to newly-created volumes.
    pub fn labels(&self) -> &[(String, String)] {
        &self.labels
    }
}

impl VolumeMount {
    /// The absolute path where this mount appears inside the guest.
    pub fn guest(&self) -> &str {
        match self {
            Self::Bind { guest, .. }
            | Self::Named { guest, .. }
            | Self::Tmpfs { guest, .. }
            | Self::DiskImage { guest, .. } => guest,
        }
    }

    /// Return named-volume creation metadata when this mount provisions a named volume.
    pub fn named_create(&self) -> Option<&NamedVolumeCreate> {
        match self {
            Self::Named { create, .. } => create.as_ref(),
            _ => None,
        }
    }
}

impl RlimitResource {
    /// Returns the lowercase string representation used on the wire.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Cpu => "cpu",
            Self::Fsize => "fsize",
            Self::Data => "data",
            Self::Stack => "stack",
            Self::Core => "core",
            Self::Rss => "rss",
            Self::Nproc => "nproc",
            Self::Nofile => "nofile",
            Self::Memlock => "memlock",
            Self::As => "as",
            Self::Locks => "locks",
            Self::Sigpending => "sigpending",
            Self::Msgqueue => "msgqueue",
            Self::Nice => "nice",
            Self::Rtprio => "rtprio",
            Self::Rttime => "rttime",
        }
    }
}

impl LogSource {
    /// Apply the empty-means-default rule used by log readers.
    pub fn effective(requested: &[Self]) -> Vec<Self> {
        if requested.is_empty() {
            vec![Self::Stdout, Self::Stderr, Self::Output]
        } else {
            let mut sources = requested.to_vec();
            sources.sort_by_key(|src| match src {
                Self::Stdout => 0,
                Self::Stderr => 1,
                Self::Output => 2,
                Self::System => 3,
            });
            sources.dedup();
            sources
        }
    }
}

impl SandboxLogLevel {
    /// Return the lowercase string representation for this level.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warn => "warn",
            Self::Info => "info",
            Self::Debug => "debug",
            Self::Trace => "trace",
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl std::fmt::Display for DiskImageFormat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for DiskImageFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "qcow2" => Ok(Self::Qcow2),
            "raw" => Ok(Self::Raw),
            "vmdk" => Ok(Self::Vmdk),
            _ => Err(format!("unknown disk image format: {s}")),
        }
    }
}

impl Default for RootfsSource {
    fn default() -> Self {
        Self::oci(String::new())
    }
}

impl Default for SandboxResources {
    fn default() -> Self {
        Self {
            vcpus: DEFAULT_SANDBOX_VCPUS,
            memory_mib: DEFAULT_SANDBOX_MEMORY_MIB,
            max_vcpus: DEFAULT_SANDBOX_VCPUS,
            max_memory_mib: DEFAULT_SANDBOX_MEMORY_MIB,
        }
    }
}

impl<'de> Deserialize<'de> for SandboxResources {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct RawResources {
            #[serde(default = "default_sandbox_vcpus")]
            vcpus: u8,
            #[serde(default = "default_sandbox_memory_mib")]
            memory_mib: u32,
            max_vcpus: Option<u8>,
            max_memory_mib: Option<u32>,
        }

        let raw = RawResources::deserialize(deserializer)?;
        Ok(Self {
            vcpus: raw.vcpus,
            memory_mib: raw.memory_mib,
            // Legacy configs predate boot-capacity fields. Treat their effective
            // resources as their maximum capacity so old sandboxes do not
            // deserialize into an impossible vcpus > max_vcpus state.
            max_vcpus: raw.max_vcpus.unwrap_or(raw.vcpus),
            max_memory_mib: raw.max_memory_mib.unwrap_or(raw.memory_mib),
        })
    }
}

impl Default for SandboxRuntimeOptions {
    fn default() -> Self {
        Self {
            workdir: None,
            shell: None,
            scripts: BTreeMap::new(),
            entrypoint: None,
            cmd: None,
            hostname: None,
            user: None,
            log_level: None,
            metrics_sample_interval_ms: Some(DEFAULT_METRICS_SAMPLE_INTERVAL_MS),
            disable_metrics_sample: false,
        }
    }
}

impl Default for NetworkSpec {
    fn default() -> Self {
        Self {
            enabled: true,
            interface: None,
            ports: Vec::new(),
            policy: None,
            dns: None,
            tls: None,
            secrets: None,
            max_connections: None,
            trust_host_cas: false,
        }
    }
}

impl Default for PublishedPortSpec {
    fn default() -> Self {
        Self {
            host_port: 0,
            guest_port: 0,
            protocol: PortProtocol::Tcp,
            host_bind: "127.0.0.1".into(),
        }
    }
}

impl From<(String, String)> for EnvVar {
    fn from((key, value): (String, String)) -> Self {
        Self { key, value }
    }
}

impl From<EnvVar> for (String, String) {
    fn from(var: EnvVar) -> Self {
        (var.key, var.value)
    }
}

impl FromStr for SandboxLogLevel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "error" => Ok(Self::Error),
            "warn" => Ok(Self::Warn),
            "info" => Ok(Self::Info),
            "debug" => Ok(Self::Debug),
            "trace" => Ok(Self::Trace),
            _ => Err(format!("unknown sandbox log level: {s}")),
        }
    }
}

/// Case-insensitive string to [`RlimitResource`] conversion.
impl TryFrom<&str> for RlimitResource {
    type Error = String;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match s.to_ascii_lowercase().as_str() {
            "cpu" => Ok(Self::Cpu),
            "fsize" => Ok(Self::Fsize),
            "data" => Ok(Self::Data),
            "stack" => Ok(Self::Stack),
            "core" => Ok(Self::Core),
            "rss" => Ok(Self::Rss),
            "nproc" => Ok(Self::Nproc),
            "nofile" => Ok(Self::Nofile),
            "memlock" => Ok(Self::Memlock),
            "as" => Ok(Self::As),
            "locks" => Ok(Self::Locks),
            "sigpending" => Ok(Self::Sigpending),
            "msgqueue" => Ok(Self::Msgqueue),
            "nice" => Ok(Self::Nice),
            "rtprio" => Ok(Self::Rtprio),
            "rttime" => Ok(Self::Rttime),
            _ => Err(format!("unknown rlimit resource: {s}")),
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

fn default_sandbox_vcpus() -> u8 {
    DEFAULT_SANDBOX_VCPUS
}

fn default_sandbox_memory_mib() -> u32 {
    DEFAULT_SANDBOX_MEMORY_MIB
}

fn empty_secret_value() -> Zeroizing<String> {
    Zeroizing::new(String::new())
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn casing_is_canonical_with_legacy_aliases() {
        // RlimitResource: canonical lowercase; legacy PascalCase still deserializes.
        assert_eq!(
            serde_json::to_string(&RlimitResource::Nofile).unwrap(),
            r#""nofile""#
        );
        assert_eq!(
            serde_json::from_str::<RlimitResource>(r#""Nofile""#).unwrap(),
            RlimitResource::Nofile
        );

        // SnapshotDestination: canonical lowercase tag; legacy PascalCase accepted.
        assert_eq!(
            serde_json::to_string(&SnapshotDestination::Name("snap".into())).unwrap(),
            r#"{"name":"snap"}"#
        );
        assert!(matches!(
            serde_json::from_str::<SnapshotDestination>(r#"{"Name":"snap"}"#).unwrap(),
            SnapshotDestination::Name(_)
        ));
        assert!(matches!(
            serde_json::from_str::<SnapshotDestination>(r#"{"path":"/tmp/x"}"#).unwrap(),
            SnapshotDestination::Path(_)
        ));
    }

    #[test]
    fn disk_image_format_from_extension() {
        assert_eq!(
            DiskImageFormat::from_extension("qcow2"),
            Some(DiskImageFormat::Qcow2)
        );
        assert_eq!(
            DiskImageFormat::from_extension("raw"),
            Some(DiskImageFormat::Raw)
        );
        assert_eq!(
            DiskImageFormat::from_extension("vmdk"),
            Some(DiskImageFormat::Vmdk)
        );
        assert_eq!(DiskImageFormat::from_extension("ext4"), None);
        assert_eq!(DiskImageFormat::from_extension(""), None);
    }

    #[test]
    fn sandbox_resources_deserialize_legacy_capacity_from_effective_values() {
        let resources: SandboxResources =
            serde_json::from_str(r#"{"vcpus":4,"memory_mib":2048}"#).unwrap();

        assert_eq!(resources.vcpus, 4);
        assert_eq!(resources.max_vcpus, 4);
        assert_eq!(resources.memory_mib, 2048);
        assert_eq!(resources.max_memory_mib, 2048);
    }

    #[test]
    fn disk_image_format_display_roundtrip() {
        for format in [
            DiskImageFormat::Qcow2,
            DiskImageFormat::Raw,
            DiskImageFormat::Vmdk,
        ] {
            let rendered = format.to_string();
            let parsed: DiskImageFormat = rendered.parse().unwrap();
            assert_eq!(parsed, format);
        }
    }

    #[test]
    fn disk_image_format_from_str_unknown() {
        assert!("ext4".parse::<DiskImageFormat>().is_err());
    }

    #[test]
    fn log_source_effective_uses_default_user_program_sources() {
        assert_eq!(
            LogSource::effective(&[]),
            vec![LogSource::Stdout, LogSource::Stderr, LogSource::Output]
        );
    }

    #[test]
    fn log_source_effective_sorts_and_deduplicates_requested_sources() {
        assert_eq!(
            LogSource::effective(&[LogSource::System, LogSource::Stdout, LogSource::System]),
            vec![LogSource::Stdout, LogSource::System]
        );
    }

    #[test]
    fn rlimit_resource_parses_case_insensitively() {
        assert_eq!(
            RlimitResource::try_from("NOFILE").unwrap(),
            RlimitResource::Nofile
        );
        assert!(RlimitResource::try_from("bogus").is_err());
    }

    #[test]
    fn sandbox_policy_serde_roundtrip() {
        let policy = SandboxPolicy {
            ephemeral: true,
            max_duration_secs: Some(3600),
            idle_timeout_secs: Some(120),
        };

        let json = serde_json::to_string(&policy).unwrap();
        let decoded: SandboxPolicy = serde_json::from_str(&json).unwrap();

        assert!(decoded.ephemeral);
        assert_eq!(decoded.max_duration_secs, Some(3600));
        assert_eq!(decoded.idle_timeout_secs, Some(120));
    }

    #[test]
    fn sandbox_policy_defaults_to_persistent() {
        assert!(!SandboxPolicy::default().ephemeral);
    }

    #[test]
    fn sandbox_policy_deserializes_missing_ephemeral_as_persistent() {
        // `ephemeral` has a persistent default so partial policy payloads
        // deserialize to the conservative behavior.
        let decoded: SandboxPolicy =
            serde_json::from_str(r#"{"max_duration_secs":60,"idle_timeout_secs":null}"#).unwrap();
        assert!(!decoded.ephemeral);
        assert_eq!(decoded.max_duration_secs, Some(60));
    }

    #[test]
    fn sandbox_spec_default_uses_static_resource_defaults() {
        let spec = SandboxSpec::default();

        assert_eq!(spec.resources.vcpus, DEFAULT_SANDBOX_VCPUS);
        assert_eq!(spec.resources.memory_mib, DEFAULT_SANDBOX_MEMORY_MIB);
        assert_eq!(
            spec.runtime.metrics_sample_interval_ms,
            Some(DEFAULT_METRICS_SAMPLE_INTERVAL_MS)
        );
    }

    #[test]
    fn sandbox_log_level_roundtrips_lowercase_values() {
        for (input, expected) in [
            ("error", SandboxLogLevel::Error),
            ("warn", SandboxLogLevel::Warn),
            ("info", SandboxLogLevel::Info),
            ("debug", SandboxLogLevel::Debug),
            ("trace", SandboxLogLevel::Trace),
        ] {
            let parsed: SandboxLogLevel = input.parse().unwrap();
            assert_eq!(parsed, expected);
            assert_eq!(parsed.as_str(), input);
        }
    }
}

#[cfg(test)]
mod secret_tests {
    use super::*;

    fn valid_secret() -> SecretEntry {
        SecretEntry {
            env_var: "API_KEY".into(),
            value: "secret".to_string().into(),
            source: None,
            placeholder: "$MSB_API_KEY".into(),
            allowed_hosts: vec![HostPattern::Exact("api.example.com".into())],
            injection: SecretInjection::default(),
            on_violation: None,
            require_tls_identity: true,
        }
    }

    #[test]
    fn exact_host_match() {
        let p = HostPattern::Exact("api.openai.com".into());
        assert!(p.matches("api.openai.com"));
        assert!(p.matches("API.OpenAI.com"));
        assert!(!p.matches("evil.com"));
    }

    #[test]
    fn wildcard_host_match() {
        let p = HostPattern::Wildcard("*.openai.com".into());
        assert!(p.matches("api.openai.com"));
        assert!(p.matches("openai.com"));
        assert!(!p.matches("evil.com"));
    }

    #[test]
    fn any_host_match() {
        assert!(HostPattern::Any.matches("anything.com"));
    }

    #[test]
    fn default_injection_scopes() {
        let inj = SecretInjection::default();
        assert!(inj.headers);
        assert!(inj.basic_auth);
        assert!(!inj.query_params);
        assert!(!inj.body);
    }

    #[test]
    fn default_require_tls_identity_when_deserialized() {
        let entry: SecretEntry = serde_json::from_str(
            r#"{"env_var":"K","value":"v","placeholder":"$K","allowed_hosts":[{"exact":"h"}]}"#,
        )
        .unwrap();
        assert!(entry.require_tls_identity);
    }

    #[test]
    fn secret_validation_accepts_linux_environment_name_shape() {
        let mut entry = valid_secret();
        entry.env_var = "1TOKEN.with-dashes".into();
        assert!(entry.validate(0).is_ok());
    }

    #[test]
    fn secret_validation_rejects_invalid_env_var_names() {
        let cases = [
            ("", SecretConfigError::EmptyEnvVar { secret_index: 0 }),
            (
                "API=KEY",
                SecretConfigError::EnvVarContainsEquals { secret_index: 0 },
            ),
            (
                "API\0KEY",
                SecretConfigError::EnvVarContainsNul { secret_index: 0 },
            ),
        ];
        for (env_var, expected) in cases {
            let mut entry = valid_secret();
            entry.env_var = env_var.into();
            assert_eq!(entry.validate(0), Err(expected));
        }
    }

    #[test]
    fn secret_validation_rejects_missing_allowed_hosts() {
        let mut entry = valid_secret();
        entry.allowed_hosts.clear();
        assert_eq!(
            entry.validate(0),
            Err(SecretConfigError::MissingAllowedHosts { secret_index: 0 })
        );
    }

    #[test]
    fn secret_validation_rejects_invalid_placeholders() {
        let too_long = "x".repeat(MAX_SECRET_PLACEHOLDER_BYTES + 1);
        let cases = [
            ("", SecretConfigError::EmptyPlaceholder { secret_index: 0 }),
            (
                too_long.as_str(),
                SecretConfigError::PlaceholderTooLong {
                    secret_index: 0,
                    actual_bytes: MAX_SECRET_PLACEHOLDER_BYTES + 1,
                    max_bytes: MAX_SECRET_PLACEHOLDER_BYTES,
                },
            ),
            (
                "abc\0def",
                SecretConfigError::PlaceholderContainsNul { secret_index: 0 },
            ),
            (
                "abc\rdef",
                SecretConfigError::PlaceholderContainsLineBreak { secret_index: 0 },
            ),
            (
                "abc\ndef",
                SecretConfigError::PlaceholderContainsLineBreak { secret_index: 0 },
            ),
        ];
        for (placeholder, expected) in cases {
            let mut entry = valid_secret();
            entry.placeholder = placeholder.into();
            assert_eq!(entry.validate(0), Err(expected));
        }
    }

    #[test]
    fn violation_action_serializes_with_sdk_casing() {
        let action = ViolationAction::Passthrough(vec![
            HostPattern::Exact("api.anthropic.com".into()),
            HostPattern::Wildcard("*.anthropic.com".into()),
            HostPattern::Any,
        ]);
        assert_eq!(
            serde_json::to_string(&action).unwrap(),
            r#"{"passthrough":[{"exact":"api.anthropic.com"},{"wildcard":"*.anthropic.com"},"any"]}"#
        );
        assert_eq!(
            serde_json::to_string(&ViolationAction::BlockAndLog).unwrap(),
            r#""block_and_log""#
        );
        assert_eq!(
            serde_json::to_string(&ViolationAction::BlockAndTerminate).unwrap(),
            r#""block_and_terminate""#
        );
    }

    #[test]
    fn violation_action_accepts_legacy_pascal_case() {
        let action: ViolationAction =
            serde_json::from_str(r#"{"Passthrough":[{"Exact":"api.anthropic.com"}]}"#).unwrap();
        assert_eq!(
            action,
            ViolationAction::Passthrough(vec![HostPattern::Exact("api.anthropic.com".into())])
        );
        assert_eq!(
            serde_json::from_str::<ViolationAction>(r#""BlockAndTerminate""#).unwrap(),
            ViolationAction::BlockAndTerminate
        );
    }

    #[test]
    fn secret_entry_debug_redacts_value() {
        let mut entry = valid_secret();
        entry.value = "uniq-sensitive-12345".to_string().into();
        let dbg = format!("{entry:?}");
        assert!(dbg.contains("[REDACTED]"));
        assert!(!dbg.contains("uniq-sensitive-12345"));
    }
}

#[cfg(test)]
mod tls_tests {
    use super::*;

    #[test]
    fn tls_config_defaults() {
        let t = TlsConfig::default();
        assert!(!t.enabled);
        assert_eq!(t.intercepted_ports, vec![443]);
        assert!(t.verify_upstream);
        assert!(t.block_quic_on_intercept);
        assert_eq!(t.cache.capacity, 1000);
        assert_eq!(t.cache.validity_hours, 24);
    }

    #[test]
    fn tls_config_round_trips_and_accepts_ca_alias() {
        // `ca` is an accepted alias for `intercept_ca`.
        let cfg: TlsConfig = serde_json::from_str(
            r#"{"enabled":true,"bypass":["*.internal"],"ca":{"cert_path":"/etc/ca.pem"}}"#,
        )
        .unwrap();
        assert!(cfg.enabled);
        assert_eq!(cfg.bypass, vec!["*.internal".to_string()]);
        assert_eq!(
            cfg.intercept_ca.cert_path.as_deref(),
            Some(std::path::Path::new("/etc/ca.pem"))
        );
        let back: TlsConfig = serde_json::from_str(&serde_json::to_string(&cfg).unwrap()).unwrap();
        assert_eq!(back.bypass, cfg.bypass);
    }
}