nucleus-container 0.3.6

Extremely lightweight Docker alternative for agents and production services — isolated execution using cgroups, namespaces, seccomp, Landlock, and gVisor
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
use crate::error::{NucleusError, Result};
use nix::fcntl::{open, OFlag};
use nix::mount::{mount, MsFlags};
use nix::sys::stat::{fstat, makedev, mknod, Mode, SFlag};
use nix::unistd::chroot;
use std::fs::OpenOptions;
use std::io::Read;
use std::os::fd::AsRawFd;
use std::os::unix::fs::OpenOptionsExt;
use std::path::{Component, Path, PathBuf};
use tracing::{debug, info, warn};

/// Expected mount flags for audit verification.
struct ExpectedMount {
    path: &'static str,
    required_flags: &'static [&'static str],
    /// If true, the mount *must* exist in production mode. A missing critical
    /// mount (e.g. /proc) is treated as a violation rather than silently skipped.
    critical: bool,
}

/// Known mount paths and the flags they must carry in production mode.
const PRODUCTION_MOUNT_EXPECTATIONS: &[ExpectedMount] = &[
    ExpectedMount {
        path: "/bin",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: true,
    },
    ExpectedMount {
        path: "/usr",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: true,
    },
    ExpectedMount {
        path: "/lib",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: false, // not all rootfs layouts have /lib
    },
    ExpectedMount {
        path: "/lib64",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: false, // not all rootfs layouts have /lib64
    },
    ExpectedMount {
        path: "/etc",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: true,
    },
    ExpectedMount {
        path: "/nix",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: false, // only present on NixOS-based rootfs
    },
    ExpectedMount {
        path: "/sbin",
        required_flags: &["ro", "nosuid", "nodev"],
        critical: false, // not all rootfs layouts have /sbin
    },
    ExpectedMount {
        path: "/proc",
        required_flags: &["nosuid", "nodev", "noexec"],
        critical: true,
    },
    ExpectedMount {
        path: "/run/secrets",
        required_flags: &["nosuid", "nodev", "noexec"],
        critical: false, // only present when secrets are configured
    },
];

/// Normalize an absolute container destination path and reject traversal.
///
/// Returns a normalized absolute path containing only `RootDir` and `Normal`
/// components. `.` segments are ignored; `..` and relative paths are rejected.
pub fn normalize_container_destination(dest: &Path) -> Result<PathBuf> {
    if !dest.is_absolute() {
        return Err(NucleusError::ConfigError(format!(
            "Container destination must be absolute: {:?}",
            dest
        )));
    }

    let mut normalized = PathBuf::from("/");
    let mut saw_component = false;

    for component in dest.components() {
        match component {
            Component::RootDir => {}
            Component::CurDir => {}
            Component::Normal(part) => {
                normalized.push(part);
                saw_component = true;
            }
            Component::ParentDir => {
                return Err(NucleusError::ConfigError(format!(
                    "Container destination must not contain parent traversal: {:?}",
                    dest
                )));
            }
            Component::Prefix(_) => {
                return Err(NucleusError::ConfigError(format!(
                    "Unsupported container destination prefix: {:?}",
                    dest
                )));
            }
        }
    }

    if !saw_component {
        return Err(NucleusError::ConfigError(format!(
            "Container destination must not be the root directory: {:?}",
            dest
        )));
    }

    Ok(normalized)
}

/// Resolve a validated container destination under a host-side root directory.
pub fn resolve_container_destination(root: &Path, dest: &Path) -> Result<PathBuf> {
    let normalized = normalize_container_destination(dest)?;
    let relative = normalized.strip_prefix("/").map_err(|_| {
        NucleusError::ConfigError(format!(
            "Container destination is not absolute after normalization: {:?}",
            normalized
        ))
    })?;
    Ok(root.join(relative))
}

fn validate_rootfs_path_under_store(rootfs_path: &Path, store_root: &Path) -> Result<PathBuf> {
    if !rootfs_path.is_absolute() {
        return Err(NucleusError::ConfigError(format!(
            "Production rootfs path must be absolute: {}",
            rootfs_path.display()
        )));
    }

    for component in rootfs_path.components() {
        match component {
            Component::ParentDir => {
                return Err(NucleusError::ConfigError(format!(
                    "Production rootfs path must not contain parent traversal: {}",
                    rootfs_path.display()
                )));
            }
            Component::Prefix(_) => {
                return Err(NucleusError::ConfigError(format!(
                    "Unsupported production rootfs path prefix: {}",
                    rootfs_path.display()
                )));
            }
            Component::RootDir | Component::CurDir | Component::Normal(_) => {}
        }
    }

    let canonical = std::fs::canonicalize(rootfs_path).map_err(|e| {
        NucleusError::ConfigError(format!(
            "Failed to canonicalize production rootfs path '{}': {}",
            rootfs_path.display(),
            e
        ))
    })?;

    if !canonical.starts_with(store_root) {
        return Err(NucleusError::ConfigError(format!(
            "Production mode requires rootfs path to resolve under {}: {} -> {}",
            store_root.display(),
            rootfs_path.display(),
            canonical.display()
        )));
    }

    if !canonical.is_dir() {
        return Err(NucleusError::ConfigError(format!(
            "Production rootfs path must resolve to a directory: {}",
            canonical.display()
        )));
    }

    Ok(canonical)
}

/// Validate a production rootfs path and return the canonical path to use.
///
/// Production rootfs paths must not contain parent traversal, and the resolved
/// target must be a directory under the immutable Nix store.
pub fn validate_production_rootfs_path(rootfs_path: &Path) -> Result<PathBuf> {
    validate_rootfs_path_under_store(rootfs_path, Path::new("/nix/store"))
}

pub(crate) fn read_regular_file_nofollow(path: &Path) -> Result<Vec<u8>> {
    let mut file = OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
        .open(path)
        .map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to open file {:?} with O_NOFOLLOW: {}",
                path, e
            ))
        })?;

    let metadata = file.metadata().map_err(|e| {
        NucleusError::FilesystemError(format!("Failed to stat file {:?}: {}", path, e))
    })?;
    if !metadata.is_file() {
        return Err(NucleusError::FilesystemError(format!(
            "Expected regular file for {:?}, found non-file source",
            path
        )));
    }

    let mut content = Vec::new();
    file.read_to_end(&mut content).map_err(|e| {
        NucleusError::FilesystemError(format!("Failed to read file {:?}: {}", path, e))
    })?;
    Ok(content)
}

fn decode_mountinfo_field(field: &str) -> String {
    let mut decoded = String::with_capacity(field.len());
    let mut chars = field.chars().peekable();

    while let Some(ch) = chars.next() {
        if ch == '\\' {
            let code: String = chars.by_ref().take(3).collect();
            match code.as_str() {
                "040" => decoded.push(' '),
                "011" => decoded.push('\t'),
                "012" => decoded.push('\n'),
                "134" => decoded.push('\\'),
                _ => {
                    decoded.push('\\');
                    decoded.push_str(&code);
                }
            }
        } else {
            decoded.push(ch);
        }
    }

    decoded
}

