ferrosys-cli 0.1.0

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

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

/// The binary under test, built by cargo before the test runs.
const FERROSYS: &str = env!("CARGO_BIN_EXE_ferrosys");

const UUID: &str = "f0e17055-0000-4000-8000-000000000000";
const TIME: &str = "1700000000";

// The host-tool helpers below — `tool`, `available`, `e2fsck_clean`, the version pin —
// mirror `ferrosys/tests/util/mod.rs`. They are a copy rather than an include
// because a crate's packaged tests cannot include a file from a sibling crate's
// directory; a behavioral change here belongs there too.

/// The `e2fsprogs` release the gates are written against: the version CI builds from
/// source, and the one whose observed behavior pinned every expected value in these
/// tests.
const E2FSPROGS_VERSION: &str = "1.47.0";

/// The tools that ship in `e2fsprogs` and so are held to [`E2FSPROGS_VERSION`].
/// Anything else (`tar`, `python3`, `getfattr`) has no version pin.
const E2FSPROGS_TOOLS: &[&str] = &["debugfs", "dumpe2fs", "e2fsck", "mke2fs", "resize2fs"];

/// A host-tool invocation with its environment pinned.
///
/// `LC_ALL=C`, because the gates read tool output — `dumpe2fs` field names, `tar`
/// listings — and a translated message would fail them for reasons that have nothing
/// to do with the image. `mke2fs` additionally gets the vendored configuration, so the
/// feature set an oracle image carries is the project's, not whatever the host
/// distribution enables.
fn tool(name: &str) -> Command {
    let mut cmd = Command::new(name);
    cmd.env("LC_ALL", "C");
    if name == "mke2fs" {
        cmd.env("MKE2FS_CONFIG", mke2fs_config());
    }
    cmd
}

/// The vendored `mke2fs.conf`, applied at every `mke2fs` call site via [`tool`].
fn mke2fs_config() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("../../ci/mke2fs.conf")
}

/// The exit codes the tool contracts to, mirroring `e2fsck`'s.
const OK: i32 = 0;
const IMAGE_BAD: i32 = 4;
const OPERATIONAL: i32 = 8;
const USAGE: i32 = 16;

/// Whether `name` is runnable, printing a loud skip banner when it is not.
///
/// A gate that needs a foreign implementation and does not get one has verified nothing,
/// so where the gates are expected to run (CI sets `FERROSYS_REQUIRE_HOST_TOOLS`) a
/// missing tool fails the run outright.
///
/// The probe only asks whether the binary exists and runs, so any output — a version
/// line, or a complaint that `-V` is not its flag — counts as present; the flag just has
/// to make the tool exit promptly rather than block on input. `-V` is the e2fsprogs
/// version flag, and the tools that spell it `--version` instead (`tar`, `python3`)
/// answer `-V` with a prompt exit all the same.
///
/// An `e2fsprogs` tool is also held to [`E2FSPROGS_VERSION`]: under
/// `FERROSYS_REQUIRE_HOST_TOOLS` a different version is a hard failure — the run would
/// otherwise claim an oracle it did not consult — and elsewhere it is reported once per
/// gate, so a local divergence from CI reads as what it is.
fn available(name: &str) -> bool {
    let probe = tool(name).arg("-V").output();
    let ok = probe
        .as_ref()
        .map(|o| o.status.success() || !o.stderr.is_empty() || !o.stdout.is_empty())
        .unwrap_or(false);
    if !ok {
        assert!(
            std::env::var_os("FERROSYS_REQUIRE_HOST_TOOLS").is_none(),
            "gate requires `{name}` but it was not found on PATH"
        );
        eprintln!(
            "\n!!! SKIPPING gate: `{name}` not found on PATH — \
             this was NOT verified against a foreign implementation !!!\n"
        );
        return false;
    }
    if E2FSPROGS_TOOLS.contains(&name) {
        let probe = probe.expect("probed above");
        // The banner is "<name> 1.47.0 (5-Feb-2023)"; the version is the token after
        // the tool's own name.
        let banner = format!(
            "{}{}",
            String::from_utf8_lossy(&probe.stdout),
            String::from_utf8_lossy(&probe.stderr)
        );
        let version = banner
            .split_whitespace()
            .skip_while(|t| *t != name)
            .nth(1)
            .unwrap_or("unknown");
        if version != E2FSPROGS_VERSION {
            assert!(
                std::env::var_os("FERROSYS_REQUIRE_HOST_TOOLS").is_none(),
                "the gates pin e2fsprogs {E2FSPROGS_VERSION} as their oracle, \
                 but `{name}` reports {version}"
            );
            eprintln!(
                "note: `{name}` is version {version}, not the {E2FSPROGS_VERSION} the \
                 gates are written against — a divergence may not reproduce under CI's \
                 pinned oracle"
            );
        }
    }
    true
}

/// Run the tool and hand back everything it produced.
fn run(args: &[&str]) -> Output {
    Command::new(FERROSYS)
        .args(args)
        .output()
        .expect("the binary runs")
}

/// Run the tool, feeding `input` to its standard input.
fn run_with_stdin(args: &[&str], input: &[u8]) -> Output {
    let mut child = Command::new(FERROSYS)
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("the binary runs");
    child
        .stdin
        .take()
        .expect("stdin is piped")
        .write_all(input)
        .expect("write the input");
    child.wait_with_output().expect("the binary finishes")
}

/// The exit code a run reported.
fn code(out: &Output) -> i32 {
    out.status.code().expect("the process exited normally")
}

/// A run that must succeed, with its standard output.
fn ok(args: &[&str]) -> Vec<u8> {
    let out = run(args);
    assert_eq!(
        code(&out),
        OK,
        "`ferrosys {}` failed:\n{}",
        args.join(" "),
        String::from_utf8_lossy(&out.stderr)
    );
    out.stdout
}

/// A scratch directory that lives as long as the test.
fn scratch() -> tempfile::TempDir {
    tempfile::tempdir().expect("a scratch directory")
}

/// The path to a file in the scratch directory, as the tool takes it.
fn at(dir: &tempfile::TempDir, name: &str) -> PathBuf {
    dir.path().join(name)
}

/// Format an image of `size` from `archive`, if one is given.
fn format(image: &Path, size: &str, archive: Option<&Path>) -> Output {
    let image = image.to_str().expect("a text path");
    let mut args = vec![
        "format", "--size", size, "--uuid", UUID, "--time", TIME, image,
    ];
    let archive = archive.map(|a| a.to_str().expect("a text path").to_string());
    if let Some(a) = &archive {
        args.insert(1, "--from-tar");
        args.insert(2, a);
    }
    run(&args)
}

