ostrya 0.17.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
//! The composefs image commit.
//!
//! The image commit holds the composefs image of the tree of another commit.
//! Its tree holds one regular file, `/root.cfs`, which is the EROFS image.
//! A commit names its image commit by the name [`COMPOSEFS_RELATION`], as an
//! attachment (field 2 of the commit object) or as a supplement (the key
//! `ostrya.related` of the detached metadata).
//!
//! - [`Transaction::write_composefs_commit`] stages the image commit of a
//!   tree.
//! - [`Repo::open_composefs_image`] finds the image commit that a commit
//!   names, checks it, and opens its `/root.cfs`.
//! - [`Repo::add_composefs_supplement`] writes the image commit of a commit
//!   and names it as the supplement [`COMPOSEFS_RELATION`] of the commit.
//!
//! The key [`COMPOSEFS_DIGEST_KEY`] of a commit records the fs-verity digest
//! of the image that a build of its tree with no hook gives. The lookup
//! compares the key with the image of a supplement, and refuses a supplement
//! of a commit with no key. The lookup does not read the key for an
//! attachment.
//!
//! The shape of the image commit is fixed:
//!
//! - The root directory is `0:0` with the mode `040755` and no xattrs.
//! - The root directory holds the file `root.cfs` alone. The file is `0:0`
//!   with the mode `0100400` and no xattrs. Its content is the image that an
//!   export with [`ComposefsOptions::RECORDED`] writes for the tree, with the
//!   hook that the caller gives or with no hook.
//! - The commit has the subject `composefs image`, an empty body, the
//!   timestamp 0, no parent, no metadata key, and no related entry.
//!
//! The same image therefore gives the same image commit.

use ostrya_core::{Checksum, Commit, DirMeta, DirTree, ObjectType, Value, Xattrs};

use async_compression::futures::bufread::DeflateDecoder;

use crate::composefs::{
    COMPOSEFS_DIGEST_KEY, ComposefsEntryFn, ComposefsOptions, DIGEST_CHUNK, digest_hex,
    image_file_digest, recorded_digest,
};
use crate::config::Tristate;
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject, Payload};
use crate::inflate::BufSource;
use crate::read::CommitState;
use crate::related::{self, RelationField};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::FileMeta;

/// The name of the attachment and of the supplement that names the
/// composefs image commit of a commit.
pub const COMPOSEFS_RELATION: &str = "composefs";

/// The name of the image file in the root directory of the image commit.
const IMAGE_FILE: &str = "root.cfs";

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

/// The permission bits of the image file.
const IMAGE_PERM: u32 = 0o400;

/// The mode of the root directory of the image commit.
const ROOT_DIR_MODE: u32 = 0o040755;

/// The field of a commit that names the image commit that
/// [`Repo::open_composefs_image`] opens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageSource {
    /// The attachment [`COMPOSEFS_RELATION`]: an entry of field 2 of the
    /// commit object.
    Attachment,
    /// The supplement [`COMPOSEFS_RELATION`]: an entry of the key
    /// `ostrya.related` of the detached metadata.
    Supplement,
}

impl std::fmt::Display for ComposefsImageSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(match self {
            ComposefsImageSource::Attachment => "attachment",
            ComposefsImageSource::Supplement => "supplement",
        })
    }
}

/// The open composefs image of a commit, from
/// [`Repo::open_composefs_image`].
#[derive(Debug)]
pub struct ComposefsImage {
    /// The loose object of `/root.cfs` in the image commit, open read-only at
    /// offset 0.
    pub file: std::fs::File,
    /// The size of the image in bytes.
    pub size: u64,
    /// The field of the commit that names the image commit.
    pub source: ComposefsImageSource,
    /// The checksum of the image commit.
    pub commit: Checksum,
}

/// The result of [`Repo::add_composefs_supplement`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsSupplementAdd {
    /// The commit has the supplement [`COMPOSEFS_RELATION`], and its image
    /// commit passes the checks of [`Repo::open_composefs_image`]. The call
    /// writes nothing.
    Valid {
        /// The checksum of the image commit.
        image: Checksum,
    },
    /// The call wrote the image commit and set the supplement
    /// [`COMPOSEFS_RELATION`] of the commit to it.
    Written {
        /// The checksum of the image commit.
        image: Checksum,
        /// The image commit that the supplement named before the call, if
        /// the commit had the supplement and its image commit failed a
        /// check. It can be equal to `image`: for example, a partial image
        /// commit that the call completes.
        replaced: Option<Checksum>,
    },
}

/// The defect of an image commit, or of the way that a commit names it, that
/// [`Repo::open_composefs_image`] refuses with
/// [`Error::InvalidComposefsImage`].
///
/// The text of each defect is a clause that follows the checksum of the image
/// commit in the text of the error.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ComposefsImageDefect {
    /// The commit names the image commit as a supplement and carries no key
    /// `ostree.composefs.digest.v0`.
    NoKey,
    /// The repository does not hold the image commit.
    Absent,
    /// The repository marks the image commit partial.
    Partial,
    /// The root directory of the image commit holds no entry `root.cfs`.
    NoImageFile,
    /// The entry `root.cfs` is a directory or a symlink.
    NotRegular,
    /// The root directory of the image commit holds an entry other than
    /// `root.cfs`. The value is the name of the entry.
    ExtraEntry(String),
    /// The repository sets `[ex-integrity] fsverity=yes`, and the file object
    /// of `root.cfs` has no fs-verity seal with SHA-256, 4096-byte blocks, no
    /// salt, and its full size.
    NotSealed,
    /// The fs-verity digest of `/root.cfs` is not the value of the key
    /// `ostree.composefs.digest.v0` of the commit.
    DigestMismatch {
        /// The digest that the commit records.
        expected: [u8; 32],
        /// The fs-verity digest of `/root.cfs`.
        actual: [u8; 32],
    },
}

