ostrya 0.14.0

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

//! Tests of the composefs image commit and of its lookup.
//!
//! The tests check these facts:
//!
//! - The image commit has the fixed shape: the subject, the timestamp 0, no
//!   parent, no metadata key, no related entry, and no detached metadata. Its
//!   root directory is `0:0 040755` with no xattrs and holds `root.cfs`
//!   alone, a regular file `0:0 0100400`. The file is the image of an export
//!   with `ComposefsOptions::RECORDED`, and the call returns its digest.
//! - Two writes of one image give one image commit. One tree gives one image
//!   commit in the `bare-user-only`, `bare-user`, and `archive` modes.
//! - The lookup finds the attachment, else the supplement, and gives `None`
//!   for a commit with neither. The attachment wins over the supplement.
//! - The lookup refuses each defect of the image commit of the attachment
//!   and of the supplement, and a bad attachment stops the lookup when a
//!   valid supplement exists. Two entries of the name in one field, and a
//!   defective entry of field 2 or of `ostrya.related`, fail the lookup.
//!   With a valid attachment, the lookup reads no `.commitmeta`.
//! - The lookup reads the key only if the commit names an image commit.
//! - A complete image commit with a missing dirtree or image object fails
//!   the lookup with `ObjectNotFound`.
//! - The lookup refuses an `archive` repository before any read. The write
//!   of the image commit works in `archive` mode and writes no
//!   `ostree.sizes`.
//! - With no key, the lookup gives the file with no check.
//! - In a sealing repository, the returned descriptor is sealed and its
//!   kernel digest is the key, and a wrong key gives `DigestMismatch`. These
//!   tests skip if the file system has no fs-verity.
//! - `Repo::add_composefs_supplement` writes the image commit and the
//!   supplement, writes nothing for a valid supplement, replaces a bad
//!   supplement, completes a partial image commit, refuses a commit with the
//!   attachment and a key that is not the digest of the image, makes no
//!   check with no key, and works in an `archive` repository. In `archive`
//!   mode, it replaces a supplement that names another image commit.
//! - `CheckedAttachments::add` checks the new entry alone: an entry of the
//!   first check that the repository marks partial after that check fails
//!   neither the add nor the write of the commit. The add keeps the entries
//!   sorted.
//! - With a hook, the image file is the image that
//!   `Repo::export_composefs_to` writes for the tree with the same hook, and
//!   the call returns its digest. A commit that names the image commit as
//!   the attachment and carries that digest as the key gives the image. A
//!   key with the digest of the image with no hook gives `DigestMismatch`.

mod common;

use std::io::Read;
use std::os::fd::AsFd;
use std::path::Path;

use ostrya::{
    COMPOSEFS_RELATION, Checksum, Commit, ComposefsEntryFn, ComposefsImageDefect,
    ComposefsImageSource, ComposefsOptions, ComposefsSupplementAdd, DirMeta, DirTree, EntryKind,
    Error, FileMeta, Metadata, ObjectType, RelationField, Repo, RepoMode, RepoTree, Transaction,
    Value, Xattrs, loose_path,
};
use ostrya_rt::block_on;

use common::composefs::{
    DIGEST_KEY, build_owned_source, commit_owned, dict, key_dict, new_repo, verity_supported,
};
use common::{TmpDir, mark_partial};

/// The subject of each image commit.
const IMAGE_SUBJECT: &str = "composefs image";

/// Makes the owned source tree under `scratch/tree`, a repository of `mode`
/// with `config` at `scratch/repo`, and a commit of the tree. Returns the
/// repository and the commit of the tree.
async fn setup(scratch: &TmpDir, mode: RepoMode, config: &str) -> (Repo, Checksum) {
    let base = scratch.path().join("tree");
    build_owned_source(&base);
    let repo = new_repo(&scratch.path().join("repo"), mode, config).await;
    let tree = commit_owned(&repo, &base).await;
    (repo, tree)
}

/// Returns the root of the tree of `commit`.
async fn root_of(repo: &Repo, commit: &Checksum) -> RepoTree {
    repo.read_commit(&commit.to_string()).await.unwrap().0
}

/// Writes the image commit of the tree of `tree` in its own transaction, and
/// returns the image commit and the digest of the image.
async fn write_image_commit(repo: &Repo, tree: &Checksum) -> (Checksum, [u8; 32]) {
    let root = root_of(repo, tree).await;
    let txn = repo.transaction().await.unwrap();
    let written = txn.write_composefs_commit(&root, None).await.unwrap();
    txn.commit().await.unwrap();
    written
}

/// Stages `bytes` as a commit object in a transaction of its own, with no
/// check of field 2, and returns its checksum.
async fn store_commit_bytes(repo: &Repo, bytes: &[u8]) -> Checksum {
    let txn = repo.transaction().await.unwrap();
    let written = txn
        .write_metadata(ObjectType::Commit, None, bytes)
        .await
        .unwrap();
    txn.commit().await.unwrap();
    written
}

/// Stores a copy of the commit `tree` with the subject `subject`, the key
/// `key` if given, and field 2 set to `attachments`, with no check of the
/// entries. Returns the checksum of the copy.
async fn store_named(
    repo: &Repo,
    tree: &Checksum,
    subject: &str,
    key: Option<&[u8; 32]>,
    attachments: &[(&str, &[u8])],
) -> Checksum {
    let metadata = key.map_or_else(|| Value::Array(Vec::new()), key_dict);
    store_with_metadata(repo, tree, subject, metadata, attachments).await
}

/// Stores a copy of the commit `tree` with the subject `subject`, the
/// metadata dict `metadata`, and field 2 set to `attachments`, with no check
/// of the entries or of the dict. Returns the checksum of the copy.
async fn store_with_metadata(
    repo: &Repo,
    tree: &Checksum,
    subject: &str,
    metadata: Value,
    attachments: &[(&str, &[u8])],
) -> Checksum {
    let (mut commit, _) = repo.load_commit(tree).await.unwrap();
    commit.subject = subject.to_owned();
    commit.metadata = metadata;
    commit.related = attachments
        .iter()
        .map(|(name, bytes)| ((*name).to_owned(), bytes.to_vec()))
        .collect();
    store_commit_bytes(repo, &commit.serialize().unwrap()).await
}

/// Stages an image commit with the root directory `files` and `dirs` in
/// `txn`, and returns its checksum. The other fields are those of an image
/// commit.
async fn stage_image_commit(
    txn: &Transaction,
    files: Vec<(String, Checksum)>,
    dirs: Vec<(String, Checksum, Checksum)>,
) -> Checksum {
    let root_dirmeta = txn.write_dirmeta(&root_dirmeta()).await.unwrap();
    let tree = DirTree { files, dirs };
    let root_dirtree = txn
        .write_metadata(ObjectType::DirTree, None, &tree.serialize().unwrap())
        .await
        .unwrap();
    let commit = Commit {
        metadata: Value::Array(Vec::new()),
        parent: None,
        related: Vec::new(),
        subject: IMAGE_SUBJECT.to_owned(),
        body: String::new(),
        timestamp: 0,
        root_dirtree,
        root_dirmeta,
    };
    txn.write_metadata(ObjectType::Commit, None, &commit.serialize().unwrap())
        .await
        .unwrap()
}