/// A tar archive carrying the whole fidelity list: ownership and modes, times to the
/// nanosecond, a fast and a slow symlink, a hard link, device and FIFO nodes, extended
/// attributes inline and in a block, POSIX ACLs, and a directory large enough that the
/// filesystem must index it by hash rather than scan it.
fn fidelity_archive() -> Vec<u8> {
    use tar::{Builder, EntryType, Header};

    let mut b = Builder::new(Vec::new());

    // A directory, a file in it, and the modes and owners that must survive.
    let push = |b: &mut Builder<Vec<u8>>,
                records: Vec<(&str, Vec<u8>)>,
                kind: EntryType,
                path: &str,
                mode: u32,
                uid: u64,
                gid: u64,
                link: Option<&str>,
                device: Option<(u32, u32)>,
                data: &[u8]| {
        let mut recs: Vec<(String, Vec<u8>)> = records
            .into_iter()
            .map(|(k, v)| (k.to_string(), v))
            .collect();
        recs.push(("path".to_string(), path.as_bytes().to_vec()));
        if let Some(l) = link {
            recs.push(("linkpath".to_string(), l.as_bytes().to_vec()));
        }
        let borrowed: Vec<(&str, &[u8])> = recs
            .iter()
            .map(|(k, v)| (k.as_str(), v.as_slice()))
            .collect();
        b.append_pax_extensions(borrowed).expect("pax records");

        let mut h = Header::new_ustar();
        h.set_entry_type(kind);
        h.set_mode(mode);
        h.set_uid(uid);
        h.set_gid(gid);
        h.set_mtime(1_700_000_000);
        // The ustar header holds 100 bytes of path and of link target. A value longer
        // than that is left out of the header, exactly as the tool itself leaves it out:
        // the PAX record above carries it, and every reader that honours PAX — GNU tar,
        // bsdtar, and the archive source under test — reads it from there.
        let _ = h.set_path(path);
        if let Some(l) = link {
            let _ = h.set_link_name(l);
        }
        if let Some((major, minor)) = device {
            h.set_device_major(major).expect("a major number");
            h.set_device_minor(minor).expect("a minor number");
        }
        h.set_size(data.len() as u64);
        h.set_cksum();
        b.append(&h, data).expect("append");
    };

    // The archive's own root member: the filesystem root's mode and ownership.
    push(
        &mut b,
        vec![],
        EntryType::Directory,
        "./",
        0o755,
        0,
        0,
        None,
        None,
        &[],
    );
    push(
        &mut b,
        vec![],
        EntryType::Directory,
        "./etc/",
        0o755,
        0,
        0,
        None,
        None,
        &[],
    );
    // A file with a sub-second time and a non-root owner, carrying an inline attribute.
    push(
        &mut b,
        vec![
            ("mtime", b"1700000000.123456789".to_vec()),
            ("atime", b"1600000000".to_vec()),
            ("ctime", b"1650000000".to_vec()),
            ("SCHILY.xattr.user.note", b"hello".to_vec()),
        ],
        EntryType::Regular,
        "./etc/hostname",
        0o644,
        1000,
        1000,
        None,
        None,
        b"ferrosys\n",
    );
    // A value too large for the inode spills into an external attribute block.
    push(
        &mut b,
        vec![("SCHILY.xattr.user.big", vec![0xcd; 400])],
        EntryType::Regular,
        "./etc/big",
        0o600,
        0,
        0,
        None,
        None,
        &vec![b'x'; 5000],
    );
    // A directory carrying both a POSIX access ACL and a default one, in the version-2
    // form `getxattr` returns — which is what an archiver copies into an archive.
    push(
        &mut b,
        vec![
            ("SCHILY.xattr.system.posix_acl_access", acl_v2_access()),
            ("SCHILY.xattr.system.posix_acl_default", acl_v2_default()),
        ],
        EntryType::Directory,
        "./home/",
        0o750,
        1000,
        1000,
        None,
        None,
        &[],
    );
    // A fast symlink (inline in the inode) and a slow one (in a block).
    push(
        &mut b,
        vec![],
        EntryType::Symlink,
        "./etc/mtab",
        0o777,
        0,
        0,
        Some("/proc/self/mounts"),
        None,
        &[],
    );
    let long_target = "/".to_string() + &"p".repeat(120);
    push(
        &mut b,
        vec![],
        EntryType::Symlink,
        "./etc/long",
        0o777,
        0,
        0,
        Some(&long_target),
        None,
        &[],
    );
    // A hard link: a second name for a file already in the archive.
    push(
        &mut b,
        vec![],
        EntryType::Link,
        "./etc/hostname.link",
        0o644,
        1000,
        1000,
        Some("./etc/hostname"),
        None,
        &[],
    );
    // Device and FIFO nodes.
    push(
        &mut b,
        vec![],
        EntryType::Directory,
        "./dev/",
        0o755,
        0,
        0,
        None,
        None,
        &[],
    );
    push(
        &mut b,
        vec![],
        EntryType::Char,
        "./dev/null",
        0o666,
        0,
        0,
        None,
        Some((1, 3)),
        &[],
    );
    push(
        &mut b,
        vec![],
        EntryType::Block,
        "./dev/sda",
        0o660,
        0,
        6,
        None,
        Some((8, 0)),
        &[],
    );
    push(
        &mut b,
        vec![],
        EntryType::Fifo,
        "./dev/initctl",
        0o600,
        0,
        0,
        None,
        None,
        &[],
    );
    // A directory of more than a thousand names, which no linear directory holds: the
    // filesystem must index it by hash, and reading it back must walk that index.
    push(
        &mut b,
        vec![],
        EntryType::Directory,
        "./many/",
        0o755,
        0,
        0,
        None,
        None,
        &[],
    );
    for i in 0..1200 {
        push(
            &mut b,
            vec![],
            EntryType::Regular,
            &format!("./many/file-{i:05}"),
            0o644,
            0,
            0,
            None,
            None,
            format!("{i}").as_bytes(),
        );
    }

    b.into_inner().expect("finish the archive")
}

/// The version-2 `posix_acl_xattr` bytes for an access ACL naming a user: owner rwx, user
/// 1000 rw-, owning group r-x, mask rwx, other r--.
fn acl_v2_access() -> Vec<u8> {
    vec![
        0x02, 0x00, 0x00, 0x00, // a_version = 2
        0x01, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, // USER_OBJ rwx
        0x02, 0x00, 0x06, 0x00, 0xe8, 0x03, 0x00, 0x00, // USER 1000 rw-
        0x04, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, // GROUP_OBJ r-x
        0x10, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, // MASK rwx
        0x20, 0x00, 0x04, 0x00, 0xff, 0xff, 0xff, 0xff, // OTHER r--
    ]
}