fn parse_mountinfo_line(line: &str) -> Option<(String, std::collections::HashSet<String>)> {
    let (left, _) = line.split_once(" - ")?;
    let fields: Vec<&str> = left.split_whitespace().collect();
    if fields.len() < 6 {
        return None;
    }

    let mount_point = decode_mountinfo_field(fields[4]);
    let options = fields[5]
        .split(',')
        .map(str::trim)
        .filter(|opt| !opt.is_empty())
        .map(str::to_string)
        .collect();

    Some((mount_point, options))
}

/// Audit all mounts in the container's mount namespace.
///
/// Reads `/proc/self/mountinfo` and verifies that each known mount point carries
/// its expected per-mount flags. In production mode, any missing flag is fatal.
/// Returns Ok(()) if all checks pass, or a list of violations.
pub fn audit_mounts(production_mode: bool) -> Result<()> {
    let mounts_content = std::fs::read_to_string("/proc/self/mountinfo").map_err(|e| {
        NucleusError::FilesystemError(format!("Failed to read /proc/self/mountinfo: {}", e))
    })?;
    let mount_table: std::collections::HashMap<String, std::collections::HashSet<String>> =
        mounts_content
            .lines()
            .filter_map(parse_mountinfo_line)
            .collect();

    let mut violations = Vec::new();

    for expectation in PRODUCTION_MOUNT_EXPECTATIONS {
        if let Some(options) = mount_table.get(expectation.path) {
            for &flag in expectation.required_flags {
                if !options.contains(flag) {
                    let rendered = options
                        .iter()
                        .map(String::as_str)
                        .collect::<Vec<_>>()
                        .join(",");
                    violations.push(format!(
                        "Mount {} missing required flag '{}' (has: {})",
                        expectation.path, flag, rendered
                    ));
                }
            }
        } else if expectation.critical && production_mode {
            violations.push(format!(
                "Critical mount {} is missing from the mount namespace",
                expectation.path
            ));
        }
    }

    if violations.is_empty() {
        info!("Mount audit passed: all expected flags verified");
        Ok(())
    } else if production_mode {
        Err(NucleusError::FilesystemError(format!(
            "Mount audit failed in production mode:\n  {}",
            violations.join("\n  ")
        )))
    } else {
        for v in &violations {
            warn!("Mount audit: {}", v);
        }
        Ok(())
    }
}

/// Create minimal filesystem structure in the new root
pub fn create_minimal_fs(root: &Path) -> Result<()> {
    info!("Creating minimal filesystem structure at {:?}", root);

    // Create essential directories
    let dirs = vec![
        "dev",
        "proc",
        "sys",
        "tmp",
        "bin",
        "sbin",
        "usr",
        "lib",
        "lib64",
        "etc",
        "nix",
        "nix/store",
        "run",
        "context",
    ];

    for dir in dirs {
        let path = root.join(dir);
        std::fs::create_dir_all(&path).map_err(|e| {
            NucleusError::FilesystemError(format!("Failed to create directory {:?}: {}", path, e))
        })?;
    }

    info!("Created minimal filesystem structure");

    Ok(())
}

/// Create essential device nodes in /dev
///
/// In rootless mode, device node creation will fail gracefully
pub fn create_dev_nodes(dev_path: &Path, include_tty: bool) -> Result<()> {
    info!("Creating device nodes at {:?}", dev_path);

    // Device nodes: (name, type, major, minor)
    let mut devices = vec![
        ("null", SFlag::S_IFCHR, 1, 3),
        ("zero", SFlag::S_IFCHR, 1, 5),
        ("full", SFlag::S_IFCHR, 1, 7),
        ("random", SFlag::S_IFCHR, 1, 8),
        ("urandom", SFlag::S_IFCHR, 1, 9),
    ];
    if include_tty {
        devices.push(("tty", SFlag::S_IFCHR, 5, 0));
    }

    let mut created_count = 0;
    let mut failed_count = 0;

    for (name, dev_type, major, minor) in devices {
        let path = dev_path.join(name);
        let mode = Mode::from_bits_truncate(0o660);
        let dev = makedev(major, minor);

        match mknod(&path, dev_type, mode, dev) {
            Ok(_) => {
                info!("Created device node: {:?}", path);
                created_count += 1;
            }
            Err(e) => {
                // In rootless mode, mknod fails - this is expected
                warn!(
                    "Failed to create device node {:?}: {} (this is normal in rootless mode)",
                    path, e
                );
                failed_count += 1;
            }
        }
    }

    if created_count > 0 {
        info!("Successfully created {} device nodes", created_count);
    }
    if failed_count > 0 {
        info!("Skipped {} device nodes (rootless mode)", failed_count);
    }

    Ok(())
}

/// Bind mount a pre-built rootfs (e.g. a Nix store closure) into the container.
///
/// Instead of exposing the full host /bin, /usr, /lib, /lib64, /nix, this mounts
/// a minimal, purpose-built root filesystem. Suitable for production services.
pub fn bind_mount_rootfs(root: &Path, rootfs_path: &Path) -> Result<()> {
    info!(
        "Bind mounting production rootfs {:?} into container {:?}",
        rootfs_path, root
    );

    if std::fs::symlink_metadata(rootfs_path).is_err() {
        return Err(NucleusError::FilesystemError(format!(
            "Rootfs path does not exist: {:?}",
            rootfs_path
        )));
    }

    // Bind mount the rootfs contents into the container root.
    // The rootfs is expected to contain a standard FHS layout (/bin, /lib, /etc, etc.)
    // produced by a Nix buildEnv or similar.
    let subdirs = ["bin", "sbin", "lib", "lib64", "usr", "etc", "nix"];

    for subdir in &subdirs {
        let source = rootfs_path.join(subdir);
        if !source.exists() {
            debug!("Rootfs subdir {} not present, skipping", subdir);
            continue;
        }

        let target = root.join(subdir);
        std::fs::create_dir_all(&target).map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to create mount point {:?}: {}",
                target, e
            ))
        })?;

        mount(
            Some(&source),
            &target,
            None::<&str>,
            MsFlags::MS_BIND | MsFlags::MS_REC,
            None::<&str>,
        )
        .map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to bind mount rootfs {:?} -> {:?}: {}",
                source, target, e
            ))
        })?;

        // Remount read-only
        mount(
            None::<&str>,
            &target,
            None::<&str>,
            MsFlags::MS_REMOUNT
                | MsFlags::MS_BIND
                | MsFlags::MS_RDONLY
                | MsFlags::MS_REC
                | MsFlags::MS_NOSUID
                | MsFlags::MS_NODEV,
            None::<&str>,
        )
        .map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to remount rootfs {:?} read-only: {}",
                target, e
            ))
        })?;

        info!("Mounted rootfs/{} read-only", subdir);
    }

    Ok(())
}