/// The root dirmeta of an image commit.
fn root_dirmeta() -> DirMeta {
    DirMeta {
        uid: 0,
        gid: 0,
        mode: 0o040755,
        xattrs: Xattrs::empty(),
    }
}

/// Returns the checksum of the file object of `root.cfs` in the image
/// commit `image`.
async fn image_object(repo: &Repo, image: &Checksum) -> Checksum {
    let (commit, _) = repo.load_commit(image).await.unwrap();
    let tree = repo.load_dirtree(&commit.root_dirtree).await.unwrap();
    assert_eq!(tree.files.len(), 1);
    tree.files[0].1
}

/// Returns the bytes of the loose object of the file `object` in the
/// repository `repo` of a mode other than `archive`.
fn raw_object(repo: &Repo, object: &Checksum) -> Vec<u8> {
    let path = loose_path(object, ObjectType::File, repo.mode());
    std::fs::read(repo.path().join("objects").join(path)).unwrap()
}

/// Returns the bytes of the RECORDED export of the commit `tree`.
async fn recorded_export(repo: &Repo, tree: &Checksum) -> ostrya::Image {
    repo.export_composefs(tree, &ComposefsOptions::RECORDED, None)
        .await
        .unwrap()
}

/// Returns the SELinux label that [`label_entry`] gives the node at `path`,
/// with a NUL at its end.
fn label_of(path: &Path) -> Vec<u8> {
    let mut label = format!("system_u:object_r:image_t:s0:{}", path.display()).into_bytes();
    label.push(0);
    label
}

/// A hook that adds to each node the label of its path.
fn label_entry(path: &Path, _: EntryKind, meta: &mut Metadata) -> Result<(), Error> {
    meta.xattrs
        .push((b"security.selinux".to_vec(), label_of(path)));
    Ok(())
}

/// Writes the RECORDED export of the commit `tree` with the hook `filter` to
/// the file `path`. Returns the bytes of the file and the returned digest.
async fn hooked_export(
    repo: &Repo,
    tree: &Checksum,
    filter: ComposefsEntryFn<'_>,
    path: &Path,
) -> (Vec<u8>, [u8; 32]) {
    let file = std::fs::File::create(path).unwrap();
    let digest = repo
        .export_composefs_to(
            tree,
            &ComposefsOptions::RECORDED,
            Some(filter),
            file.as_fd(),
        )
        .await
        .unwrap();
    drop(file);
    (std::fs::read(path).unwrap(), digest)
}

/// Returns `true` if `haystack` holds `needle`.
fn holds(haystack: &[u8], needle: &[u8]) -> bool {
    haystack
        .windows(needle.len())
        .any(|window| window == needle)
}

/// Reads the whole file `file` from its current offset.
fn read_all(mut file: &std::fs::File) -> Vec<u8> {
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes).unwrap();
    bytes
}

/// Returns the parts of an [`Error::InvalidComposefsImage`].
fn invalid_image(
    err: Error,
) -> (
    Checksum,
    ComposefsImageSource,
    Checksum,
    ComposefsImageDefect,
) {
    match err {
        Error::InvalidComposefsImage {
            commit,
            relation,
            image,
            defect,
        } => (commit, relation, image, *defect),
        other => panic!("expected InvalidComposefsImage, got {other:?}"),
    }
}

/// Returns the detached metadata dict that holds `entries` as the
/// supplements, with no check.
fn supplement_dict(entries: &[(&str, &Checksum)]) -> Value {
    let raw: Vec<(&str, &[u8])> = entries
        .iter()
        .map(|(name, checksum)| (*name, checksum.as_bytes().as_slice()))
        .collect();
    raw_supplement_dict(&raw)
}

/// Returns the detached metadata dict that holds `entries`, names and raw
/// checksum bytes, as the supplements, with no check.
fn raw_supplement_dict(entries: &[(&str, &[u8])]) -> Value {
    dict(
        "ostrya.related",
        "a(say)",
        Value::Array(
            entries
                .iter()
                .map(|(name, bytes)| {
                    Value::Tuple(vec![
                        Value::Str((*name).to_owned()),
                        Value::Bytes(bytes.to_vec()),
                    ])
                })
                .collect(),
        ),
    )
}

/// Writes `meta` as the `.commitmeta` of `commit` with no check, as a write
/// out of band does. The write calls of the library refuse a defective
/// `ostrya.related` value.
fn write_raw_detached(repo: &Repo, commit: &Checksum, meta: &Value) {
    let bytes = ostrya_core::to_bytes(&ostrya_core::Type::parse("a{sv}").unwrap(), meta).unwrap();
    let path =
        repo.path()
            .join("objects")
            .join(loose_path(commit, ObjectType::CommitMeta, repo.mode()));
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    std::fs::write(path, bytes).unwrap();
}

/// Writes a commit of a tree with the one file `a`, `0:0 0100644`, in
/// `repo`, with explicit objects, so that each repository mode stores the
/// same tree. Returns the commit.
async fn plain_tree_commit(repo: &Repo) -> Checksum {
    let txn = repo.transaction().await.unwrap();
    let file = txn
        .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"payload\n")
        .await
        .unwrap();
    let root_dirmeta = txn.write_dirmeta(&root_dirmeta()).await.unwrap();
    let tree = DirTree {
        files: vec![("a".to_owned(), file)],
        dirs: Vec::new(),
    };
    let root_dirtree = txn
        .write_metadata(ObjectType::DirTree, None, &tree.serialize().unwrap())
        .await
        .unwrap();
    let commit = Commit {
        metadata: Value::Array(Vec::new()),
        parent: None,
        related: Vec::new(),
        subject: "plain tree".to_owned(),
        body: String::new(),
        timestamp: 0,
        root_dirtree,
        root_dirmeta,
    };
    let checksum = txn
        .write_metadata(ObjectType::Commit, None, &commit.serialize().unwrap())
        .await
        .unwrap();
    txn.commit().await.unwrap();
    checksum
}