/// The version-2 bytes for a minimal default ACL, which only a directory may carry.
fn acl_v2_default() -> Vec<u8> {
    vec![
        0x02, 0x00, 0x00, 0x00, // a_version = 2
        0x01, 0x00, 0x07, 0x00, 0xff, 0xff, 0xff, 0xff, // USER_OBJ rwx
        0x04, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, // GROUP_OBJ r-x
        0x20, 0x00, 0x05, 0x00, 0xff, 0xff, 0xff, 0xff, // OTHER r-x
    ]
}

/// Write the fidelity archive into the scratch directory.
fn write_archive(dir: &tempfile::TempDir) -> PathBuf {
    let path = at(dir, "source.tar");
    std::fs::write(&path, fidelity_archive()).expect("write the archive");
    path
}

// ---------------------------------------------------------------------------
// format
// ---------------------------------------------------------------------------

#[test]
fn a_formatted_image_checks_clean_and_is_reproducible() {
    let dir = scratch();
    let image = at(&dir, "fs.img");
    let out = format(&image, "64M", None);
    assert_eq!(code(&out), OK, "{}", String::from_utf8_lossy(&out.stderr));
    // The summary is a diagnostic, so it goes to the standard error: the artifact of a
    // format is the image, and the standard output stays clear for one the caller asked
    // for.
    assert!(out.stdout.is_empty(), "nothing goes to the standard output");
    assert!(String::from_utf8_lossy(&out.stderr).contains("Filesystem UUID:"));

    // The same inputs write the same bytes. Nothing in the tool reads the clock or a
    // random source, so this holds without a flag asking for it.
    let again = at(&dir, "again.img");
    assert_eq!(code(&format(&again, "64M", None)), OK);
    assert_eq!(
        std::fs::read(&image).expect("read"),
        std::fs::read(&again).expect("read"),
        "two formats from the same inputs wrote different bytes"
    );

    if !available("e2fsck") {
        return;
    }
    e2fsck_clean(&image);
}

#[test]
fn an_image_built_from_an_archive_checks_clean() {
    let dir = scratch();
    let archive = write_archive(&dir);
    let image = at(&dir, "fs.img");
    let out = format(&image, "128M", Some(&archive));
    assert_eq!(code(&out), OK, "{}", String::from_utf8_lossy(&out.stderr));

    if !available("e2fsck") {
        return;
    }
    e2fsck_clean(&image);
}

/// Assert `e2fsck -fn` finds nothing to fault, reporting both streams labeled.
fn e2fsck_clean(image: &Path) {
    let out = tool("e2fsck")
        .args(["-f", "-n"])
        .arg(image)
        .output()
        .expect("spawn e2fsck");
    assert!(
        out.status.success(),
        "e2fsck faulted the image (exit {:?})\nstdout:\n{}\nstderr:\n{}",
        out.status.code(),
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn format_writes_the_selected_base_profile() {
    // `-t` makes ext2 and ext3 first-class on the command line: one flag seeds the base
    // feature set, the image checks clean, and `inspect` reads the profile back as the one
    // that was asked for. The whole ext lineage the writer emits is reachable this way.
    let dir = scratch();
    for profile in ["ext2", "ext3", "ext4"] {
        let image = at(&dir, &format!("{profile}.img"));
        let path = image.to_str().expect("a text path");
        let out = run(&[
            "format", "-t", profile, "--size", "64M", "--uuid", UUID, "--time", TIME, path,
        ]);
        assert_eq!(
            code(&out),
            OK,
            "format -t {profile} failed:\n{}",
            String::from_utf8_lossy(&out.stderr)
        );
        // The realized profile is in the format summary and read back by inspect alike.
        let summary = fields(&String::from_utf8_lossy(&out.stderr));
        assert_eq!(
            summary["Filesystem profile"], profile,
            "the format summary names the profile it wrote"
        );
        let report = fields(&String::from_utf8_lossy(&ok(&["inspect", path])));
        assert_eq!(
            report["Filesystem profile"], profile,
            "inspect labels the {profile} image as {profile}"
        );

        if available("e2fsck") {
            e2fsck_clean(&image);
        }
    }
}

#[test]
fn format_refuses_a_destination_that_is_not_a_regular_file() {
    // A format writes only the blocks the filesystem uses, so every byte it does not
    // write must already read as zero. A directory is not a regular file, and neither is
    // a device; the tool refuses both rather than writing a filesystem into whatever was
    // already there.
    let dir = scratch();
    let out = format(dir.path(), "64M", None);
    assert_eq!(code(&out), OPERATIONAL);
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("not a regular file"),
        "the refusal says why: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn format_takes_its_time_from_the_environment_when_the_option_is_absent() {
    let dir = scratch();
    let image = at(&dir, "fs.img");
    let out = Command::new(FERROSYS)
        .args(["format", "--size", "64M", "--uuid", UUID])
        .arg(&image)
        .env("SOURCE_DATE_EPOCH", TIME)
        .output()
        .expect("the binary runs");
    assert_eq!(code(&out), OK, "{}", String::from_utf8_lossy(&out.stderr));
    // And it is the same image the option would have written: one input, two ways in.
    let explicit = at(&dir, "explicit.img");
    assert_eq!(code(&format(&explicit, "64M", None)), OK);
    assert_eq!(
        std::fs::read(&image).expect("read"),
        std::fs::read(&explicit).expect("read")
    );

    // With neither, the tool has no clock to fall back on, and says so.
    let neither = at(&dir, "neither.img");
    let out = Command::new(FERROSYS)
        .args(["format", "--size", "64M", "--uuid", UUID])
        .arg(&neither)
        .env_remove("SOURCE_DATE_EPOCH")
        .output()
        .expect("the binary runs");
    assert_eq!(code(&out), USAGE);
}

// ---------------------------------------------------------------------------
// inspect
// ---------------------------------------------------------------------------

/// The `KEY: value` pairs a `dumpe2fs -h`-shaped report prints, by key.
fn fields(text: &str) -> std::collections::HashMap<String, String> {
    text.lines()
        .filter_map(|l| l.split_once(':'))
        .map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
        .collect()
}

#[test]
fn inspect_agrees_with_dumpe2fs_field_by_field() {
    // This is what earns the claim that the tool reimplements `dumpe2fs`'s inspection
    // natively: not that it prints something, but that what it prints is what e2fsprogs
    // prints, field by field, about the same image.
    if !available("dumpe2fs") {
        return;
    }
    let dir = scratch();
    let archive = write_archive(&dir);
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "128M", Some(&archive))), OK);

    let ours = fields(&String::from_utf8_lossy(&ok(&[
        "inspect",
        image.to_str().expect("a text path"),
    ])));
    let theirs = tool("dumpe2fs")
        .arg("-h")
        .arg(&image)
        .output()
        .expect("spawn dumpe2fs");
    let theirs = fields(&String::from_utf8_lossy(&theirs.stdout));

    // Every field both tools name must agree. A field one of them does not print (their
    // "Fragment size", our "Block groups") is not a disagreement.
    let shared = [
        "Filesystem volume name",
        "Filesystem UUID",
        "Filesystem magic number",
        "Filesystem state",
        "Errors behavior",
        "Filesystem OS type",
        "Inode count",
        "Block count",
        "Reserved block count",
        "Free blocks",
        "Free inodes",
        "First block",
        "Block size",
        "Group descriptor size",
        "Reserved GDT blocks",
        "Blocks per group",
        "Inodes per group",
        "Inode blocks per group",
        "Flex block group size",
        "First inode",
        "Inode size",
        "Journal inode",
        "Orphan file inode",
        "Default directory hash",
        "Directory Hash Seed",
        "Checksum type",
        "Checksum seed",
    ];
    for key in shared {
        let ours = ours
            .get(key)
            .unwrap_or_else(|| panic!("inspect prints {key}"));
        let theirs = theirs
            .get(key)
            .unwrap_or_else(|| panic!("dumpe2fs prints {key}"));
        assert_eq!(ours, theirs, "the two tools disagree about {key}");
    }

    // The feature line is compared as a set: both print the same names, and the order
    // they print them in says nothing about whether the same features are present.
    let sorted = |s: &str| {
        let mut v: Vec<&str> = s.split_whitespace().collect();
        v.sort_unstable();
        v.join(" ")
    };
    let f = "Filesystem features";
    assert_eq!(
        sorted(&ours[f]),
        sorted(&theirs[f]),
        "the two tools disagree about which features the image carries"
    );
}