impl std::fmt::Display for ComposefsImageDefect {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ComposefsImageDefect::NoKey => {
                f.write_str("and the commit carries no ostree.composefs.digest.v0")
            }
            ComposefsImageDefect::Absent => f.write_str(related::ABSENT_REASON),
            ComposefsImageDefect::Partial => f.write_str(related::PARTIAL_REASON),
            ComposefsImageDefect::NoImageFile => write!(f, "whose tree holds no /{IMAGE_FILE}"),
            ComposefsImageDefect::NotRegular => {
                write!(f, "whose /{IMAGE_FILE} is not a regular file")
            }
            ComposefsImageDefect::ExtraEntry(name) => {
                write!(f, "whose tree holds the entry {name} next to /{IMAGE_FILE}")
            }
            ComposefsImageDefect::NotSealed => write!(
                f,
                "whose /{IMAGE_FILE} has no fs-verity seal with SHA-256, 4096-byte blocks, \
                 no salt, and its full size"
            ),
            ComposefsImageDefect::DigestMismatch { expected, actual } => write!(
                f,
                "whose /{IMAGE_FILE} has the fs-verity digest {}, and the commit records {}",
                digest_hex(actual),
                digest_hex(expected)
            ),
        }
    }
}

/// Methods that write the composefs image commit.
impl Transaction {
    /// Stages the composefs image commit of a tree that this transaction
    /// staged.
    ///
    /// The call returns the checksum of the image commit and the fs-verity
    /// digest of the image. The image is the image that
    /// [`Repo::export_composefs_to`] writes for the tree with
    /// [`ComposefsOptions::RECORDED`] and the hook `filter`. With `None`, the
    /// digest is the value that
    /// [`composefs_digest`](Transaction::composefs_digest) gives.
    ///
    /// The call takes no [`ComposefsOptions`]. It always uses
    /// [`ComposefsOptions::RECORDED`], so each backed file of the image carries
    /// the fs-verity digest of its content.
    ///
    /// `filter` is an entry hook. [`ComposefsEntryFn`] states its rules. The
    /// hook gets one call for each node of the tree, and for each top-level
    /// directory that the call adds to the image. The whiteout stubs of the
    /// image get no call. Each stub takes the owner, the mtime, and the
    /// `security.selinux` xattr of the root after the hook. With `None`, the
    /// call uses no hook.
    ///
    /// The image commit has a fixed shape:
    ///
    /// - The root directory is `0:0` with the mode `040755` and no xattrs.
    /// - The root directory holds the file `root.cfs` alone. The file is the
    ///   image, `0:0` with the mode `0100400` and no xattrs.
    /// - The commit has the subject `composefs image`, an empty body, the
    ///   timestamp 0, no parent, no metadata key, and no related entry.
    ///
    /// So the same image gives the same image commit.
    ///
    /// The call writes the image file with
    /// [`write_composefs_content`](Transaction::write_composefs_content). It
    /// then stages the root dirmeta, the root dirtree, and the commit object
    /// with no `ostree.sizes` key. The image commit
    /// does not name the commit of the tree. The caller names the image commit
    /// from that commit as the attachment or the supplement
    /// [`COMPOSEFS_RELATION`].
    ///
    /// The key [`COMPOSEFS_DIGEST_KEY`] of the commit of the tree records the
    /// digest of the image that the call gives with no hook. With a hook, the
    /// caller writes the value of
    /// [`composefs_digest`](Transaction::composefs_digest) under the key, or
    /// no key, and names the image commit as an attachment.
    /// [`Repo::open_composefs_image`] compares the key with the digest of
    /// `/root.cfs` for a supplement alone, so it refuses a supplement whose
    /// image a hook changed.
    ///
    /// In an `archive` repository, the image file is a `.filez` object.
    /// [`Repo::open_composefs_image`] refuses an `archive` repository.
    ///
    /// If the repository already holds the image commit and marks it partial,
    /// the call does not remove the partial marker. The image commit then
    /// stays partial, and [`Repo::open_composefs_image`] refuses it.
    ///
    /// # Errors
    ///
    /// - The errors of
    ///   [`write_composefs_content`](Transaction::write_composefs_content).
    /// - The errors of [`write_dirmeta`](Transaction::write_dirmeta) and of
    ///   [`write_metadata`](Transaction::write_metadata).
    pub async fn write_composefs_commit(
        &self,
        root: &RepoTree,
        filter: Option<ComposefsEntryFn<'_>>,
    ) -> Result<(Checksum, [u8; 32])> {
        let (commit, _, digest) = self.stage_image_commit(root, filter).await?;
        Ok((commit, digest))
    }

    /// Stages the image commit of `root` as
    /// [`write_composefs_commit`](Transaction::write_composefs_commit) does,
    /// and returns the checksum of the image commit, the checksum of the file
    /// object of `root.cfs`, and the fs-verity digest of the image.
    async fn stage_image_commit(
        &self,
        root: &RepoTree,
        filter: Option<ComposefsEntryFn<'_>>,
    ) -> Result<(Checksum, Checksum, [u8; 32])> {
        let meta = FileMeta::regular(0, 0, IMAGE_PERM);
        let (image, digest) = self
            .write_composefs_content(root, &ComposefsOptions::RECORDED, filter, &meta)
            .await?;
        let root_dirmeta = self
            .write_dirmeta(&DirMeta {
                uid: 0,
                gid: 0,
                mode: ROOT_DIR_MODE,
                xattrs: Xattrs::empty(),
            })
            .await?;
        let tree = DirTree {
            files: vec![(IMAGE_FILE.to_owned(), image)],
            dirs: Vec::new(),
        };
        let root_dirtree = self
            .write_metadata(ObjectType::DirTree, None, &tree.serialize()?)
            .await?;
        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,
        };
        let checksum = self
            .write_metadata(ObjectType::Commit, None, &commit.serialize()?)
            .await?;
        Ok((checksum, image, digest))
    }
}