/// The image commit has the fixed shape, its image file holds the RECORDED
/// export of the tree, and the call returns the digest of that image.
#[test]
fn the_image_commit_has_the_fixed_shape() {
    let scratch = TmpDir::new("cfs-commit-shape");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;

        let (commit, _) = repo.load_commit(&image).await.unwrap();
        assert_eq!(commit.subject, IMAGE_SUBJECT);
        assert_eq!(commit.body, "");
        assert_eq!(commit.timestamp, 0);
        assert_eq!(commit.parent, None);
        assert_eq!(commit.metadata, Value::Array(Vec::new()));
        assert!(commit.related.is_empty());
        assert_eq!(
            repo.read_commit_detached_metadata(&image).await.unwrap(),
            None
        );

        let dirmeta = repo.load_dirmeta(&commit.root_dirmeta).await.unwrap();
        assert_eq!(dirmeta, root_dirmeta());
        let dirtree = repo.load_dirtree(&commit.root_dirtree).await.unwrap();
        assert!(dirtree.dirs.is_empty());
        assert_eq!(dirtree.files.len(), 1);
        assert_eq!(dirtree.files[0].0, "root.cfs");

        let object = dirtree.files[0].1;
        let file = repo.load_file(&object).await.unwrap();
        assert_eq!((file.uid, file.gid, file.mode), (0, 0, 0o100400));
        assert!(file.xattrs.is_empty());

        let export = recorded_export(&repo, &tree).await;
        assert_eq!(raw_object(&repo, &object), export.bytes);
        assert_eq!(digest, export.fs_verity);
    });
}

/// Two transactions that write the image commit of one tree give the same
/// image commit and the same digest.
#[test]
fn two_writes_of_one_image_give_one_image_commit() {
    let scratch = TmpDir::new("cfs-commit-twice");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let first = write_image_commit(&repo, &tree).await;
        let second = write_image_commit(&repo, &tree).await;
        assert_eq!(first, second);
    });
}

/// A commit that a transaction writes with the key and the attachment of an
/// image commit of the same transaction gives that image. The file is at
/// offset 0 and holds the image.
#[test]
fn the_lookup_gives_the_image_of_an_attachment() {
    let scratch = TmpDir::new("cfs-commit-attachment");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let root = root_of(&repo, &tree).await;
        let txn = repo.transaction().await.unwrap();
        let (image, digest) = txn.write_composefs_commit(&root, None).await.unwrap();
        let commit = txn
            .write_commit(
                ostrya::CommitOptions {
                    subject: Some("with image".to_owned()),
                    timestamp: Some(0),
                    metadata: Some(key_dict(&digest)),
                    attachments: vec![(COMPOSEFS_RELATION.to_owned(), image)],
                    ..ostrya::CommitOptions::default()
                },
                &root,
            )
            .await
            .unwrap();
        txn.commit().await.unwrap();

        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.source, ComposefsImageSource::Attachment);
        assert_eq!(found.commit, image);
        let export = recorded_export(&repo, &tree).await;
        assert_eq!(found.size, export.bytes.len() as u64);
        assert_eq!(read_all(&found.file), export.bytes);
    });
}

/// With a hook, the image file holds the export of the tree with the same
/// hook, and the call returns the digest of that export. The image holds the
/// label of each path, and differs from the image with no hook.
#[test]
fn the_image_commit_holds_the_image_of_the_hook() {
    let scratch = TmpDir::new("cfs-commit-hook");
    let hook: ComposefsEntryFn<'_> = &label_entry;
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let root = root_of(&repo, &tree).await;
        let txn = repo.transaction().await.unwrap();
        let (image, digest) = txn.write_composefs_commit(&root, Some(hook)).await.unwrap();
        txn.commit().await.unwrap();

        let object = image_object(&repo, &image).await;
        let stored = raw_object(&repo, &object);
        let (export, export_digest) =
            hooked_export(&repo, &tree, hook, &scratch.path().join("hooked.cfs")).await;
        assert_eq!(stored, export);
        assert_eq!(digest, export_digest);
        for path in [
            "/",
            "/hello.txt",
            "/sub",
            "/sub/nested.txt",
            "/link",
            "/usr",
        ] {
            assert!(holds(&stored, &label_of(Path::new(path))), "{path}");
        }

        let plain = recorded_export(&repo, &tree).await;
        assert_ne!(stored, plain.bytes);
        assert_ne!(digest, plain.fs_verity);
    });
}

/// A transaction writes the image commit with a hook, and a commit of the
/// same tree that names the image commit as the attachment and carries the
/// returned digest as the key. The lookup gives the image of the hook. A
/// commit with the key of the image with no hook fails the lookup.
#[test]
fn the_lookup_accepts_the_key_of_the_image_of_the_hook() {
    let scratch = TmpDir::new("cfs-commit-hook-lookup");
    let hook: ComposefsEntryFn<'_> = &label_entry;
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let root = root_of(&repo, &tree).await;
        let txn = repo.transaction().await.unwrap();
        let (image, digest) = txn.write_composefs_commit(&root, Some(hook)).await.unwrap();
        let commit = txn
            .write_commit(
                ostrya::CommitOptions {
                    subject: Some("with labeled image".to_owned()),
                    timestamp: Some(0),
                    metadata: Some(key_dict(&digest)),
                    attachments: vec![(COMPOSEFS_RELATION.to_owned(), image)],
                    ..ostrya::CommitOptions::default()
                },
                &root,
            )
            .await
            .unwrap();
        txn.commit().await.unwrap();

        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.source, ComposefsImageSource::Attachment);
        assert_eq!(found.commit, image);
        let stored = raw_object(&repo, &image_object(&repo, &image).await);
        assert_eq!(found.size, stored.len() as u64);
        assert_eq!(read_all(&found.file), stored);

        let plain = recorded_export(&repo, &tree).await.fs_verity;
        let unlabeled = store_named(
            &repo,
            &tree,
            "key of the image with no hook",
            Some(&plain),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        let err = repo.open_composefs_image(&unlabeled).await.unwrap_err();
        assert_eq!(
            invalid_image(err),
            (
                unlabeled,
                ComposefsImageSource::Attachment,
                image,
                ComposefsImageDefect::DigestMismatch {
                    expected: plain,
                    actual: digest,
                }
            )
        );
    });
}

/// A commit with the supplement of an image commit gives that image.
#[test]
fn the_lookup_gives_the_image_of_a_supplement() {
    let scratch = TmpDir::new("cfs-commit-supplement");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(&repo, &tree, "supplement", Some(&digest), &[]).await;
        repo.add_supplement(&commit, COMPOSEFS_RELATION, &image)
            .await
            .unwrap();

        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.source, ComposefsImageSource::Supplement);
        assert_eq!(found.commit, image);
        let export = recorded_export(&repo, &tree).await;
        assert_eq!(found.size, export.bytes.len() as u64);
        assert_eq!(read_all(&found.file), export.bytes);
    });
}

/// With an attachment and a supplement, the lookup gives the image commit of
/// the attachment.
#[test]
fn the_attachment_wins_over_the_supplement() {
    let scratch = TmpDir::new("cfs-commit-both");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        // The supplement names an image commit of another tree.
        let txn = repo.transaction().await.unwrap();
        let other = txn
            .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o400), b"other")
            .await
            .unwrap();
        let other = stage_image_commit(&txn, vec![("root.cfs".to_owned(), other)], vec![]).await;
        txn.commit().await.unwrap();
        let commit = store_named(
            &repo,
            &tree,
            "both",
            Some(&digest),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        repo.add_supplement(&commit, COMPOSEFS_RELATION, &other)
            .await
            .unwrap();

        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.source, ComposefsImageSource::Attachment);
        assert_eq!(found.commit, image);
    });
}