#[test]
fn format_applies_the_label_inode_and_reserved_options() {
    let dir = scratch();
    let image = at(&dir, "labelled.img");
    let path = image.to_str().expect("a text path");
    // 256 MiB is two whole groups, so `--inodes 5000` and `--reserved-percent 1.5` have
    // exact, checkable outcomes.
    let out = run(&[
        "format",
        "--size",
        "256M",
        "--uuid",
        UUID,
        "--time",
        TIME,
        "--label",
        "rootfs",
        "--inodes",
        "5000",
        "--reserved-percent",
        "1.5",
        path,
    ]);
    assert_eq!(
        code(&out),
        OK,
        "format failed:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );

    let report = fields(&String::from_utf8_lossy(&ok(&["inspect", path])));
    assert_eq!(report["Filesystem volume name"], "rootfs");
    // The writer emits ext4, and inspect labels it as the family its feature words classify to.
    assert_eq!(report["Filesystem profile"], "ext4");
    // 5000 spread across two groups, each rounded up to fill its inode-table blocks.
    assert_eq!(report["Inode count"], "5024");
    // floor(65536 blocks * 1.5%), computed exactly, no floating point.
    assert_eq!(report["Reserved block count"], "983");
}

#[test]
fn format_refuses_an_over_long_label_and_an_out_of_range_percent() {
    let dir = scratch();
    let image = at(&dir, "fs.img");
    let path = image.to_str().expect("a text path");

    // Seventeen bytes of label is one too many: a usage error, caught before any file is
    // opened, so nothing is written.
    let out = run(&[
        "format",
        "--size",
        "64M",
        "--uuid",
        UUID,
        "--time",
        TIME,
        "--label",
        "0123456789abcdefX",
        path,
    ]);
    assert_eq!(code(&out), USAGE);
    assert!(!image.exists(), "a refused format writes nothing");

    // A reserved percentage past the 50% ceiling is refused the same way.
    let out = run(&[
        "format",
        "--size",
        "64M",
        "--uuid",
        UUID,
        "--time",
        TIME,
        "--reserved-percent",
        "60",
        path,
    ]);
    assert_eq!(code(&out), USAGE);
}

#[test]
fn inspect_reports_every_group_and_scans_by_default() {
    let dir = scratch();
    let image = at(&dir, "fs.img");
    // Large enough to have several groups, so the group table has something to say.
    assert_eq!(code(&format(&image, "512M", None)), OK);

    let text = String::from_utf8(ok(&[
        "inspect",
        "--groups",
        image.to_str().expect("a text path"),
    ]))
    .expect("the report is text");
    assert!(text.contains("GROUP"), "the group table has a header");
    // Four groups at 32768 blocks each, and each one named.
    for group in 0..4 {
        assert!(
            text.lines().any(|l| l.starts_with(&format!("{group} "))),
            "group {group} is in the table"
        );
    }
    // The scan ran, and found nothing.
    assert!(text.contains("no anomalies"));
}

#[test]
fn inspect_groups_survives_a_hostile_group_count() {
    // A crafted superblock can claim ~4 billion block groups (`blocks_count` maxed,
    // `blocks_per_group` of one). The group listing must not pre-size a vector from that
    // count: reserving capacity for it requested hundreds of gigabytes and aborted the
    // process before a single descriptor was read. The descriptor loop grows as real
    // descriptors are found and stops when the table runs past the image — a clean
    // image-bad exit, not a crash.
    let dir = scratch();
    let image = at(&dir, "fs.img");
    // Small on purpose: the loop reads descriptors until it runs off the end of the
    // image, so the image's size, not the claimed group count, bounds the work.
    assert_eq!(code(&format(&image, "16M", None)), OK);

    let mut bytes = std::fs::read(&image).expect("read the image");
    // The primary superblock sits at byte 1024. `s_blocks_count_lo` is at 0x04 and
    // `s_blocks_per_group` at 0x20, both little-endian u32.
    bytes[1024 + 0x04..1024 + 0x08].copy_from_slice(&u32::MAX.to_le_bytes());
    bytes[1024 + 0x20..1024 + 0x24].copy_from_slice(&1u32.to_le_bytes());
    std::fs::write(&image, &bytes).expect("write the image");

    let out = run(&["inspect", "--groups", image.to_str().expect("a text path")]);
    // An aborted (signal-killed) process has no exit code, so reading one at all is half
    // the assertion: the preallocation crash would fail here.
    let exit = out
        .status
        .code()
        .expect("the process exited rather than aborting");
    assert_eq!(
        exit,
        IMAGE_BAD,
        "a hostile group count is a bad image, not a crash:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn inspect_json_parses_as_json() {
    // Validated by a real parser, not by one we wrote: our own JSON writer agreeing with
    // our own JSON reader would prove nothing.
    if !available("python3") {
        return;
    }
    let dir = scratch();
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "64M", None)), OK);
    let json = ok(&[
        "inspect",
        "--json",
        "--groups",
        image.to_str().expect("a text path"),
    ]);

    // The judge parses with a foreign implementation and then checks *values*, not key
    // presence: the fields a consumer reads must equal what the format was given (the
    // UUID, the time, the 64 MiB of 4 KiB blocks) or what the profile pins (the
    // feature lists, a clean scan, and the unknown-feature words, which must be
    // reported as zero rather than omitted — an absent field would read as though an
    // image carrying a foreign feature carried none).
    let judge = r#"