/// Bind mount essential host directories into container
///
/// This allows host binaries to be accessible inside the container.
/// Used in agent mode. Production mode should use bind_mount_rootfs() instead.
pub fn bind_mount_host_paths(root: &Path, best_effort: bool) -> Result<()> {
    info!("Bind mounting host paths into container");

    // Essential paths to bind mount (read-only)
    let host_paths = vec![
        "/bin", "/usr", "/lib", "/lib64", "/nix", // For NixOS
    ];

    for host_path in host_paths {
        let host = Path::new(host_path);

        // Only mount if the path exists on the host
        if !host.exists() {
            debug!("Skipping {} (not present on host)", host_path);
            continue;
        }

        let container_path = root.join(host_path.trim_start_matches('/'));

        // Create mount point
        if let Err(e) = std::fs::create_dir_all(&container_path) {
            if best_effort {
                warn!("Failed to create mount point {:?}: {}", container_path, e);
                continue;
            }
            return Err(NucleusError::FilesystemError(format!(
                "Failed to create mount point {:?}: {}",
                container_path, e
            )));
        }

        // Attempt bind mount
        // Note: Linux ignores MS_RDONLY on the initial bind mount call.
        // A second remount is required to actually enforce read-only.
        match mount(
            Some(host),
            &container_path,
            None::<&str>,
            MsFlags::MS_BIND | MsFlags::MS_REC,
            None::<&str>,
        ) {
            Ok(_) => {
                // Remount as read-only – required because MS_RDONLY is ignored on initial bind
                mount(
                    None::<&str>,
                    &container_path,
                    None::<&str>,
                    MsFlags::MS_REMOUNT
                        | MsFlags::MS_BIND
                        | MsFlags::MS_RDONLY
                        | MsFlags::MS_REC
                        | MsFlags::MS_NOSUID
                        | MsFlags::MS_NODEV,
                    None::<&str>,
                )
                .map_err(|e| {
                    NucleusError::FilesystemError(format!(
                        "Failed to remount {} as read-only: {}",
                        host_path, e
                    ))
                })?;
                info!(
                    "Bind mounted {} to {:?} (read-only)",
                    host_path, container_path
                );
            }
            Err(e) => {
                if best_effort {
                    warn!(
                        "Failed to bind mount {}: {} (continuing anyway)",
                        host_path, e
                    );
                } else {
                    return Err(NucleusError::FilesystemError(format!(
                        "Failed to bind mount {}: {}",
                        host_path, e
                    )));
                }
            }
        }
    }

    Ok(())
}

/// H7: Sensitive host paths that must not be bind-mounted into containers.
const DENIED_BIND_MOUNT_SOURCES_EXACT: &[&str] = &["/"];

/// Sensitive host subtrees that must not be exposed to a container at all.
const DENIED_BIND_MOUNT_SOURCE_PREFIXES: &[&str] = &[
    "/boot", "/dev", "/etc", "/home", "/proc", "/root", "/run", "/sys", "/var/log", "/var/run",
];

/// Container destinations where user-supplied volumes must not be mounted.
///
/// These paths carry trusted runtime/rootfs state. Allowing a volume over them
/// would let a caller replace attested container contents or pseudo-filesystems
/// after validation has completed.
const RESERVED_VOLUME_DESTINATION_PREFIXES: &[&str] = &[
    "/bin",
    "/boot",
    "/dev",
    "/etc",
    "/lib",
    "/lib64",
    "/nix",
    "/proc",
    "/run/secrets",
    "/sbin",
    "/sys",
    "/usr",
];

fn normalize_bind_mount_source_for_policy(source: &Path) -> Result<PathBuf> {
    if !source.is_absolute() {
        return Err(NucleusError::ConfigError(format!(
            "Bind mount source must be absolute: {:?}",
            source
        )));
    }

    let mut normalized = PathBuf::from("/");

    for component in source.components() {
        match component {
            Component::RootDir => {}
            Component::CurDir => {}
            Component::Normal(part) => normalized.push(part),
            Component::ParentDir => {
                normalized.pop();
                if normalized.as_os_str().is_empty() {
                    normalized.push("/");
                }
            }
            Component::Prefix(_) => {
                return Err(NucleusError::ConfigError(format!(
                    "Unsupported bind mount source prefix: {:?}",
                    source
                )));
            }
        }
    }

    Ok(normalized)
}

fn reject_denied_bind_mount_source(source: &Path) -> Result<()> {
    for denied in DENIED_BIND_MOUNT_SOURCES_EXACT {
        if source == Path::new(denied) {
            return Err(NucleusError::ConfigError(format!(
                "Bind mount source '{}' is a sensitive host path and cannot be mounted into containers",
                source.display()
            )));
        }
    }

    for denied in DENIED_BIND_MOUNT_SOURCE_PREFIXES {
        let denied_path = Path::new(denied);
        if source == denied_path || source.starts_with(denied_path) {
            return Err(NucleusError::ConfigError(format!(
                "Bind mount source '{}' is under sensitive host path '{}' and cannot be mounted into containers",
                source.display(),
                denied
            )));
        }
    }

    Ok(())
}

/// Validate bind-mount source policy without requiring the source to exist.
///
/// Topology persistent volumes use this before creating missing host paths, so
/// sensitive host locations are rejected before any mkdir/chown side effects.
pub fn validate_bind_mount_source_policy(source: &Path) -> Result<PathBuf> {
    let normalized = normalize_bind_mount_source_for_policy(source)?;
    reject_denied_bind_mount_source(&normalized)?;
    Ok(normalized)
}

/// Validate that a bind mount source exists and is not a sensitive host path or subtree.
pub fn validate_bind_mount_source(source: &Path) -> Result<()> {
    validate_bind_mount_source_policy(source)?;

    let canonical = std::fs::canonicalize(source).map_err(|e| {
        NucleusError::ConfigError(format!(
            "Failed to resolve bind mount source {:?}: {}",
            source, e
        ))
    })?;
    reject_denied_bind_mount_source(&canonical)
}

fn reject_reserved_volume_destination(dest: &Path) -> Result<()> {
    for reserved in RESERVED_VOLUME_DESTINATION_PREFIXES {
        let reserved_path = Path::new(reserved);
        if dest == reserved_path || dest.starts_with(reserved_path) {
            return Err(NucleusError::ConfigError(format!(
                "Volume destination '{}' is reserved for trusted container/runtime paths and cannot be overlaid",
                dest.display()
            )));
        }
    }

    Ok(())
}

/// Normalize and validate a user-supplied volume destination inside the container.
pub fn normalize_volume_destination(dest: &Path) -> Result<PathBuf> {
    let normalized = normalize_container_destination(dest)?;
    reject_reserved_volume_destination(&normalized)?;
    Ok(normalized)
}

/// Resolve a validated user-supplied volume destination under a host-side root directory.
pub fn resolve_volume_destination(root: &Path, dest: &Path) -> Result<PathBuf> {
    let normalized = normalize_volume_destination(dest)?;
    let relative = normalized.strip_prefix("/").map_err(|_| {
        NucleusError::ConfigError(format!(
            "Volume destination is not absolute after normalization: {:?}",
            normalized
        ))
    })?;
    Ok(root.join(relative))
}