/// A commit with no attachment and no supplement of the name gives `None`,
/// also if it has the key and other related entries.
#[test]
fn a_commit_with_no_image_commit_gives_none() {
    let scratch = TmpDir::new("cfs-commit-none");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        assert!(repo.open_composefs_image(&tree).await.unwrap().is_none());
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(
            &repo,
            &tree,
            "other names",
            Some(&digest),
            &[("layer/composefs", image.as_bytes())],
        )
        .await;
        repo.add_supplement(&commit, "layer/other", &image)
            .await
            .unwrap();
        assert!(repo.open_composefs_image(&commit).await.unwrap().is_none());
    });
}

/// A defect of the image commit that the lookup checks.
#[derive(Debug, Clone, Copy)]
enum Fault {
    /// The repository does not hold the image commit.
    Absent,
    /// The repository marks the image commit partial.
    Partial,
    /// The root directory holds another file and no `root.cfs`.
    NoImageFile,
    /// `root.cfs` is a symlink object.
    SymlinkImage,
    /// `root.cfs` is a directory.
    DirImage,
    /// The root directory holds `root.cfs` and another file.
    ExtraEntry,
    /// The key of the commit is not the digest of the image.
    WrongKey,
}

/// The lookup refuses each defect of the image commit, for the attachment
/// and for the supplement, with the commit, the source, the image commit,
/// and the defect.
#[test]
fn each_defect_of_the_image_commit_is_refused() {
    let scratch = TmpDir::new("cfs-commit-defects");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (valid, digest) = write_image_commit(&repo, &tree).await;
        let image_file = image_object(&repo, &valid).await;

        let txn = repo.transaction().await.unwrap();
        let other = txn
            .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o400), b"other")
            .await
            .unwrap();
        let link = txn
            .write_symlink("target", &FileMeta::regular(0, 0, 0o777), None)
            .await
            .unwrap();
        let empty_dir = txn
            .write_metadata(
                ObjectType::DirTree,
                None,
                &DirTree::default().serialize().unwrap(),
            )
            .await
            .unwrap();
        let dir_meta = txn.write_dirmeta(&root_dirmeta()).await.unwrap();
        let no_image =
            stage_image_commit(&txn, vec![("other".to_owned(), other)], Vec::new()).await;
        let symlink =
            stage_image_commit(&txn, vec![("root.cfs".to_owned(), link)], Vec::new()).await;
        let dir = stage_image_commit(
            &txn,
            Vec::new(),
            vec![("root.cfs".to_owned(), empty_dir, dir_meta)],
        )
        .await;
        let extra = stage_image_commit(
            &txn,
            vec![
                ("extra".to_owned(), other),
                ("root.cfs".to_owned(), image_file),
            ],
            Vec::new(),
        )
        .await;
        txn.commit().await.unwrap();

        let wrong = [0x11u8; 32];
        let cases = [
            (
                Fault::Absent,
                Checksum::from_bytes([0x5a; 32]),
                digest,
                ComposefsImageDefect::Absent,
            ),
            (Fault::Partial, valid, digest, ComposefsImageDefect::Partial),
            (
                Fault::NoImageFile,
                no_image,
                digest,
                ComposefsImageDefect::NoImageFile,
            ),
            (
                Fault::SymlinkImage,
                symlink,
                digest,
                ComposefsImageDefect::NotRegular,
            ),
            (
                Fault::DirImage,
                dir,
                digest,
                ComposefsImageDefect::NotRegular,
            ),
            (
                Fault::ExtraEntry,
                extra,
                digest,
                ComposefsImageDefect::ExtraEntry("extra".to_owned()),
            ),
            (
                Fault::WrongKey,
                valid,
                wrong,
                ComposefsImageDefect::DigestMismatch {
                    expected: wrong,
                    actual: digest,
                },
            ),
        ];
        for source in [
            ComposefsImageSource::Attachment,
            ComposefsImageSource::Supplement,
        ] {
            for (fault, image, key, expected) in &cases {
                let subject = format!("{fault:?} {source}");
                let commit = match source {
                    ComposefsImageSource::Attachment => {
                        store_named(
                            &repo,
                            &tree,
                            &subject,
                            Some(key),
                            &[(COMPOSEFS_RELATION, image.as_bytes())],
                        )
                        .await
                    }
                    ComposefsImageSource::Supplement => {
                        let commit = store_named(&repo, &tree, &subject, Some(key), &[]).await;
                        repo.add_supplement(&commit, COMPOSEFS_RELATION, image)
                            .await
                            .unwrap();
                        commit
                    }
                };
                if let Fault::Partial = fault {
                    mark_partial(&repo, image);
                }
                let err = repo.open_composefs_image(&commit).await.unwrap_err();
                let text = err.to_string();
                let (at, relation, named, defect) = invalid_image(err);
                assert_eq!(
                    (at, relation, named, &defect),
                    (commit, source, *image, expected),
                    "{fault:?} {source}"
                );
                assert_eq!(
                    text,
                    format!(
                        "composefs image of commit {commit}: {source} composefs names commit \
                         {image}, {expected}"
                    )
                );
                if let Fault::Partial = fault {
                    std::fs::remove_file(repo.path().join(format!("state/{image}.commitpartial")))
                        .unwrap();
                }
            }
        }
    });
}

/// The text of each defect.
#[test]
fn each_defect_has_its_text() {
    let cases = [
        (
            ComposefsImageDefect::Absent,
            "which the repository does not hold",
        ),
        (ComposefsImageDefect::Partial, "which is partial"),
        (
            ComposefsImageDefect::NoImageFile,
            "whose tree holds no /root.cfs",
        ),
        (
            ComposefsImageDefect::NotRegular,
            "whose /root.cfs is not a regular file",
        ),
        (
            ComposefsImageDefect::ExtraEntry("etc".to_owned()),
            "whose tree holds the entry etc next to /root.cfs",
        ),
    ];
    for (defect, text) in cases {
        assert_eq!(defect.to_string(), text);
    }
    let mismatch = ComposefsImageDefect::DigestMismatch {
        expected: [0x11; 32],
        actual: [0x22; 32],
    };
    assert_eq!(
        mismatch.to_string(),
        format!(
            "whose /root.cfs has the fs-verity digest {}, and the commit records {}",
            "22".repeat(32),
            "11".repeat(32)
        )
    );
}