import json, sys
doc = json.load(sys.stdin)
assert doc["version"] == 1, doc["version"]
sb = doc["superblock"]
assert sb["uuid"] == "f0e17055-0000-4000-8000-000000000000", sb["uuid"]
assert sb["block_size"] == 4096, sb["block_size"]
assert sb["blocks"] * sb["block_size"] == 64 * 1024 * 1024, sb["blocks"]
assert sb["created"] == 1700000000, sb["created"]
feats = doc["features"]
assert "has_journal" in feats["compat"], feats["compat"]
assert "extent" in feats["incompat"], feats["incompat"]
assert feats["profile"] == "ext4", feats["profile"]
assert feats["unknown"] == {"compat": 0, "incompat": 0, "ro_compat": 0}, feats["unknown"]
assert doc["scan"]["clean"] is True and doc["scan"]["anomalies"] == [], doc["scan"]
groups = doc["groups"]
assert len(groups) == 1 and groups[0]["group"] == 0, groups
assert groups[0]["free_inodes"] == sb["free_inodes"], groups
"#;
    let mut child = tool("python3")
        .args(["-c", judge])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn python3");
    child
        .stdin
        .take()
        .expect("stdin is piped")
        .write_all(&json)
        .expect("write the document");
    let out = child.wait_with_output().expect("python3 finishes");
    assert!(
        out.status.success(),
        "python3 rejected the document or its values:\n{}\n{}",
        String::from_utf8_lossy(&json),
        String::from_utf8_lossy(&out.stderr)
    );
}

// ---------------------------------------------------------------------------
// exit codes
// ---------------------------------------------------------------------------

#[test]
fn the_four_exit_codes_are_reachable_and_distinct() {
    let dir = scratch();
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "64M", None)), OK);
    let path = image.to_str().expect("a text path");

    // 0: a filesystem was read, and it is sound.
    assert_eq!(code(&run(&["inspect", path])), OK);

    // 4: a filesystem was read, and it is bad. Flip a bit in the root inode's mode so the
    // image parses — a superblock is still a superblock — but is self-inconsistent.
    let bad = at(&dir, "bad.img");
    let mut bytes = std::fs::read(&image).expect("read");
    let root_inode = inode_table_offset(&bytes) + 256; // inode 2 is the second entry
    bytes[root_inode] ^= 0xff;
    std::fs::write(&bad, &bytes).expect("write");
    let out = run(&["inspect", bad.to_str().expect("a text path")]);
    assert_eq!(
        code(&out),
        IMAGE_BAD,
        "a corrupted image is bad, not merely described:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    // The report still came out — a bad filesystem is described *and* faulted.
    assert!(!out.stdout.is_empty());

    // 8: the bytes are not an ext filesystem at all, so there is no opinion to form.
    let blob = at(&dir, "blob.img");
    std::fs::write(&blob, vec![0x5a; 64 * 1024]).expect("write");
    assert_eq!(
        code(&run(&["inspect", blob.to_str().expect("a text path")])),
        OPERATIONAL
    );

    // 16: the command line could not be understood.
    assert_eq!(code(&run(&["inspect", "--nonesuch", path])), USAGE);
    assert_eq!(code(&run(&["frobnicate"])), USAGE);
    assert_eq!(code(&run(&[])), USAGE);
}

#[test]
fn a_filesystem_another_formatter_wrote_is_not_thereby_bad() {
    // `inspect` answers "is this filesystem sound", not "did I write this". A filesystem
    // `mke2fs` made is not ours, and it is not broken — so it must inspect clean and exit
    // 0. This is the gate that keeps the default verdict threshold honest: `conformance`,
    // the threshold below the default, means *valid ext4 but not the form this tool
    // writes*, and defaulting to it would fault every healthy filesystem from every other
    // formatter.
    if !available("mke2fs") {
        return;
    }
    let dir = scratch();
    for kind in ["ext4", "ext3", "ext2"] {
        let image = at(&dir, &format!("{kind}.img"));
        std::fs::write(&image, vec![0u8; 32 << 20]).expect("make the file");
        let made = tool("mke2fs")
            .args(["-q", "-t", kind])
            .arg(&image)
            .output()
            .expect("spawn mke2fs");
        assert!(
            made.status.success(),
            "mke2fs could not make an {kind} filesystem: {}",
            String::from_utf8_lossy(&made.stderr)
        );

        let out = run(&["inspect", image.to_str().expect("a text path")]);
        assert_eq!(
            code(&out),
            OK,
            "a healthy {kind} filesystem from mke2fs was reported bad:\n{}\n{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        // And it was really read, not merely opened: the report describes it.
        let report = String::from_utf8_lossy(&out.stdout);
        assert!(
            report.contains("Block count:") && report.contains("no anomalies"),
            "the {kind} filesystem was scanned:\n{report}"
        );
    }
}

#[test]
fn a_bad_image_is_only_bad_at_the_severity_asked_for() {
    let dir = scratch();
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "64M", None)), OK);
    let bad = at(&dir, "bad.img");
    let mut bytes = std::fs::read(&image).expect("read");
    let root_inode = inode_table_offset(&bytes) + 256;
    bytes[root_inode] ^= 0xff;
    std::fs::write(&bad, &bytes).expect("write");
    let path = bad.to_str().expect("a text path");

    // The default threshold faults it...
    assert_eq!(code(&run(&["inspect", path])), IMAGE_BAD);
    // ...and `never` reports the same findings without reaching a verdict, which is what
    // a caller who wants the report and not the judgement asks for.
    let out = run(&["inspect", "--fail-on", "never", path]);
    assert_eq!(code(&out), OK);
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("integrity")
            || String::from_utf8_lossy(&out.stdout).contains("structural"),
        "the findings are still reported"
    );
    // A scan that never ran reaches no verdict either.
    assert_eq!(code(&run(&["inspect", "--quick", path])), OK);
}

