microsandbox 0.5.4

`microsandbox` is the core library for the microsandbox project.
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
//! Types for sandbox configuration.
//!
//! These types are referenced by [`SandboxConfig`](super::SandboxConfig).

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::size::Mebibytes;

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Disk image format for virtio-blk rootfs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DiskImageFormat {
    /// QEMU Copy-on-Write v2.
    Qcow2,
    /// Raw disk image.
    Raw,
    /// VMware Disk (FLAT/ZERO only, no delta links).
    Vmdk,
}

/// Root filesystem source for a sandbox.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RootfsSource {
    /// Use a host directory directly as the root filesystem.
    Bind(PathBuf),

    /// Use an OCI image reference with an EROFS lower and ext4 overlay upper.
    Oci(OciRootfsSource),

    /// Use a disk image file as the root filesystem via virtio-blk.
    DiskImage {
        /// Path to the disk image file on the host.
        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)]
pub struct OciRootfsSource {
    /// OCI image reference (e.g. `python`).
    pub reference: String,

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

/// Intermediate type for parsing user input into a [`RootfsSource`].
///
/// Accepts `&str`, `String`, or `PathBuf` and resolves to the correct
/// [`RootfsSource`] variant:
///
/// - **`PathBuf`** → always local (bind mount or disk image based on extension).
/// - **`&str` / `String`** → local path if `.`, `..`, or prefixed with `/`,
///   `./`, or `../`; otherwise [`RootfsSource::Oci`].
///
/// Disk image extensions (`.qcow2`, `.raw`, `.vmdk`) resolve to
/// [`RootfsSource::DiskImage`].
pub enum ImageSource {
    /// A string that needs to be resolved.
    Text(String),

    /// An explicit path (always local).
    Path(PathBuf),
}

/// Builder for configuring an image rootfs.
///
/// Used with [`crate::sandbox::SandboxBuilder::image_with`]:
///
/// ```ignore
/// .image_with(|i| i.oci("python:3.12").upper_size(8.gib()))
/// .image_with(|i| i.disk("./ubuntu.qcow2").fstype("ext4"))
/// ```
#[derive(Default)]
pub struct ImageBuilder {
    source: Option<RootfsSource>,
    error: Option<crate::MicrosandboxError>,
}

/// Trait for types that can be passed to [`crate::sandbox::SandboxBuilder::image`].
///
/// Implemented for:
/// - `&str`, `String`, `PathBuf` — resolved via [`ImageSource`].
/// - `FnOnce(ImageBuilder) -> ImageBuilder` — closure-based image configuration.
pub trait IntoImage {
    /// Resolve this value into a concrete root filesystem source.
    fn into_rootfs_source(self) -> crate::MicrosandboxResult<RootfsSource>;
}

/// Stat virtualization policy for a virtiofs-backed volume mount.
///
/// Mirrors `microsandbox_filesystem::StatVirtualization`. See
/// `design/filesystems/stat-virtualization.md` for the threat model.
///
/// 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)]
#[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.
///
/// Mirrors `microsandbox_filesystem::HostPermissions`.
///
/// 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)]
#[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,
}

/// Guest mount behavior shared by every volume mount kind.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[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. Guest volume mounts always also use internal
    /// `nosuid` and `nodev` safety defaults.
    pub noexec: bool,
}

/// A volume mount specification for a sandbox.
#[derive(Clone)]
pub enum VolumeMount {
    /// Bind mount a host directory into the guest.
    Bind {
        /// Host path to bind mount.
        host: PathBuf,
        /// Guest mount path.
        guest: String,
        /// Guest mount behavior.
        options: MountOptions,
        /// Guest-visible stat virtualization policy.
        stat_virtualization: StatVirtualization,
        /// Host permission propagation policy.
        host_permissions: HostPermissions,
    },

    /// Mount a named volume into the guest.
    Named {
        /// Volume name.
        name: String,
        /// Guest mount path.
        guest: String,
        /// Guest mount behavior.
        options: MountOptions,
        /// Guest-visible stat virtualization policy.
        stat_virtualization: StatVirtualization,
        /// Host permission propagation policy.
        host_permissions: HostPermissions,
    },

    /// Temporary filesystem (memory-backed).
    Tmpfs {
        /// Guest mount path.
        guest: String,
        /// Size limit in MiB.
        size_mib: Option<u32>,
        /// Guest mount behavior.
        options: MountOptions,
    },

    /// Mount a disk image file as a virtio-blk device at a guest path.
    ///
    /// The guest OS owns the inner filesystem; microsandbox just attaches
    /// the image and agentd mounts it. Use this for persistent state that
    /// should be isolated from the host filesystem, for distributing
    /// pre-built ext4/squashfs datasets, or for read-only seed volumes.
    DiskImage {
        /// Host path to the disk image file.
        host: PathBuf,
        /// Guest mount path.
        guest: String,
        /// Disk image format (qcow2 / raw / vmdk).
        format: DiskImageFormat,
        /// Inner filesystem type. When `None`, agentd probes `/proc/filesystems`.
        fstype: Option<String>,
        /// Guest mount behavior.
        options: MountOptions,
    },
}

/// Builder for constructing a [`VolumeMount`].
pub struct MountBuilder {
    guest: String,
    mount: MountKind,
    options: MountOptions,
    size_mib: Option<u32>,
    disk_format: Option<DiskImageFormat>,
    disk_fstype: Option<String>,
    stat_virtualization: Option<StatVirtualization>,
    host_permissions: Option<HostPermissions>,
    error: Option<crate::MicrosandboxError>,
}

/// Internal kind for the mount builder.
enum MountKind {
    Bind(PathBuf),
    Named(String),
    Tmpfs,
    Disk(PathBuf),
    Unset,
}

