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
use super::landlock::LandlockManager;
use crate::error::{NucleusError, Result};
use crate::oci::OciBundle;
use nix::unistd::Uid;
use sha2::{Digest, Sha256};
use std::ffi::CString;
use std::fs::{self, DirBuilder, OpenOptions};
use std::io;
use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt};
use std::path::{Component, Path, PathBuf};
use std::process::Command;
use tracing::{debug, info, warn};

#[cfg(test)]
const NIX_STORE_EXEC_ROOT: &str = "/nix/store";

/// Network mode for gVisor runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GVisorNetworkMode {
    /// No networking (fully isolated). Default for agent workloads.
    None,
    /// gVisor user-space network stack. Suitable for networked production services
    /// that need gVisor isolation with network access.
    Sandbox,
    /// Share host network namespace. Use with caution.
    Host,
}

/// Platform backend for gVisor's Sentry.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Default,
    clap::ValueEnum,
    serde::Serialize,
    serde::Deserialize,
)]
pub enum GVisorPlatform {
    /// systrap backend, the current default and most broadly compatible option.
    #[default]
    Systrap,
    /// KVM-backed sandboxing for the Sentry itself.
    Kvm,
    /// ptrace backend for maximal compatibility where systrap/KVM are unavailable.
    Ptrace,
}

impl GVisorPlatform {
    pub fn as_flag(self) -> &'static str {
        match self {
            Self::Systrap => "systrap",
            Self::Kvm => "kvm",
            Self::Ptrace => "ptrace",
        }
    }
}

/// Options for running an OCI bundle with gVisor.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GVisorOciRunOptions {
    /// gVisor networking mode passed to runsc.
    pub network_mode: GVisorNetworkMode,
    /// Skip runsc's cgroup setup when Nucleus manages cgroups externally.
    pub ignore_cgroups: bool,
    /// Use runsc's rootless execution path for pre-created user namespaces.
    pub runsc_rootless: bool,
    /// Fail if the host-side supervisor execute allowlist cannot be installed.
    pub require_supervisor_exec_policy: bool,
    /// gVisor Sentry platform backend.
    pub platform: GVisorPlatform,
}

impl Default for GVisorOciRunOptions {
    fn default() -> Self {
        Self {
            network_mode: GVisorNetworkMode::None,
            ignore_cgroups: false,
            runsc_rootless: false,
            require_supervisor_exec_policy: false,
            platform: GVisorPlatform::default(),
        }
    }
}

impl GVisorOciRunOptions {
    fn network_flag(self) -> &'static str {
        match self.network_mode {
            GVisorNetworkMode::None => "none",
            GVisorNetworkMode::Sandbox => "sandbox",
            GVisorNetworkMode::Host => "host",
        }
    }
}

/// GVisor runtime manager
///
/// Implements the gVisor state machine from
/// NucleusSecurity_GVisor_GVisorRuntime.tla
pub struct GVisorRuntime {
    runsc_path: String,
}

impl GVisorRuntime {
    /// Create a new GVisor runtime manager
    ///
    /// This checks for runsc binary availability
    pub fn new() -> Result<Self> {
        let runsc_path = Self::find_runsc()?;
        info!("Found runsc at: {}", runsc_path);
        Ok(Self { runsc_path })
    }

    /// Create a GVisor runtime with a pre-resolved runsc path.
    ///
    /// Use this when the path was resolved before privilege changes
    /// (e.g. before entering a user namespace where UID 0 would block
    /// PATH-based lookup).
    pub fn with_path(runsc_path: String) -> Self {
        Self { runsc_path }
    }

    /// Resolve the runsc path without constructing a full runtime.
    /// Call this before fork/unshare so the path is resolved while
    /// still unprivileged.
    pub fn resolve_path() -> Result<String> {
        Self::find_runsc()
    }

    /// Find the runsc binary
    fn find_runsc() -> Result<String> {
        // Try common locations
        let paths = vec![
            "/usr/local/bin/runsc",
            "/usr/bin/runsc",
            "/opt/gvisor/runsc",
        ];

        for path in &paths {
            if let Some(validated) = Self::validate_runsc_path(Path::new(path))? {
                return Ok(validated);
            }
        }

        // For privileged execution, do not resolve runtime binaries via PATH.
        // This avoids environment-based binary hijacking when running as root.
        if Uid::effective().is_root() {
            return Err(NucleusError::GVisorError(
                "runsc binary not found in trusted system paths".to_string(),
            ));
        }

        // Try to find in PATH without invoking a shell command.
        if let Some(path_var) = std::env::var_os("PATH") {
            for dir in std::env::split_paths(&path_var) {
                let candidate = dir.join("runsc");
                if let Some(validated) = Self::validate_runsc_path(&candidate)? {
                    return Ok(validated);
                }
            }
        }

        Err(NucleusError::GVisorError(
            "runsc binary not found. Please install gVisor.".to_string(),
        ))
    }