/// Mount persistent bind volumes and ephemeral tmpfs volumes into the container root.
pub fn mount_volumes(root: &Path, volumes: &[crate::container::VolumeMount]) -> Result<()> {
    use crate::container::VolumeSource;

    if volumes.is_empty() {
        return Ok(());
    }

    info!("Mounting {} volume(s) into container", volumes.len());

    for volume in volumes {
        let dest = resolve_volume_destination(root, &volume.dest)?;

        match &volume.source {
            VolumeSource::Bind { source } => {
                // H7: Deny bind-mounting sensitive host paths
                validate_bind_mount_source(source)?;

                // Use symlink_metadata (lstat) instead of .exists() to avoid
                // following symlinks in the existence check (O_NOFOLLOW semantics).
                if std::fs::symlink_metadata(source).is_err() {
                    return Err(NucleusError::FilesystemError(format!(
                        "Volume source does not exist: {:?}",
                        source
                    )));
                }

                if let Some(parent) = dest.parent() {
                    std::fs::create_dir_all(parent).map_err(|e| {
                        NucleusError::FilesystemError(format!(
                            "Failed to create volume mount parent {:?}: {}",
                            parent, e
                        ))
                    })?;
                }

                let recursive = source.is_dir();
                if source.is_file() {
                    std::fs::write(&dest, "").map_err(|e| {
                        NucleusError::FilesystemError(format!(
                            "Failed to create volume mount point {:?}: {}",
                            dest, e
                        ))
                    })?;
                } else {
                    std::fs::create_dir_all(&dest).map_err(|e| {
                        NucleusError::FilesystemError(format!(
                            "Failed to create volume mount dir {:?}: {}",
                            dest, e
                        ))
                    })?;
                }

                let initial_flags = if recursive {
                    MsFlags::MS_BIND | MsFlags::MS_REC
                } else {
                    MsFlags::MS_BIND
                };
                mount(
                    Some(source.as_path()),
                    &dest,
                    None::<&str>,
                    initial_flags,
                    None::<&str>,
                )
                .map_err(|e| {
                    NucleusError::FilesystemError(format!(
                        "Failed to bind mount volume {:?} -> {:?}: {}",
                        source, dest, e
                    ))
                })?;

                let mut remount_flags =
                    MsFlags::MS_REMOUNT | MsFlags::MS_BIND | MsFlags::MS_NOSUID | MsFlags::MS_NODEV;
                if recursive {
                    remount_flags |= MsFlags::MS_REC;
                }
                if volume.read_only {
                    remount_flags |= MsFlags::MS_RDONLY;
                }

                mount(
                    None::<&str>,
                    &dest,
                    None::<&str>,
                    remount_flags,
                    None::<&str>,
                )
                .map_err(|e| {
                    NucleusError::FilesystemError(format!(
                        "Failed to remount volume {:?} with final flags: {}",
                        dest, e
                    ))
                })?;

                info!(
                    "Mounted bind volume {:?} -> {:?} ({})",
                    source,
                    volume.dest,
                    if volume.read_only { "ro" } else { "rw" }
                );
            }
            VolumeSource::Tmpfs { size } => {
                std::fs::create_dir_all(&dest).map_err(|e| {
                    NucleusError::FilesystemError(format!(
                        "Failed to create tmpfs mount dir {:?}: {}",
                        dest, e
                    ))
                })?;

                // M8: Validate size parameter to prevent option injection.
                // Only allow digits, optionally followed by K/M/G suffix.
                if let Some(value) = size.as_ref() {
                    let valid = value
                        .chars()
                        .all(|c| c.is_ascii_digit() || "kKmMgG".contains(c));
                    if !valid || value.is_empty() {
                        return Err(NucleusError::FilesystemError(format!(
                            "Invalid tmpfs size value '{}': only digits with optional K/M/G suffix allowed",
                            value
                        )));
                    }
                }

                // M7: Default to 64MB instead of half of physical RAM to
                // prevent memory DoS from unbounded tmpfs volumes.
                let mount_data = size
                    .as_ref()
                    .map(|value| format!("size={},mode=0700", value))
                    .unwrap_or_else(|| "size=64M,mode=0700".to_string());

                let mut flags = MsFlags::MS_NOSUID | MsFlags::MS_NODEV;
                if volume.read_only {
                    flags |= MsFlags::MS_RDONLY;
                }
                mount(
                    Some("tmpfs"),
                    &dest,
                    Some("tmpfs"),
                    flags,
                    Some(mount_data.as_str()),
                )
                .map_err(|e| {
                    NucleusError::FilesystemError(format!(
                        "Failed to mount tmpfs volume at {:?}: {}",
                        dest, e
                    ))
                })?;

                info!(
                    "Mounted tmpfs volume at {:?}{}{}",
                    volume.dest,
                    size.as_ref()
                        .map(|value| format!(" (size={})", value))
                        .unwrap_or_default(),
                    if volume.read_only { " (ro)" } else { "" }
                );
            }
        }
    }

    Ok(())
}

/// Mount procfs at the given path
///
/// In rootless mode, procfs mounting should work due to user namespace capabilities.
/// When `hide_pids` is true, mounts with hidepid=2 so processes cannot enumerate
/// other PIDs (production hardening). The best-effort fallback only applies to
/// non-hardened procfs mounts; requested hidepid hardening is fail-closed.
pub fn mount_procfs(
    proc_path: &Path,
    best_effort: bool,
    read_only: bool,
    hide_pids: bool,
) -> Result<()> {
    info!(
        "Mounting procfs at {:?} (hidepid={})",
        proc_path,
        if hide_pids { "2" } else { "0" }
    );

    let mount_data: Option<&str> = if hide_pids { Some("hidepid=2") } else { None };

    let mounted = match mount(
        Some("proc"),
        proc_path,
        Some("proc"),
        MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC,
        mount_data,
    ) {
        Ok(_) => true,
        Err(e) => handle_procfs_mount_failure(e, best_effort, hide_pids)?,
    };

    if mounted {
        if read_only {
            mount(
                None::<&str>,
                proc_path,
                None::<&str>,
                MsFlags::MS_REMOUNT
                    | MsFlags::MS_RDONLY
                    | MsFlags::MS_NOSUID
                    | MsFlags::MS_NODEV
                    | MsFlags::MS_NOEXEC,
                mount_data,
            )
            .map_err(|e| {
                NucleusError::FilesystemError(format!("Failed to remount procfs read-only: {}", e))
            })?;
            info!("Successfully mounted procfs (read-only)");
        } else {
            info!("Successfully mounted procfs");
        }
    }

    Ok(())
}

fn handle_procfs_mount_failure(
    e: nix::errno::Errno,
    best_effort: bool,
    hide_pids: bool,
) -> Result<bool> {
    if hide_pids {
        return Err(NucleusError::FilesystemError(format!(
            "Failed to mount procfs with required hidepid=2: {}",
            e
        )));
    }

    if best_effort {
        warn!("Failed to mount procfs: {} (continuing anyway)", e);
        Ok(false)
    } else {
        Err(NucleusError::FilesystemError(format!(
            "Failed to mount procfs: {}",
            e
        )))
    }
}