/// A bad attachment stops the lookup, also when a valid supplement exists.
#[test]
fn a_bad_attachment_stops_the_lookup_next_to_a_valid_supplement() {
    let scratch = TmpDir::new("cfs-commit-bad-attachment");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (valid, digest) = write_image_commit(&repo, &tree).await;
        let absent = Checksum::from_bytes([0x5a; 32]);
        let commit = store_named(
            &repo,
            &tree,
            "bad attachment",
            Some(&digest),
            &[(COMPOSEFS_RELATION, absent.as_bytes())],
        )
        .await;
        repo.add_supplement(&commit, COMPOSEFS_RELATION, &valid)
            .await
            .unwrap();
        let err = repo.open_composefs_image(&commit).await.unwrap_err();
        assert_eq!(
            invalid_image(err),
            (
                commit,
                ComposefsImageSource::Attachment,
                absent,
                ComposefsImageDefect::Absent
            )
        );
    });
}

/// Two entries of the name in field 2 or in `ostrya.related`, and a
/// defective entry of another name in field 2, fail the lookup with
/// `InvalidRelations`.
#[test]
fn duplicate_and_defective_entries_are_refused() {
    let scratch = TmpDir::new("cfs-commit-duplicates");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;

        let twice = store_named(
            &repo,
            &tree,
            "two attachments",
            Some(&digest),
            &[
                (COMPOSEFS_RELATION, image.as_bytes()),
                (COMPOSEFS_RELATION, image.as_bytes()),
            ],
        )
        .await;
        match repo.open_composefs_image(&twice).await.unwrap_err() {
            Error::InvalidRelations {
                commit,
                field,
                reason,
            } => {
                assert_eq!(commit, Some(twice));
                assert_eq!(field, RelationField::Attachments);
                assert_eq!(reason, "two or more entries have the name composefs");
            }
            other => panic!("expected InvalidRelations, got {other:?}"),
        }

        let defective = store_named(
            &repo,
            &tree,
            "defective attachment",
            Some(&digest),
            &[
                (COMPOSEFS_RELATION, image.as_bytes()),
                ("layer/short", &[1, 2, 3]),
            ],
        )
        .await;
        match repo.open_composefs_image(&defective).await.unwrap_err() {
            Error::InvalidRelations { commit, field, .. } => {
                assert_eq!(commit, Some(defective));
                assert_eq!(field, RelationField::Attachments);
            }
            other => panic!("expected InvalidRelations, got {other:?}"),
        }

        let supplements = store_named(&repo, &tree, "two supplements", Some(&digest), &[]).await;
        repo.write_commit_detached_metadata(
            &supplements,
            Some(&supplement_dict(&[
                (COMPOSEFS_RELATION, &image),
                (COMPOSEFS_RELATION, &image),
            ])),
        )
        .await
        .unwrap();
        match repo.open_composefs_image(&supplements).await.unwrap_err() {
            Error::InvalidRelations { commit, field, .. } => {
                assert_eq!(commit, Some(supplements));
                assert_eq!(field, RelationField::Supplements);
            }
            other => panic!("expected InvalidRelations, got {other:?}"),
        }
    });
}

/// The lookup refuses an `archive` repository with `Unsupported`.
#[test]
fn the_lookup_refuses_an_archive_repository() {
    let scratch = TmpDir::new("cfs-commit-archive-lookup");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::Archive, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(
            &repo,
            &tree,
            "archive",
            Some(&digest),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        match repo.open_composefs_image(&commit).await.unwrap_err() {
            Error::Unsupported(message) => assert!(message.contains("archive"), "{message}"),
            other => panic!("expected Unsupported, got {other:?}"),
        }
    });
}

/// In an `archive` repository, the image file is a `.filez` object whose
/// inflated payload is the image. A transaction that generates sizes writes
/// no `ostree.sizes` into the image commit.
#[test]
fn the_image_commit_is_written_in_an_archive_repository() {
    use futures_lite::AsyncReadExt;

    let scratch = TmpDir::new("cfs-commit-archive-write");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::Archive, "").await;
        let root = root_of(&repo, &tree).await;
        let mut txn = repo.transaction().await.unwrap();
        txn.set_generate_sizes(true);
        let (image, digest) = txn.write_composefs_commit(&root, None).await.unwrap();
        txn.commit().await.unwrap();

        let (commit, _) = repo.load_commit(&image).await.unwrap();
        assert_eq!(commit.metadata, Value::Array(Vec::new()));
        let object = image_object(&repo, &image).await;
        let filez = loose_path(&object, ObjectType::File, RepoMode::Archive);
        assert!(filez.ends_with(".filez"), "{filez}");
        assert!(repo.path().join("objects").join(&filez).is_file());

        let file = repo.load_file(&object).await.unwrap();
        let mut payload = Vec::new();
        file.reader()
            .await
            .unwrap()
            .read_to_end(&mut payload)
            .await
            .unwrap();
        let export = recorded_export(&repo, &tree).await;
        assert_eq!(payload, export.bytes);
        assert_eq!(digest, export.fs_verity);
    });
}

/// A commit with no key gives the file of its image commit with no check of
/// the content, also if the image is the image of another tree.
#[test]
fn a_commit_with_no_key_gives_the_image_with_no_check() {
    let scratch = TmpDir::new("cfs-commit-no-key");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        // The image commit holds an image file whose content is not the image
        // of the tree.
        let txn = repo.transaction().await.unwrap();
        let other = txn
            .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o400), b"not an image")
            .await
            .unwrap();
        let image = stage_image_commit(&txn, vec![("root.cfs".to_owned(), other)], vec![]).await;
        txn.commit().await.unwrap();
        let commit = store_named(
            &repo,
            &tree,
            "no key",
            None,
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;

        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.source, ComposefsImageSource::Attachment);
        assert_eq!(found.commit, image);
        assert_eq!(found.size, 12);
        assert_eq!(read_all(&found.file), b"not an image");
    });
}

/// In a `bare-user` repository with `[ex-integrity] fsverity=yes`, the image
/// file is sealed, and the lookup returns the sealed descriptor whose kernel
/// digest is the key.
#[test]
fn the_lookup_returns_the_sealed_image() {
    let scratch = TmpDir::new("cfs-commit-sealed");
    if !verity_supported(scratch.path()) {
        eprintln!("skipping: the file system has no fs-verity");
        return;
    }
    block_on(async {
        let (repo, tree) = setup(
            &scratch,
            RepoMode::BareUser,
            "[ex-integrity]\nfsverity=yes\n",
        )
        .await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(
            &repo,
            &tree,
            "sealed",
            Some(&digest),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;

        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        let stat = rustix::fs::statx(
            &found.file,
            "",
            rustix::fs::AtFlags::EMPTY_PATH,
            rustix::fs::StatxFlags::SIZE,
        )
        .unwrap();
        assert!(
            stat.stx_attributes
                .contains(rustix::fs::StatxAttributes::VERITY)
        );
        assert_eq!(
            ostrya_sys::measure_verity(found.file.as_fd()).unwrap(),
            digest
        );
        assert_eq!(found.size, stat.stx_size);
    });
}

/// With a valid attachment, the lookup does not read the `.commitmeta`: a
/// defective supplement entry or two supplements of the name do not fail it.
#[test]
fn a_valid_attachment_does_not_read_the_supplements() {
    let scratch = TmpDir::new("cfs-commit-attachment-only");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let detached = [
            raw_supplement_dict(&[("layer/short", &[1, 2, 3])]),
            supplement_dict(&[(COMPOSEFS_RELATION, &image), (COMPOSEFS_RELATION, &image)]),
        ];
        for (n, dict) in detached.iter().enumerate() {
            let commit = store_named(
                &repo,
                &tree,
                &format!("attachment {n}"),
                Some(&digest),
                &[(COMPOSEFS_RELATION, image.as_bytes())],
            )
            .await;
            write_raw_detached(&repo, &commit, dict);
            let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
            assert_eq!(found.source, ComposefsImageSource::Attachment, "{n}");
            assert_eq!(found.commit, image, "{n}");
        }
    });
}