/// Rootfs patch applied before VM startup.
///
/// How patches are applied depends on the root filesystem type:
/// - **OCI images (EROFS + ext4 overlay):** Patches are baked into `upper.ext4` under
///   the overlayfs `upperdir` so the shared EROFS lower layers remain untouched.
/// - **Bind/Passthrough roots:** Patches are applied directly to the host directory.
/// - **Block device roots (Qcow2, Raw):** Patches are not supported. Returns an error at
///   create time.
///
/// By default, patches that target a path already present in the rootfs (the visible lower
/// overlay view for OCI, existing files for bind roots) will return an error. Set `replace: true` on
/// the relevant variant to allow shadowing existing files.
///
/// For `Append` patches targeting a file in a lower layer, the file is first copied up to
/// the writable overlay layer before appending.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Patch {
    /// Write text content to a file.
    Text {
        /// Absolute guest path (e.g., `/etc/app.conf`).
        path: String,
        /// Text content to write.
        content: String,
        /// File permissions (e.g., `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.
    File {
        /// Absolute guest path.
        path: String,
        /// Raw byte content to write.
        content: Vec<u8>,
        /// File permissions (e.g., `0o644`). `None` uses the default.
        mode: Option<u32>,
        /// Allow replacing a file that already exists in the rootfs.
        replace: bool,
    },
    /// Copy a file from host into the rootfs.
    CopyFile {
        /// Host path to copy from.
        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 host into the rootfs.
    CopyDir {
        /// Host directory to copy from.
        src: PathBuf,
        /// Absolute guest destination path.
        dst: String,
        /// Allow replacing files that already exist in the rootfs.
        replace: bool,
    },
    /// Create a 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 (idempotent — does not error if the directory already exists).
    Mkdir {
        /// Absolute guest path.
        path: String,
        /// Directory permissions (e.g., `0o755`). `None` uses the default.
        mode: Option<u32>,
    },
    /// Remove a file or directory (idempotent — does not error if the path does not exist).
    Remove {
        /// Absolute guest path to remove.
        path: String,
    },
    /// Append content to an existing file. If the file lives in a lower layer,
    /// it is copied up to the writable overlay layer first, then the content is
    /// appended.
    Append {
        /// Absolute guest path of the file to append to.
        path: String,
        /// Content to append.
        content: String,
    },
}

/// Builder for constructing a list of [`Patch`] operations.
pub struct PatchBuilder {
    patches: Vec<Patch>,
}

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

impl MountBuilder {
    /// Create a new mount builder for the given guest path.
    pub fn new(guest: impl Into<String>) -> Self {
        Self {
            guest: guest.into(),
            mount: MountKind::Unset,
            options: MountOptions::default(),
            size_mib: None,
            disk_format: None,
            disk_fstype: None,
            stat_virtualization: None,
            host_permissions: None,
            error: None,
        }
    }

    /// Bind mount from a host path.
    pub fn bind(mut self, host: impl Into<PathBuf>) -> Self {
        self.mount = MountKind::Bind(host.into());
        self
    }

    /// Mount a named volume created via [`Volume::create`](crate::volume::Volume::create).
    /// The volume persists across sandbox restarts and can be shared between sandboxes.
    pub fn named(mut self, name: impl Into<String>) -> Self {
        self.mount = MountKind::Named(name.into());
        self
    }

    /// Use tmpfs (memory-backed).
    pub fn tmpfs(mut self) -> Self {
        self.mount = MountKind::Tmpfs;
        self
    }

    /// Mount a disk image file as a virtio-blk device at the guest path.
    ///
    /// Format defaults to the extension of `host` (`.qcow2` → Qcow2, `.vmdk`
    /// → Vmdk, anything else → Raw). Use [`Self::format`] to override.
    pub fn disk(mut self, host: impl Into<PathBuf>) -> Self {
        self.mount = MountKind::Disk(host.into());
        self
    }

    /// Override the disk image format for the current `disk()` mount.
    ///
    /// Only valid alongside [`Self::disk`]. Calling on bind / named / tmpfs
    /// mounts produces an error when the surrounding `SandboxBuilder` is
    /// finalized so the option does not silently get dropped.
    pub fn format(mut self, format: DiskImageFormat) -> Self {
        self.disk_format = Some(format);
        self
    }

    /// Set the inner filesystem type for the current `disk()` mount. When
    /// unset, agentd probes `/proc/filesystems` to find a type that mounts
    /// cleanly.
    pub fn fstype(mut self, fstype: impl Into<String>) -> Self {
        let fstype = fstype.into();
        if fstype.is_empty() {
            self.error.get_or_insert_with(|| {
                crate::MicrosandboxError::InvalidConfig("fstype must not be empty".into())
            });
            return self;
        }
        if fstype.contains(',')
            || fstype.contains(';')
            || fstype.contains(':')
            || fstype.contains('=')
        {
            self.error.get_or_insert_with(|| {
                crate::MicrosandboxError::InvalidConfig(format!(
                    "fstype must not contain ',', ';', ':', or '=': {fstype}"
                ))
            });
            return self;
        }
        self.disk_fstype = Some(fstype);
        self
    }

    /// Prevent writes to this mount. Enforced both at the host (virtiofs
    /// server rejects writes) and guest (kernel returns `EROFS`).
    pub fn readonly(mut self) -> Self {
        self.options.readonly = true;
        self
    }

    /// Prevent direct execution from this mount.
    ///
    /// This blocks executing a file located on the mount directly. It does
    /// not block interpreters from reading files on the mount, such as
    /// `sh /mnt/script.sh`, because the interpreter binary executes from a
    /// different filesystem.
    pub fn noexec(mut self) -> Self {
        self.options.noexec = true;
        self
    }

    /// Set the guest stat virtualization policy. Default: [`StatVirtualization::Strict`].
    ///
    /// Valid only for bind and named-directory/file mounts. Calling this on
    /// a tmpfs or disk-image mount produces an error at `.build()` time.
    pub fn stat_virtualization(mut self, policy: StatVirtualization) -> Self {
        self.stat_virtualization = Some(policy);
        self
    }

    /// Set the host permission propagation policy. Default: [`HostPermissions::Private`].
    ///
    /// Valid only for bind and named-directory/file mounts. Calling this on
    /// a tmpfs or disk-image mount produces an error at `.build()` time.
    pub fn host_permissions(mut self, policy: HostPermissions) -> Self {
        self.host_permissions = Some(policy);
        self
    }

    /// Set size limit (for tmpfs).
    ///
    /// Accepts bare `u32` (interpreted as MiB) or a [`SizeExt`](crate::size::SizeExt) helper:
    /// ```ignore
    /// .tmpfs().size(100)         // 100 MiB
    /// .tmpfs().size(100.mib())   // 100 MiB (explicit)
    /// .tmpfs().size(1.gib())     // 1 GiB = 1024 MiB
    /// ```
    pub fn size(mut self, size: impl Into<Mebibytes>) -> Self {
        self.size_mib = Some(size.into().as_u32());
        self
    }

    /// Build the volume mount.
    pub fn build(self) -> crate::MicrosandboxResult<VolumeMount> {
        if let Some(err) = self.error {
            return Err(err);
        }

        // Validate guest path.
        if !self.guest.starts_with('/') {
            return Err(crate::MicrosandboxError::InvalidConfig(format!(
                "guest mount path must be absolute: {}",
                self.guest
            )));
        }
        if self.guest == "/" {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "cannot mount a volume at guest root /".into(),
            ));
        }
        if self.guest.contains(':') || self.guest.contains(';') || self.guest.contains(',') {
            return Err(crate::MicrosandboxError::InvalidConfig(format!(
                "guest mount path must not contain ':', ';', or ',': {}",
                self.guest
            )));
        }

        // Reject options set on the wrong kind.
        let is_tmpfs = matches!(self.mount, MountKind::Tmpfs);
        let is_disk = matches!(self.mount, MountKind::Disk(_));
        let is_virtiofs = matches!(self.mount, MountKind::Bind(_) | MountKind::Named(_));
        if self.size_mib.is_some() && !is_tmpfs {
            return Err(crate::MicrosandboxError::InvalidConfig(
                ".size() is only valid for tmpfs mounts".into(),
            ));
        }
        if self.disk_format.is_some() && !is_disk {
            return Err(crate::MicrosandboxError::InvalidConfig(
                ".format() is only valid for disk image mounts".into(),
            ));
        }
        if self.disk_fstype.is_some() && !is_disk {
            return Err(crate::MicrosandboxError::InvalidConfig(
                ".fstype() is only valid for disk image mounts".into(),
            ));
        }
        if self.stat_virtualization.is_some() && !is_virtiofs {
            return Err(crate::MicrosandboxError::InvalidConfig(
                ".stat_virtualization() is only valid for bind and named volume mounts".into(),
            ));
        }
        if self.host_permissions.is_some() && !is_virtiofs {
            return Err(crate::MicrosandboxError::InvalidConfig(
                ".host_permissions() is only valid for bind and named volume mounts".into(),
            ));
        }

        // `Off + Mirror` is a contradiction. With xattr disabled there is no
        // overlay to keep guest chmod private, so chmod always hits the host —
        // `Mirror` would silently be a no-op as a distinct policy. Reject only
        // when the caller explicitly chose both, so the conservative defaults
        // never trip the check.
        if matches!(self.stat_virtualization, Some(StatVirtualization::Off))
            && matches!(self.host_permissions, Some(HostPermissions::Mirror))
        {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "stat_virtualization=Off cannot be combined with host_permissions=Mirror: \
                 Off has no overlay, so chmod already operates on the host inode and Mirror \
                 would be a no-op. Drop one or the other."
                    .into(),
            ));
        }

        let stat_virtualization = self
            .stat_virtualization
            .unwrap_or(StatVirtualization::Strict);
        let host_permissions = self.host_permissions.unwrap_or(HostPermissions::Private);

        let mount = match self.mount {
            MountKind::Bind(host) => {
                // The spawn → VM wire format encodes mount specs as
                // `tag:host[:opts]`. Embedded separators in the host
                // path would collide with that grammar and could
                // silently inject policy options. Reject at the SDK
                // boundary so callers get a clear error rather than a
                // confusing parse failure later.
                if let Some(s) = host.to_str() {
                    if s.contains(',') {
                        return Err(crate::MicrosandboxError::InvalidConfig(format!(
                            "bind host path must not contain ',': {s}"
                        )));
                    }
                    if s.contains(':') {
                        return Err(crate::MicrosandboxError::InvalidConfig(format!(
                            "bind host path must not contain ':': {s}"
                        )));
                    }
                    if s.contains(';') {
                        return Err(crate::MicrosandboxError::InvalidConfig(format!(
                            "bind host path must not contain ';': {s}"
                        )));
                    }
                } else {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "bind host path must be valid UTF-8".into(),
                    ));
                }
                VolumeMount::Bind {
                    host,
                    guest: self.guest,
                    options: self.options,
                    stat_virtualization,
                    host_permissions,
                }
            }
            MountKind::Named(name) => {
                crate::volume::validate_volume_name(&name)?;
                VolumeMount::Named {
                    name,
                    guest: self.guest,
                    options: self.options,
                    stat_virtualization,
                    host_permissions,
                }
            }
            MountKind::Tmpfs => VolumeMount::Tmpfs {
                guest: self.guest,
                size_mib: self.size_mib,
                options: self.options,
            },
            MountKind::Disk(host) => {
                let format = self.disk_format.unwrap_or_else(|| {
                    host.extension()
                        .and_then(|e| e.to_str())
                        .and_then(DiskImageFormat::from_extension)
                        .unwrap_or(DiskImageFormat::Raw)
                });
                VolumeMount::DiskImage {
                    host,
                    guest: self.guest,
                    format,
                    fstype: self.disk_fstype,
                    options: self.options,
                }
            }
            MountKind::Unset => {
                return Err(crate::MicrosandboxError::InvalidConfig(
                    "MountBuilder: no mount type set (call .bind(), .named(), .tmpfs(), or .disk())"
                        .into(),
                ));
            }
        };

        validate_volume_mount(&mount)?;
        Ok(mount)
    }
}