/// Paths to mask with /dev/null (files) – matches OCI runtime spec masked paths.
/// Exposed for testing; the canonical list of sensitive /proc entries that must
/// be hidden from container processes.
pub const PROC_NULL_MASKED: &[&str] = &[
    "kallsyms",
    "kcore",
    "sched_debug",
    "timer_list",
    "timer_stats",
    "keys",
    "latency_stats",
    "config.gz",
    "sysrq-trigger",
    "kpagecount",
    "kpageflags",
    "kpagecgroup",
];

/// Paths to remount read-only – matches OCI runtime spec readonlyPaths.
pub const PROC_READONLY_PATHS: &[&str] = &["bus", "fs", "irq", "sys"];

/// Paths to mask with empty tmpfs (directories).
pub const PROC_TMPFS_MASKED: &[&str] = &["acpi", "scsi"];

fn remount_proc_path_readonly(target: &Path) -> Result<()> {
    mount(
        Some(target),
        target,
        None::<&str>,
        MsFlags::MS_BIND | MsFlags::MS_REC,
        None::<&str>,
    )
    .map_err(|e| {
        NucleusError::FilesystemError(format!(
            "Failed to bind-mount {:?} onto itself for read-only remount: {}",
            target, e
        ))
    })?;

    mount(
        None::<&str>,
        target,
        None::<&str>,
        MsFlags::MS_REMOUNT
            | MsFlags::MS_BIND
            | MsFlags::MS_RDONLY
            | MsFlags::MS_NOSUID
            | MsFlags::MS_NODEV
            | MsFlags::MS_NOEXEC,
        None::<&str>,
    )
    .map_err(|e| {
        NucleusError::FilesystemError(format!("Failed to remount {:?} read-only: {}", target, e))
    })?;

    Ok(())
}

/// Mask sensitive /proc paths by bind-mounting /dev/null or tmpfs over them
///
/// This reduces kernel information leakage from the container. Follows OCI runtime
/// conventions for masked paths.
///
/// SEC-06: When `production` is true, failures to mask critical paths
/// (kcore, kallsyms, sysrq-trigger) are fatal instead of warn-and-continue.
pub fn mask_proc_paths(proc_path: &Path, production: bool) -> Result<()> {
    info!("Masking sensitive /proc paths");

    const CRITICAL_PROC_PATHS: &[&str] = &["kcore", "kallsyms", "sysrq-trigger"];

    for name in PROC_READONLY_PATHS {
        let target = proc_path.join(name);
        if !target.exists() {
            continue;
        }
        match remount_proc_path_readonly(&target) {
            Ok(_) => debug!("Remounted /proc/{} read-only", name),
            Err(e) => {
                if production {
                    return Err(NucleusError::FilesystemError(format!(
                        "Failed to remount /proc/{} read-only in production mode: {}",
                        name, e
                    )));
                }
                warn!(
                    "Failed to remount /proc/{} read-only: {} (continuing)",
                    name, e
                );
            }
        }
    }

    let dev_null = Path::new("/dev/null");

    for name in PROC_NULL_MASKED {
        let target = proc_path.join(name);
        if !target.exists() {
            continue;
        }
        match mount(
            Some(dev_null),
            &target,
            None::<&str>,
            MsFlags::MS_BIND,
            None::<&str>,
        ) {
            Ok(_) => {
                // Remount read-only: Linux ignores MS_RDONLY on the initial bind mount,
                // so a separate MS_REMOUNT|MS_BIND|MS_RDONLY call is required.
                if let Err(e) = mount(
                    None::<&str>,
                    &target,
                    None::<&str>,
                    MsFlags::MS_REMOUNT | MsFlags::MS_BIND | MsFlags::MS_RDONLY,
                    None::<&str>,
                ) {
                    if production && CRITICAL_PROC_PATHS.contains(name) {
                        return Err(NucleusError::FilesystemError(format!(
                            "Failed to remount /proc/{} read-only in production mode: {}",
                            name, e
                        )));
                    }
                    warn!(
                        "Failed to remount /proc/{} read-only: {} (continuing)",
                        name, e
                    );
                }
                debug!("Masked /proc/{} (read-only)", name);
            }
            Err(e) => {
                if production && CRITICAL_PROC_PATHS.contains(name) {
                    return Err(NucleusError::FilesystemError(format!(
                        "Failed to mask critical /proc/{} in production mode: {}",
                        name, e
                    )));
                }
                warn!("Failed to mask /proc/{}: {} (continuing)", name, e);
            }
        }
    }

    for name in PROC_TMPFS_MASKED {
        let target = proc_path.join(name);
        if !target.exists() {
            continue;
        }
        match mount(
            Some("tmpfs"),
            &target,
            Some("tmpfs"),
            MsFlags::MS_RDONLY | MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC,
            Some("size=0"),
        ) {
            Ok(_) => debug!("Masked /proc/{}", name),
            Err(e) => {
                if production {
                    return Err(NucleusError::FilesystemError(format!(
                        "Failed to mask /proc/{} in production mode: {}",
                        name, e
                    )));
                }
                warn!("Failed to mask /proc/{}: {} (continuing)", name, e);
            }
        }
    }

    info!("Finished masking sensitive /proc paths");
    Ok(())
}

/// Switch to new root filesystem using pivot_root or chroot
///
/// This implements the transition: populated -> pivoted
/// Fails closed if root switching cannot be established.
pub fn switch_root(new_root: &Path, allow_chroot_fallback: bool) -> Result<()> {
    info!("Switching root to {:?}", new_root);

    match pivot_root_impl(new_root) {
        Ok(()) => {
            info!("Successfully switched root using pivot_root");
            Ok(())
        }
        Err(e) => {
            if allow_chroot_fallback {
                warn!(
                    "pivot_root failed ({}), falling back to chroot due to explicit \
                     configuration",
                    e
                );
                chroot_impl(new_root)
            } else {
                Err(NucleusError::PivotRootError(format!(
                    "pivot_root failed: {}. chroot fallback is disabled by default; use \
                     --allow-chroot-fallback to allow weaker isolation",
                    e
                )))
            }
        }
    }
}

/// Implement root switch using pivot_root(2)
///
/// pivot_root is preferred over chroot because:
/// - More secure (old root can be unmounted)
/// - Works better with mount namespaces
fn pivot_root_impl(new_root: &Path) -> Result<()> {
    use nix::unistd::pivot_root;

    // pivot_root requires new_root to be a mount point
    // and old_root to be under new_root

    let old_root = new_root.join(".old_root");
    std::fs::create_dir_all(&old_root).map_err(|e| {
        NucleusError::PivotRootError(format!("Failed to create old_root directory: {}", e))
    })?;

    // Perform pivot_root
    pivot_root(new_root, &old_root)
        .map_err(|e| NucleusError::PivotRootError(format!("pivot_root syscall failed: {}", e)))?;

    // Change to new root
    std::env::set_current_dir("/")
        .map_err(|e| NucleusError::PivotRootError(format!("Failed to chdir to /: {}", e)))?;

    // Unmount old root
    nix::mount::umount2("/.old_root", nix::mount::MntFlags::MNT_DETACH)
        .map_err(|e| NucleusError::PivotRootError(format!("Failed to unmount old root: {}", e)))?;

    // Remove old root directory
    let _ = std::fs::remove_dir("/.old_root");

    Ok(())
}