/// The lookup reads the key only if the commit names an image commit: a key
/// of 31 bytes gives `None` with no entry, and `InvalidFormat` with one.
#[test]
fn a_malformed_key_fails_only_a_commit_that_names_an_image() {
    let scratch = TmpDir::new("cfs-commit-bad-key");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, _) = write_image_commit(&repo, &tree).await;
        let short = || dict(DIGEST_KEY, "ay", Value::Bytes(vec![0x11; 31]));

        let unnamed = store_with_metadata(&repo, &tree, "no entry", short(), &[]).await;
        assert!(repo.open_composefs_image(&unnamed).await.unwrap().is_none());

        let named = store_with_metadata(
            &repo,
            &tree,
            "with entry",
            short(),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        match repo.open_composefs_image(&named).await.unwrap_err() {
            Error::InvalidFormat(_) => {}
            other => panic!("expected InvalidFormat, got {other:?}"),
        }
    });
}

/// In an `archive` repository, the lookup refuses an absent commit with
/// `Unsupported`, so the refusal comes before any read.
#[test]
fn the_archive_refusal_comes_before_any_read() {
    let scratch = TmpDir::new("cfs-commit-archive-absent");
    block_on(async {
        let repo = new_repo(&scratch.path().join("repo"), RepoMode::Archive, "").await;
        let absent = Checksum::from_bytes([0x5a; 32]);
        match repo.open_composefs_image(&absent).await.unwrap_err() {
            Error::Unsupported(message) => assert!(message.contains("archive"), "{message}"),
            other => panic!("expected Unsupported, got {other:?}"),
        }
    });
}

/// A defective supplement entry of another name fails the lookup of a commit
/// with no attachment of the name.
#[test]
fn a_defective_supplement_of_another_name_is_refused() {
    let scratch = TmpDir::new("cfs-commit-bad-supplement");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(&repo, &tree, "bad supplement", Some(&digest), &[]).await;
        write_raw_detached(
            &repo,
            &commit,
            &raw_supplement_dict(&[
                (COMPOSEFS_RELATION, image.as_bytes()),
                ("layer/short", &[1, 2, 3]),
            ]),
        );
        match repo.open_composefs_image(&commit).await.unwrap_err() {
            Error::InvalidRelations {
                commit: at, field, ..
            } => {
                assert_eq!(at, Some(commit));
                assert_eq!(field, RelationField::Supplements);
            }
            other => panic!("expected InvalidRelations, got {other:?}"),
        }
    });
}

/// In a sealing repository, a key that is not the kernel digest of the
/// sealed image gives `DigestMismatch` with the actual digest.
#[test]
fn a_wrong_key_of_a_sealed_image_is_refused() {
    let scratch = TmpDir::new("cfs-commit-sealed-wrong");
    if !verity_supported(scratch.path()) {
        eprintln!("skipping: the file system has no fs-verity");
        return;
    }
    block_on(async {
        let (repo, tree) = setup(
            &scratch,
            RepoMode::BareUser,
            "[ex-integrity]\nfsverity=yes\n",
        )
        .await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let wrong = [0x11u8; 32];
        let commit = store_named(
            &repo,
            &tree,
            "sealed wrong key",
            Some(&wrong),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        let err = repo.open_composefs_image(&commit).await.unwrap_err();
        assert_eq!(
            invalid_image(err),
            (
                commit,
                ComposefsImageSource::Attachment,
                image,
                ComposefsImageDefect::DigestMismatch {
                    expected: wrong,
                    actual: digest,
                }
            )
        );
    });
}

/// A complete image commit whose file object of `root.cfs` or whose root
/// dirtree is missing fails the lookup with `ObjectNotFound`.
#[test]
fn a_missing_object_of_a_complete_image_commit_is_not_found() {
    let scratch = TmpDir::new("cfs-commit-missing-object");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(
            &repo,
            &tree,
            "missing objects",
            Some(&digest),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        let (image_commit, _) = repo.load_commit(&image).await.unwrap();
        let file = image_object(&repo, &image).await;
        let dirtree = image_commit.root_dirtree;
        let remove = |checksum: &Checksum, ty: ObjectType| {
            let path = loose_path(checksum, ty, repo.mode());
            std::fs::remove_file(repo.path().join("objects").join(path)).unwrap();
        };

        for (checksum, ty) in [(file, ObjectType::File), (dirtree, ObjectType::DirTree)] {
            remove(&checksum, ty);
            match repo.open_composefs_image(&commit).await.unwrap_err() {
                Error::ObjectNotFound {
                    checksum: missing,
                    ty: missing_ty,
                } => assert_eq!((missing, missing_ty), (checksum, ty)),
                other => panic!("expected ObjectNotFound for {ty:?}, got {other:?}"),
            }
        }
    });
}

/// A `bare-user-only` repository writes the image commit in the fixed
/// shape, and the image commit of one tree has the same checksum in the
/// `bare-user-only`, `bare-user`, and `archive` modes.
#[test]
fn the_image_commit_is_the_same_in_each_mode() {
    let scratch = TmpDir::new("cfs-commit-modes");
    block_on(async {
        let mut images = Vec::new();
        for (n, mode) in [
            RepoMode::BareUserOnly,
            RepoMode::BareUser,
            RepoMode::Archive,
        ]
        .into_iter()
        .enumerate()
        {
            let repo = new_repo(&scratch.path().join(format!("repo{n}")), mode, "").await;
            let tree = plain_tree_commit(&repo).await;
            let (image, digest) = write_image_commit(&repo, &tree).await;
            let export = recorded_export(&repo, &tree).await;
            assert_eq!(digest, export.fs_verity, "{mode:?}");
            if mode == RepoMode::BareUserOnly {
                let (commit, _) = repo.load_commit(&image).await.unwrap();
                assert_eq!(commit.subject, IMAGE_SUBJECT);
                assert_eq!(commit.timestamp, 0);
                assert_eq!(commit.metadata, Value::Array(Vec::new()));
                let dirmeta = repo.load_dirmeta(&commit.root_dirmeta).await.unwrap();
                assert_eq!(dirmeta, root_dirmeta());
                let object = image_object(&repo, &image).await;
                let file = repo.load_file(&object).await.unwrap();
                assert_eq!((file.uid, file.gid, file.mode), (0, 0, 0o100400));
                assert!(file.xattrs.is_empty());
                assert_eq!(raw_object(&repo, &object), export.bytes);
                let found = store_named(
                    &repo,
                    &tree,
                    "bare-user-only",
                    Some(&digest),
                    &[(COMPOSEFS_RELATION, image.as_bytes())],
                )
                .await;
                let found = repo.open_composefs_image(&found).await.unwrap().unwrap();
                assert_eq!(read_all(&found.file), export.bytes);
            }
            images.push((image, digest));
        }
        assert_eq!(images[0], images[1]);
        assert_eq!(images[0], images[2]);
    });
}