/// Methods that find and open the composefs image of a commit.
impl Repo {
    /// Opens the composefs image of the image commit that `commit` names.
    ///
    /// The call returns `None` if `commit` names no image commit.
    ///
    /// # Lookup
    ///
    /// The call reads the commit object and finds the image commit in this
    /// order:
    ///
    /// 1. The attachment [`COMPOSEFS_RELATION`] of field 2. If the commit has
    ///    it, the call does not read the detached metadata.
    /// 2. Else the supplement [`COMPOSEFS_RELATION`] of the key
    ///    `ostrya.related` of the detached metadata.
    ///
    /// The call checks each entry of field 2, and each entry of
    /// `ostrya.related` if it reads that key. A
    /// defective entry fails the call, also if its name is not
    /// [`COMPOSEFS_RELATION`]. Two entries of the name in one field fail the
    /// call. If the image commit of the selected entry has a defect, the call
    /// fails and does not try the other field.
    ///
    /// The call does not check the state of `commit`. A partial commit gives
    /// its image as a complete commit does.
    ///
    /// # Checks
    ///
    /// The call checks the image commit in this order:
    ///
    /// 1. For a supplement, `commit` carries the key
    ///    `ostree.composefs.digest.v0`. The call reads no part of the image
    ///    commit before this check.
    /// 2. The repository holds the image commit.
    /// 3. The repository does not mark the image commit partial.
    /// 4. The root directory holds the entry `root.cfs`.
    /// 5. The entry `root.cfs` is not a directory.
    /// 6. The root directory holds no other entry.
    /// 7. The file object of `root.cfs` is not a symlink.
    /// 8. If the repository sets `[ex-integrity] fsverity=yes`, the file
    ///    object of `root.cfs` is sealed with fs-verity with SHA-256,
    ///    4096-byte blocks, no salt, and its full size. This applies to an
    ///    attachment and to a supplement.
    /// 9. For a supplement, the fs-verity digest of `/root.cfs` is the value
    ///    of the key.
    ///
    /// The call does not check the owners, the modes, or the xattrs of the
    /// image commit.
    ///
    /// For an attachment, the call does not read the key and does not
    /// compare it with the image. The checksum chain from `commit` to the
    /// image commit, its tree, and `/root.cfs` binds the image to `commit`,
    /// and the repository checked each object when it wrote it. A labeled
    /// image, which an entry hook changed, can therefore be an attachment.
    ///
    /// The key records the digest of the image that a build of the tree of
    /// `commit` with no hook gives. For a supplement, the call compares that
    /// key with the image. It builds no image to check the key. If the file
    /// object has the seal of step 8, the call reads the digest from the
    /// kernel. Otherwise it streams the file through the fs-verity hasher in
    /// chunks of 128 KiB, one time. The call measures the digest through the
    /// descriptor that it returns. A process that can write the unsealed file
    /// can change it after the call returns, so the check holds only for the
    /// bytes that the call read.
    ///
    /// The checks guard against damage and against a writer of the
    /// repository other than the caller. They do not guard against the
    /// caller, who can write the commit and the image commit.
    ///
    /// # Errors
    ///
    /// - [`Error::Unsupported`] if the repository is in `archive` mode. The
    ///   call refuses this mode before it reads a file.
    /// - [`Error::ObjectNotFound`] if the repository does not hold the commit
    ///   object of `commit`.
    /// - [`Error::Core`] if the commit tuple does not frame, if field 2 does
    ///   not decode, if the detached metadata does not parse, or if a commit
    ///   object or the root dirtree of the image commit does not parse.
    /// - [`Error::InvalidRelations`] with `commit` and the field, if an entry
    ///   of field 2 or of `ostrya.related` has an empty name or a checksum
    ///   that is not 32 bytes, if the value of `ostrya.related` is not a
    ///   variant of type `a(say)`, or if two entries of one field have the
    ///   name [`COMPOSEFS_RELATION`].
    /// - [`Error::InvalidFormat`] if `commit` names a supplement and the
    ///   first entry of `ostree.composefs.digest.v0` is not a variant of type
    ///   `ay` with 32 bytes.
    /// - The errors of [`RepoConfig::fsverity`](crate::RepoConfig::fsverity),
    ///   if `commit` names an image commit. If `commit` names no image commit,
    ///   the call does not read `[ex-integrity] fsverity`.
    /// - [`Error::InvalidComposefsImage`] with `commit`, the source, the
    ///   image commit, and the [`ComposefsImageDefect`], if a check fails.
    /// - [`Error::ObjectNotFound`] if the repository holds the image commit
    ///   complete and does not hold its root dirtree or the file object of
    ///   `root.cfs`.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, if a symlink is on its path, or if the file object does not
    ///   have the form of the repository mode. [`Repo::load_file`] lists the
    ///   cases.
    /// - [`Error::Io`] if a read of the image or another file system
    ///   operation fails.
    pub async fn open_composefs_image(&self, commit: &Checksum) -> Result<Option<ComposefsImage>> {
        if self.mode().is_archive() {
            return Err(archive_refusal());
        }
        let repo = self.clone();
        let key = *commit;
        ostrya_rt::unblock(move || {
            let Some(named) = repo.named_image_blocking(&key)? else {
                return Ok(None);
            };
            let require_seal = repo.requires_sealed_image()?;
            let (file, size) = repo.check_raw_image_blocking(
                &key,
                named.source,
                &named.image,
                named.key,
                require_seal,
            )?;
            Ok(Some(ComposefsImage {
                file,
                size,
                source: named.source,
                commit: named.image,
            }))
        })
        .await
    }