/// Implement root switch using chroot(2)
///
/// chroot is less secure than pivot_root but works in more situations
fn chroot_impl(new_root: &Path) -> Result<()> {
    fn close_non_stdio_fds_after_chroot() -> Result<()> {
        // Any pre-chroot fd can still reach outside the jail, so close every
        // non-stdio descriptor before continuing setup inside the fallback root.
        let ret = unsafe { libc::syscall(libc::SYS_close_range, 3u32, u32::MAX, 0u32) };
        if ret == 0 {
            return Ok(());
        }

        let max_fd = match unsafe { libc::sysconf(libc::_SC_OPEN_MAX) } {
            n if n > 3 && n <= i32::MAX as libc::c_long => n as i32,
            _ => 1024,
        };

        for fd in 3..max_fd {
            if unsafe { libc::close(fd) } != 0 {
                let err = std::io::Error::last_os_error();
                if err.raw_os_error() != Some(libc::EBADF) {
                    return Err(NucleusError::PivotRootError(format!(
                        "Failed to close inherited fd {} after chroot: {}",
                        fd, err
                    )));
                }
            }
        }

        Ok(())
    }

    chroot(new_root)
        .map_err(|e| NucleusError::PivotRootError(format!("chroot syscall failed: {}", e)))?;

    // Change to new root
    std::env::set_current_dir("/")
        .map_err(|e| NucleusError::PivotRootError(format!("Failed to chdir to /: {}", e)))?;

    close_non_stdio_fds_after_chroot()?;

    // L3: Drop CAP_SYS_CHROOT after chroot to prevent escape via nested chroot.
    if let Err(e) = caps::drop(
        None,
        caps::CapSet::Bounding,
        caps::Capability::CAP_SYS_CHROOT,
    ) {
        debug!(
            "Could not drop CAP_SYS_CHROOT after chroot: {} (may not be present)",
            e
        );
    }
    if let Err(e) = caps::drop(
        None,
        caps::CapSet::Effective,
        caps::Capability::CAP_SYS_CHROOT,
    ) {
        debug!(
            "Could not drop effective CAP_SYS_CHROOT: {} (may not be present)",
            e
        );
    }
    if let Err(e) = caps::drop(
        None,
        caps::CapSet::Permitted,
        caps::Capability::CAP_SYS_CHROOT,
    ) {
        debug!(
            "Could not drop permitted CAP_SYS_CHROOT: {} (may not be present)",
            e
        );
    }

    info!("Successfully switched root using chroot (CAP_SYS_CHROOT dropped)");

    Ok(())
}

/// Mount secret files into the container root.
///
/// Each secret is bind-mounted read-only from its source to the destination
/// path inside the container. Intermediate directories are created as needed.
pub fn mount_secrets(root: &Path, secrets: &[crate::container::SecretMount]) -> Result<()> {
    if secrets.is_empty() {
        return Ok(());
    }

    info!("Mounting {} secret(s) into container", secrets.len());

    for secret in secrets {
        let source_fd = open(
            &secret.source,
            OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,
            Mode::empty(),
        )
        .map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to open secret source {:?} with O_NOFOLLOW: {}",
                secret.source, e
            ))
        })?;
        let source_stat = fstat(&source_fd).map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to stat secret source {:?}: {}",
                secret.source, e
            ))
        })?;
        let source_kind = SFlag::from_bits_truncate(source_stat.st_mode);
        let source_is_file = source_kind == SFlag::S_IFREG;
        let source_is_dir = source_kind == SFlag::S_IFDIR;
        if !source_is_file && !source_is_dir {
            return Err(NucleusError::FilesystemError(format!(
                "Secret source {:?} must be a regular file or directory",
                secret.source
            )));
        }
        let source_fd_path = PathBuf::from(format!("/proc/self/fd/{}", source_fd.as_raw_fd()));

        // Destination inside container root
        let dest = resolve_container_destination(root, &secret.dest)?;

        // Create parent directories
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to create secret mount parent {:?}: {}",
                    parent, e
                ))
            })?;
        }

        // Create mount point file
        if source_is_file {
            std::fs::write(&dest, "").map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to create secret mount point {:?}: {}",
                    dest, e
                ))
            })?;
        } else {
            std::fs::create_dir_all(&dest).map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to create secret mount dir {:?}: {}",
                    dest, e
                ))
            })?;
        }

        // Bind mount read-only
        mount(
            Some(source_fd_path.as_path()),
            &dest,
            None::<&str>,
            MsFlags::MS_BIND,
            None::<&str>,
        )
        .map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to bind mount secret {:?}: {}",
                secret.source, e
            ))
        })?;

        mount(
            None::<&str>,
            &dest,
            None::<&str>,
            MsFlags::MS_REMOUNT
                | MsFlags::MS_BIND
                | MsFlags::MS_RDONLY
                | MsFlags::MS_NOSUID
                | MsFlags::MS_NODEV
                | MsFlags::MS_NOEXEC,
            None::<&str>,
        )
        .map_err(|e| {
            NucleusError::FilesystemError(format!(
                "Failed to remount secret {:?} read-only: {}",
                dest, e
            ))
        })?;

        // Apply configured file permissions on the mount point
        if source_is_file {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(secret.mode);
            if let Err(e) = std::fs::set_permissions(&dest, perms) {
                warn!(
                    "Failed to set mode {:04o} on secret {:?}: {} (bind mount may override)",
                    secret.mode, dest, e
                );
            }
        }

        debug!(
            "Mounted secret {:?} -> {:?} (mode {:04o})",
            secret.source, secret.dest, secret.mode
        );
    }

    Ok(())
}