/// The byte offset of group 0's inode table, read out of the image's own superblock and
/// first group descriptor.
///
/// The test corrupts an inode, so it has to find one; doing that by hand rather than
/// through the reader keeps the gate honest about what it broke.
fn inode_table_offset(bytes: &[u8]) -> usize {
    let u32_at = |off: usize| {
        u32::from_le_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]) as usize
    };
    // The primary superblock is 1024 bytes in; the descriptor table follows the block it
    // sits in. At a 4096-byte block size that is block 1.
    let block_size = 1024usize << u32_at(1024 + 0x18);
    let gdt = block_size; // first_data_block is 0 at 4096 bytes, so the table is block 1
    // bg_inode_table_lo is at offset 8 of the descriptor.
    u32_at(gdt + 8) * block_size
}

// ---------------------------------------------------------------------------
// extract
// ---------------------------------------------------------------------------

#[test]
fn a_tar_survives_a_round_trip_through_a_filesystem() {
    let dir = scratch();
    let archive = write_archive(&dir);
    let image = at(&dir, "fs.img");
    assert_eq!(
        code(&format(&image, "128M", Some(&archive))),
        OK,
        "the archive formats"
    );

    // Out again, and back in: the second image must be the first one, byte for byte. That
    // is the round trip closing — every name, mode, owner, time, link, device, attribute,
    // and ACL survived, because a single lost bit would move a byte.
    let out_tar = at(&dir, "out.tar");
    assert_eq!(
        code(&run(&[
            "extract",
            image.to_str().expect("a text path"),
            "--to-tar",
            out_tar.to_str().expect("a text path"),
        ])),
        OK
    );

    // Before comparing the two images, prove the hard things are actually in the archive.
    // A byte-identical round trip is symmetric: a field dropped on the way out and never
    // looked for on the way back in would leave both images equal and the gate green,
    // having verified nothing about it. These are the positive controls that keep it
    // honest.
    let tar_bytes = std::fs::read(&out_tar).expect("read the archive");
    let contains = |needle: &[u8]| tar_bytes.windows(needle.len()).any(|w| w == needle);
    assert!(
        contains(b"SCHILY.xattr.system.posix_acl_access"),
        "the archive carries the access ACL"
    );
    assert!(
        contains(b"SCHILY.xattr.system.posix_acl_default"),
        "the archive carries the default ACL"
    );
    // And it carries it in the version-2 form the syscall boundary speaks — the bytes
    // `getxattr` would have returned — not ext4's compact on-disk form, which GNU tar and
    // our own archive source both reject.
    assert!(
        contains(&acl_v2_access()),
        "the ACL travels in the version-2 form, not ext4's on-disk form"
    );
    assert!(
        contains(b"SCHILY.xattr.user.big"),
        "the archive carries the attribute that spilled into a block"
    );
    assert!(
        contains(b"./etc/hostname.link"),
        "the archive carries the hard link"
    );
    assert!(
        contains(b"1700000000.123456789"),
        "the archive carries the sub-second time the header cannot hold"
    );

    // The hash-indexed directory came back whole. Reading it means walking the hash tree,
    // which no linear scan would have found the way through.
    let listing = String::from_utf8(ok(&[
        "extract",
        image.to_str().expect("a text path"),
        "--list",
    ]))
    .expect("text");
    let many = listing
        .lines()
        .filter(|l| l.contains("/many/file-"))
        .count();
    assert_eq!(
        many, 1200,
        "every name in the hash-indexed directory is read back"
    );

    let again = at(&dir, "again.img");
    let out = format(&again, "128M", Some(&out_tar));
    assert_eq!(
        code(&out),
        OK,
        "the archive we wrote is one we can read back:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        std::fs::read(&image).expect("read"),
        std::fs::read(&again).expect("read"),
        "the filesystem did not survive the round trip through our own archive"
    );

    if !available("e2fsck") {
        return;
    }
    e2fsck_clean(&again);
}

#[test]
fn gnu_tar_reads_the_archive_we_write() {
    // Round-tripping through our own reader proves nothing about interoperability: it
    // would pass just as well if we had invented a private archive format. A foreign tar
    // reading it is what makes it a tar.
    if !available("tar") {
        return;
    }
    let dir = scratch();
    let archive = write_archive(&dir);
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "128M", Some(&archive))), OK);
    let out_tar = at(&dir, "out.tar");
    assert_eq!(
        code(&run(&[
            "extract",
            image.to_str().expect("a text path"),
            "--to-tar",
            out_tar.to_str().expect("a text path"),
        ])),
        OK
    );

    // GNU tar lists it without complaint. The `x` header our PAX records travel in carries
    // an empty name field, and this is where a foreign tool gets to object to that.
    let out = tool("tar")
        .args(["--xattrs", "-tvf"])
        .arg(&out_tar)
        .output()
        .expect("spawn tar");
    let listing = String::from_utf8_lossy(&out.stdout);
    let complaints = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success() && complaints.is_empty(),
        "GNU tar objected to our archive:\n{complaints}"
    );
    for name in ["./etc/hostname", "./dev/null", "./etc/mtab"] {
        assert!(listing.contains(name), "GNU tar lists {name}:\n{listing}");
    }
    // It sees the kinds, not just the names: a device is a device, a link is a link.
    assert!(
        listing.contains("crw-rw-rw-") && listing.contains("1,3") || listing.contains("1, 3"),
        "GNU tar sees the device node:\n{listing}"
    );

    // And it unpacks: the mode and the extended attribute survive into a real directory.
    let unpacked = at(&dir, "unpacked");
    std::fs::create_dir(&unpacked).expect("make the directory");
    let out = tool("tar")
        .args(["--xattrs", "--xattrs-include=*", "-xf"])
        .arg(&out_tar)
        .arg("-C")
        .arg(&unpacked)
        .arg("./etc/hostname")
        .output()
        .expect("spawn tar");
    assert!(
        out.status.success(),
        "GNU tar could not unpack our archive:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    let hostname = unpacked.join("etc/hostname");
    assert_eq!(
        std::fs::read(&hostname).expect("read the unpacked file"),
        b"ferrosys\n"
    );
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mode = std::fs::metadata(&hostname)
            .expect("stat")
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o644, "the mode survived into a real file");
    }
    // The user attribute survived, as GNU tar itself reports it. `getfattr`'s absence is
    // loud under the require-env, not a silent skip: an unrun check must never read as a
    // pass it did not earn.
    if available("getfattr") {
        let out = tool("getfattr")
            .args(["-n", "user.note", "--only-values"])
            .arg(&hostname)
            .output()
            .expect("spawn getfattr");
        assert!(
            out.status.success(),
            "getfattr could not read the attribute:\n{}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(out.stdout, b"hello");
    }
}

