ognibuild 0.2.19

Detect and run any build system
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
use crate::session::{CommandBuilder, Error, ImageError, Project, Session};
use std::path::{Path, PathBuf};

/// An unshare based session
pub struct UnshareSession {
    root: PathBuf,
    /// Owns the session root when it is a temporary directory this session
    /// created, and removes it on drop. `None` for a session pointed at a root
    /// it does not own. Held only for its `Drop`.
    _root_dir: Option<RootDir>,
    cwd: PathBuf,
    /// Whether to isolate the network namespace (deny network access).
    ///
    /// Held in a `Cell` so it can be toggled through a shared reference: the
    /// network needs to be turned on and off around individual install steps
    /// while the session is borrowed immutably elsewhere (e.g. by an installer).
    isolate_network: std::cell::Cell<bool>,
}

/// A temporary session root, removed on drop.
///
/// Deliberately not a [`tempfile::TempDir`]. The root is populated by `tar` or
/// `mmdebstrap` running in a user namespace, which leaves files owned by uids
/// from the caller's `/etc/subuid` range. Those are not the caller's uid, and the
/// directories holding them are not writable by the caller, so the plain
/// `remove_dir_all` that `TempDir` performs on drop fails with EPERM -- and
/// `TempDir` discards that error, leaving several hundred MB behind per session.
struct RootDir(PathBuf);