    /// Writes the composefs image commit of `commit` and names it as the
    /// supplement [`COMPOSEFS_RELATION`] of `commit`, if the commit has no
    /// valid image commit.
    ///
    /// The call begins a transaction before it reads the commit, so a prune
    /// cannot remove the commit or its objects during the build. It then
    /// makes these steps in this order:
    ///
    /// 1. If field 2 of the commit has the attachment
    ///    [`COMPOSEFS_RELATION`], the call refuses the commit. It does not
    ///    check the attachment.
    /// 2. If the commit carries no key `ostree.composefs.digest.v0`, the call
    ///    refuses the commit. [`open_composefs_image`](Repo::open_composefs_image)
    ///    refuses a supplement of such a commit.
    ///    [`Repo::commit_add_composefs_metadata`] stages a commit that carries
    ///    the key.
    /// 3. If the commit has the supplement [`COMPOSEFS_RELATION`], the call
    ///    checks its image commit with the checks of
    ///    [`open_composefs_image`](Repo::open_composefs_image). If the image
    ///    commit passes, the call writes nothing and gives
    ///    [`ComposefsSupplementAdd::Valid`]. If a check fails with
    ///    [`Error::InvalidComposefsImage`], the call writes the entry again in
    ///    step 7. Thus the call replaces an entry that names another image
    ///    commit, an image commit that the repository does not hold or holds
    ///    partial, or an image commit whose tree has a defect. For the defect
    ///    [`ComposefsImageDefect::NotSealed`], the call first streams the file
    ///    through the fs-verity hasher. If the digest is the value of the key,
    ///    the build gives the same object, so the call refuses the commit with
    ///    this defect.
    /// 4. The call builds the image of the tree of the commit with
    ///    [`ComposefsOptions::RECORDED`] and stages the image commit with
    ///    [`Transaction::write_composefs_commit`].
    /// 5. If the fs-verity digest of the image is not the value of the key,
    ///    the call refuses the commit with [`Error::ComposefsDigestMismatch`].
    ///    The call builds the image with no hook, so it refuses a commit whose
    ///    key records the digest of an image that a hook changed.
    /// 6. If the repository sets `[ex-integrity] fsverity=yes`, the file
    ///    object of `/root.cfs` of the built image commit must have the seal
    ///    of [`open_composefs_image`](Repo::open_composefs_image). If it has
    ///    no seal, the call refuses the commit with
    ///    [`Error::InvalidComposefsImage`] and
    ///    [`ComposefsImageDefect::NotSealed`].
    /// 7. The call sets the supplement [`COMPOSEFS_RELATION`] of the commit
    ///    to the image commit, as [`Transaction::add_supplement`] does, and
    ///    commits the transaction.
    /// 8. If the repository marked the image commit partial before the call,
    ///    the call removes the partial marker. After the commit of the
    ///    transaction, the repository holds each object of the image commit.
    ///
    /// The transaction does not write an object that the repository already
    /// holds. If the entry names the image commit that the build gives, and
    /// the file object of its `/root.cfs` is changed on disk, the check of
    /// step 3 fails and the build gives the same image commit. The call then
    /// gives [`ComposefsSupplementAdd::Written`] with this image commit as
    /// `replaced`, and the changed object stays. A changed object is a defect
    /// that [`Repo::fsck`] reports. With `[ex-integrity] fsverity=yes`, step 6
    /// refuses such an object if it has no seal.
    ///
    /// An object that the repository wrote before it set `fsverity=yes` can
    /// have no seal. The transaction does not write such an object again, so
    /// the build does not seal it. With `fsverity=yes`, step 3 or step 6
    /// refuses it, and the call writes nothing.
    ///
    /// The checks of step 3 work in each repository mode. In `archive` mode,
    /// the call inflates the image and streams it through the fs-verity
    /// hasher. Steps 3 and 6 apply no seal rule in `archive` mode. The call
    /// writes the image commit in each mode. In `archive` mode, the image
    /// file is a `.filez` object, and
    /// [`open_composefs_image`](Repo::open_composefs_image) refuses the
    /// repository.
    ///
    /// The call does not check the state of `commit`. If an object of its
    /// tree is absent, the build fails.
    ///
    /// On a refusal or an error before the commit of the transaction, the
    /// call writes nothing.
    ///
    /// # Errors
    ///
    /// - The errors of [`Repo::transaction`].
    /// - The errors of [`RepoConfig::fsverity`](crate::RepoConfig::fsverity).
    /// - The errors of [`Repo::load_object_bytes`] for the commit object.
    /// - [`Error::Core`] if the commit object does not parse.
    /// - [`Error::InvalidFormat`] if the first entry of
    ///   `ostree.composefs.digest.v0` is not a variant of type `ay` with 32
    ///   bytes.
    /// - [`Error::InvalidRelations`] with `commit` and the field, if an entry
    ///   of field 2 or of `ostrya.related` is defective, or if two entries of
    ///   one field have the name [`COMPOSEFS_RELATION`].
    /// - [`Error::InvalidInput`] if field 2 of the commit has the attachment
    ///   [`COMPOSEFS_RELATION`], or if the commit carries no key
    ///   `ostree.composefs.digest.v0`.
    /// - [`Error::InvalidComposefsImage`] with
    ///   [`ComposefsImageDefect::NotSealed`] if the check of step 3 finds a
    ///   `/root.cfs` with no seal whose digest is the value of the key, under
    ///   `[ex-integrity] fsverity=yes`.
    /// - The errors of the checks of step 3 other than
    ///   [`Error::InvalidComposefsImage`], as
    ///   [`open_composefs_image`](Repo::open_composefs_image) lists them.
    /// - The errors of [`Transaction::write_composefs_commit`]. The build
    ///   fails with [`Error::ObjectNotFound`] if an object of the tree is
    ///   absent.
    /// - [`Error::ComposefsDigestMismatch`] if the digest of the image is not
    ///   the value of the key.
    /// - [`Error::InvalidComposefsImage`] with
    ///   [`ComposefsImageDefect::NotSealed`] if the check of step 6 finds a
    ///   `/root.cfs` with no seal.
    /// - The errors of [`Repo::load_file`] for the file object of `/root.cfs`
    ///   in step 6.
    /// - The errors of [`Transaction::commit`].
    /// - The error of the removal of the partial marker.
    pub async fn add_composefs_supplement(
        &self,
        commit: &Checksum,
    ) -> Result<ComposefsSupplementAdd> {
        let txn = self.transaction().await?;
        let (result, was_partial) = match self.stage_composefs_supplement(&txn, commit).await {
            Ok(staged) => staged,
            Err(e) => {
                txn.abort().await?;
                return Err(e);
            }
        };
        let ComposefsSupplementAdd::Written { image, .. } = result else {
            txn.abort().await?;
            return Ok(result);
        };
        let fsync = txn.fsync_flags().0;
        txn.commit().await?;
        if was_partial {
            let failed = self.remove_partial_markers(vec![image], fsync).await?;
            if let Some((_, e)) = failed.into_iter().next() {
                return Err(e);
            }
        }
        Ok(result)
    }