#[test]
fn extract_writes_one_artifact_and_nothing_else() {
    let dir = scratch();
    let archive = write_archive(&dir);
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "128M", Some(&archive))), OK);
    let path = image.to_str().expect("a text path");

    // `--cat` is the file's bytes, and nothing else at all.
    let out = run(&["extract", path, "--cat", "/etc/hostname"]);
    assert_eq!(code(&out), OK);
    assert_eq!(out.stdout, b"ferrosys\n");
    assert!(out.stderr.is_empty());

    // A path the filesystem does not have is an operational failure, not a bad image: the
    // filesystem is fine, the request was not.
    let out = run(&["extract", path, "--cat", "/nowhere"]);
    assert_eq!(code(&out), OPERATIONAL);
    assert!(out.stdout.is_empty(), "no bytes are written for no file");

    // The listing names every file, with its mode, owner, and target.
    let listing = String::from_utf8(ok(&["extract", path, "--list"])).expect("text");
    assert!(listing.contains("/etc/hostname"));
    assert!(listing.contains("lrwxrwxrwx"), "a symlink reads as one");
    assert!(
        listing.contains("/etc/mtab -> /proc/self/mounts"),
        "a link says where it points"
    );
    assert!(listing.contains("crw-rw-rw-"), "a device reads as one");
    assert!(
        listing.contains("/lost+found"),
        "a listing describes the filesystem, and /lost+found is in it"
    );
}

#[test]
fn a_pipe_carries_the_filesystem_from_one_run_to_the_next() {
    // The tar goes out on the standard output and back in on the standard input, with no
    // file in between — and it is still the same filesystem.
    let dir = scratch();
    let archive = write_archive(&dir);
    let image = at(&dir, "fs.img");
    assert_eq!(code(&format(&image, "128M", Some(&archive))), OK);

    let tar = ok(&[
        "extract",
        image.to_str().expect("a text path"),
        "--to-tar",
        "-",
    ]);
    let piped = at(&dir, "piped.img");
    let out = run_with_stdin(
        &[
            "format",
            "--size",
            "128M",
            "--uuid",
            UUID,
            "--time",
            TIME,
            "--from-tar",
            "-",
            piped.to_str().expect("a text path"),
        ],
        &tar,
    );
    assert_eq!(
        code(&out),
        OK,
        "the piped archive formats:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(
        std::fs::read(&image).expect("read"),
        std::fs::read(&piped).expect("read"),
        "the filesystem did not survive the pipe"
    );
}

#[test]
fn a_socket_is_a_typed_error_rather_than_a_missing_file() {
    // tar has no entry type for a socket. Extracting one would have to drop it, and a
    // filesystem that comes back missing a file is worse than one that will not come back
    // at all — so the tool refuses, by name.
    let dir = scratch();
    let image = at(&dir, "fs.img");
    build_image_with_socket(&image);
    let out = run(&[
        "extract",
        image.to_str().expect("a text path"),
        "--to-tar",
        "-",
    ]);
    assert_eq!(code(&out), OPERATIONAL);
    let complaint = String::from_utf8_lossy(&out.stderr);
    assert!(
        complaint.contains("/run/sock") && complaint.contains("socket"),
        "the refusal names the file and why: {complaint}"
    );
}

/// A filesystem holding a socket, which no archive can express — built through the
/// library, since no archive could describe it to `format --from-tar` either.
fn build_image_with_socket(path: &Path) {
    use ferrosys::ext::ondisk::Timestamp;
    use ferrosys::ext::{FormatOptions, GrowReservation, Metadata, TreeBuilder, format_to};

    let time = Timestamp::from_secs(1_700_000_000);
    let source = TreeBuilder::new()
        .directory(b"/run".to_vec(), Metadata::new(0o755, time))
        .socket(b"/run/sock".to_vec(), Metadata::new(0o666, time));
    let mut options = FormatOptions::new([0x11; 16], time, [0u8; 16]);
    options.grow = GrowReservation::UpTo(1 << 30);
    let file = std::fs::File::create(path).expect("create the image");
    format_to(source, 64 << 20, options, &file).expect("format");
}

// ---------------------------------------------------------------------------
// offset
// ---------------------------------------------------------------------------

#[test]
fn a_filesystem_inside_a_larger_image_is_read_at_its_offset() {
    // A partition inside a whole-disk image: the filesystem does not begin at byte zero,
    // and every read has to be relative to where it does begin.
    let dir = scratch();
    let image = at(&dir, "fs.img");
    let archive = write_archive(&dir);
    assert_eq!(code(&format(&image, "128M", Some(&archive))), OK);

    const OFFSET: usize = 1 << 20; // a megabyte in, where a partition table would leave it
    let disk = at(&dir, "disk.img");
    let mut bytes = vec![0x00; OFFSET];
    bytes.extend_from_slice(&std::fs::read(&image).expect("read"));
    std::fs::write(&disk, &bytes).expect("write");
    let path = disk.to_str().expect("a text path");

    // Without the offset the bytes at the front are not a filesystem, and the tool says so
    // rather than guessing.
    assert_eq!(code(&run(&["inspect", path])), OPERATIONAL);

    // With it, the filesystem is there, sound, and readable.
    let report = String::from_utf8(ok(&["inspect", "--offset", "1M", path])).expect("text");
    assert!(report.contains(UUID));
    assert!(report.contains("no anomalies"));
    assert_eq!(
        ok(&["extract", "--offset", "1M", path, "--cat", "/etc/hostname"]),
        b"ferrosys\n"
    );
}

// ---------------------------------------------------------------------------
// help
// ---------------------------------------------------------------------------