/// Returns the sorted paths of the files below `objects/` of `repo`.
fn object_files(repo: &Repo) -> Vec<std::path::PathBuf> {
    fn walk(dir: &std::path::Path, out: &mut Vec<std::path::PathBuf>) {
        for entry in std::fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                walk(&path, out);
            } else {
                out.push(path);
            }
        }
    }
    let mut out = Vec::new();
    walk(&repo.path().join("objects"), &mut out);
    out.sort();
    out
}

/// Returns the bytes of the `.commitmeta` of `commit`, or `None` if the
/// repository holds none.
fn commitmeta_bytes(repo: &Repo, commit: &Checksum) -> Option<Vec<u8>> {
    let path = loose_path(commit, ObjectType::CommitMeta, repo.mode());
    std::fs::read(repo.path().join("objects").join(path)).ok()
}

/// Returns the supplements of `commit`.
async fn supplements(repo: &Repo, commit: &Checksum) -> Vec<(String, Checksum)> {
    repo.read_commit_relations(commit)
        .await
        .unwrap()
        .supplements
}

/// A commit with the key and no image commit gets the image commit of its
/// tree as the supplement. The lookup then gives it. A second call finds the
/// valid supplement and writes nothing.
#[test]
fn the_add_writes_the_supplement_of_a_commit_with_the_key() {
    let scratch = TmpDir::new("cfs-add-key");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let digest = recorded_export(&repo, &tree).await.fs_verity;
        let commit = store_named(&repo, &tree, "add", Some(&digest), &[]).await;

        let added = repo.add_composefs_supplement(&commit).await.unwrap();
        let ComposefsSupplementAdd::Written { image, replaced } = added else {
            panic!("expected Written, got {added:?}");
        };
        assert_eq!(replaced, None);
        assert_eq!(
            supplements(&repo, &commit).await,
            vec![(COMPOSEFS_RELATION.to_owned(), image)]
        );
        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.source, ComposefsImageSource::Supplement);
        assert_eq!(found.commit, image);
        assert_eq!(
            read_all(&found.file),
            recorded_export(&repo, &tree).await.bytes
        );

        let objects = object_files(&repo);
        let meta = commitmeta_bytes(&repo, &commit);
        assert_eq!(
            repo.add_composefs_supplement(&commit).await.unwrap(),
            ComposefsSupplementAdd::Valid { image }
        );
        assert_eq!(object_files(&repo), objects);
        assert_eq!(commitmeta_bytes(&repo, &commit), meta);
    });
}

/// A commit with no key gets the image commit with no check.
#[test]
fn the_add_makes_no_check_for_a_commit_with_no_key() {
    let scratch = TmpDir::new("cfs-add-no-key");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let commit = store_named(&repo, &tree, "no key", None, &[]).await;
        let added = repo.add_composefs_supplement(&commit).await.unwrap();
        let ComposefsSupplementAdd::Written { image, replaced } = added else {
            panic!("expected Written, got {added:?}");
        };
        assert_eq!(replaced, None);
        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.commit, image);
    });
}

/// A key that is not the digest of the built image refuses the commit with
/// both digests, and the call writes no object and no supplement.
#[test]
fn the_add_refuses_a_key_that_is_not_the_digest() {
    let scratch = TmpDir::new("cfs-add-mismatch");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let digest = recorded_export(&repo, &tree).await.fs_verity;
        let wrong = [0x11u8; 32];
        let commit = store_named(&repo, &tree, "wrong key", Some(&wrong), &[]).await;
        let objects = object_files(&repo);

        match repo.add_composefs_supplement(&commit).await.unwrap_err() {
            Error::ComposefsDigestMismatch {
                commit: refused,
                expected,
                actual,
            } => {
                assert_eq!(refused, commit);
                assert_eq!(expected, wrong);
                assert_eq!(actual, digest);
            }
            other => panic!("expected ComposefsDigestMismatch, got {other:?}"),
        }
        assert_eq!(object_files(&repo), objects);
        assert!(commitmeta_bytes(&repo, &commit).is_none());
        assert!(repo.open_composefs_image(&commit).await.unwrap().is_none());
    });
}

/// A commit that names an image commit as the attachment is refused, and
/// the call writes nothing.
#[test]
fn the_add_refuses_a_commit_with_the_attachment() {
    let scratch = TmpDir::new("cfs-add-attachment");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(
            &repo,
            &tree,
            "attached",
            Some(&digest),
            &[(COMPOSEFS_RELATION, image.as_bytes())],
        )
        .await;
        let objects = object_files(&repo);
        match repo.add_composefs_supplement(&commit).await.unwrap_err() {
            Error::InvalidInput(message) => assert_eq!(
                message,
                format!(
                    "commit {commit} names its composefs image commit {image} as an \
                     attachment; a supplement is not written"
                )
            ),
            other => panic!("expected InvalidInput, got {other:?}"),
        }
        assert_eq!(object_files(&repo), objects);
        assert!(commitmeta_bytes(&repo, &commit).is_none());
    });
}

/// A supplement whose image commit fails a check is replaced: an absent
/// image commit, and an image commit whose digest is not the key.
#[test]
fn the_add_replaces_a_bad_supplement() {
    let scratch = TmpDir::new("cfs-add-replace");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let digest = recorded_export(&repo, &tree).await.fs_verity;
        let txn = repo.transaction().await.unwrap();
        let other = txn
            .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o400), b"other")
            .await
            .unwrap();
        let other = stage_image_commit(&txn, vec![("root.cfs".to_owned(), other)], vec![]).await;
        txn.commit().await.unwrap();
        let absent = Checksum::from_bytes([0x5a; 32]);

        for (subject, bad) in [("absent", absent), ("other", other)] {
            let commit = store_named(&repo, &tree, subject, Some(&digest), &[]).await;
            repo.add_supplement(&commit, COMPOSEFS_RELATION, &bad)
                .await
                .unwrap();
            let added = repo.add_composefs_supplement(&commit).await.unwrap();
            let ComposefsSupplementAdd::Written { image, replaced } = added else {
                panic!("expected Written, got {added:?}");
            };
            assert_eq!(replaced, Some(bad), "{subject}");
            assert_eq!(
                supplements(&repo, &commit).await,
                vec![(COMPOSEFS_RELATION.to_owned(), image)]
            );
            let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
            assert_eq!(found.commit, image);
        }
    });
}