    fn validate_runsc_path(path: &Path) -> Result<Option<String>> {
        if !path.exists() {
            return Ok(None);
        }
        if !path.is_file() {
            return Ok(None);
        }

        let canonical = std::fs::canonicalize(path).map_err(|e| {
            NucleusError::GVisorError(format!(
                "Failed to canonicalize runsc path {:?}: {}",
                path, e
            ))
        })?;

        // If the candidate is a shell wrapper script (common on NixOS where
        // nix wraps binaries to inject PATH), look for the real ELF binary
        // next to it. The gVisor helper re-exec path must stay on the real
        // binary, not a bash wrapper.
        let resolved = Self::unwrap_nix_wrapper(&canonical).unwrap_or_else(|| canonical.clone());

        let metadata = std::fs::metadata(&resolved).map_err(|e| {
            NucleusError::GVisorError(format!("Failed to stat runsc path {:?}: {}", resolved, e))
        })?;

        let mode = metadata.permissions().mode();
        if mode & 0o022 != 0 {
            return Err(NucleusError::GVisorError(format!(
                "Refusing insecure runsc binary permissions at {:?} (mode {:o})",
                resolved, mode
            )));
        }
        if mode & 0o111 == 0 {
            return Ok(None);
        }

        // Reject binaries owned by other non-root users – a malicious user
        // could place a trojan runsc earlier in PATH.
        use std::os::unix::fs::MetadataExt;
        let owner = metadata.uid();
        let current_uid = nix::unistd::Uid::effective().as_raw();
        if !Self::is_trusted_runsc_owner(&resolved, owner, current_uid) {
            return Err(NucleusError::GVisorError(format!(
                "Refusing runsc binary at {:?} owned by uid {} (expected root, current user {}, or immutable /nix/store artifact)",
                resolved, owner, current_uid
            )));
        }

        Ok(Some(resolved.to_string_lossy().to_string()))
    }

    fn is_trusted_runsc_owner(path: &Path, owner: u32, current_uid: u32) -> bool {
        if owner == 0 || owner == current_uid {
            return true;
        }

        // Nix store artifacts are immutable content-addressed paths and are
        // commonly owned by `nobody` rather than root/current user.
        // Extra hardening: verify the binary is not writable by *anyone* and
        // the parent directory is also not writable, to guard against a
        // compromised or mutable store.
        if path.starts_with("/nix/store") {
            if let Ok(meta) = std::fs::metadata(path) {
                let mode = meta.permissions().mode();
                // Reject if owner-writable (group/other already checked by caller)
                if mode & 0o200 != 0 {
                    return false;
                }
            } else {
                return false;
            }
            // Verify the immediate parent directory is not writable
            if let Some(parent) = path.parent() {
                if let Ok(parent_meta) = std::fs::metadata(parent) {
                    let parent_mode = parent_meta.permissions().mode();
                    if parent_mode & 0o222 != 0 {
                        return false;
                    }
                } else {
                    return false;
                }
            }
            return true;
        }

        false
    }

    /// If `path` is a Nix wrapper script, extract the real binary path.
    ///
    /// Nix wrapper scripts end with a line like:
    ///   exec -a "$0" "/nix/store/…/.runsc-wrapped"  "$@"
    /// We parse that to find the actual ELF binary.
    fn unwrap_nix_wrapper(path: &Path) -> Option<std::path::PathBuf> {
        let content = std::fs::read_to_string(path).ok()?;
        // Only process short scripts (wrapper scripts are small)
        if content.len() > 4096 || !content.starts_with("#!") {
            return None;
        }
        // Look for the exec line that references the wrapped binary
        for line in content.lines().rev() {
            let trimmed = line.trim();
            if trimmed.starts_with("exec ") {
                // Parse: exec -a "$0" "/nix/store/.../bin/.runsc-wrapped"  "$@"
                // or:    exec "/nix/store/.../bin/.runsc-wrapped"  "$@"
                for token in trimmed.split_whitespace() {
                    let unquoted = token.trim_matches('"');
                    if unquoted.starts_with('/') && unquoted.contains("runsc") {
                        let candidate = std::path::PathBuf::from(unquoted);
                        if candidate.exists() && candidate.is_file() {
                            debug!("Resolved Nix wrapper {:?} → {:?}", path, candidate);
                            return Some(candidate);
                        }
                    }
                }
            }
        }
        None
    }

    /// Execute using gVisor with an OCI bundle
    ///
    /// This is the OCI-compliant way to run containers with gVisor using
    /// default options: no networking, systrap platform, no rootless flag,
    /// and no internal cgroup setup override.
    pub fn exec_with_oci_bundle(&self, container_id: &str, bundle: &OciBundle) -> Result<()> {
        self.exec_with_oci_bundle_options(container_id, bundle, GVisorOciRunOptions::default())
    }