impl Default for PatchBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl PatchBuilder {
    /// Create a new patch builder.
    pub fn new() -> Self {
        Self {
            patches: Vec::new(),
        }
    }

    /// Write text content to a file.
    pub fn text(
        mut self,
        path: impl Into<String>,
        content: impl Into<String>,
        mode: Option<u32>,
        replace: bool,
    ) -> Self {
        self.patches.push(Patch::Text {
            path: path.into(),
            content: content.into(),
            mode,
            replace,
        });
        self
    }

    /// Write raw bytes to a file.
    pub fn file(
        mut self,
        path: impl Into<String>,
        content: impl Into<Vec<u8>>,
        mode: Option<u32>,
        replace: bool,
    ) -> Self {
        self.patches.push(Patch::File {
            path: path.into(),
            content: content.into(),
            mode,
            replace,
        });
        self
    }

    /// Copy a file from host into the rootfs.
    pub fn copy_file(
        mut self,
        src: impl Into<PathBuf>,
        dst: impl Into<String>,
        mode: Option<u32>,
        replace: bool,
    ) -> Self {
        self.patches.push(Patch::CopyFile {
            src: src.into(),
            dst: dst.into(),
            mode,
            replace,
        });
        self
    }

    /// Copy a directory from host into the rootfs.
    pub fn copy_dir(
        mut self,
        src: impl Into<PathBuf>,
        dst: impl Into<String>,
        replace: bool,
    ) -> Self {
        self.patches.push(Patch::CopyDir {
            src: src.into(),
            dst: dst.into(),
            replace,
        });
        self
    }