    /// Runs the steps of
    /// [`add_composefs_supplement`](Repo::add_composefs_supplement) up to the
    /// commit of `txn`.
    ///
    /// For [`ComposefsSupplementAdd::Written`], the call stages the image
    /// commit and queues the supplement in `txn`. The second value is `true`
    /// if the repository marked the image commit partial before the call.
    /// For [`ComposefsSupplementAdd::Valid`], the call stages nothing.
    async fn stage_composefs_supplement(
        &self,
        txn: &Transaction,
        commit: &Checksum,
    ) -> Result<(ComposefsSupplementAdd, bool)> {
        let repo = self.clone();
        let read_commit = *commit;
        let read = ostrya_rt::unblock(move || repo.supplement_state_blocking(&read_commit)).await?;
        let replaced = match read.state {
            SupplementState::Valid(image) => {
                return Ok((ComposefsSupplementAdd::Valid { image }, false));
            }
            SupplementState::Build { replaced } => replaced,
        };
        let root = RepoTree::from_parts(self.clone(), read.root_dirtree, read.root_dirmeta);
        let (image, file, digest) = txn.stage_image_commit(&root, None).await?;
        if read.key != digest {
            return Err(Error::ComposefsDigestMismatch {
                commit: *commit,
                expected: read.key,
                actual: digest,
            });
        }
        if read.require_seal && !self.mode().is_archive() {
            let object = txn.load_file_staged_first_with(&file, true).await?;
            if object.kernel_fs_verity().is_none() {
                return Err(invalid_image(
                    commit,
                    ComposefsImageSource::Supplement,
                    &image,
                    ComposefsImageDefect::NotSealed,
                ));
            }
        }
        let was_partial = self.commit_state(&image).await? == CommitState::Partial;
        txn.add_supplement(commit, COMPOSEFS_RELATION, &image)?;
        Ok((
            ComposefsSupplementAdd::Written { image, replaced },
            was_partial,
        ))
    }

    /// Reads the commit object of `commit` one time and gives the parts of it
    /// that [`add_composefs_supplement`](Repo::add_composefs_supplement) uses:
    /// the root of its tree, the value of the key
    /// `ostree.composefs.digest.v0`, and the state of its supplement
    /// [`COMPOSEFS_RELATION`].
    ///
    /// The call checks the attachments of the parsed commit and refuses a
    /// commit whose field 2 has the attachment [`COMPOSEFS_RELATION`]. It
    /// then refuses a commit that carries no key. Only then does it read the
    /// detached metadata. If the commit has the supplement, the call checks
    /// its image commit with
    /// [`check_composefs_commit_blocking`](Repo::check_composefs_commit_blocking).
    /// A defect gives [`SupplementState::Build`]. For
    /// [`ComposefsImageDefect::NotSealed`], the call checks the image again
    /// with no seal rule, which hashes the file. If the digest is the value
    /// of the key, the call gives the `NotSealed` error. The reads block the
    /// thread, so an async caller runs this call on the blocking pool.
    fn supplement_state_blocking(&self, commit: &Checksum) -> Result<SupplementRead> {
        let require_seal = self.requires_sealed_image()?;
        let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
        let parsed = Commit::parse(&bytes)?;
        let key = recorded_digest(&parsed)?;
        if let Some(image) = attached_image(commit, related::entries_of(&parsed.related))? {
            return Err(Error::InvalidInput(format!(
                "commit {commit} names its composefs image commit {image} as an \
                 attachment; a supplement is not written"
            )));
        }
        let Some(key) = key else {
            return Err(Error::InvalidInput(format!(
                "commit {commit} carries no {COMPOSEFS_DIGEST_KEY}; a supplement is not \
                 written (Repo::commit_add_composefs_metadata stages a commit that carries \
                 the key)"
            )));
        };
        let read = |state| SupplementRead {
            root_dirtree: parsed.root_dirtree,
            root_dirmeta: parsed.root_dirmeta,
            key,
            require_seal,
            state,
        };
        let Some(image) = self.supplemented_image_blocking(commit)? else {
            return Ok(read(SupplementState::Build { replaced: None }));
        };
        let source = ComposefsImageSource::Supplement;
        let check =
            |seal| self.check_composefs_commit_blocking(commit, source, &image, Some(key), seal);
        let replace = || {
            read(SupplementState::Build {
                replaced: Some(image),
            })
        };
        match check(require_seal) {
            Ok(_) => Ok(read(SupplementState::Valid(image))),
            // The hash of the file tells a wrong image, which the build
            // replaces, from the image of the key, which the build gives again
            // with the same object.
            Err(e) if is_not_sealed(&e) => match check(false) {
                Ok(_) => Err(e),
                Err(Error::InvalidComposefsImage { .. }) => Ok(replace()),
                Err(other) => Err(other),
            },
            Err(Error::InvalidComposefsImage { .. }) => Ok(replace()),
            Err(e) => Err(e),
        }
    }

    /// Reads the commit `commit` and returns the image commit that it names,
    /// as [`open_composefs_image`](Repo::open_composefs_image) selects it,
    /// with the value of the key `ostree.composefs.digest.v0` of `commit`.
    ///
    /// The call parses the key only if `commit` names a supplement. For an
    /// attachment, the key of the result is `None`. The reads and the parse
    /// block the thread, so an async caller runs this call on the blocking
    /// pool.
    fn named_image_blocking(&self, commit: &Checksum) -> Result<Option<NamedImage>> {
        let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
        let Some((source, image)) = self.named_entry_blocking(commit, &bytes)? else {
            return Ok(None);
        };
        let key = match source {
            ComposefsImageSource::Attachment => None,
            ComposefsImageSource::Supplement => recorded_digest(&Commit::parse(&bytes)?)?,
        };
        Ok(Some(NamedImage { source, image, key }))
    }

    /// Returns the field and the checksum of the image commit that the commit
    /// `commit` names, as
    /// [`open_composefs_image`](Repo::open_composefs_image) selects it.
    /// `bytes` are the bytes of the commit object of `commit`.
    ///
    /// The call reads the detached metadata only if field 2 has no entry
    /// [`COMPOSEFS_RELATION`]. The read blocks the thread, so an async caller
    /// runs this call on the blocking pool.
    fn named_entry_blocking(
        &self,
        commit: &Checksum,
        bytes: &[u8],
    ) -> Result<Option<(ComposefsImageSource, Checksum)>> {
        if let Some(image) = attached_image(commit, related::parse_attachments(bytes)?)? {
            return Ok(Some((ComposefsImageSource::Attachment, image)));
        }
        Ok(self
            .supplemented_image_blocking(commit)?
            .map(|image| (ComposefsImageSource::Supplement, image)))
    }