impl RootDir {
    fn new() -> Result<Self, crate::session::Error> {
        // Only the directory is taken from tempfile; cleanup is ours.
        let td = tempfile::tempdir().map_err(|e| {
            crate::session::Error::SetupFailure("tempdir failed".to_string(), e.to_string())
        })?;
        Ok(Self(td.keep()))
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for RootDir {
    fn drop(&mut self) {
        if let Err(e) = remove_root(&self.0) {
            log::warn!("Failed to remove session root {}: {}", self.0.display(), e);
        }
    }
}

/// Remove a session root, including files owned by mapped subuids.
///
/// Re-entering a user namespace with `--map-auto` maps the caller's whole subuid
/// range, and `--map-root-user` makes the caller root within it, which is enough
/// to unlink files owned by those subuids.
///
/// That namespace is not always available: `unshare` may be missing, or the
/// caller may have no `/etc/subuid` range (as on GitHub Actions runners). Both
/// are only a hard requirement for *running* a session, so fall back to a direct
/// removal -- if a session root cannot be populated through a user namespace, it
/// holds nothing but caller-owned files, and `remove_dir_all` handles it.
fn remove_root(root: &Path) -> std::io::Result<()> {
    let status = std::process::Command::new("unshare")
        .arg("--map-auto")
        .arg("--map-root-user")
        .arg("--setuid=0")
        .arg("--setgid=0")
        .arg("--")
        .arg("rm")
        .arg("-rf")
        .arg("--")
        .arg(root)
        .status();

    if matches!(status, Ok(status) if status.success()) {
        return Ok(());
    }

    std::fs::remove_dir_all(root)
}

fn compression_flag(path: &Path) -> Result<Option<&str>, crate::session::Error> {
    match path.extension().unwrap().to_str().unwrap() {
        "tar" => Ok(None),
        "gz" => Ok(Some("-z")),
        "bz2" => Ok(Some("-j")),
        "xz" => Ok(Some("-J")),
        "zst" => Ok(Some("--zstd")),
        e => Err(crate::session::Error::SetupFailure(
            "unknown extension".to_string(),
            format!("unknown extension: {}", e),
        )),
    }
}

/// Enter the session root with a working `/dev`, then exec the command.
///
/// A tarball cannot carry device nodes (creating them needs CAP_MKNOD, which an
/// unprivileged extraction does not have, and which the kernel forbids in a user
/// namespace regardless), so the root's `/dev` holds at best plain files. apt,
/// among others, needs a real `/dev/null`, and fails in ways that look like
/// network timeouts when it cannot open one.
///
/// mknod being out, the host's nodes are bind-mounted in instead. Only the
/// handful a build environment expects are bound, rather than the whole host
/// `/dev` -- no reason to expose its disks, loop devices or `/dev/mem` to a
/// build. `/dev/shm` comes from the host too, so shared memory is real tmpfs and
/// not just a writable directory. This has to happen before entering the root,
/// since the host's devices are unreachable by path afterwards, so the binds are
/// done here and a nested `unshare --root` then enters the root to run the
/// command.
///
/// $1 is the root, $2 the working directory, and the rest the command. They are
/// passed as arguments rather than interpolated so a command containing spaces
/// or shell metacharacters survives intact.
const DEV_SETUP: &str = r#"
set -e
root="$1"
wd="$2"
shift 2
for node in null zero full random urandom tty; do
    [ -e "/dev/$node" ] || continue
    : > "$root/dev/$node"
    mount --bind "/dev/$node" "$root/dev/$node"
done
mkdir -p "$root/dev/shm"
mount --rbind /dev/shm "$root/dev/shm"
exec unshare --root="$root" --wd="$wd" -- "$@"
"#;

/// Get the path to a cached Debian tarball if it exists
///
/// # Arguments
/// * `suite` - The Debian suite to use (e.g., "sid", "bookworm")
///
/// # Returns
/// * `Option<PathBuf>` - Path to the cached tarball if it exists
pub fn cached_debian_tarball_path(suite: &str) -> Result<PathBuf, crate::session::Error> {
    let arch = std::env::consts::ARCH;
    let arch_name = match arch {
        "x86_64" => "amd64",
        "aarch64" => "arm64",
        other => other,
    };

    // Use ~/.cache/ognibuild/images/ for caching
    let base_cache_dir = dirs::cache_dir()
        .ok_or_else(|| crate::session::Error::ImageError(ImageError::NoCachedImage))?;
    let cache_dir = base_cache_dir.join("ognibuild").join("images");

    let tarball_name = format!("debian-{}-{}.tar.gz", suite, arch_name);
    Ok(cache_dir.join(&tarball_name))
}

impl UnshareSession {
    /// Set whether to isolate the network namespace.
    ///
    /// When true (the default), the session will have no network access.
    /// When false, the session shares the host's network namespace.
    pub fn set_isolate_network(&self, isolate: bool) {
        self.isolate_network.set(isolate);
    }

    /// Create a cached Debian session from a cloud image
    ///
    /// Looks for a cached tarball in ~/.cache/ognibuild/images/debian-{suite}-{arch}.tar.xz
    /// # Arguments
    /// * `suite` - The Debian suite to use (e.g., "sid", "bookworm")
    pub fn cached_debian_session(suite: &str) -> Result<Self, crate::session::Error> {
        let tarball_path = cached_debian_tarball_path(suite)?;
        if !tarball_path.exists() {
            Err(Error::ImageError(ImageError::NoCachedImage))
        } else {
            log::info!(
                "Using cached Debian {} image from: {}",
                suite,
                tarball_path.display()
            );
            Self::from_tarball(&tarball_path)
        }
    }

    /// Create a session from a tarball
    pub fn from_tarball(path: &Path) -> Result<Self, crate::session::Error> {
        let td = RootDir::new()?;

        // Run tar within unshare to extract the tarball. This is necessary because
        // the tarball may contain files that are owned by a different user.
        //
        // However, the tar executable is not available within the unshare environment.
        // Therefore, we need to extract the tarball to a temporary directory and then
        // move it to the final location.
        let root = td.path();

        let f = std::fs::File::open(path).map_err(|e| {
            crate::session::Error::SetupFailure("open failed".to_string(), e.to_string())
        })?;

        // Create necessary directories for mounting before extraction
        // These might not exist in cloud images
        for dir in &["proc", "sys", "dev"] {
            std::fs::create_dir_all(root.join(dir)).map_err(|e| {
                crate::session::Error::SetupFailure(
                    format!("Failed to create {} directory", dir),
                    e.to_string(),
                )
            })?;
        }

        let output = std::process::Command::new("unshare")
            .arg("--map-users=auto")
            .arg("--map-groups=auto")
            .arg("--fork")
            .arg("--pid")
            .arg("--mount-proc")
            .arg("--net")
            .arg("--uts")
            .arg("--ipc")
            .arg("--wd")
            .arg(root)
            .arg("--")
            .arg("tar")
            // -p preserves special permission bits (notably the sticky bit on
            // /tmp). Without it tar applies the umask and drops them, leaving
            // /tmp non-sticky and unwritable by apt's _apt sandbox user.
            .arg("xp")
            .arg(compression_flag(path)?.unwrap_or("--"))
            .stdin(std::process::Stdio::from(f))
            .stderr(std::process::Stdio::piped())
            .output()?;

        if !output.status.success() {
            let stderr = String::from_utf8(output.stderr).unwrap();
            return Err(crate::session::Error::SetupFailure(
                "tar failed".to_string(),
                stderr,
            ));
        }

        let root = root.to_path_buf();
        let s = Self {
            root,
            _root_dir: Some(td),
            cwd: std::path::PathBuf::from("/"),
            isolate_network: std::cell::Cell::new(true),
        };

        s.ensure_current_user()?;

        Ok(s)
    }

    /// Save the session to a tarball
    pub fn save_to_tarball(&self, path: &Path) -> Result<(), crate::session::Error> {
        // Create the tarball from within the session, dumping it to stdout
        let mut child = self.popen(
            vec![
                "tar",
                "c",
                "--absolute-names",
                "--exclude",
                "/dev/*",
                "--exclude",
                "/proc/*",
                "--exclude",
                "/sys/*",
                compression_flag(path)?.unwrap_or("--"),
                "/",
            ],
            Some(std::path::Path::new("/")),
            Some("root"),
            Some(std::process::Stdio::piped()),
            None,
            None,
            None,
        )?;

        let f = std::fs::File::create(path).map_err(|e| {
            crate::session::Error::SetupFailure("create failed".to_string(), e.to_string())
        })?;

        let mut writer = std::io::BufWriter::new(f);

        std::io::copy(child.stdout.as_mut().unwrap(), &mut writer).map_err(|e| {
            crate::session::Error::SetupFailure("copy failed".to_string(), e.to_string())
        })?;

        if child.wait()?.success() {
            Ok(())
        } else {
            Err(crate::session::Error::SetupFailure(
                "tar failed".to_string(),
                "tar failed".to_string(),
            ))
        }
    }

    /// Bootstrap the session environment with Debian sid
    pub fn bootstrap() -> Result<Self, crate::session::Error> {
        bootstrap_debian_tarball("sid", true, &[])
    }

    /// Verify that the current user has an account in the session
    pub fn ensure_current_user(&self) -> Result<(), crate::session::Error> {
        // Ensure that the current user has an entry in /etc/passwd
        let user = whoami::username().map_err(|e| {
            crate::session::Error::SetupFailure(
                "Failed to get current username".to_string(),
                e.to_string(),
            )
        })?;
        let uid = nix::unistd::getuid().to_string();
        let gid = nix::unistd::getgid().to_string();

        match self.check_call(
            vec![
                "/usr/sbin/groupadd",
                "--force",
                "--non-unique",
                "--gid",
                &gid,
                user.as_str(),
            ],
            Some(std::path::Path::new("/")),
            Some("root"),
            None,
        ) {
            Ok(_) => {}
            Err(e) => panic!("Error: {:?}", e),
        }

        let child = self.popen(
            vec![
                "/usr/sbin/useradd",
                "--uid",
                &uid,
                "--gid",
                &gid,
                user.as_str(),
            ],
            Some(std::path::Path::new("/")),
            Some("root"),
            None,
            Some(std::process::Stdio::piped()),
            None,
            None,
        )?;

        match child.wait_with_output() {
            Ok(output) => {
                match output.status.code() {
                    // User created
                    Some(0) => Ok(()),
                    // Ignore if user already exists
                    Some(9) => Ok(()),
                    Some(4) => Ok(()),
                    _ => panic!(
                        "Error: {:?}: {}",
                        output.status,
                        String::from_utf8(output.stdout).unwrap()
                    ),
                }
            }
            Err(e) => panic!("Error: {:?}", e),
        }
    }

    /// Run a command in the session
    pub fn run_argv(
        &self,
        argv: Vec<&str>,
        cwd: Option<&std::path::Path>,
        user: Option<&str>,
    ) -> std::vec::Vec<String> {
        let mut ret: Vec<String> = [
            "unshare",
            "--map-users=auto",
            "--map-groups=auto",
            "--fork",
            "--pid",
            "--mount-proc",
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        if self.isolate_network.get() {
            ret.push("--net".to_string());
        }
        // Always map root, which DEV_SETUP needs in order to mount. Root inside
        // the namespace is the calling user outside it, so files a command
        // creates still belong to the caller on the host -- which the host-side
        // copy in project_from_directory, and cleanup, both rely on.
        ret.extend(
            ["--uts", "--ipc", "--map-root-user"]
                .iter()
                .map(|s| s.to_string()),
        );
        ret.push("--".to_string());
        ret.extend([
            "/bin/sh".to_string(),
            "-c".to_string(),
            DEV_SETUP.to_string(),
            // $0 for the shell; DEV_SETUP takes the root and the cwd as $1 and $2.
            "unshare-session".to_string(),
            self.root.to_str().unwrap().to_string(),
            cwd.unwrap_or(&self.cwd).to_str().unwrap().to_string(),
        ]);
        // Only a user other than root needs dropping to; root is what the
        // namespace already maps to.
        if let Some(user) = user.filter(|u| *u != "root") {
            ret.extend([
                "/usr/bin/setpriv".to_string(),
                format!("--reuid={}", user),
                "--init-groups".to_string(),
            ]);
        }
        ret.extend(argv.into_iter().map(|s| s.to_string()));
        ret
    }

    fn build_tempdir(&self, user: Option<&str>) -> std::path::PathBuf {
        let build_dir = "/build";

        // Ensure that the build directory exists
        self.check_call(vec!["mkdir", "-p", build_dir], None, user, None)
            .unwrap();

        String::from_utf8(
            self.check_output(
                vec!["mktemp", "-d", format!("--tmpdir={}", build_dir).as_str()],
                Some(std::path::Path::new("/")),
                user,
                None,
            )
            .unwrap(),
        )
        .unwrap()
        .trim_end_matches('\n')
        .to_string()
        .into()
    }
}

/// Create a Debian UnshareSession for testing, with fallback options
///
/// This function tries the following in order:
/// 1. If OGNIBUILD_DEBIAN_TEST_TARBALL is set, use that tarball
/// 2. If a cached image exists, use it
/// 3. Otherwise, bootstrap from network using mmdebstrap
///
/// # Arguments
/// * `suite` - The Debian suite to use (e.g., "sid", "unstable", "bookworm", "stable")
pub fn create_debian_session_for_testing(
    suite: &str,
    allow_network: bool,
) -> Result<UnshareSession, crate::session::Error> {
    // Check if a custom tarball path is provided for testing
    if let Ok(tarball_path) = std::env::var("OGNIBUILD_DEBIAN_TEST_TARBALL") {
        let path = Path::new(&tarball_path);
        if path.exists() {
            log::info!(
                "Using Debian test tarball from OGNIBUILD_DEBIAN_TEST_TARBALL: {}",
                tarball_path
            );
            return UnshareSession::from_tarball(path);
        } else {
            return Err(Error::SetupFailure(
                "Tarball not found".to_string(),
                format!(
                    "OGNIBUILD_DEBIAN_TEST_TARBALL points to non-existent file: {}",
                    tarball_path
                ),
            ));
        }
    }

    // Try to use cached session first (without downloading if not present)
    match UnshareSession::cached_debian_session(suite) {
        Ok(session) => {
            // cached_debian_session already logged which image is being used.
            return Ok(session);
        }
        Err(Error::ImageError(ImageError::NoCachedImage)) => {
            log::debug!("No cached image available for Debian {}", suite);
            // Continue to next option: bootstrap from network
        }
        Err(Error::ImageError(ImageError::CachedImageNotFound { path })) => {
            log::debug!("Cached image not found at {}", path.display());
            // Continue to next option: bootstrap from network
        }
        Err(e) => return Err(e), // Other errors should propagate
    }

    if !allow_network {
        return Err(Error::ImageError(ImageError::NoCachedImage));
    }

    // Default: bootstrap from network
    log::info!(
        "No cached image found, bootstrapping Debian {} test session from network using mmdebstrap",
        suite
    );
    bootstrap_debian_tarball(suite, true, &[])
}

/// Bootstrap a Debian system using mmdebstrap and create a tarball
///
/// # Arguments
/// * `suite` - The Debian suite to use (e.g., "sid", "unstable", "bookworm", "stable")
/// * `setup_apt_file` - Whether to install and configure apt-file during bootstrap (requires network)
/// * `extra_packages` - Additional packages to install into the bootstrapped image
pub fn bootstrap_debian_tarball(
    suite: &str,
    setup_apt_file: bool,
    extra_packages: &[&str],
) -> Result<UnshareSession, crate::session::Error> {
    let td = RootDir::new()?;
    let root = td.path();

    // Build mmdebstrap command
    let mut cmd = std::process::Command::new("mmdebstrap");
    cmd.current_dir(root)
        .arg("--mode=unshare")
        .arg("--variant=minbase");

    if !extra_packages.is_empty() {
        cmd.arg(format!("--include={}", extra_packages.join(",")));
    }

    // The customizations below need network access to download indexes, so they
    // are gated on the same flag as apt-file setup.
    if setup_apt_file {
        log::info!(
            "Setting up apt-file and the Sources index in bootstrap (this requires network access)"
        );
        cmd.arg("--include=apt-file")
            // Add a deb-src entry and fetch the Sources index. ognibuild's
            // build-dependency tie-breaker counts how often each candidate
            // package is build-depended on across all source packages; without
            // the Sources index every count is zero and ties are broken
            // arbitrarily (e.g. picking the unusable "rustup" over "cargo").
            .arg(format!(
                "--customize-hook=echo 'deb-src http://deb.debian.org/debian/ {} main' >> \"$1\"/etc/apt/sources.list",
                suite
            ))
            .arg("--customize-hook=chroot \"$1\" apt-get update")
            // Download apt-file Contents files (used to map files to packages).
            .arg("--customize-hook=chroot \"$1\" apt-file update")
            // Preserve apt lists (Sources + Contents) for the tie-breaker and
            // apt-file inside the session.
            .arg("--skip=cleanup/apt/lists");
    }

    cmd.arg("--quiet")
        .arg(suite)
        .arg(root)
        .arg("http://deb.debian.org/debian/");

    let status = cmd.status().map_err(|e| {
        crate::session::Error::SetupFailure(
            "mmdebstrap command not found or failed to execute".to_string(),
            format!("Failed to run mmdebstrap (ensure it's installed): {}", e),
        )
    })?;

    if !status.success() {
        return Err(crate::session::Error::SetupFailure(
            "mmdebstrap failed".to_string(),
            format!("mmdebstrap exited with status: {}. This likely requires network access to http://deb.debian.org/debian/", status),
        ));
    }

    let root = root.to_path_buf();
    let s = UnshareSession {
        root,
        _root_dir: Some(td),
        cwd: std::path::PathBuf::from("/"),
        isolate_network: std::cell::Cell::new(true),
    };

    s.ensure_current_user()?;

    Ok(s)
}

impl Session for UnshareSession {
    fn chdir(&mut self, path: &std::path::Path) -> Result<(), crate::session::Error> {
        self.cwd = self.cwd.join(path);
        Ok(())
    }

    fn pwd(&self) -> &std::path::Path {
        &self.cwd
    }

    fn external_path(&self, path: &std::path::Path) -> std::path::PathBuf {
        if let Ok(rest) = path.strip_prefix("/") {
            return self.location().join(rest);
        }
        self.location()
            .join(
                self.cwd
                    .to_string_lossy()
                    .to_string()
                    .trim_start_matches('/'),
            )
            .join(path)
    }

    fn location(&self) -> std::path::PathBuf {
        self.root.clone()
    }

    fn check_output(
        &self,
        argv: Vec<&str>,
        cwd: Option<&std::path::Path>,
        user: Option<&str>,
        env: Option<std::collections::HashMap<String, String>>,
    ) -> Result<Vec<u8>, super::Error> {
        let argv = self.run_argv(argv, cwd, user);

        let output = std::process::Command::new(&argv[0])
            .args(&argv[1..])
            .stderr(std::process::Stdio::inherit())
            .envs(env.unwrap_or_default())
            .output();

        match output {
            Ok(output) => {
                if output.status.success() {
                    Ok(output.stdout)
                } else {
                    Err(Error::CalledProcessError(output.status))
                }
            }
            Err(e) => Err(Error::IoError(e)),
        }
    }

    fn create_home(&self) -> Result<(), super::Error> {
        crate::session::create_home(self)
    }

    fn check_call(
        &self,
        argv: Vec<&str>,
        cwd: Option<&std::path::Path>,
        user: Option<&str>,
        env: Option<std::collections::HashMap<String, String>>,
    ) -> Result<(), crate::session::Error> {
        let argv = self.run_argv(argv, cwd, user);

        let status = std::process::Command::new(&argv[0])
            .args(&argv[1..])
            .envs(env.unwrap_or_default())
            .status();

        match status {
            Ok(status) => {
                if status.success() {
                    Ok(())
                } else {
                    Err(Error::CalledProcessError(status))
                }
            }
            Err(e) => Err(Error::IoError(e)),
        }
    }

    fn exists(&self, path: &std::path::Path) -> bool {
        let args = vec!["test", "-e", path.to_str().unwrap()];
        self.check_call(args, None, None, None).is_ok()
    }

    fn mkdir(&self, path: &std::path::Path) -> Result<(), crate::session::Error> {
        let args = vec!["mkdir", path.to_str().unwrap()];
        self.check_call(args, None, None, None)
    }

    fn rmtree(&self, path: &std::path::Path) -> Result<(), crate::session::Error> {
        let args = vec!["rm", "-rf", path.to_str().unwrap()];
        self.check_call(args, None, None, None)
    }

    fn project_from_directory(
        &self,
        path: &std::path::Path,
        subdir: Option<&str>,
    ) -> Result<Project, super::Error> {
        let subdir = subdir.unwrap_or("package");
        let reldir = self.build_tempdir(Some("root"));

        let export_directory = self.external_path(&reldir).join(subdir);
        // Copy tree from path to export_directory

        let mut options = fs_extra::dir::CopyOptions::new();
        options.copy_inside = true; // Copy contents inside the source directory
        options.content_only = false; // Copy the entire directory
        options.skip_exist = false; // Skip if file already exists in the destination
        options.overwrite = true; // Overwrite files if they already exist
        options.buffer_size = 64000; // Buffer size in bytes
        options.depth = 0; // Recursion depth (0 for unlimited depth)

        // Perform the copy operation
        fs_extra::dir::copy(path, &export_directory, &options).map_err(|e| {
            crate::session::Error::SetupFailure(
                format!("failed to copy {} into session", path.display()),
                e.to_string(),
            )
        })?;

        Ok(Project::Temporary {
            external_path: export_directory,
            internal_path: reldir.join(subdir),
            td: self.external_path(&reldir),
        })
    }

    fn popen(
        &self,
        argv: Vec<&str>,
        cwd: Option<&std::path::Path>,
        user: Option<&str>,
        stdout: Option<std::process::Stdio>,
        stderr: Option<std::process::Stdio>,
        stdin: Option<std::process::Stdio>,
        env: Option<&std::collections::HashMap<String, String>>,
    ) -> Result<std::process::Child, Error> {
        let argv = self.run_argv(argv, cwd, user);

        let mut binding = std::process::Command::new(&argv[0]);
        let mut cmd = binding.args(&argv[1..]);

        if let Some(env) = env {
            cmd = cmd.envs(env);
        }

        if let Some(stdin) = stdin {
            cmd = cmd.stdin(stdin);
        }

        if let Some(stdout) = stdout {
            cmd = cmd.stdout(stdout);
        }

        if let Some(stderr) = stderr {
            cmd = cmd.stderr(stderr);
        }

        Ok(cmd.spawn()?)
    }

    fn is_temporary(&self) -> bool {
        true
    }

    #[cfg(feature = "breezy")]
    fn project_from_vcs(
        &self,
        tree: &dyn crate::vcs::DupableTree,
        include_controldir: Option<bool>,
        subdir: Option<&str>,
    ) -> Result<Project, Error> {
        let reldir = self.build_tempdir(None);

        let subdir = subdir.unwrap_or("package");

        let export_directory = self.external_path(&reldir).join(subdir);
        if !include_controldir.unwrap_or(false) {
            tree.export_to(&export_directory, None).unwrap();
        } else {
            crate::vcs::dupe_vcs_tree(tree, &export_directory).unwrap();
        }

        Ok(Project::Temporary {
            external_path: export_directory,
            internal_path: reldir.join(subdir),
            td: self.external_path(&reldir),
        })
    }

    fn command<'a>(&'a self, argv: Vec<&'a str>) -> CommandBuilder<'a> {
        CommandBuilder::new(self, argv)
    }

    fn read_dir(&self, path: &std::path::Path) -> Result<Vec<std::fs::DirEntry>, Error> {
        std::fs::read_dir(self.external_path(path))
            .map_err(Error::IoError)?
            .collect::<Result<Vec<_>, _>>()
            .map_err(Error::IoError)
    }

    fn set_isolate_network(&self, isolate: bool) {
        self.isolate_network.set(isolate);
    }

    fn is_network_isolated(&self) -> bool {
        self.isolate_network.get()
    }
}

#[cfg(test)]
lazy_static::lazy_static! {
    // Serializes access to the process-global OGNIBUILD_DEBIAN_TEST_TARBALL
    // environment variable so that tests mutating it cannot race with the shared
    // session initializer (which also reads it).
    pub(crate) static ref TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    // None when no cached image or test tarball is available, so tests can skip
    // gracefully rather than the lazy initializer panicking on first access.
    //
    // The session is extracted once and shared by every test in the binary, which
    // means it has to outlive them all -- and a `lazy_static` is never dropped, so
    // `RootDir` would never get to remove its root. `drop_test_session` below runs
    // at process exit to do it.
    static ref TEST_SESSION: std::sync::Mutex<Option<UnshareSession>> = std::sync::Mutex::new({
        let _guard = TEST_ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        create_debian_session_for_testing("sid", false).ok()
    });
}

/// Drop the shared test session at exit, so its root gets removed.
#[cfg(test)]
#[ctor::dtor]
fn drop_test_session() {
    let mut guard = TEST_SESSION.lock().unwrap_or_else(|p| p.into_inner());
    guard.take();
}

/// A locked, available [`UnshareSession`] for use in tests.
///
/// Derefs to the session so existing call sites can use it directly. Only
/// constructed when the underlying session is present.
#[cfg(test)]
pub(crate) struct TestSession(std::sync::MutexGuard<'static, Option<UnshareSession>>);

#[cfg(test)]
impl std::ops::Deref for TestSession {
    type Target = UnshareSession;

    fn deref(&self) -> &Self::Target {
        self.0.as_ref().expect("test session present")
    }
}

#[cfg(test)]
impl std::ops::DerefMut for TestSession {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.0.as_mut().expect("test session present")
    }
}

#[cfg(test)]
pub(crate) fn test_session() -> Option<TestSession> {
    // Don't run tests if we're in github actions (CI environment restrictions)
    if std::env::var("GITHUB_ACTIONS").is_ok() {
        return None;
    }
    // Handle poisoned mutex: if a previous test panicked while holding the lock,
    // we recover the guard to allow tests to continue.
    let guard = match TEST_SESSION.lock() {
        Ok(guard) => guard,
        Err(poisoned) => poisoned.into_inner(),
    };
    // Skip gracefully when no cached image or test tarball is available.
    if guard.is_none() {
        return None;
    }
    Some(TestSession(guard))
}

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

    /// A root populated in a user namespace holds files owned by mapped subuids,
    /// which the calling user cannot unlink. Dropping the session has to remove
    /// them anyway; a plain `remove_dir_all` (as `tempfile::TempDir` does) fails
    /// with EPERM and would leave the whole tree behind.
    #[test]
    fn test_drop_removes_subuid_owned_root() {
        if std::env::var("GITHUB_ACTIONS").is_ok() {
            return;
        }

        let td = tempfile::tempdir().unwrap();
        let root = td.keep();

        // Populate the root the way mmdebstrap does: as root inside a user
        // namespace, so the files land owned by a subuid on the host.
        let status = std::process::Command::new("unshare")
            .arg("--map-auto")
            .arg("--map-root-user")
            .arg("--setuid=0")
            .arg("--setgid=0")
            .arg("--")
            .arg("sh")
            .arg("-c")
            .arg(format!(
                "mkdir -p {0}/usr/bin && touch {0}/usr/bin/f && chown -R 1:1 {0}/usr && chmod -R a-w {0}/usr",
                root.display()
            ))
            .status();

        match status {
            Ok(status) if status.success() => {}
            // No unshare, or no subuid range configured: nothing to test here.
            _ => {
                std::fs::remove_dir_all(&root).ok();
                return;
            }
        }

        // Confirm the setup actually reproduces the condition: the caller must
        // not be able to remove this tree by itself, or the test proves nothing.
        assert!(
            std::fs::remove_dir_all(&root).is_err(),
            "expected the subuid-owned root to be unremovable by the calling user"
        );

        std::mem::drop(RootDir(root.clone()));

        assert!(!root.exists(), "session root {} leaked", root.display());
    }

    /// The root has to be removed even when setup fails partway through, which
    /// is where a `mmdebstrap` root -- already populated, already subuid-owned --
    /// used to be abandoned.
    #[test]
    fn test_root_removed_when_setup_fails() {
        let td = RootDir::new().unwrap();
        let root = td.path().to_path_buf();
        std::fs::write(root.join("half-extracted"), "x").unwrap();

        std::mem::drop(td);

        assert!(!root.exists(), "session root {} leaked", root.display());
    }

    #[test]
    fn test_drop_leaves_unowned_root_alone() {
        let td = tempfile::tempdir().unwrap();
        let session = UnshareSession {
            root: td.path().to_path_buf(),
            _root_dir: None,
            cwd: std::path::PathBuf::from("/"),
            isolate_network: std::cell::Cell::new(true),
        };
        std::mem::drop(session);
        assert!(td.path().exists());
    }

    #[test]
    fn test_is_temporary() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        assert!(session.is_temporary());
    }

    #[test]
    fn test_chdir() {
        let mut session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        session.chdir(std::path::Path::new("/")).unwrap();
    }

    #[test]
    fn test_check_output() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        let output = String::from_utf8(
            session
                .check_output(vec!["ls"], Some(std::path::Path::new("/")), None, None)
                .unwrap(),
        )
        .unwrap();
        let dirs = output.split_whitespace().collect::<Vec<&str>>();
        assert!(dirs.contains(&"bin"));
        assert!(dirs.contains(&"dev"));
        assert!(dirs.contains(&"etc"));
        assert!(dirs.contains(&"home"));
        assert!(dirs.contains(&"lib"));
        assert!(dirs.contains(&"usr"));
        assert!(dirs.contains(&"proc"));

        assert_eq!(
            "root",
            String::from_utf8(
                session
                    .check_output(vec!["whoami"], None, Some("root"), None)
                    .unwrap()
            )
            .unwrap()
            .trim_end()
        );
        assert_eq!(
            // Get current process uid
            String::from_utf8(
                session
                    .check_output(vec!["id", "-u"], None, None, None)
                    .unwrap()
            )
            .unwrap()
            .trim_end(),
            String::from_utf8(
                session
                    .check_output(vec!["id", "-u"], None, None, None)
                    .unwrap()
            )
            .unwrap()
            .trim_end()
        );

        assert_eq!(
            "nobody",
            String::from_utf8(
                session
                    .check_output(vec!["whoami"], None, Some("nobody"), None)
                    .unwrap()
            )
            .unwrap()
            .trim_end()
        );
    }