    /// Execute using gVisor with an OCI bundle and explicit run options.
    ///
    /// `ignore_cgroups` skips runsc's internal cgroup configuration because
    /// Nucleus already manages cgroups externally and unprivileged callers
    /// cannot configure them directly. `runsc_rootless` selects gVisor's
    /// built-in rootless execution path for cases where Nucleus already
    /// entered a mapped user namespace and therefore cannot express the
    /// namespace setup as an OCI `linux.uidMappings` request.
    /// `require_supervisor_exec_policy` fail-closes if Nucleus cannot install
    /// the host-side execute allowlist before handing control to runsc.
    pub fn exec_with_oci_bundle_options(
        &self,
        container_id: &str,
        bundle: &OciBundle,
        options: GVisorOciRunOptions,
    ) -> Result<()> {
        info!(
            "Executing with gVisor using OCI bundle at {:?} (network: {:?}, platform: {:?})",
            bundle.bundle_path(),
            options.network_mode,
            options.platform,
        );

        // Create a per-container root directory for runsc state. Do not derive
        // this from the OCI bundle parent: --bundle may be operator-provided,
        // shared, or attacker-writable, while runsc state includes a staged
        // executable used by the supervisor process.
        let runsc_root = Self::secure_runsc_root(container_id)?;

        let runsc_runtime_dir = runsc_root.join("runtime");
        Self::ensure_secure_runsc_dir(&runsc_runtime_dir, "runsc runtime directory")?;

        let (program_path, exec_allow_roots) =
            self.prepare_supervisor_runsc_program(&runsc_root)?;

        // Build runsc command with OCI bundle.
        // Global flags (--root, --network, --platform) must come BEFORE the subcommand.
        // runsc --root <dir> --network <mode> --platform <plat> run --bundle <path> <id>
        let mut args = self.build_oci_run_args(container_id, bundle, &runsc_root, options);
        args[0] = program_path.to_string_lossy().to_string();

        debug!("runsc OCI args: {:?}", args);

        // Convert to CStrings for exec
        let program = CString::new(program_path.to_string_lossy().as_ref())
            .map_err(|e| NucleusError::GVisorError(format!("Invalid runsc path: {}", e)))?;

        let c_args: Result<Vec<CString>> = args
            .iter()
            .map(|arg| {
                CString::new(arg.as_str())
                    .map_err(|e| NucleusError::GVisorError(format!("Invalid argument: {}", e)))
            })
            .collect();
        let c_args = c_args?;

        let c_env = self.exec_environment(&runsc_runtime_dir)?;

        // For the rootless bridge path, Nucleus has already entered a mapped
        // user namespace. Install an execute-only Landlock allowlist there:
        // runsc may still re-exec itself, but escaped host-side code cannot
        // exec arbitrary host binaries such as NixOS setuid wrappers.
        if options.runsc_rootless {
            self.apply_supervisor_exec_policy(
                &exec_allow_roots,
                options.require_supervisor_exec_policy,
            )?;
        }

        // execve - this replaces the current process with runsc
        nix::unistd::execve::<std::ffi::CString, std::ffi::CString>(&program, &c_args, &c_env)?;

        // Should never reach here
        Ok(())
    }

    /// Execute using gVisor with an OCI bundle and explicit network mode.
    ///
    /// Prefer [`Self::exec_with_oci_bundle_options`] for new call sites.
    #[allow(clippy::too_many_arguments)]
    pub fn exec_with_oci_bundle_network(
        &self,
        container_id: &str,
        bundle: &OciBundle,
        network_mode: GVisorNetworkMode,
        ignore_cgroups: bool,
        runsc_rootless: bool,
        require_supervisor_exec_policy: bool,
        platform: GVisorPlatform,
    ) -> Result<()> {
        self.exec_with_oci_bundle_options(
            container_id,
            bundle,
            GVisorOciRunOptions {
                network_mode,
                ignore_cgroups,
                runsc_rootless,
                require_supervisor_exec_policy,
                platform,
            },
        )
    }

    /// Check if gVisor is available on this system
    pub fn is_available() -> bool {
        Self::find_runsc().is_ok()
    }

    /// Get runsc version
    pub fn version(&self) -> Result<String> {
        let output = Command::new(&self.runsc_path)
            .arg("--version")
            .output()
            .map_err(|e| NucleusError::GVisorError(format!("Failed to get version: {}", e)))?;

        if !output.status.success() {
            return Err(NucleusError::GVisorError(
                "Failed to get runsc version".to_string(),
            ));
        }

        let version = String::from_utf8_lossy(&output.stdout).to_string();
        Ok(version.trim().to_string())
    }

    fn exec_environment(&self, runtime_dir: &Path) -> Result<Vec<CString>> {
        let mut env = Vec::new();
        let mut push = |key: &str, value: String| -> Result<()> {
            env.push(
                CString::new(format!("{}={}", key, value))
                    .map_err(|e| NucleusError::GVisorError(format!("Invalid {}: {}", key, e)))?,
            );
            Ok(())
        };

        // Use a hardcoded PATH for the runsc supervisor process to prevent
        // host PATH from leaking into the gVisor environment.
        push(
            "PATH",
            "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".to_string(),
        )?;
        let runtime_dir = runtime_dir.to_string_lossy().to_string();
        push("TMPDIR", runtime_dir.clone())?;
        push("XDG_RUNTIME_DIR", runtime_dir)?;

        // Hardcode safe values instead of leaking host identity/paths.
        // HOME could point to an attacker-controlled directory; USER/LOGNAME
        // leak host identity information – none of which gVisor needs.
        push("HOME", "/root".to_string())?;
        push("USER", "root".to_string())?;
        push("LOGNAME", "root".to_string())?;

        Ok(env)
    }