    /// Returns the checksum of the image commit that the supplement
    /// [`COMPOSEFS_RELATION`] of `commit` names, or `None` if `commit` has no
    /// such supplement.
    ///
    /// The call reads the detached metadata of `commit` and checks each entry
    /// of `ostrya.related`. The read blocks the thread, so an async caller
    /// runs this call on the blocking pool.
    fn supplemented_image_blocking(&self, commit: &Checksum) -> Result<Option<Checksum>> {
        let detached = self.read_supplement_dict_blocking(commit)?;
        let supplements = related::supplements(detached.as_ref())
            .map_err(|reason| Error::InvalidRelations {
                commit: Some(*commit),
                field: RelationField::Supplements,
                reason,
            })?
            .map(|entries| {
                related::checked_entries(RelationField::Supplements, Some(*commit), entries)
            })
            .transpose()?
            .unwrap_or_default();
        composefs_entry(commit, RelationField::Supplements, &supplements)
    }

    /// Checks the image commit `image`, which `commit` names in the field
    /// `relation`, by the checks of
    /// [`open_composefs_image`](Repo::open_composefs_image). `key` is the
    /// value of the key `ostree.composefs.digest.v0` of `commit`, or `None`
    /// if `commit` carries no key. The call uses `key` for a supplement
    /// alone. `require_seal` is the seal rule of `[ex-integrity]
    /// fsverity=yes`.
    ///
    /// The call works in each repository mode. In a mode other than
    /// `archive`, it returns the file object of `root.cfs`, open read-only at
    /// offset 0, and its size. In `archive` mode, it returns `None` and
    /// applies no seal rule. For a supplement, it first streams the inflated
    /// payload through the fs-verity hasher in chunks of 128 KiB. For an
    /// attachment, it reads no byte of the payload. The reads block the
    /// thread, so an async caller runs this call on the blocking pool.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidComposefsImage`] with `commit`, `relation`, `image`,
    /// and the defect, and the errors of the reads that
    /// [`open_composefs_image`](Repo::open_composefs_image) lists.
    fn check_composefs_commit_blocking(
        &self,
        commit: &Checksum,
        relation: ComposefsImageSource,
        image: &Checksum,
        key: Option<[u8; 32]>,
        require_seal: bool,
    ) -> Result<Option<(std::fs::File, u64)>> {
        if !self.mode().is_archive() {
            return self
                .check_raw_image_blocking(commit, relation, image, key, require_seal)
                .map(Some);
        }
        let expected = expected_digest(commit, relation, image, key)?;
        let (object, payload) = self.image_file_blocking(commit, relation, image, false)?;
        let Some(expected) = expected else {
            return Ok(None);
        };
        let Some((file, len)) = payload else {
            return Err(no_payload(&object));
        };
        let actual = inflated_digest_blocking(file, len)?;
        check_digest(&expected, &actual)
            .map_err(|defect| invalid_image(commit, relation, image, defect))?;
        Ok(None)
    }

    /// Checks the image commit `image` as
    /// [`check_composefs_commit_blocking`](Repo::check_composefs_commit_blocking) does in a mode
    /// other than `archive`, and returns the file object of `root.cfs`, open
    /// read-only at offset 0, and its size.
    ///
    /// If `require_seal` is set, the file object must have the fs-verity
    /// seal that the kernel gives the digest of. For a supplement, the digest
    /// of the file comes from the kernel when the load of the object gives
    /// one. Else the call streams the file through the fs-verity hasher in
    /// chunks of 128 KiB and seeks back to offset 0. The reads block the
    /// thread, so an async caller runs this call on the blocking pool.
    fn check_raw_image_blocking(
        &self,
        commit: &Checksum,
        relation: ComposefsImageSource,
        image: &Checksum,
        key: Option<[u8; 32]>,
        require_seal: bool,
    ) -> Result<(std::fs::File, u64)> {
        use std::io::{Seek, SeekFrom};

        let expected = expected_digest(commit, relation, image, key)?;
        let measure = require_seal || expected.is_some();
        let (object, payload) = self.image_file_blocking(commit, relation, image, measure)?;
        let Some((mut file, size)) = payload else {
            return Err(no_payload(&object));
        };
        if require_seal && object.kernel_fs_verity().is_none() {
            return Err(invalid_image(
                commit,
                relation,
                image,
                ComposefsImageDefect::NotSealed,
            ));
        }
        let Some(expected) = expected else {
            return Ok((file, size));
        };
        let actual = match object.kernel_fs_verity() {
            Some(digest) => digest,
            None => {
                let digest = image_file_digest(&mut file)?;
                file.seek(SeekFrom::Start(0))?;
                digest
            }
        };
        check_digest(&expected, &actual)
            .map_err(|defect| invalid_image(commit, relation, image, defect))?;
        Ok((file, size))
    }

    /// Returns `true` if the repository sets `[ex-integrity] fsverity=yes`.
    /// The lookup then requires a sealed `/root.cfs`.
    ///
    /// # Errors
    ///
    /// The errors of [`RepoConfig::fsverity`](crate::RepoConfig::fsverity).
    fn requires_sealed_image(&self) -> Result<bool> {
        Ok(self.config().fsverity()? == Tristate::Yes)
    }

    /// Runs the checks of the image commit `image` up to the type of the file
    /// object of `root.cfs`, and returns that object with its object file,
    /// open at the start of its payload.
    ///
    /// If `measure` is set, the load of the object also reads the fs-verity
    /// digest that the kernel holds for it. The reads block the thread, so an
    /// async caller runs this call on the blocking pool.
    fn image_file_blocking(
        &self,
        commit: &Checksum,
        relation: ComposefsImageSource,
        image: &Checksum,
        measure: bool,
    ) -> Result<(FileObject, Option<Payload>)> {
        let invalid = |defect| invalid_image(commit, relation, image, defect);
        let Some(bytes) = self.held_object_bytes_blocking(ObjectType::Commit, image)? else {
            return Err(invalid(ComposefsImageDefect::Absent));
        };
        if self.commit_state_blocking(image)? == CommitState::Partial {
            return Err(invalid(ComposefsImageDefect::Partial));
        }
        let root = Commit::parse(&bytes)?.root_dirtree;
        let tree = DirTree::parse(&self.load_object_bytes_blocking(ObjectType::DirTree, &root)?)?;
        let file = image_entry(&tree).map_err(invalid)?;
        let (object, payload) = self.open_file_blocking(&file, measure)?;
        if !matches!(object.kind, FileKind::Regular { .. }) {
            return Err(invalid(ComposefsImageDefect::NotRegular));
        }
        Ok((object, payload))
    }
}