#[test]
fn help_is_an_artifact_and_a_usage_error_is_not() {
    // Asking for help is a run that succeeded, and the help is what it produced.
    let out = run(&["--help"]);
    assert_eq!(code(&out), OK);
    assert!(String::from_utf8_lossy(&out.stdout).contains("usage:"));
    assert!(out.stderr.is_empty());

    for topic in ["format", "inspect", "extract"] {
        let out = run(&[topic, "--help"]);
        assert_eq!(code(&out), OK);
        let text = String::from_utf8_lossy(&out.stdout);
        assert!(text.contains(topic), "the {topic} help names {topic}");
    }

    // The `--from-tar` memory cost is documented where a user meets it, not left to be
    // discovered on a large archive.
    let out = run(&["format", "--help"]);
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(
        text.contains("memory"),
        "format's help says what --from-tar costs in memory"
    );

    // A usage error is a failure: it goes to the standard error, and the standard output
    // stays empty, so a pipe never receives half a usage message where an artifact should
    // have been.
    let out = run(&["inspect", "--nonesuch", "x.img"]);
    assert_eq!(code(&out), USAGE);
    assert!(out.stdout.is_empty());
    assert!(!out.stderr.is_empty());
}

#[test]
fn inspect_sarif_is_valid_sarif_a_foreign_parser_accepts() {
    // The SARIF projection exists so a CI system can ingest a scan. That claim is only
    // worth anything if a real JSON parser accepts the document *and* the document is
    // internally consistent: every result's `ruleId` has to name a rule the run
    // declares, or an ingesting tool drops the finding. Both are checked here by
    // python3, not by a reader of our own.
    if !available("python3") {
        return;
    }
    let dir = scratch();
    // The image is deliberately at an awkward path: SARIF locates an artifact by a URI
    // reference, and a path is not one. This name carries every character the URI grammar
    // treats specially — a space (not allowed in a URI at all), `#` (a fragment), `?` (a
    // query), `%` (the escape itself), a backslash, and a multi-byte character — so the
    // judge's decode-compare has something to catch.
    let image = at(&dir, "a b#c?d%e\\f\u{e9}.img");
    assert_eq!(code(&format(&image, "64M", None)), OK);

    // A clean image projects an empty findings list — exercised first, since an empty
    // `results` array is the shape most likely to be malformed.
    let clean = ok(&["inspect", "--sarif", image.to_str().expect("a text path")]);
    check_sarif(&clean, image.to_str().expect("a text path"), 0);

    // Corrupting a superblock field the checksum covers gives the scan something to
    // report, so the result objects themselves are projected and validated. `s_wtime`
    // at offset 0x30 is covered by the superblock checksum and read by nothing that
    // would fail earlier.
    {
        use std::io::{Read, Seek, SeekFrom, Write};
        let mut f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(&image)
            .expect("reopen the image");
        f.seek(SeekFrom::Start(1024 + 0x30))
            .expect("seek to s_wtime");
        let mut byte = [0u8; 1];
        f.read_exact(&mut byte).expect("read s_wtime");
        byte[0] ^= 0xff;
        f.seek(SeekFrom::Start(1024 + 0x30)).expect("seek back");
        f.write_all(&byte).expect("corrupt s_wtime");
    }

    // A faulted image exits `IMAGE_BAD`, so the document comes off a failing run.
    let out = run(&["inspect", "--sarif", image.to_str().expect("a text path")]);
    assert_eq!(
        code(&out),
        IMAGE_BAD,
        "a corrupted superblock is a bad image:\n{}",
        String::from_utf8_lossy(&out.stderr)
    );
    check_sarif(&out.stdout, image.to_str().expect("a text path"), 1);
}

/// Judge a SARIF document with `python3`: it must parse, carry the 2.1.0 envelope this
/// tool writes, name at least `min_results` findings, and — the part a substring check
/// cannot see — every result must reference a declared rule, carry a SARIF-legal level,
/// and locate itself in the image `artifact` names.
///
/// The location is judged as a URI, which is what SARIF asks for and what a path is not:
/// the string has to be spelled in the characters RFC 3986 allows, and it has to
/// percent-decode back to the exact path the run was given. Checking the decode rather
/// than the encoding keeps the judge from restating our own escaping rule back at us — any
/// correct encoding passes, and a path passed through raw fails on the first space.
fn check_sarif(document: &[u8], artifact: &str, min_results: usize) {
    let script = r#"
import json, os, re, sys, urllib.parse
doc = json.load(sys.stdin)
artifact, min_results = sys.argv[1], int(sys.argv[2])
# A rooted path names a file on this host, so it is located by an absolute `file://` URI;
# anything else stays the relative reference the invocation named.
expected = os.fsencode(("file://" + artifact) if artifact.startswith("/") else artifact)
# RFC 3986 3.2: a URI reference is spelled in unreserved and reserved characters and
# percent-escapes, and nothing else. A space, a backslash, or a raw non-ASCII byte is
# outside the grammar however permissive the reader.
uri_grammar = re.compile(r"(?:[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=]|%[0-9A-Fa-f]{2})*")
assert doc["version"] == "2.1.0", doc["version"]
assert doc["$schema"].endswith("sarif-2.1.0.json"), doc["$schema"]
runs = doc["runs"]
assert len(runs) == 1, len(runs)
driver = runs[0]["tool"]["driver"]
assert driver["name"] == "ferrosys", driver["name"]
declared = {r["id"] for r in driver["rules"]}
for r in driver["rules"]:
    assert r["name"] and r["shortDescription"]["text"], r
results = runs[0]["results"]
assert len(results) >= min_results, f"{len(results)} results, wanted >= {min_results}"
for r in results:
    # A result naming an undeclared rule is silently dropped by an ingesting tool.
    assert r["ruleId"] in declared, f'{r["ruleId"]} not in {declared}'
    assert r["level"] in ("error", "warning", "note", "none"), r["level"]
    assert isinstance(r["message"]["text"], str) and r["message"]["text"], r
    uris = [
        loc["physicalLocation"]["artifactLocation"]["uri"]
        for loc in r.get("locations", [])
        if "physicalLocation" in loc
    ]
    assert len(uris) == 1, f"one artifact location per result, got {uris}"
    assert uri_grammar.fullmatch(uris[0]), f"not a URI reference: {uris[0]!r}"
    decoded = urllib.parse.unquote_to_bytes(uris[0])
    assert decoded == expected, f"{decoded!r} != {expected!r}"
print("ok")
"#;
    let mut child = tool("python3")
        .args(["-c", script, artifact, &min_results.to_string()])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn python3");
    child
        .stdin
        .take()
        .expect("stdin is piped")
        .write_all(document)
        .expect("write the document");
    let out = child.wait_with_output().expect("python3 finishes");
    assert!(
        out.status.success(),
        "python3 rejected the SARIF document:\n{}\n{}",
        String::from_utf8_lossy(document),
        String::from_utf8_lossy(&out.stderr)
    );
}