    fn prepare_supervisor_runsc_program(
        &self,
        runsc_root: &Path,
    ) -> Result<(PathBuf, Vec<PathBuf>)> {
        let canonical = fs::canonicalize(&self.runsc_path).map_err(|e| {
            NucleusError::GVisorError(format!(
                "Failed to canonicalize runsc path {:?}: {}",
                self.runsc_path, e
            ))
        })?;

        Self::ensure_secure_runsc_dir(runsc_root, "runsc root directory")?;
        let private_dir = runsc_root.join("exec-allow");
        Self::ensure_secure_runsc_dir(&private_dir, "private runsc exec directory")?;

        // Stage every runsc binary, including immutable Nix store artifacts.
        // gVisor re-execs runsc helpers after Landlock is installed; keeping the
        // executable under a per-container allowlist avoids granting execute over
        // the whole store.
        let stage_dir = Self::create_unique_runsc_stage_dir(&private_dir)?;
        let staged = stage_dir.join("runsc");
        Self::copy_runsc_nofollow(&canonical, &staged)?;

        Ok((staged, Self::supervisor_exec_allow_roots(private_dir)))
    }

    fn supervisor_exec_allow_roots(program_root: PathBuf) -> Vec<PathBuf> {
        // Do not allow procfs execution here. The packaged runsc is patched to
        // re-exec helper processes through its real executable path; allowing
        // /proc would also allow procfs fd magic-link execution attempts that
        // are outside the supervisor policy's intended executable root.
        vec![program_root]
    }

    fn secure_runsc_root(container_id: &str) -> Result<PathBuf> {
        let artifact_base = Self::gvisor_artifact_base()?;
        let artifact_dir = artifact_base.join(Self::runsc_state_component(container_id));

        if Self::host_root_requires_trusted_runsc_ancestry() {
            Self::ensure_trusted_host_root_runsc_ancestry(
                &artifact_base,
                "gVisor runsc artifact base",
            )?;
        }

        Self::ensure_secure_runsc_dir(&artifact_base, "gVisor runsc artifact base")?;
        Self::ensure_secure_runsc_dir(&artifact_dir, "gVisor runsc artifact directory")?;

        let runsc_root = artifact_dir.join("runsc-root");
        Self::ensure_secure_runsc_dir(&runsc_root, "runsc root directory")?;
        Ok(runsc_root)
    }

    fn gvisor_artifact_base() -> Result<PathBuf> {
        if let Some(path) =
            std::env::var_os("NUCLEUS_GVISOR_ARTIFACT_BASE").filter(|path| !path.is_empty())
        {
            return Self::absolute_path(Path::new(&path), "gVisor artifact base");
        }

        if !Uid::effective().is_root() || Self::root_uid_maps_to_unprivileged_host_uid_from_proc() {
            if let Some(dir) = dirs::runtime_dir() {
                return Ok(dir.join("nucleus-gvisor"));
            }
        }

        if Uid::effective().is_root() {
            Ok(PathBuf::from("/run/nucleus-gvisor"))
        } else {
            Ok(std::env::temp_dir().join(format!("nucleus-gvisor-{}", Uid::effective().as_raw())))
        }
    }

    fn absolute_path(path: &Path, label: &str) -> Result<PathBuf> {
        if path.is_absolute() {
            return Ok(path.to_path_buf());
        }

        std::env::current_dir()
            .map(|cwd| cwd.join(path))
            .map_err(|e| {
                NucleusError::GVisorError(format!(
                    "Failed to resolve current directory for {} {:?}: {}",
                    label, path, e
                ))
            })
    }

    fn runsc_state_component(container_id: &str) -> String {
        if container_id.len() == 32 && container_id.chars().all(|c| c.is_ascii_hexdigit()) {
            return container_id.to_string();
        }

        let digest = Sha256::digest(container_id.as_bytes());
        format!("id-{}", hex::encode(&digest[..16]))
    }

    fn root_uid_maps_to_unprivileged_host_uid_from_proc() -> bool {
        fs::read_to_string("/proc/self/uid_map")
            .map(|uid_map| Self::root_uid_maps_to_unprivileged_host_uid(&uid_map))
            .unwrap_or(false)
    }

    fn root_uid_maps_to_unprivileged_host_uid(uid_map: &str) -> bool {
        for line in uid_map.lines() {
            let mut fields = line.split_whitespace();
            let Some(namespace_start) = fields.next() else {
                continue;
            };
            let Some(host_start) = fields.next() else {
                continue;
            };
            let Some(length) = fields.next() else {
                continue;
            };
            if fields.next().is_some() {
                continue;
            }

            let Ok(namespace_start) = namespace_start.parse::<u64>() else {
                continue;
            };
            let Ok(host_start) = host_start.parse::<u64>() else {
                continue;
            };
            let Ok(length) = length.parse::<u64>() else {
                continue;
            };

            if namespace_start == 0 && length > 0 {
                return host_start != 0;
            }
        }

        false
    }

    fn host_root_requires_trusted_runsc_ancestry() -> bool {
        Uid::effective().is_root() && !Self::root_uid_maps_to_unprivileged_host_uid_from_proc()
    }