/// The parts of a commit that [`Repo::add_composefs_supplement`] uses, from
/// [`Repo::supplement_state_blocking`].
struct SupplementRead {
    /// The checksum of the root dirtree of the commit.
    root_dirtree: Checksum,
    /// The checksum of the root dirmeta of the commit.
    root_dirmeta: Checksum,
    /// The value of the key `ostree.composefs.digest.v0` of the commit.
    key: [u8; 32],
    /// `true` if the repository sets `[ex-integrity] fsverity=yes`.
    require_seal: bool,
    /// The state of the supplement [`COMPOSEFS_RELATION`] of the commit.
    state: SupplementState,
}

/// The state of the supplement [`COMPOSEFS_RELATION`] of a commit, from
/// [`Repo::supplement_state_blocking`].
enum SupplementState {
    /// The supplement names this image commit, and the image commit passes
    /// the checks.
    Valid(Checksum),
    /// The call builds the image commit. `replaced` is the image commit that
    /// the supplement names and that fails a check, or `None` if the commit
    /// has no supplement.
    Build { replaced: Option<Checksum> },
}

/// The image commit that a commit names, from
/// [`Repo::named_image_blocking`].
struct NamedImage {
    /// The field of the commit that names the image commit.
    source: ComposefsImageSource,
    /// The checksum of the image commit.
    image: Checksum,
    /// The value of the key `ostree.composefs.digest.v0` of the commit for a
    /// supplement, or `None` if the commit does not carry the key or names
    /// an attachment.
    key: Option<[u8; 32]>,
}

/// Returns the error of the defect `defect` of the image commit `image`,
/// which `commit` names in the field `relation`.
fn invalid_image(
    commit: &Checksum,
    relation: ComposefsImageSource,
    image: &Checksum,
    defect: ComposefsImageDefect,
) -> Error {
    Error::InvalidComposefsImage {
        commit: *commit,
        relation,
        image: *image,
        defect: Box::new(defect),
    }
}

/// Returns the error of the file object `object` of `/root.cfs` that the load
/// gives with no payload.
fn no_payload(object: &FileObject) -> Error {
    Error::InvalidFormat(format!(
        "the file object {} of /{IMAGE_FILE} has no payload",
        object.checksum()
    ))
}

/// Returns the error of a lookup of the composefs image in an `archive`
/// repository.
fn archive_refusal() -> Error {
    Error::Unsupported(
        "the lookup of a composefs image refuses an archive repository: it stores \
         /root.cfs compressed, and a mount needs the raw image"
            .into(),
    )
}

/// Returns the checksum of the image commit that the attachment
/// [`COMPOSEFS_RELATION`] of `commit` names, or `None` if `commit` has no
/// such attachment. `entries` are the entries of field 2 of `commit`.
///
/// # Errors
///
/// [`Error::InvalidRelations`] with `commit` and
/// [`RelationField::Attachments`] if an entry is defective, or if two or more
/// entries have the name.
fn attached_image(
    commit: &Checksum,
    entries: Vec<related::RelatedEntry>,
) -> Result<Option<Checksum>> {
    let attachments = related::checked_entries(RelationField::Attachments, Some(*commit), entries)?;
    composefs_entry(commit, RelationField::Attachments, &attachments)
}

/// Returns `true` if `error` is the refusal of an image commit whose
/// `/root.cfs` has no fs-verity seal.
fn is_not_sealed(error: &Error) -> bool {
    matches!(
        error,
        Error::InvalidComposefsImage { defect, .. } if **defect == ComposefsImageDefect::NotSealed
    )
}

/// Returns the checksum of the entry [`COMPOSEFS_RELATION`] of `entries`, the
/// checked entries of the field `field` of `commit`, or `None` if no entry
/// has the name.
///
/// # Errors
///
/// [`Error::InvalidRelations`] with `commit` and `field` if two or more
/// entries have the name.
fn composefs_entry(
    commit: &Checksum,
    field: RelationField,
    entries: &[(String, Checksum)],
) -> Result<Option<Checksum>> {
    let mut named = entries
        .iter()
        .filter(|(name, _)| name == COMPOSEFS_RELATION);
    let first = named.next().map(|(_, checksum)| *checksum);
    if named.next().is_some() {
        return Err(Error::InvalidRelations {
            commit: Some(*commit),
            field,
            reason: format!("two or more entries have the name {COMPOSEFS_RELATION}"),
        });
    }
    Ok(first)
}

/// Returns the checksum of the file object of `root.cfs` in `tree`, the root
/// dirtree of an image commit, or the structural defect of the tree.
///
/// A tree with no entry `root.cfs` gives [`ComposefsImageDefect::NoImageFile`],
/// a directory `root.cfs` gives [`ComposefsImageDefect::NotRegular`], and
/// each other entry gives [`ComposefsImageDefect::ExtraEntry`], in this order.
fn image_entry(tree: &DirTree) -> std::result::Result<Checksum, ComposefsImageDefect> {
    let file = tree
        .files
        .iter()
        .find(|(name, _)| name == IMAGE_FILE)
        .map(|(_, checksum)| *checksum);
    let dir = tree.dirs.iter().any(|(name, _, _)| name == IMAGE_FILE);
    if file.is_none() && !dir {
        return Err(ComposefsImageDefect::NoImageFile);
    }
    if dir {
        return Err(ComposefsImageDefect::NotRegular);
    }
    let extra = tree
        .files
        .iter()
        .map(|(name, _)| name)
        .chain(tree.dirs.iter().map(|(name, _, _)| name))
        .find(|name| *name != IMAGE_FILE);
    if let Some(name) = extra {
        return Err(ComposefsImageDefect::ExtraEntry(name.clone()));
    }
    Ok(file.expect("the tree holds the file root.cfs"))
}