/// Mount secrets onto a dedicated in-memory tmpfs instead of bind-mounting host paths.
///
/// Creates a per-container tmpfs at `<root>/run/secrets` with MS_NOEXEC | MS_NOSUID | MS_NODEV,
/// copies secret contents into it, then zeros the read buffer. This ensures secrets
/// never reference host-side files after setup and are never persisted to disk.
pub fn mount_secrets_inmemory(
    root: &Path,
    secrets: &[crate::container::SecretMount],
    identity: &crate::container::ProcessIdentity,
) -> Result<()> {
    if secrets.is_empty() {
        return Ok(());
    }

    info!("Mounting {} secret(s) on in-memory tmpfs", secrets.len());

    let secrets_dir = root.join("run/secrets");
    std::fs::create_dir_all(&secrets_dir).map_err(|e| {
        NucleusError::FilesystemError(format!(
            "Failed to create secrets dir {:?}: {}",
            secrets_dir, e
        ))
    })?;

    // Mount a size-limited tmpfs for secrets (16 MiB max)
    if let Err(e) = mount(
        Some("tmpfs"),
        &secrets_dir,
        Some("tmpfs"),
        MsFlags::MS_NOSUID | MsFlags::MS_NODEV | MsFlags::MS_NOEXEC,
        Some("size=16m,mode=0700"),
    ) {
        let _ = std::fs::remove_dir_all(&secrets_dir);
        return Err(NucleusError::FilesystemError(format!(
            "Failed to mount secrets tmpfs at {:?}: {}",
            secrets_dir, e
        )));
    }

    if !identity.is_root() {
        nix::unistd::chown(
            &secrets_dir,
            Some(nix::unistd::Uid::from_raw(identity.uid)),
            Some(nix::unistd::Gid::from_raw(identity.gid)),
        )
        .map_err(|e| {
            let _ = nix::mount::umount2(&secrets_dir, nix::mount::MntFlags::MNT_DETACH);
            let _ = std::fs::remove_dir_all(&secrets_dir);
            NucleusError::FilesystemError(format!(
                "Failed to set /run/secrets owner to {}:{}: {}",
                identity.uid, identity.gid, e
            ))
        })?;
    }

    // Rollback: unmount tmpfs and remove dir if any secret fails
    let result = mount_secrets_inmemory_inner(&secrets_dir, root, secrets, identity);
    if let Err(ref e) = result {
        let _ = nix::mount::umount2(&secrets_dir, nix::mount::MntFlags::MNT_DETACH);
        let _ = std::fs::remove_dir_all(&secrets_dir);
        return Err(NucleusError::FilesystemError(format!(
            "Secret mount failed (rolled back): {}",
            e
        )));
    }

    info!("All secrets mounted on in-memory tmpfs");
    Ok(())
}