    fn ensure_trusted_host_root_runsc_ancestry(path: &Path, label: &str) -> Result<()> {
        let path = Self::absolute_path(path, label)?;

        let mut current = PathBuf::new();
        for component in path.components() {
            match component {
                Component::Prefix(prefix) => current.push(prefix.as_os_str()),
                Component::RootDir => current.push(component.as_os_str()),
                Component::CurDir => {}
                Component::ParentDir => {
                    return Err(NucleusError::GVisorError(format!(
                        "{} {:?} contains a parent-directory component",
                        label, path
                    )));
                }
                Component::Normal(name) => {
                    current.push(name);
                    match fs::symlink_metadata(&current) {
                        Ok(metadata) => Self::ensure_trusted_host_root_runsc_ancestor_component(
                            &current, metadata, label,
                        )?,
                        Err(e) if e.kind() == io::ErrorKind::NotFound => break,
                        Err(e) => {
                            return Err(NucleusError::GVisorError(format!(
                                "Failed to stat {} ancestor {:?}: {}",
                                label, current, e
                            )));
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn ensure_trusted_host_root_runsc_ancestor_component(
        path: &Path,
        metadata: fs::Metadata,
        label: &str,
    ) -> Result<()> {
        if metadata.file_type().is_symlink() {
            return Err(NucleusError::GVisorError(format!(
                "Refusing symlink {} ancestor {:?}",
                label, path
            )));
        }
        if !metadata.file_type().is_dir() {
            return Err(NucleusError::GVisorError(format!(
                "{} ancestor {:?} is not a directory",
                label, path
            )));
        }

        let owner = metadata.uid();
        if owner != 0 {
            return Err(NucleusError::GVisorError(format!(
                "{} ancestor {:?} is owned by uid {} (expected root)",
                label, path, owner
            )));
        }

        let mode = metadata.permissions().mode();
        if mode & 0o022 != 0 && mode & 0o1000 == 0 {
            return Err(NucleusError::GVisorError(format!(
                "{} ancestor {:?} has unsafe permissions {:o}",
                label,
                path,
                mode & 0o7777
            )));
        }

        Ok(())
    }

    fn ensure_secure_runsc_dir(path: &Path, label: &str) -> Result<()> {
        if let Some(parent) = path
            .parent()
            .filter(|parent| !parent.as_os_str().is_empty())
        {
            Self::ensure_trusted_runsc_parent(parent, label)?;
        }

        let mut created = false;
        match fs::symlink_metadata(path) {
            Ok(metadata) if metadata.file_type().is_symlink() => {
                return Err(NucleusError::GVisorError(format!(
                    "Refusing symlink {} {:?}",
                    label, path
                )));
            }
            Ok(metadata) if !metadata.file_type().is_dir() => {
                return Err(NucleusError::GVisorError(format!(
                    "{} {:?} is not a directory",
                    label, path
                )));
            }
            Ok(_) => {}
            Err(e) if e.kind() == io::ErrorKind::NotFound => {
                match DirBuilder::new().mode(0o700).create(path) {
                    Ok(()) => {
                        created = true;
                    }
                    Err(create_err) if create_err.kind() == io::ErrorKind::AlreadyExists => {}
                    Err(create_err) => {
                        return Err(NucleusError::GVisorError(format!(
                            "Failed to create {} {:?}: {}",
                            label, path, create_err
                        )));
                    }
                }
            }
            Err(e) => {
                return Err(NucleusError::GVisorError(format!(
                    "Failed to stat {} {:?}: {}",
                    label, path, e
                )));
            }
        }

        if created {
            fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(|e| {
                NucleusError::GVisorError(format!(
                    "Failed to secure newly-created {} permissions {:?}: {}",
                    label, path, e
                ))
            })?;
        }

        let dir = OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC | libc::O_DIRECTORY)
            .open(path)
            .map_err(|e| {
                NucleusError::GVisorError(format!(
                    "Failed to open {} {:?} without following symlinks: {}",
                    label, path, e
                ))
            })?;

        let metadata = dir.metadata().map_err(|e| {
            NucleusError::GVisorError(format!("Failed to stat {} {:?}: {}", label, path, e))
        })?;
        if !metadata.file_type().is_dir() {
            return Err(NucleusError::GVisorError(format!(
                "{} {:?} is not a directory",
                label, path
            )));
        }

        let owner = metadata.uid();
        let expected = Uid::effective().as_raw();
        if owner != expected {
            return Err(NucleusError::GVisorError(format!(
                "{} {:?} is owned by uid {} (expected {})",
                label, path, owner, expected
            )));
        }

        let mode = metadata.permissions().mode() & 0o777;
        if mode != 0o700 {
            dir.set_permissions(fs::Permissions::from_mode(0o700))
                .map_err(|e| {
                    NucleusError::GVisorError(format!(
                        "Failed to secure {} permissions {:?}: {}",
                        label, path, e
                    ))
                })?;
        }

        Ok(())
    }

    fn ensure_trusted_runsc_parent(parent: &Path, label: &str) -> Result<()> {
        let metadata = fs::symlink_metadata(parent).map_err(|e| {
            NucleusError::GVisorError(format!(
                "Failed to stat parent for {} {:?}: {}",
                label, parent, e
            ))
        })?;
        if metadata.file_type().is_symlink() {
            return Err(NucleusError::GVisorError(format!(
                "Refusing symlink parent for {} {:?}",
                label, parent
            )));
        }
        if !metadata.file_type().is_dir() {
            return Err(NucleusError::GVisorError(format!(
                "Parent for {} {:?} is not a directory",
                label, parent
            )));
        }

        let owner = metadata.uid();
        let current = Uid::effective().as_raw();
        let owner_trusted = owner == current || owner == 0;
        let mode = metadata.permissions().mode();
        let unsafe_writable = mode & 0o022 != 0 && mode & 0o1000 == 0;
        if !owner_trusted || unsafe_writable {
            return Err(NucleusError::GVisorError(format!(
                "Parent for {} {:?} is not trusted (owner uid {}, mode {:o})",
                label,
                parent,
                owner,
                mode & 0o7777
            )));
        }

        Ok(())
    }

    fn create_unique_runsc_stage_dir(private_dir: &Path) -> Result<PathBuf> {
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or_default();

        for attempt in 0..100u32 {
            let stage_dir = private_dir.join(format!(
                "stage-{}-{}-{}",
                std::process::id(),
                nonce,
                attempt
            ));
            match DirBuilder::new().mode(0o700).create(&stage_dir) {
                Ok(()) => {
                    Self::ensure_secure_runsc_dir(&stage_dir, "runsc stage directory")?;
                    return Ok(stage_dir);
                }
                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(e) => {
                    return Err(NucleusError::GVisorError(format!(
                        "Failed to create runsc stage directory {:?}: {}",
                        stage_dir, e
                    )));
                }
            }
        }

        Err(NucleusError::GVisorError(format!(
            "Failed to create unique runsc stage directory under {:?}",
            private_dir
        )))
    }

    fn copy_runsc_nofollow(source: &Path, staged: &Path) -> Result<()> {
        let mut source_file = OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_CLOEXEC)
            .open(source)
            .map_err(|e| {
                NucleusError::GVisorError(format!(
                    "Failed to open runsc source {:?}: {}",
                    source, e
                ))
            })?;

        let source_meta = source_file.metadata().map_err(|e| {
            NucleusError::GVisorError(format!("Failed to stat runsc source {:?}: {}", source, e))
        })?;
        if !source_meta.file_type().is_file() {
            return Err(NucleusError::GVisorError(format!(
                "runsc source {:?} is not a regular file",
                source
            )));
        }

        let mut staged_file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o500)
            .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
            .open(staged)
            .map_err(|e| {
                NucleusError::GVisorError(format!(
                    "Failed to create staged runsc binary {:?}: {}",
                    staged, e
                ))
            })?;

        io::copy(&mut source_file, &mut staged_file).map_err(|e| {
            NucleusError::GVisorError(format!(
                "Failed to stage runsc binary from {:?} to {:?}: {}",
                source, staged, e
            ))
        })?;
        staged_file
            .set_permissions(fs::Permissions::from_mode(0o500))
            .map_err(|e| {
                NucleusError::GVisorError(format!(
                    "Failed to secure staged runsc binary {:?}: {}",
                    staged, e
                ))
            })?;
        staged_file.sync_all().map_err(|e| {
            NucleusError::GVisorError(format!(
                "Failed to sync staged runsc binary {:?}: {}",
                staged, e
            ))
        })?;

        Ok(())
    }

    fn apply_supervisor_exec_policy(
        &self,
        allowed_roots: &[PathBuf],
        required: bool,
    ) -> Result<()> {
        let mut landlock = LandlockManager::new();
        let applied = landlock.apply_execute_allowlist_policy(allowed_roots, !required)?;
        if applied {
            info!(
                allowed_roots = ?allowed_roots,
                "Applied gVisor supervisor execute allowlist"
            );
        } else if required {
            return Err(NucleusError::LandlockError(
                "Required gVisor supervisor execute allowlist was not applied".to_string(),
            ));
        } else {
            warn!(
                allowed_roots = ?allowed_roots,
                "gVisor supervisor execute allowlist unavailable"
            );
        }
        Ok(())
    }

    fn build_oci_run_args(
        &self,
        container_id: &str,
        bundle: &OciBundle,
        runsc_root: &Path,
        options: GVisorOciRunOptions,
    ) -> Vec<String> {
        let mut args = vec![
            self.runsc_path.clone(),
            "--root".to_string(),
            runsc_root.to_string_lossy().to_string(),
        ];

        if options.runsc_rootless {
            args.push("--rootless".to_string());
        }

        if options.ignore_cgroups {
            args.push("--ignore-cgroups".to_string());
        }

        args.extend([
            "--network".to_string(),
            options.network_flag().to_string(),
            "--platform".to_string(),
            options.platform.as_flag().to_string(),
            "run".to_string(),
            "--bundle".to_string(),
            bundle.bundle_path().to_string_lossy().to_string(),
            container_id.to_string(),
        ]);

        args
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::oci::OciConfig;
    use std::path::{Path, PathBuf};
    use std::sync::{Mutex, MutexGuard};

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    struct EnvLock {
        _guard: MutexGuard<'static, ()>,
    }

    impl EnvLock {
        fn acquire() -> Self {
            Self {
                _guard: ENV_LOCK.lock().unwrap(),
            }
        }
    }

    struct EnvVarGuard {
        key: &'static str,
        previous: Option<std::ffi::OsString>,
    }

    impl EnvVarGuard {
        fn set(key: &'static str, value: impl AsRef<std::ffi::OsStr>) -> Self {
            let previous = std::env::var_os(key);
            std::env::set_var(key, value);
            Self { key, previous }
        }

        fn remove(key: &'static str) -> Self {
            let previous = std::env::var_os(key);
            std::env::remove_var(key);
            Self { key, previous }
        }
    }

    impl Drop for EnvVarGuard {
        fn drop(&mut self) {
            match &self.previous {
                Some(value) => std::env::set_var(self.key, value),
                None => std::env::remove_var(self.key),
            }
        }
    }

    #[test]
    fn test_gvisor_availability() {
        // This test just checks if we can determine availability
        // It may pass or fail depending on whether gVisor is installed
        let available = GVisorRuntime::is_available();
        println!("gVisor available: {}", available);
    }

    #[test]
    fn test_gvisor_new() {
        let runtime = GVisorRuntime::new();
        if let Ok(rt) = runtime {
            println!("Found runsc at: {}", rt.runsc_path);
            if let Ok(version) = rt.version() {
                println!("runsc version: {}", version);
            }
        }
    }

    #[test]
    fn test_find_runsc() {
        // Test that find_runsc either succeeds or returns appropriate error
        match GVisorRuntime::find_runsc() {
            Ok(path) => {
                println!("Found runsc at: {}", path);
                assert!(!path.is_empty());
            }
            Err(e) => {
                println!("runsc not found (expected if gVisor not installed): {}", e);
            }
        }
    }

    #[test]
    fn test_validate_runsc_rejects_world_writable() {
        let dir = tempfile::tempdir().unwrap();
        let fake_runsc = dir.path().join("runsc");
        std::fs::write(&fake_runsc, "#!/bin/sh\necho fake").unwrap();
        // Make world-writable
        std::fs::set_permissions(&fake_runsc, std::fs::Permissions::from_mode(0o777)).unwrap();

        let result = GVisorRuntime::validate_runsc_path(&fake_runsc);
        assert!(
            result.is_err(),
            "validate_runsc_path must reject world-writable binaries"
        );
    }

    #[test]
    fn test_validate_runsc_rejects_group_writable() {
        let dir = tempfile::tempdir().unwrap();
        let fake_runsc = dir.path().join("runsc");
        std::fs::write(&fake_runsc, "#!/bin/sh\necho fake").unwrap();
        // Make group-writable
        std::fs::set_permissions(&fake_runsc, std::fs::Permissions::from_mode(0o775)).unwrap();

        let result = GVisorRuntime::validate_runsc_path(&fake_runsc);
        assert!(
            result.is_err(),
            "validate_runsc_path must reject group-writable binaries"
        );
    }

    #[test]
    fn test_runsc_owner_accepts_nix_store_artifact_owner() {
        // Use a real Nix store binary so the metadata/permission checks pass.
        // The /nix/store contents are read-only and content-addressed, so any
        // existing file with mode 555 works.
        let nix_binary = std::fs::read_dir("/nix/store")
            .ok()
            .and_then(|mut entries| {
                entries.find_map(|e| {
                    let dir = e.ok()?.path();
                    let candidate = dir.join("bin/runsc");
                    if candidate.exists() {
                        Some(candidate)
                    } else {
                        None
                    }
                })
            });

        let path = match nix_binary {
            Some(p) => p,
            None => {
                eprintln!("skipping: no runsc binary found in /nix/store");
                return;
            }
        };

        assert!(GVisorRuntime::is_trusted_runsc_owner(&path, 65534, 1000));
    }

    #[test]
    fn test_exec_environment_uses_hardcoded_path() {
        // The gVisor supervisor must NOT inherit the host PATH, to prevent
        // host filesystem layout leaking into the container environment.
        // Verify by setting a distinctive PATH and checking exec_environment
        // returns a hardcoded value instead.
        std::env::set_var("PATH", "/tmp/evil-inject/bin:/opt/attacker/sbin");
        let rt = GVisorRuntime::with_path("/fake/runsc".to_string());
        let tmp = tempfile::tempdir().unwrap();
        let env = rt.exec_environment(tmp.path()).unwrap();
        let path_entry = env
            .iter()
            .find(|e| e.to_str().is_ok_and(|s| s.starts_with("PATH=")))
            .expect("exec_environment must set PATH");
        let path_val = path_entry.to_str().unwrap();
        assert!(
            !path_val.contains("evil-inject") && !path_val.contains("attacker"),
            "exec_environment must use hardcoded PATH, not host PATH. Got: {}",
            path_val
        );
        assert_eq!(
            path_val, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
            "exec_environment PATH must be the standard hardcoded value"
        );
    }

    #[test]
    fn test_precreated_rootless_args_pass_runsc_rootless() {
        let rt = GVisorRuntime::with_path("/nix/store/fake-runsc/bin/runsc".to_string());
        let tmp = tempfile::tempdir().unwrap();
        let bundle = OciBundle::new(
            tmp.path().join("bundle"),
            OciConfig::new(vec!["/bin/true".to_string()], None),
        );

        let args = rt.build_oci_run_args(
            "container-id",
            &bundle,
            tmp.path(),
            GVisorOciRunOptions {
                network_mode: GVisorNetworkMode::Host,
                ignore_cgroups: true,
                runsc_rootless: true,
                require_supervisor_exec_policy: false,
                platform: GVisorPlatform::Systrap,
            },
        );

        assert!(args.iter().any(|arg| arg == "--rootless"));
        assert!(args.iter().any(|arg| arg == "--ignore-cgroups"));
    }

    #[test]
    fn test_rootless_oci_args_do_not_pass_runsc_rootless() {
        let rt = GVisorRuntime::with_path("/nix/store/fake-runsc/bin/runsc".to_string());
        let tmp = tempfile::tempdir().unwrap();
        let bundle = OciBundle::new(
            tmp.path().join("bundle"),
            OciConfig::new(vec!["/bin/true".to_string()], None),
        );

        let args = rt.build_oci_run_args(
            "container-id",
            &bundle,
            tmp.path(),
            GVisorOciRunOptions {
                network_mode: GVisorNetworkMode::Host,
                ignore_cgroups: true,
                runsc_rootless: false,
                require_supervisor_exec_policy: false,
                platform: GVisorPlatform::Systrap,
            },
        );

        assert!(!args.iter().any(|arg| arg == "--rootless"));
        assert!(args.iter().any(|arg| arg == "--ignore-cgroups"));
    }

    #[test]
    fn test_non_nix_runsc_is_staged_for_supervisor_exec_policy() {
        let tmp = tempfile::tempdir().unwrap();
        let fake_runsc = tmp.path().join("runsc-source");
        std::fs::write(&fake_runsc, b"fake-runsc").unwrap();
        std::fs::set_permissions(&fake_runsc, std::fs::Permissions::from_mode(0o500)).unwrap();

        let rt = GVisorRuntime::with_path(fake_runsc.to_string_lossy().to_string());
        let runsc_root = tmp.path().join("runsc-root");
        let (program, allow_roots) = rt.prepare_supervisor_runsc_program(&runsc_root).unwrap();

        assert!(program.starts_with(runsc_root.join("exec-allow")));
        assert_eq!(allow_roots, vec![runsc_root.join("exec-allow")]);
        assert_eq!(std::fs::read(&program).unwrap(), b"fake-runsc");
        let mode = std::fs::metadata(&program).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o500);
    }

    #[test]
    fn test_supervisor_exec_allow_roots_do_not_include_procfs() {
        let roots = GVisorRuntime::supervisor_exec_allow_roots(PathBuf::from(NIX_STORE_EXEC_ROOT));

        assert_eq!(roots, vec![PathBuf::from(NIX_STORE_EXEC_ROOT)]);
        assert!(
            !roots.iter().any(|root| root == Path::new("/proc")),
            "the supervisor policy must not allow recursive procfs execution"
        );
    }

    #[test]
    fn test_runsc_root_uses_hardened_artifact_dir_not_bundle_parent() {
        let _env_lock = EnvLock::acquire();
        let tmp = tempfile::tempdir().unwrap();
        let artifact_base = tmp.path().join("gvisor-artifacts");
        let _artifact_base = EnvVarGuard::set("NUCLEUS_GVISOR_ARTIFACT_BASE", &artifact_base);
        let _runtime = EnvVarGuard::remove("XDG_RUNTIME_DIR");

        let bundle_parent = tmp.path().join("shared");
        std::fs::create_dir_all(&bundle_parent).unwrap();
        std::fs::set_permissions(&bundle_parent, std::fs::Permissions::from_mode(0o777)).unwrap();
        let bundle = OciBundle::new(
            bundle_parent.join("bundle"),
            OciConfig::new(vec!["/bin/true".to_string()], None),
        );

        let runsc_root = GVisorRuntime::secure_runsc_root("container-id").unwrap();

        assert!(runsc_root
            .starts_with(artifact_base.join(GVisorRuntime::runsc_state_component("container-id"))));
        assert!(
            !runsc_root.starts_with(bundle.bundle_path().parent().unwrap()),
            "runsc root must not be derived from a custom bundle parent"
        );
    }

    #[test]
    fn test_runsc_staging_rejects_symlink_exec_allow_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let fake_runsc = tmp.path().join("runsc-source");
        std::fs::write(&fake_runsc, b"fake-runsc").unwrap();
        std::fs::set_permissions(&fake_runsc, std::fs::Permissions::from_mode(0o500)).unwrap();

        let runsc_root = tmp.path().join("runsc-root");
        std::fs::create_dir(&runsc_root).unwrap();
        std::fs::set_permissions(&runsc_root, std::fs::Permissions::from_mode(0o700)).unwrap();
        let victim_dir = tmp.path().join("victim");
        std::fs::create_dir(&victim_dir).unwrap();
        std::os::unix::fs::symlink(&victim_dir, runsc_root.join("exec-allow")).unwrap();

        let rt = GVisorRuntime::with_path(fake_runsc.to_string_lossy().to_string());
        let err = rt
            .prepare_supervisor_runsc_program(&runsc_root)
            .unwrap_err()
            .to_string();

        assert!(
            err.contains("Refusing symlink private runsc exec directory"),
            "unexpected error: {}",
            err
        );
        assert!(
            !victim_dir.join("runsc").exists(),
            "staging must not follow the exec-allow symlink"
        );
    }

    #[test]
    fn test_runsc_owner_rejects_untrusted_non_store_owner() {
        assert!(!GVisorRuntime::is_trusted_runsc_owner(
            Path::new("/tmp/runsc"),
            4242,
            1000
        ));
    }
}