    /// Create a symlink.
    pub fn symlink(
        mut self,
        target: impl Into<String>,
        link: impl Into<String>,
        replace: bool,
    ) -> Self {
        self.patches.push(Patch::Symlink {
            target: target.into(),
            link: link.into(),
            replace,
        });
        self
    }

    /// Create a directory (idempotent).
    pub fn mkdir(mut self, path: impl Into<String>, mode: Option<u32>) -> Self {
        self.patches.push(Patch::Mkdir {
            path: path.into(),
            mode,
        });
        self
    }

    /// Remove a file or directory (idempotent).
    pub fn remove(mut self, path: impl Into<String>) -> Self {
        self.patches.push(Patch::Remove { path: path.into() });
        self
    }

    /// Append content to an existing file. Copies up from lower layer if needed.
    pub fn append(mut self, path: impl Into<String>, content: impl Into<String>) -> Self {
        self.patches.push(Patch::Append {
            path: path.into(),
            content: content.into(),
        });
        self
    }

    /// Build the list of patches.
    pub fn build(self) -> Vec<Patch> {
        self.patches
    }
}

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,
        }
    }
}

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

    /// Set the writable overlay upper size.
    pub fn upper_size(mut self, size: impl Into<Mebibytes>) -> Self {
        self.upper_size_mib = Some(size.into().as_u32());
        self
    }
}

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 configured OCI upper size in MiB if this is an OCI rootfs.
    pub fn oci_upper_size_mib(&self) -> Option<u32> {
        match self {
            Self::Oci(oci) => oci.upper_size_mib,
            _ => None,
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: ImageSource
//--------------------------------------------------------------------------------------------------

impl ImageSource {
    /// Resolve into a [`RootfsSource`].
    pub fn into_rootfs_source(self) -> crate::MicrosandboxResult<RootfsSource> {
        match self {
            Self::Path(path) => Self::resolve_path(path),
            Self::Text(s) => {
                if microsandbox_utils::looks_like_local_path_text(&s) {
                    Self::resolve_path(PathBuf::from(s))
                } else {
                    Ok(RootfsSource::oci(s))
                }
            }
        }
    }

    /// Resolve a local path into either a bind mount or a disk image source.
    fn resolve_path(path: PathBuf) -> crate::MicrosandboxResult<RootfsSource> {
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        if let Some(format) = DiskImageFormat::from_extension(ext) {
            Ok(RootfsSource::DiskImage {
                path,
                format,
                fstype: None,
            })
        } else {
            Ok(RootfsSource::Bind(path))
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: DiskImageFormat
//--------------------------------------------------------------------------------------------------

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,
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Methods: ImageBuilder
//--------------------------------------------------------------------------------------------------

impl ImageBuilder {
    /// Create a new image builder.
    pub fn new() -> Self {
        Self::default()
    }

    /// Use an OCI image reference as the root filesystem.
    ///
    /// ```ignore
    /// .image_with(|i| i.oci("python:3.12").upper_size(8.gib()))
    /// ```
    pub fn oci(mut self, reference: impl Into<String>) -> Self {
        self.source = Some(RootfsSource::oci(reference));
        self
    }

    /// Set the writable overlay upper size for an OCI rootfs.
    ///
    /// This is valid only after [`oci`](Self::oci).
    pub fn upper_size(mut self, size: impl Into<Mebibytes>) -> Self {
        let size_mib = size.into().as_u32();
        match &mut self.source {
            Some(RootfsSource::Oci(oci)) => {
                oci.upper_size_mib = Some(size_mib);
            }
            _ => {
                if self.error.is_none() {
                    self.error = Some(crate::MicrosandboxError::InvalidConfig(
                        "upper_size() requires oci() to be called first".into(),
                    ));
                }
            }
        }
        self
    }

    /// Use a disk image file as the root filesystem.
    ///
    /// The format is derived from the file extension:
    /// `.qcow2`, `.raw`, `.vmdk`.
    ///
    /// ```ignore
    /// .image_with(|i| i.disk("./ubuntu.qcow2"))
    /// .image_with(|i| i.disk("./alpine.raw").fstype("ext4"))
    /// ```
    pub fn disk(mut self, path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
        let format = match DiskImageFormat::from_extension(ext) {
            Some(f) => f,
            None => {
                self.error = Some(crate::MicrosandboxError::InvalidConfig(format!(
                    "unrecognized disk image extension: {ext:?} (expected .qcow2, .raw, or .vmdk)"
                )));
                return self;
            }
        };
        self.source = Some(RootfsSource::DiskImage {
            path,
            format,
            fstype: None,
        });
        self
    }

    /// Set the inner filesystem type for a disk image.
    ///
    /// If omitted, agentd auto-detects the filesystem by probing
    /// `/proc/filesystems`.
    ///
    /// ```ignore
    /// .image_with(|i| i.disk("./ubuntu.raw").fstype("ext4"))
    /// ```
    pub fn fstype(mut self, fstype: impl Into<String>) -> Self {
        let fstype = fstype.into();
        if fstype.is_empty() {
            self.error = Some(crate::MicrosandboxError::InvalidConfig(
                "fstype must not be empty".into(),
            ));
            return self;
        }
        if fstype.contains(',')
            || fstype.contains(';')
            || fstype.contains(':')
            || fstype.contains('=')
        {
            self.error = Some(crate::MicrosandboxError::InvalidConfig(format!(
                "fstype must not contain ',', ';', ':', or '=': {fstype}"
            )));
            return self;
        }
        match &mut self.source {
            Some(RootfsSource::DiskImage { fstype: ft, .. }) => {
                *ft = Some(fstype);
            }
            _ => {
                if self.error.is_none() {
                    self.error = Some(crate::MicrosandboxError::InvalidConfig(
                        "fstype() requires disk() to be called first".into(),
                    ));
                }
            }
        }
        self
    }

    /// Consume the builder and return the resolved [`RootfsSource`].
    pub fn build(self) -> crate::MicrosandboxResult<RootfsSource> {
        if let Some(e) = self.error {
            return Err(e);
        }
        self.source.ok_or_else(|| {
            crate::MicrosandboxError::InvalidConfig(
                "ImageBuilder: no image source set (call .oci() or .disk())".into(),
            )
        })
    }
}

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

pub(crate) fn validate_volume_mounts(mounts: &[VolumeMount]) -> crate::MicrosandboxResult<()> {
    for mount in mounts {
        validate_volume_mount(mount)?;
    }
    Ok(())
}

fn validate_volume_mount(mount: &VolumeMount) -> crate::MicrosandboxResult<()> {
    match mount {
        VolumeMount::Bind {
            host,
            guest,
            stat_virtualization,
            host_permissions,
            ..
        } => {
            validate_guest_mount_path(guest)?;
            validate_host_path_wire_safe(host, "bind host path")?;
            validate_virtiofs_policies(*stat_virtualization, *host_permissions)?;
        }
        VolumeMount::Named {
            name,
            guest,
            stat_virtualization,
            host_permissions,
            ..
        } => {
            validate_guest_mount_path(guest)?;
            crate::volume::validate_volume_name(name)?;
            validate_virtiofs_policies(*stat_virtualization, *host_permissions)?;
        }
        VolumeMount::Tmpfs { guest, .. } => {
            validate_guest_mount_path(guest)?;
        }
        VolumeMount::DiskImage {
            host,
            guest,
            fstype,
            ..
        } => {
            validate_guest_mount_path(guest)?;
            validate_host_path_wire_safe(host, "disk image host path")?;
            if let Some(fstype) = fstype {
                validate_fstype(fstype)?;
            }
        }
    }
    Ok(())
}

fn validate_guest_mount_path(guest: &str) -> crate::MicrosandboxResult<()> {
    if !guest.starts_with('/') {
        return Err(crate::MicrosandboxError::InvalidConfig(format!(
            "guest mount path must be absolute: {guest}"
        )));
    }
    if guest == "/" {
        return Err(crate::MicrosandboxError::InvalidConfig(
            "cannot mount a volume at guest root /".into(),
        ));
    }
    if guest.contains(':') || guest.contains(';') || guest.contains(',') {
        return Err(crate::MicrosandboxError::InvalidConfig(format!(
            "guest mount path must not contain ':', ';', or ',': {guest}"
        )));
    }
    Ok(())
}

fn validate_host_path_wire_safe(path: &Path, label: &str) -> crate::MicrosandboxResult<()> {
    let Some(path) = path.to_str() else {
        return Err(crate::MicrosandboxError::InvalidConfig(format!(
            "{label} must be valid UTF-8"
        )));
    };

    if path.contains(',') || path.contains(':') || path.contains(';') {
        return Err(crate::MicrosandboxError::InvalidConfig(format!(
            "{label} must not contain ',', ':', or ';': {path}"
        )));
    }
    Ok(())
}

fn validate_fstype(fstype: &str) -> crate::MicrosandboxResult<()> {
    if fstype.is_empty() {
        return Err(crate::MicrosandboxError::InvalidConfig(
            "fstype must not be empty".into(),
        ));
    }
    if fstype.contains(',') || fstype.contains(';') || fstype.contains(':') || fstype.contains('=')
    {
        return Err(crate::MicrosandboxError::InvalidConfig(format!(
            "fstype must not contain ',', ';', ':', or '=': {fstype}"
        )));
    }
    Ok(())
}

fn validate_virtiofs_policies(
    stat_virtualization: StatVirtualization,
    host_permissions: HostPermissions,
) -> crate::MicrosandboxResult<()> {
    if stat_virtualization == StatVirtualization::Off && host_permissions == HostPermissions::Mirror
    {
        return Err(crate::MicrosandboxError::InvalidConfig(
            "stat_virtualization=Off cannot be combined with host_permissions=Mirror: Off has no \
             overlay, so chmod already operates on the host inode and Mirror would be a no-op. \
             Drop one or the other."
                .into(),
        ));
    }
    Ok(())
}

fn decode_mount_options(options: Option<MountOptions>, readonly: bool) -> MountOptions {
    options.unwrap_or(MountOptions {
        readonly,
        ..MountOptions::default()
    })
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations: IntoImage
//--------------------------------------------------------------------------------------------------

impl IntoImage for &str {
    fn into_rootfs_source(self) -> crate::MicrosandboxResult<RootfsSource> {
        ImageSource::from(self).into_rootfs_source()
    }
}

impl IntoImage for String {
    fn into_rootfs_source(self) -> crate::MicrosandboxResult<RootfsSource> {
        ImageSource::from(self).into_rootfs_source()
    }
}

impl IntoImage for PathBuf {
    fn into_rootfs_source(self) -> crate::MicrosandboxResult<RootfsSource> {
        ImageSource::from(self).into_rootfs_source()
    }
}

//--------------------------------------------------------------------------------------------------
// 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 std::str::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 From<&str> for ImageSource {
    fn from(s: &str) -> Self {
        Self::Text(s.to_string())
    }
}

impl From<String> for ImageSource {
    fn from(s: String) -> Self {
        Self::Text(s)
    }
}

impl From<PathBuf> for ImageSource {
    fn from(p: PathBuf) -> Self {
        Self::Path(p)
    }
}

/// Custom serialization for `VolumeMount` covering all four variants.
impl Serialize for VolumeMount {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use serde::ser::SerializeMap;

        match self {
            Self::Bind {
                host,
                guest,
                options,
                stat_virtualization,
                host_permissions,
            } => {
                let mut map = serializer.serialize_map(Some(6))?;
                map.serialize_entry("type", "Bind")?;
                map.serialize_entry("host", host)?;
                map.serialize_entry("guest", guest)?;
                map.serialize_entry("options", options)?;
                map.serialize_entry("stat_virtualization", stat_virtualization)?;
                map.serialize_entry("host_permissions", host_permissions)?;
                map.end()
            }
            Self::Named {
                name,
                guest,
                options,
                stat_virtualization,
                host_permissions,
            } => {
                let mut map = serializer.serialize_map(Some(6))?;
                map.serialize_entry("type", "Named")?;
                map.serialize_entry("name", name)?;
                map.serialize_entry("guest", guest)?;
                map.serialize_entry("options", options)?;
                map.serialize_entry("stat_virtualization", stat_virtualization)?;
                map.serialize_entry("host_permissions", host_permissions)?;
                map.end()
            }
            Self::Tmpfs {
                guest,
                size_mib,
                options,
            } => {
                let mut map = serializer.serialize_map(Some(4))?;
                map.serialize_entry("type", "Tmpfs")?;
                map.serialize_entry("guest", guest)?;
                map.serialize_entry("size_mib", size_mib)?;
                map.serialize_entry("options", options)?;
                map.end()
            }
            Self::DiskImage {
                host,
                guest,
                format,
                fstype,
                options,
            } => {
                let mut map = serializer.serialize_map(Some(6))?;
                map.serialize_entry("type", "DiskImage")?;
                map.serialize_entry("host", host)?;
                map.serialize_entry("guest", guest)?;
                map.serialize_entry("format", format)?;
                map.serialize_entry("fstype", fstype)?;
                map.serialize_entry("options", options)?;
                map.end()
            }
        }
    }
}

/// Custom deserialization for `VolumeMount` covering all four variants.
impl<'de> Deserialize<'de> for VolumeMount {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// Helper for tagged deserialization.
        fn default_strict() -> StatVirtualization {
            StatVirtualization::Strict
        }
        fn default_private() -> HostPermissions {
            HostPermissions::Private
        }

        #[derive(Deserialize)]
        #[serde(tag = "type")]
        enum VolumeMountHelper {
            Bind {
                host: PathBuf,
                guest: String,
                #[serde(default)]
                options: Option<MountOptions>,
                #[serde(default)]
                readonly: bool,
                #[serde(default = "default_strict")]
                stat_virtualization: StatVirtualization,
                #[serde(default = "default_private")]
                host_permissions: HostPermissions,
            },
            Named {
                name: String,
                guest: String,
                #[serde(default)]
                options: Option<MountOptions>,
                #[serde(default)]
                readonly: bool,
                #[serde(default = "default_strict")]
                stat_virtualization: StatVirtualization,
                #[serde(default = "default_private")]
                host_permissions: HostPermissions,
            },
            Tmpfs {
                guest: String,
                #[serde(default)]
                size_mib: Option<u32>,
                #[serde(default)]
                options: Option<MountOptions>,
                #[serde(default)]
                readonly: bool,
            },
            DiskImage {
                host: PathBuf,
                guest: String,
                format: DiskImageFormat,
                #[serde(default)]
                fstype: Option<String>,
                #[serde(default)]
                options: Option<MountOptions>,
                #[serde(default)]
                readonly: bool,
            },
        }

        let helper = VolumeMountHelper::deserialize(deserializer)?;
        Ok(match helper {
            VolumeMountHelper::Bind {
                host,
                guest,
                options,
                readonly,
                stat_virtualization,
                host_permissions,
            } => Self::Bind {
                host,
                guest,
                options: decode_mount_options(options, readonly),
                stat_virtualization,
                host_permissions,
            },
            VolumeMountHelper::Named {
                name,
                guest,
                options,
                readonly,
                stat_virtualization,
                host_permissions,
            } => Self::Named {
                name,
                guest,
                options: decode_mount_options(options, readonly),
                stat_virtualization,
                host_permissions,
            },
            VolumeMountHelper::Tmpfs {
                guest,
                size_mib,
                options,
                readonly,
            } => Self::Tmpfs {
                guest,
                size_mib,
                options: decode_mount_options(options, readonly),
            },
            VolumeMountHelper::DiskImage {
                host,
                guest,
                format,
                fstype,
                options,
                readonly,
            } => Self::DiskImage {
                host,
                guest,
                format,
                fstype,
                options: decode_mount_options(options, readonly),
            },
        })
    }
}

impl std::fmt::Debug for VolumeMount {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Bind {
                host,
                guest,
                options,
                stat_virtualization,
                host_permissions,
            } => f
                .debug_struct("Bind")
                .field("host", host)
                .field("guest", guest)
                .field("options", options)
                .field("stat_virtualization", stat_virtualization)
                .field("host_permissions", host_permissions)
                .finish(),
            Self::Named {
                name,
                guest,
                options,
                stat_virtualization,
                host_permissions,
            } => f
                .debug_struct("Named")
                .field("name", name)
                .field("guest", guest)
                .field("options", options)
                .field("stat_virtualization", stat_virtualization)
                .field("host_permissions", host_permissions)
                .finish(),
            Self::Tmpfs {
                guest,
                size_mib,
                options,
            } => f
                .debug_struct("Tmpfs")
                .field("guest", guest)
                .field("size_mib", size_mib)
                .field("options", options)
                .finish(),
            Self::DiskImage {
                host,
                guest,
                format,
                fstype,
                options,
            } => f
                .debug_struct("DiskImage")
                .field("host", host)
                .field("guest", guest)
                .field("format", format)
                .field("fstype", fstype)
                .field("options", options)
                .finish(),
        }
    }
}

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

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

    #[test]
    fn test_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 test_disk_image_format_display_roundtrip() {
        for fmt in [
            DiskImageFormat::Qcow2,
            DiskImageFormat::Raw,
            DiskImageFormat::Vmdk,
        ] {
            let s = fmt.to_string();
            let parsed: DiskImageFormat = s.parse().unwrap();
            assert_eq!(parsed, fmt);
        }
    }

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

    //----------------------------------------------------------------------------------------------
    // MountBuilder validation
    //----------------------------------------------------------------------------------------------

    #[test]
    fn test_mount_builder_size_rejected_on_disk() {
        let err = MountBuilder::new("/data")
            .disk("/host/data.qcow2")
            .size(64u32)
            .build()
            .unwrap_err();
        assert!(err.to_string().contains(".size() is only valid for tmpfs"));
    }

    #[test]
    fn test_mount_builder_size_rejected_on_bind() {
        let err = MountBuilder::new("/data")
            .bind("/host/data")
            .size(64u32)
            .build()
            .unwrap_err();
        assert!(err.to_string().contains(".size() is only valid for tmpfs"));
    }

    #[test]
    fn test_mount_builder_format_rejected_on_non_disk() {
        let err = MountBuilder::new("/data")
            .bind("/host/data")
            .format(DiskImageFormat::Qcow2)
            .build()
            .unwrap_err();
        assert!(
            err.to_string()
                .contains(".format() is only valid for disk image mounts")
        );
    }

    #[test]
    fn test_mount_builder_fstype_rejected_on_non_disk() {
        let err = MountBuilder::new("/data")
            .tmpfs()
            .fstype("ext4")
            .build()
            .unwrap_err();
        assert!(
            err.to_string()
                .contains(".fstype() is only valid for disk image mounts")
        );
    }

    #[test]
    fn test_mount_builder_accepts_valid_named_volume() {
        let mount = MountBuilder::new("/data").named("cache_1").build().unwrap();
        match mount {
            VolumeMount::Named { name, guest, .. } => {
                assert_eq!(name, "cache_1");
                assert_eq!(guest, "/data");
            }
            other => panic!("expected Named, got {other:?}"),
        }
    }

    #[test]
    fn test_mount_builder_rejects_invalid_named_volume() {
        let err = MountBuilder::new("/data")
            .named("cache/../../secrets")
            .build()
            .unwrap_err();
        assert!(err.to_string().contains("volume name"));
    }

    #[test]
    fn test_validate_volume_mounts_rejects_direct_guest_separators() {
        let mount = VolumeMount::Tmpfs {
            guest: "/data,ro".to_string(),
            size_mib: None,
            options: MountOptions::default(),
        };

        let err = validate_volume_mounts(&[mount]).unwrap_err();
        assert!(err.to_string().contains("guest mount path"));
    }

    #[test]
    fn test_validate_volume_mounts_rejects_direct_disk_host_separators() {
        let mount = VolumeMount::DiskImage {
            host: PathBuf::from("/host/data:ro.raw"),
            guest: "/data".to_string(),
            format: DiskImageFormat::Raw,
            fstype: None,
            options: MountOptions::default(),
        };

        let err = validate_volume_mounts(&[mount]).unwrap_err();
        assert!(err.to_string().contains("disk image host path"));
    }

    #[test]
    fn test_validate_volume_mounts_rejects_direct_empty_fstype() {
        let mount = VolumeMount::DiskImage {
            host: PathBuf::from("/host/data.raw"),
            guest: "/data".to_string(),
            format: DiskImageFormat::Raw,
            fstype: Some(String::new()),
            options: MountOptions::default(),
        };

        let err = validate_volume_mounts(&[mount]).unwrap_err();
        assert!(err.to_string().contains("fstype must not be empty"));
    }

    #[test]
    fn test_validate_volume_mounts_rejects_direct_off_mirror() {
        let mount = VolumeMount::Bind {
            host: PathBuf::from("/host/data"),
            guest: "/data".to_string(),
            options: MountOptions::default(),
            stat_virtualization: StatVirtualization::Off,
            host_permissions: HostPermissions::Mirror,
        };

        let err = validate_volume_mounts(&[mount]).unwrap_err();
        assert!(err.to_string().contains("stat_virtualization=Off"));
    }

    #[test]
    fn test_volume_mount_json_uses_options_object() {
        let mount = VolumeMount::Bind {
            host: PathBuf::from("/host/data"),
            guest: "/data".to_string(),
            options: MountOptions {
                readonly: true,
                noexec: true,
            },
            stat_virtualization: StatVirtualization::Strict,
            host_permissions: HostPermissions::Private,
        };

        let value = serde_json::to_value(&mount).unwrap();
        assert!(value.get("readonly").is_none());
        assert!(value.get("noexec").is_none());
        assert_eq!(value["options"]["readonly"], true);
        assert_eq!(value["options"]["noexec"], true);

        let decoded: VolumeMount = serde_json::from_value(value).unwrap();
        match decoded {
            VolumeMount::Bind { options, .. } => {
                assert!(options.readonly);
                assert!(options.noexec);
            }
            other => panic!("expected Bind, got {other:?}"),
        }
    }

    #[test]
    fn test_volume_mount_json_accepts_legacy_readonly_field() {
        let bind: VolumeMount = serde_json::from_str(
            r#"{"type":"Bind","host":"/host/data","guest":"/data","readonly":true}"#,
        )
        .unwrap();
        match bind {
            VolumeMount::Bind { options, .. } => {
                assert!(options.readonly);
                assert!(!options.noexec);
            }
            other => panic!("expected Bind, got {other:?}"),
        }

        let named: VolumeMount =
            serde_json::from_str(r#"{"type":"Named","name":"cache","guest":"/cache"}"#).unwrap();
        match named {
            VolumeMount::Named { options, .. } => assert_eq!(options, MountOptions::default()),
            other => panic!("expected Named, got {other:?}"),
        }

        let tmpfs: VolumeMount =
            serde_json::from_str(r#"{"type":"Tmpfs","guest":"/tmp","readonly":false}"#).unwrap();
        match tmpfs {
            VolumeMount::Tmpfs { options, .. } => assert_eq!(options, MountOptions::default()),
            other => panic!("expected Tmpfs, got {other:?}"),
        }

        let disk: VolumeMount = serde_json::from_str(
            r#"{"type":"DiskImage","host":"/host/data.raw","guest":"/data","format":"Raw","readonly":true}"#,
        )
        .unwrap();
        match disk {
            VolumeMount::DiskImage { options, .. } => {
                assert!(options.readonly);
                assert!(!options.noexec);
            }
            other => panic!("expected DiskImage, got {other:?}"),
        }
    }

    #[test]
    fn test_mount_options_json_defaults_missing_fields() {
        let options: MountOptions = serde_json::from_str(r#"{"readonly":true}"#).unwrap();

        assert!(options.readonly);
        assert!(!options.noexec);
    }

    #[test]
    fn test_mount_builder_disk_then_format_overrides_inference() {
        // .disk(qcow2 path) would infer Qcow2; .format(Raw) afterwards must win.
        let mount = MountBuilder::new("/data")
            .disk("/host/data.qcow2")
            .format(DiskImageFormat::Raw)
            .build()
            .unwrap();
        match mount {
            VolumeMount::DiskImage { format, .. } => assert_eq!(format, DiskImageFormat::Raw),
            other => panic!("expected DiskImage, got {other:?}"),
        }
    }

    #[test]
    fn test_mount_builder_format_before_disk_still_overrides() {
        // Builder methods are call-order independent on the disk path.
        let mount = MountBuilder::new("/data")
            .format(DiskImageFormat::Vmdk)
            .disk("/host/data.qcow2")
            .build()
            .unwrap();
        match mount {
            VolumeMount::DiskImage { format, .. } => assert_eq!(format, DiskImageFormat::Vmdk),
            other => panic!("expected DiskImage, got {other:?}"),
        }
    }

    #[test]
    fn test_mount_builder_disk_extension_inference() {
        // No explicit format → infer from extension.
        for (path, expected) in [
            ("/host/data.qcow2", DiskImageFormat::Qcow2),
            ("/host/data.vmdk", DiskImageFormat::Vmdk),
            ("/host/data.raw", DiskImageFormat::Raw),
            ("/host/data.img", DiskImageFormat::Raw), // unknown → Raw fallback
        ] {
            let mount = MountBuilder::new("/data").disk(path).build().unwrap();
            match mount {
                VolumeMount::DiskImage { format, .. } => assert_eq!(format, expected, "{path}"),
                other => panic!("expected DiskImage for {path}, got {other:?}"),
            }
        }
    }

    #[test]
    fn test_image_source_resolves_qcow2() {
        let source = ImageSource::from("./disk.qcow2");
        let rootfs = source.into_rootfs_source().unwrap();
        match rootfs {
            RootfsSource::DiskImage { format, .. } => assert_eq!(format, DiskImageFormat::Qcow2),
            _ => panic!("expected DiskImage"),
        }
    }

    #[test]
    fn test_image_source_resolves_raw() {
        let source = ImageSource::from("/images/test.raw");
        let rootfs = source.into_rootfs_source().unwrap();
        match rootfs {
            RootfsSource::DiskImage { format, .. } => assert_eq!(format, DiskImageFormat::Raw),
            _ => panic!("expected DiskImage"),
        }
    }

    #[test]
    fn test_image_source_resolves_directory_as_bind() {
        let source = ImageSource::from("./rootfs");
        let rootfs = source.into_rootfs_source().unwrap();
        assert!(matches!(rootfs, RootfsSource::Bind(_)));
    }

    #[test]
    fn test_image_source_resolves_dot_as_bind() {
        let source = ImageSource::from(".");
        let rootfs = source.into_rootfs_source().unwrap();
        match rootfs {
            RootfsSource::Bind(path) => assert_eq!(path, PathBuf::from(".")),
            _ => panic!("expected Bind"),
        }
    }

    #[test]
    fn test_image_source_resolves_dot_dot_as_bind() {
        let source = ImageSource::from("..");
        let rootfs = source.into_rootfs_source().unwrap();
        match rootfs {
            RootfsSource::Bind(path) => assert_eq!(path, PathBuf::from("..")),
            _ => panic!("expected Bind"),
        }
    }

    #[test]
    fn test_image_source_resolves_oci_reference() {
        let source = ImageSource::from("python");
        let rootfs = source.into_rootfs_source().unwrap();
        match rootfs {
            RootfsSource::Oci(oci) => {
                assert_eq!(oci.reference, "python");
                assert_eq!(oci.upper_size_mib, None);
            }
            _ => panic!("expected Oci"),
        }
    }

    #[test]
    fn test_image_builder_oci_with_upper_size() {
        let rootfs = ImageBuilder::new()
            .oci("python:3.12")
            .upper_size(8192u32)
            .build()
            .unwrap();

        match rootfs {
            RootfsSource::Oci(oci) => {
                assert_eq!(oci.reference, "python:3.12");
                assert_eq!(oci.upper_size_mib, Some(8192));
            }
            _ => panic!("expected Oci"),
        }
    }

    #[test]
    fn test_image_builder_upper_size_requires_oci() {
        let result = ImageBuilder::new().upper_size(8192u32).build();
        let err = result.unwrap_err();

        assert!(err.to_string().contains("upper_size() requires oci()"));
    }

    #[test]
    fn test_image_builder_disk_with_fstype() {
        let rootfs = ImageBuilder::new()
            .disk("./test.qcow2")
            .fstype("ext4")
            .build()
            .unwrap();
        match rootfs {
            RootfsSource::DiskImage { format, fstype, .. } => {
                assert_eq!(format, DiskImageFormat::Qcow2);
                assert_eq!(fstype.as_deref(), Some("ext4"));
            }
            _ => panic!("expected DiskImage"),
        }
    }

    #[test]
    fn test_image_builder_disk_without_fstype() {
        let rootfs = ImageBuilder::new().disk("./test.raw").build().unwrap();
        match rootfs {
            RootfsSource::DiskImage { format, fstype, .. } => {
                assert_eq!(format, DiskImageFormat::Raw);
                assert_eq!(fstype, None);
            }
            _ => panic!("expected DiskImage"),
        }
    }

    #[test]
    fn test_image_builder_bad_extension_errors() {
        let result = ImageBuilder::new().disk("./test.txt").build();
        assert!(result.is_err());
    }

    #[test]
    fn test_image_builder_fstype_without_disk_errors() {
        let result = ImageBuilder::new().fstype("ext4").build();
        assert!(result.is_err());
    }

    #[test]
    fn test_image_builder_fstype_rejects_comma() {
        let result = ImageBuilder::new()
            .disk("./test.qcow2")
            .fstype("ext4,size=100")
            .build();
        assert!(result.is_err());
    }

    #[test]
    fn test_image_builder_fstype_rejects_equals() {
        let result = ImageBuilder::new()
            .disk("./test.qcow2")
            .fstype("key=value")
            .build();
        assert!(result.is_err());
    }
}