/// Returns the digest that the lookup compares with the digest of
/// `/root.cfs` of the image commit `image`, which `commit` names in the field
/// `relation`. `key` is the value of the key `ostree.composefs.digest.v0` of
/// `commit`.
///
/// An attachment gives `None`: the lookup does not compare the key with an
/// attachment. A supplement gives the key.
///
/// # Errors
///
/// [`Error::InvalidComposefsImage`] with [`ComposefsImageDefect::NoKey`] for
/// a supplement and no key.
fn expected_digest(
    commit: &Checksum,
    relation: ComposefsImageSource,
    image: &Checksum,
    key: Option<[u8; 32]>,
) -> Result<Option<[u8; 32]>> {
    match relation {
        ComposefsImageSource::Attachment => Ok(None),
        ComposefsImageSource::Supplement => key
            .map(Some)
            .ok_or_else(|| invalid_image(commit, relation, image, ComposefsImageDefect::NoKey)),
    }
}

/// Refuses `actual`, the fs-verity digest of `/root.cfs`, with
/// [`ComposefsImageDefect::DigestMismatch`] if it is not `expected`.
fn check_digest(
    expected: &[u8; 32],
    actual: &[u8; 32],
) -> std::result::Result<(), ComposefsImageDefect> {
    if actual == expected {
        return Ok(());
    }
    Err(ComposefsImageDefect::DigestMismatch {
        expected: *expected,
        actual: *actual,
    })
}

/// Returns the fs-verity digest of the inflated payload of an `archive`
/// object. `file` is open at the start of the raw-DEFLATE stream, and `len`
/// is the number of bytes from there to the end of the file.
///
/// The call reads the stream in bounded chunks and hashes the inflated bytes
/// in chunks of 128 KiB. The reads block the thread, so an async caller runs
/// this call on the blocking pool.
fn inflated_digest_blocking(file: std::fs::File, len: u64) -> Result<[u8; 32]> {
    use futures_lite::AsyncReadExt;

    let source = BufSource::with_len_hint(futures_lite::io::AssertAsync::new(file), len);
    let mut decoder = DeflateDecoder::new(source);
    let mut hasher = ostrya_composefs::FsVerityHasher::new();
    let mut buf = vec![0u8; DIGEST_CHUNK];
    // The reader over a blocking file never returns `Pending`, so `block_on`
    // drives it on this thread with no executor.
    futures_lite::future::block_on(async {
        loop {
            let n = decoder.read(&mut buf).await.map_err(Error::Io)?;
            if n == 0 {
                return Ok::<(), Error>(());
            }
            hasher.update(&buf[..n]);
        }
    })?;
    Ok(hasher.finalize())
}

/// Compile-time checks that [`ComposefsImage`] is `Send + Sync` and that the
/// futures of the calls of this module are `Send`.
const _: fn() = || {
    fn assert_send_sync<T: Send + Sync>() {}
    fn assert_send<T: Send>(_: &T) {}
    assert_send_sync::<ComposefsImage>();
    assert_send_sync::<ComposefsImageDefect>();
    let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.open_composefs_image(commit));
    let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.add_composefs_supplement(commit));
    let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>| {
        assert_send(&txn.write_composefs_commit(root, Some(filter)));
    };
    let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>, meta: &FileMeta| {
        assert_send(&txn.write_composefs_content(
            root,
            &ComposefsOptions::RECORDED,
            Some(filter),
            meta,
        ));
    };
};

#[cfg(test)]
mod tests {
    use ostrya_core::{Checksum, DirMeta, DirTree, ObjectType, RepoMode, Xattrs};
    use ostrya_rt::block_on;

    use super::{ComposefsImageDefect, ComposefsImageSource, ROOT_DIR_MODE};
    use crate::tree::RepoTree;
    use crate::{CreateOptions, Error, FileMeta, Repo};

    /// In an `archive` repository, the check of a supplement hashes the
    /// inflated payload of `root.cfs`, refuses a key that is not its digest
    /// and a commit with no key, and gives no descriptor.
    #[test]
    fn the_check_hashes_the_inflated_image_in_archive_mode() {
        let path = std::env::temp_dir().join(format!(
            "ostrya-image-commit-archive-{}-{}",
            std::process::id(),
            crate::write::unique()
        ));
        let _ = std::fs::remove_dir_all(&path);
        block_on(async {
            let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
                .await
                .unwrap();
            let txn = repo.transaction().await.unwrap();
            let file = txn
                .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"payload\n")
                .await
                .unwrap();
            let dirmeta = txn
                .write_dirmeta(&DirMeta {
                    uid: 0,
                    gid: 0,
                    mode: ROOT_DIR_MODE,
                    xattrs: Xattrs::empty(),
                })
                .await
                .unwrap();
            let tree = DirTree {
                files: vec![("a".to_owned(), file)],
                dirs: Vec::new(),
            };
            let dirtree = txn
                .write_metadata(ObjectType::DirTree, None, &tree.serialize().unwrap())
                .await
                .unwrap();
            let root = RepoTree::from_parts(repo.clone(), dirtree, dirmeta);
            let (image, digest) = txn.write_composefs_commit(&root, None).await.unwrap();
            txn.commit().await.unwrap();

            let commit = Checksum::from_bytes([1; 32]);
            let source = ComposefsImageSource::Supplement;
            let checked = repo
                .check_composefs_commit_blocking(&commit, source, &image, Some(digest), false)
                .unwrap();
            assert!(checked.is_none());
            let wrong = [0x11; 32];
            let refusals = [
                (
                    Some(wrong),
                    ComposefsImageDefect::DigestMismatch {
                        expected: wrong,
                        actual: digest,
                    },
                ),
                (None, ComposefsImageDefect::NoKey),
            ];
            for (key, expected) in refusals {
                match repo
                    .check_composefs_commit_blocking(&commit, source, &image, key, false)
                    .unwrap_err()
                {
                    Error::InvalidComposefsImage { defect, .. } => assert_eq!(*defect, expected),
                    other => panic!("expected InvalidComposefsImage, got {other:?}"),
                }
            }
        });
        let _ = std::fs::remove_dir_all(&path);
    }
}