    #[test]
    fn test_missing_command_is_recognisable() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        // The build fixers only install a missing command if the failure is
        // phrased in a way buildlog-consultant recognises, so the wording of the
        // shim that execs the command matters.
        let err = crate::analyze::run_detecting_problems(
            &*session,
            vec!["definitely-not-a-real-command"],
            None,
            true,
            Some(std::path::Path::new("/")),
            None,
            None,
            None,
        )
        .unwrap_err();

        let crate::analyze::AnalyzedError::Detailed { error, .. } = err else {
            panic!("missing command not identified: {:?}", err);
        };
        assert_eq!(error.kind(), "command-missing");
    }

    #[test]
    fn test_dev_nodes_are_devices() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        // A tarball cannot carry device nodes, so an unpacked root has at best a
        // regular file here. apt needs a real one, and fails obscurely without it.
        let out = session
            .check_output(
                vec!["stat", "-c", "%F", "/dev/null", "/dev/urandom"],
                Some(std::path::Path::new("/")),
                None,
                None,
            )
            .unwrap();
        assert_eq!(
            String::from_utf8(out).unwrap(),
            "character special file\ncharacter special file\n"
        );
    }

    #[test]
    fn test_dev_shm_writable() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        // Some build tools rely on a writable /dev/shm as the calling user;
        // verify a command run without an explicit user can create a file there.
        session
            .check_call(
                vec!["touch", "/dev/shm/ognibuild-test"],
                Some(std::path::Path::new("/")),
                None,
                None,
            )
            .unwrap();
        session
            .check_call(
                vec!["rm", "/dev/shm/ognibuild-test"],
                Some(std::path::Path::new("/")),
                None,
                None,
            )
            .unwrap();
    }

    #[test]
    fn test_check_call() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        session
            .check_call(vec!["true"], Some(std::path::Path::new("/")), None, None)
            .unwrap();
    }

    #[test]
    fn test_create_home() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        session.create_home().unwrap();
    }

    fn save_and_reuse(name: &str) {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        let tempdir = tempfile::tempdir().unwrap();
        let path = tempdir.path().join(name);
        session.save_to_tarball(&path).unwrap();
        std::mem::drop(session);
        let session = UnshareSession::from_tarball(&path).unwrap();
        assert!(session.exists(std::path::Path::new("/bin")));
        // Verify that the session works
        let output = String::from_utf8(
            session
                .check_output(vec!["ls"], Some(std::path::Path::new("/")), None, None)
                .unwrap(),
        )
        .unwrap();
        let dirs = output.split_whitespace().collect::<Vec<&str>>();
        assert!(dirs.contains(&"bin"));
        assert!(dirs.contains(&"dev"));
        assert!(dirs.contains(&"etc"));
        assert!(dirs.contains(&"home"));
        assert!(dirs.contains(&"lib"));
    }

    #[test]
    fn test_save_and_reuse() {
        save_and_reuse("test.tar");
    }

    #[test]
    fn test_save_and_reuse_gz() {
        save_and_reuse("test.tar.gz");
    }

    #[test]
    fn test_mkdir_rmdir() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        let path = std::path::Path::new("/tmp/test");
        session.mkdir(path).unwrap();
        assert!(session.exists(path));
        session.rmtree(path).unwrap();
        assert!(!session.exists(path));
    }

    #[test]
    fn test_project_from_directory() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        let tempdir = tempfile::tempdir().unwrap();
        std::fs::write(tempdir.path().join("test"), "test").unwrap();
        let project = session
            .project_from_directory(tempdir.path(), None)
            .unwrap();
        assert!(project.external_path().exists());
        assert!(session.exists(project.internal_path()));
        session.rmtree(project.internal_path()).unwrap();
        assert!(!session.exists(project.internal_path()));
        assert!(!project.external_path().exists());
    }

    #[test]
    fn test_session_works_after_panic() {
        // Skip if we're in CI
        if std::env::var("GITHUB_ACTIONS").is_ok() {
            return;
        }

        // First, verify we can get the session normally
        let session1 = test_session().unwrap();
        assert!(session1.exists(std::path::Path::new("/bin")));
        std::mem::drop(session1);

        // Now cause a panic while holding the lock
        let result = std::panic::catch_unwind(|| {
            let _session = test_session().unwrap();
            panic!("Intentional panic to test recovery");
        });

        // Verify the panic happened
        assert!(result.is_err());

        // Now verify we can still get the session (it shouldn't be blocked)
        let session2 = test_session().unwrap();
        assert!(session2.exists(std::path::Path::new("/bin")));

        // Verify the session is still functional by running a command
        session2
            .check_call(vec!["true"], Some(std::path::Path::new("/")), None, None)
            .unwrap();
    }

    #[test]
    fn test_cached_debian_session_no_download() {
        // Test that cached_debian_session returns the correct error when download is not allowed
        // and no cached file exists
        let result = UnshareSession::cached_debian_session("test-suite-nonexistent");
        assert!(result.is_err());
        if let Err(err) = result {
            assert!(
                matches!(
                    err,
                    crate::session::Error::ImageError(
                        crate::session::ImageError::CachedImageNotFound { .. }
                            | crate::session::ImageError::NoCachedImage
                    )
                ),
                "Expected CachedImageNotFound error, got {:?}",
                err
            );
        }
    }

    #[test]
    fn test_cached_debian_session_unsupported_arch() {
        // This test will only work on architectures that are not x86_64 or aarch64
        let arch = std::env::consts::ARCH;
        if arch == "x86_64" || arch == "aarch64" {
            // Skip this test on supported architectures
            return;
        }

        let result = UnshareSession::cached_debian_session("sid");
        assert!(result.is_err());
        if let Err(err) = result {
            assert!(
                matches!(
                    err,
                    crate::session::Error::ImageError(
                        crate::session::ImageError::UnsupportedArchitecture { .. }
                    )
                ),
                "Expected UnsupportedArchitecture error, got {:?}",
                err
            );
        }
    }

    #[test]
    fn test_create_debian_session_with_env_var() {
        // Test that create_debian_session_for_testing respects OGNIBUILD_DEBIAN_TEST_TARBALL
        let _env_guard = TEST_ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        let temp_dir = tempfile::tempdir().unwrap();
        let tarball_path = temp_dir.path().join("test.tar.xz");

        // Create a minimal test tarball (invalid but exists)
        std::fs::write(&tarball_path, b"test").unwrap();

        // Set the environment variable to use this tarball
        std::env::set_var(
            "OGNIBUILD_DEBIAN_TEST_TARBALL",
            tarball_path.to_str().unwrap(),
        );

        // This should attempt to use the tarball (will fail because it's not valid, but that's ok)
        let result = create_debian_session_for_testing("sid", false);

        // Clean up
        std::env::remove_var("OGNIBUILD_DEBIAN_TEST_TARBALL");

        // We expect this to fail because our test tarball is not valid,
        // but it should fail in from_tarball with a SetupFailure, not because the file doesn't exist
        assert!(result.is_err());
        if let Err(err) = result {
            // Should be a SetupFailure from tar extraction, not a file not found error
            assert!(
                matches!(err, crate::session::Error::SetupFailure(_, _)),
                "Expected SetupFailure from tar extraction, got {:?}",
                err
            );
        }
    }

    #[test]
    fn test_create_debian_session_nonexistent_tarball() {
        // Test that pointing to a non-existent tarball gives the right error
        let _env_guard = TEST_ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());
        std::env::set_var(
            "OGNIBUILD_DEBIAN_TEST_TARBALL",
            "/nonexistent/path/tarball.tar.xz",
        );

        let result = create_debian_session_for_testing("sid", false);

        std::env::remove_var("OGNIBUILD_DEBIAN_TEST_TARBALL");

        assert!(result.is_err());
        if let Err(err) = result {
            // Should be a SetupFailure about non-existent file
            match err {
                crate::session::Error::SetupFailure(_msg, detail) => {
                    assert!(
                        detail.contains("non-existent file"),
                        "Expected error about non-existent file, got: {}",
                        detail
                    );
                }
                _ => panic!("Expected SetupFailure, got {:?}", err),
            }
        }
    }

    #[cfg(not(feature = "debian"))]
    #[test]
    fn test_cached_debian_session_no_debian_feature() {
        // When debian feature is not enabled, downloading should return DownloadNotAvailable error
        let result = UnshareSession::cached_debian_session("sid");

        // If the cache doesn't exist, it should fail with DownloadNotAvailable
        // (assuming the cache doesn't exist for this test)
        if result.is_err() {
            if let Err(err) = result {
                // Could be CachedImageNotFound if cache exists, or DownloadNotAvailable if trying to download
                assert!(
                    matches!(err, crate::session::Error::ImageError(_)),
                    "Expected ImageError, got {:?}",
                    err
                );
            }
        }
    }

    #[test]
    fn test_popen() {
        let session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        let child = session
            .popen(
                vec!["ls"],
                Some(std::path::Path::new("/")),
                None,
                Some(std::process::Stdio::piped()),
                Some(std::process::Stdio::piped()),
                Some(std::process::Stdio::piped()),
                None,
            )
            .unwrap();
        let output = String::from_utf8(child.wait_with_output().unwrap().stdout).unwrap();
        let dirs = output.split_whitespace().collect::<Vec<&str>>();
        assert!(dirs.contains(&"etc"));
        assert!(dirs.contains(&"home"));
        assert!(dirs.contains(&"lib"));
        assert!(dirs.contains(&"usr"));
        assert!(dirs.contains(&"proc"));
    }

    #[test]
    fn test_set_isolate_network() {
        let session = UnshareSession {
            root: std::path::PathBuf::from("/fakechroot"),
            _root_dir: None,
            cwd: std::path::PathBuf::from("/"),
            isolate_network: std::cell::Cell::new(true),
        };
        let argv = session.run_argv(vec!["true"], Some(std::path::Path::new("/")), None);
        assert!(argv.iter().any(|a| a == "--net"));

        session.set_isolate_network(false);
        let argv = session.run_argv(vec!["true"], Some(std::path::Path::new("/")), None);
        assert!(!argv.iter().any(|a| a == "--net"));

        session.set_isolate_network(true);
        let argv = session.run_argv(vec!["true"], Some(std::path::Path::new("/")), None);
        assert!(argv.iter().any(|a| a == "--net"));
    }

    #[test]
    fn test_with_network_restores_isolation() {
        let session = UnshareSession {
            root: std::path::PathBuf::from("/fakechroot"),
            _root_dir: None,
            cwd: std::path::PathBuf::from("/"),
            isolate_network: std::cell::Cell::new(true),
        };

        let inside = crate::session::with_network(&session, || session.isolate_network.get());
        assert!(!inside);
        assert!(session.isolate_network.get());
    }

    #[test]
    fn test_external_path() {
        let mut session = if let Some(session) = test_session() {
            session
        } else {
            return;
        };
        // Test absolute path
        let path = std::path::Path::new("/tmp/test");
        assert_eq!(
            session.external_path(path),
            session.location().join("tmp/test")
        );
        // Test relative path
        session.chdir(std::path::Path::new("/tmp")).unwrap();
        let path = std::path::Path::new("test");
        assert_eq!(
            session.external_path(path),
            session.location().join("tmp/test")
        );
    }
}