fn mount_secrets_inmemory_inner(
    secrets_dir: &Path,
    root: &Path,
    secrets: &[crate::container::SecretMount],
    identity: &crate::container::ProcessIdentity,
) -> Result<()> {
    for secret in secrets {
        let mut content = read_regular_file_nofollow(&secret.source)?;

        // Determine destination path inside the secrets tmpfs
        let dest = resolve_container_destination(secrets_dir, &secret.dest)?;

        // Create parent directories within the tmpfs
        if let Some(parent) = dest.parent() {
            std::fs::create_dir_all(parent).map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to create secret parent dir {:?}: {}",
                    parent, e
                ))
            })?;
        }

        // Write secret content to tmpfs
        std::fs::write(&dest, &content).map_err(|e| {
            NucleusError::FilesystemError(format!("Failed to write secret to {:?}: {}", dest, e))
        })?;

        // Set permissions
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = std::fs::Permissions::from_mode(secret.mode);
            std::fs::set_permissions(&dest, perms).map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to set permissions on secret {:?}: {}",
                    dest, e
                ))
            })?;
        }

        if !identity.is_root() {
            nix::unistd::chown(
                &dest,
                Some(nix::unistd::Uid::from_raw(identity.uid)),
                Some(nix::unistd::Gid::from_raw(identity.gid)),
            )
            .map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to set permissions owner on secret {:?} to {}:{}: {}",
                    dest, identity.uid, identity.gid, e
                ))
            })?;
        }

        // Zero the in-memory buffer
        zeroize::Zeroize::zeroize(&mut content);
        drop(content);

        // Also bind-mount the secret to its expected container path for compatibility
        let container_dest = resolve_container_destination(root, &secret.dest)?;
        if container_dest != dest {
            if let Some(parent) = container_dest.parent() {
                std::fs::create_dir_all(parent).map_err(|e| {
                    NucleusError::FilesystemError(format!(
                        "Failed to create secret mount parent {:?}: {}",
                        parent, e
                    ))
                })?;
            }

            std::fs::write(&container_dest, "").map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to create secret mount point {:?}: {}",
                    container_dest, e
                ))
            })?;

            mount(
                Some(dest.as_path()),
                &container_dest,
                None::<&str>,
                MsFlags::MS_BIND,
                None::<&str>,
            )
            .map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to bind mount secret {:?} -> {:?}: {}",
                    dest, container_dest, e
                ))
            })?;

            mount(
                None::<&str>,
                &container_dest,
                None::<&str>,
                MsFlags::MS_REMOUNT
                    | MsFlags::MS_BIND
                    | MsFlags::MS_RDONLY
                    | MsFlags::MS_NOSUID
                    | MsFlags::MS_NODEV
                    | MsFlags::MS_NOEXEC,
                None::<&str>,
            )
            .map_err(|e| {
                NucleusError::FilesystemError(format!(
                    "Failed to remount secret {:?} read-only: {}",
                    container_dest, e
                ))
            })?;
        }

        debug!(
            "Secret {:?} -> {:?} (in-memory tmpfs, mode {:04o})",
            secret.source, secret.dest, secret.mode
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::symlink;

    #[test]
    fn test_validate_bind_mount_source_rejects_sensitive_subtrees() {
        for path in [
            "/",
            "/boot",
            "/dev/kmsg",
            "/etc",
            "/etc/passwd",
            "/home/alice/.ssh",
            "/proc/sys",
            "/root/.ssh",
            "/run/secrets",
            "/sys/fs/cgroup",
            "/var/log",
        ] {
            let err = validate_bind_mount_source(Path::new(path)).unwrap_err();
            assert!(
                err.to_string().contains("sensitive host path"),
                "expected sensitive-path rejection for {path}, got: {err}"
            );
        }
    }

    #[test]
    fn test_validate_bind_mount_source_allows_regular_host_paths() {
        let temp = tempfile::TempDir::new().unwrap();
        let safe_path = temp.path().join("data");
        std::fs::create_dir(&safe_path).unwrap();

        validate_bind_mount_source(&safe_path).unwrap();
    }

    #[test]
    fn test_validate_bind_mount_source_normalizes_parent_components_before_filtering() {
        let temp = tempfile::TempDir::new().unwrap();
        let safe_path = temp.path().join("data");
        std::fs::create_dir(&safe_path).unwrap();

        validate_bind_mount_source(&safe_path.join("../data")).unwrap();
    }

    #[test]
    fn test_bind_mount_source_policy_rejects_sensitive_paths_before_creation() {
        let err = validate_bind_mount_source_policy(Path::new("/tmp/../../etc/nucleus-volume"))
            .unwrap_err();
        assert!(
            err.to_string().contains("sensitive host path"),
            "expected sensitive-path rejection before path creation, got: {err}"
        );
    }

    #[test]
    fn test_volume_destinations_reject_reserved_container_paths() {
        for path in [
            "/bin/tool",
            "/dev/null",
            "/etc/app",
            "/lib64/ld-linux-x86-64.so.2",
            "/nix/store/data",
            "/proc/sys",
            "/run/secrets/token",
            "/usr/local/bin",
        ] {
            let err = normalize_volume_destination(Path::new(path)).unwrap_err();
            assert!(
                err.to_string().contains("reserved"),
                "expected reserved destination rejection for {path}, got: {err}"
            );
        }
    }

    #[test]
    fn test_volume_destinations_allow_data_paths() {
        assert_eq!(
            normalize_volume_destination(Path::new("/var/lib/app")).unwrap(),
            PathBuf::from("/var/lib/app")
        );
        assert_eq!(
            normalize_volume_destination(Path::new("/opt/app/data")).unwrap(),
            PathBuf::from("/opt/app/data")
        );
    }

    #[test]
    fn test_production_rootfs_path_rejects_parent_traversal() {
        let temp = tempfile::TempDir::new().unwrap();
        let store = temp.path().join("store");
        std::fs::create_dir(&store).unwrap();

        let err =
            validate_rootfs_path_under_store(&store.join("../outside-rootfs"), &store).unwrap_err();

        assert!(
            err.to_string().contains("parent traversal"),
            "expected parent traversal rejection, got: {err}"
        );
    }

    #[test]
    fn test_production_rootfs_path_rejects_symlink_escape() {
        let temp = tempfile::TempDir::new().unwrap();
        let store = temp.path().join("store");
        let outside = temp.path().join("outside-rootfs");
        std::fs::create_dir(&store).unwrap();
        std::fs::create_dir(&outside).unwrap();
        symlink(&outside, store.join("rootfs-link")).unwrap();

        let err = validate_rootfs_path_under_store(&store.join("rootfs-link"), &store).unwrap_err();

        assert!(
            err.to_string().contains("resolve under"),
            "expected symlink escape rejection, got: {err}"
        );
    }

    #[test]
    fn test_production_rootfs_path_returns_canonical_store_target() {
        let temp = tempfile::TempDir::new().unwrap();
        let store = temp.path().join("store");
        let rootfs = store.join("abcd-rootfs");
        std::fs::create_dir(&store).unwrap();
        std::fs::create_dir(&rootfs).unwrap();
        symlink(&rootfs, store.join("rootfs-link")).unwrap();

        let canonical =
            validate_rootfs_path_under_store(&store.join("rootfs-link"), &store).unwrap();

        assert_eq!(canonical, std::fs::canonicalize(rootfs).unwrap());
    }

    #[test]
    fn test_proc_mask_includes_sysrq_trigger() {
        assert!(
            PROC_NULL_MASKED.contains(&"sysrq-trigger"),
            "/proc/sysrq-trigger must be masked to prevent host DoS"
        );
    }

    #[test]
    fn test_proc_mask_includes_timer_stats() {
        assert!(
            PROC_NULL_MASKED.contains(&"timer_stats"),
            "/proc/timer_stats must be masked to prevent kernel info leakage"
        );
    }

    #[test]
    fn test_proc_mask_includes_kpage_files() {
        for path in &["kpagecount", "kpageflags", "kpagecgroup"] {
            assert!(
                PROC_NULL_MASKED.contains(path),
                "/proc/{} must be masked to prevent host memory layout leakage",
                path
            );
        }
    }

    #[test]
    fn test_proc_mask_includes_oci_standard_paths() {
        // OCI runtime spec required masked paths
        for path in &["kallsyms", "kcore", "sched_debug", "keys", "config.gz"] {
            assert!(
                PROC_NULL_MASKED.contains(path),
                "/proc/{} must be in null-masked list (OCI spec)",
                path
            );
        }
        for path in &["acpi", "scsi"] {
            assert!(
                PROC_TMPFS_MASKED.contains(path),
                "/proc/{} must be in tmpfs-masked list (OCI spec)",
                path
            );
        }
        for path in &["bus", "fs", "irq", "sys"] {
            assert!(
                PROC_READONLY_PATHS.contains(path),
                "/proc/{} must be in read-only remount list (OCI spec)",
                path
            );
            assert!(
                !PROC_TMPFS_MASKED.contains(path),
                "/proc/{} must stay visible read-only, not hidden behind tmpfs",
                path
            );
        }
    }

    #[test]
    fn test_procfs_hidepid_failure_fails_closed_even_best_effort() {
        let err = handle_procfs_mount_failure(nix::errno::Errno::EINVAL, true, true).unwrap_err();

        assert!(
            err.to_string().contains("required hidepid=2"),
            "hidepid=2 failures must remain fatal in production/rootless paths, got: {err}"
        );
    }

    #[test]
    fn test_procfs_best_effort_only_applies_without_hidepid() {
        assert!(
            !handle_procfs_mount_failure(nix::errno::Errno::EPERM, true, false).unwrap(),
            "best-effort procfs mount failures may only continue when hidepid was not requested"
        );
    }

    #[test]
    fn test_parse_mountinfo_line_uses_mountinfo_mount_point_and_flags() {
        let line =
            "36 25 0:32 / /run/secrets rw,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,size=1024k";
        let (mount_point, flags) = parse_mountinfo_line(line).unwrap();

        assert_eq!(mount_point, "/run/secrets");
        assert!(flags.contains("nosuid"));
        assert!(flags.contains("nodev"));
        assert!(flags.contains("noexec"));
    }

    #[test]
    fn test_parse_mountinfo_line_decodes_escaped_mount_points() {
        let line = "41 25 0:40 / /path\\040with\\040spaces ro,nosuid,nodev - ext4 /dev/root ro";
        let (mount_point, flags) = parse_mountinfo_line(line).unwrap();

        assert_eq!(mount_point, "/path with spaces");
        assert!(flags.contains("ro"));
    }

    #[test]
    fn test_chroot_impl_closes_non_stdio_fds() {
        let source = include_str!("mount.rs");
        let fn_start = source.find("fn chroot_impl").unwrap();
        let after = &source[fn_start..];
        let open = after.find('{').unwrap();
        let mut depth = 0u32;
        let mut fn_end = open;
        for (i, ch) in after[open..].char_indices() {
            match ch {
                '{' => depth += 1,
                '}' => {
                    depth -= 1;
                    if depth == 0 {
                        fn_end = open + i + 1;
                        break;
                    }
                }
                _ => {}
            }
        }
        let body = &after[..fn_end];
        assert!(
            body.contains("close_non_stdio_fds_after_chroot()?"),
            "chroot fallback must close inherited non-stdio fds before continuing setup"
        );
    }

    #[test]
    fn test_read_regular_file_nofollow_reads_regular_file() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("secret.txt");
        std::fs::write(&path, "supersecret").unwrap();

        let content = read_regular_file_nofollow(&path).unwrap();
        assert_eq!(content, b"supersecret");
    }

    #[test]
    fn test_read_regular_file_nofollow_rejects_symlink() {
        let temp = tempfile::tempdir().unwrap();
        let target = temp.path().join("target.txt");
        let link = temp.path().join("secret-link");
        std::fs::write(&target, "supersecret").unwrap();
        symlink(&target, &link).unwrap();

        let err = read_regular_file_nofollow(&link).unwrap_err();
        assert!(
            err.to_string().contains("O_NOFOLLOW"),
            "symlink reads must fail via O_NOFOLLOW"
        );
    }
}