/// A supplement that names a partial image commit is replaced by the same
/// image commit, and the call removes the partial marker.
#[test]
fn the_add_completes_a_partial_image_commit() {
    let scratch = TmpDir::new("cfs-add-partial");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (image, digest) = write_image_commit(&repo, &tree).await;
        let commit = store_named(&repo, &tree, "partial", Some(&digest), &[]).await;
        repo.add_supplement(&commit, COMPOSEFS_RELATION, &image)
            .await
            .unwrap();
        mark_partial(&repo, &image);
        // The object of the image is absent, as after a pull that stopped.
        let object = image_object(&repo, &image).await;
        let path = loose_path(&object, ObjectType::File, repo.mode());
        std::fs::remove_file(repo.path().join("objects").join(path)).unwrap();

        let added = repo.add_composefs_supplement(&commit).await.unwrap();
        assert_eq!(
            added,
            ComposefsSupplementAdd::Written {
                image,
                replaced: Some(image),
            }
        );
        assert_eq!(
            repo.commit_state(&image).await.unwrap(),
            ostrya::CommitState::Normal
        );
        let found = repo.open_composefs_image(&commit).await.unwrap().unwrap();
        assert_eq!(found.commit, image);
    });
}

/// In an `archive` repository, the add writes the image commit, and a
/// second call checks the inflated image and writes nothing. A supplement
/// that names another image commit fails the check of the inflated image
/// and is replaced. A supplement whose image is not the key of a commit
/// fails the check, and the key refuses the built image.
#[test]
fn the_add_works_in_an_archive_repository() {
    let scratch = TmpDir::new("cfs-add-archive");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::Archive, "").await;
        let digest = recorded_export(&repo, &tree).await.fs_verity;
        let commit = store_named(&repo, &tree, "archive", Some(&digest), &[]).await;
        let added = repo.add_composefs_supplement(&commit).await.unwrap();
        let ComposefsSupplementAdd::Written { image, replaced } = added else {
            panic!("expected Written, got {added:?}");
        };
        assert_eq!(replaced, None);
        let objects = object_files(&repo);
        assert_eq!(
            repo.add_composefs_supplement(&commit).await.unwrap(),
            ComposefsSupplementAdd::Valid { image }
        );
        assert_eq!(object_files(&repo), objects);

        // The supplement of a commit with the right key names the valid
        // image commit of another tree: the digest of its inflated image is
        // not the key, so the add builds the image and replaces the entry.
        let plain = plain_tree_commit(&repo).await;
        let (another, _) = write_image_commit(&repo, &plain).await;
        let renamed = store_named(&repo, &tree, "archive another", Some(&digest), &[]).await;
        repo.add_supplement(&renamed, COMPOSEFS_RELATION, &another)
            .await
            .unwrap();
        assert_eq!(
            repo.add_composefs_supplement(&renamed).await.unwrap(),
            ComposefsSupplementAdd::Written {
                image,
                replaced: Some(another),
            }
        );
        assert_eq!(
            supplements(&repo, &renamed).await,
            vec![(COMPOSEFS_RELATION.to_owned(), image)]
        );

        // The supplement of another commit with another key names the same
        // image commit: its inflated digest is not that key, so the add
        // builds the image, and the key refuses it.
        let wrong = [0x11u8; 32];
        let other = store_named(&repo, &tree, "archive wrong", Some(&wrong), &[]).await;
        repo.add_supplement(&other, COMPOSEFS_RELATION, &image)
            .await
            .unwrap();
        match repo.add_composefs_supplement(&other).await.unwrap_err() {
            Error::ComposefsDigestMismatch {
                expected, actual, ..
            } => {
                assert_eq!(expected, wrong);
                assert_eq!(actual, digest);
            }
            other => panic!("expected ComposefsDigestMismatch, got {other:?}"),
        }
        assert_eq!(
            supplements(&repo, &other).await,
            vec![(COMPOSEFS_RELATION.to_owned(), image)]
        );
    });
}

/// `CheckedAttachments::add` checks the new entry alone: after the first
/// check, the repository marks the commit of the other entries partial, and
/// the add and the write of the commit pass. The add takes an image commit
/// that the transaction stages, keeps the entries sorted, and refuses an
/// empty name, a name that the entries hold, and a partial commit with no
/// change to the entries.
#[test]
fn checked_attachments_add_checks_the_new_entry() {
    let scratch = TmpDir::new("cfs-checked-add");
    block_on(async {
        let (repo, tree) = setup(&scratch, RepoMode::BareUser, "").await;
        let (partial, _) = write_image_commit(&repo, &tree).await;
        let other = plain_tree_commit(&repo).await;
        let root = root_of(&repo, &tree).await;
        let txn = repo.transaction().await.unwrap();
        let mut checked = txn
            .check_attachments(&[("z/last".to_owned(), other), ("a/first".to_owned(), other)])
            .await
            .unwrap();
        // The repository holds the image commit `partial` and marks it
        // partial. It also marks the checked attachment `other` partial, so
        // a check of an entry of the first check fails.
        mark_partial(&repo, &partial);
        mark_partial(&repo, &other);
        let refusal = |err: Error| match err {
            Error::InvalidRelations {
                commit: None,
                field: RelationField::Attachments,
                reason,
            } => reason,
            other => panic!("expected InvalidRelations, got {other:?}"),
        };
        assert_eq!(
            refusal(checked.add("", &other).await.unwrap_err()),
            "the new entry has an empty name"
        );
        assert_eq!(
            refusal(checked.add("a/first", &other).await.unwrap_err()),
            "two entries have the name a/first"
        );
        let reason = refusal(checked.add(COMPOSEFS_RELATION, &partial).await.unwrap_err());
        assert!(reason.contains("partial"), "{reason}");
        assert!(reason.contains(&partial.to_string()), "{reason}");
        assert!(!reason.contains(&other.to_string()), "{reason}");
        std::fs::remove_file(repo.path().join(format!("state/{partial}.commitpartial"))).unwrap();

        let staged = txn
            .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o400), b"staged")
            .await
            .unwrap();
        let staged = stage_image_commit(&txn, vec![("root.cfs".to_owned(), staged)], vec![]).await;
        checked.add(COMPOSEFS_RELATION, &staged).await.unwrap();
        let commit = txn
            .write_commit_checked(
                ostrya::CommitOptions {
                    subject: Some("checked".to_owned()),
                    timestamp: Some(0),
                    ..ostrya::CommitOptions::default()
                },
                checked,
                &root,
            )
            .await
            .unwrap();
        txn.commit().await.unwrap();
        let relations = repo.read_commit_relations(&commit).await.unwrap();
        assert_eq!(
            relations.attachments,
            vec![
                ("a/first".to_owned(), other),
                (COMPOSEFS_RELATION.to_owned(), staged),
                ("z/last".to_owned(), other),
            ]
        );
    });
}