ostrya 0.19.1

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
//! Export of a commit as a composefs EROFS image.
//!
//! - [`Repo::export_composefs`] builds the image in memory and returns its
//!   bytes and its fs-verity digest.
//! - [`Repo::export_composefs_to`] writes the image through a file
//!   descriptor.
//! - [`Repo::commit_add_composefs_metadata`] stages a new commit that records
//!   the image digest under `ostree.composefs.digest.v0`.
//! - [`Transaction::composefs_digest`] returns the image digest of a staged
//!   tree.
//! - [`Transaction::write_composefs_content`] stages the image of a staged
//!   tree as a regular content object.
//! - [`Transaction::write_composefs_commit`] stages the composefs image commit
//!   of a staged tree, and [`Repo::open_composefs_image`] opens the image of
//!   the image commit that a commit names.
//! - [`Repo::objects_dir`] gives the descriptor of the object store. A
//!   composefs mount reads the backing objects of the image through it.
//!
//! [`ComposefsOptions`] and [`VerityPolicy`] select the verity form of the
//! image. [`ComposefsEntryFn`] is the entry hook, and [`EntryKind`] is the kind
//! of a node that the hook gets. [`COMPOSEFS_DIGEST_KEY`] is the commit
//! metadata key of the image digest.
//!
//! # Entry hook
//!
//! [`Repo::export_composefs`], [`Repo::export_composefs_to`],
//! [`Transaction::write_composefs_content`], and
//! [`Transaction::write_composefs_commit`] take an entry hook as the argument
//! `filter`. The hook gets the path, the kind, and the [`Metadata`] of each
//! node. It can change the mode, the owner, the mtime, and the xattrs. For
//! example, the hook gives each inode the SELinux label of a policy of the
//! caller. The image gets the labels, and the objects of the commit do not
//! change. [`ComposefsEntryFn`] states the rules of the hook.
//!
//! [`Transaction::composefs_digest`] and
//! [`Repo::commit_add_composefs_metadata`] take no hook. The digest that they
//! give and record is the digest of the image with no hook.
//!
//! # Labeled images
//!
//! The lookup ([`Repo::open_composefs_image`]) and the mount daemon have no
//! hook, so they cannot build a labeled image from the tree. A labeled image
//! therefore goes into the repository as an image commit. To write a commit
//! with a labeled image:
//!
//! 1. Stage the tree. Call [`Transaction::write_composefs_commit`] with the
//!    hook. The call returns the checksum of the image commit and the
//!    fs-verity digest of the labeled image.
//! 2. Call [`Transaction::composefs_digest`] for the tree. The call returns
//!    the fs-verity digest of the image with no hook.
//! 3. In [`CommitOptions::attachments`], name the image commit as
//!    [`COMPOSEFS_RELATION`].
//! 4. In [`CommitOptions::metadata`], put the digest of step 2 under
//!    [`COMPOSEFS_DIGEST_KEY`] as an `ay` value, or put no key.
//! 5. Write the commit of the tree with these options and
//!    [`Transaction::write_commit`].
//! 6. Commit the transaction.
//!
//! The key records the digest of the image with no hook. The digest of a
//! labeled image never goes under the key. The image commit carries no
//! [`COMPOSEFS_DIGEST_KEY`].
//!
//! A labeled image is an attachment alone. [`Repo::open_composefs_image`]
//! does not read the key for an attachment and does not compare it with the
//! image. The checksum chain from the commit of the tree to `/root.cfs` binds
//! the image to the commit. For a supplement, the lookup compares the key
//! with the fs-verity digest of `/root.cfs`, so a labeled supplement fails
//! the lookup. [`Repo::add_composefs_supplement`] builds the image with no
//! hook.
//!
//! ```no_run
//! # async fn run(
//! #     txn: ostrya::transaction::Transaction,
//! #     root: ostrya::tree::RepoTree,
//! # ) -> ostrya::Result<()> {
//! use std::path::Path;
//!
//! use ostrya::commit::CommitOptions;
//! use ostrya::composefs::{COMPOSEFS_DIGEST_KEY, ComposefsEntryFn, EntryKind};
//! use ostrya::{COMPOSEFS_RELATION, DictBuilder, Metadata};
//!
//! fn label(
//!     path: &Path,
//!     _kind: EntryKind,
//!     meta: &mut Metadata,
//! ) -> ostrya::Result<()> {
//!     let label: &[u8] = if path.starts_with("/etc") {
//!         b"system_u:object_r:etc_t:s0\0"
//!     } else {
//!         b"system_u:object_r:usr_t:s0\0"
//!     };
//!     meta.xattrs.retain(|(name, _)| name != b"security.selinux");
//!     meta.xattrs.push((b"security.selinux".to_vec(), label.to_vec()));
//!     Ok(())
//! }
//!
//! let hook: ComposefsEntryFn<'_> = &label;
//! let (image, _labeled) = txn.write_composefs_commit(&root, Some(hook)).await?;
//! let digest = txn.composefs_digest(&root).await?;
//! let mut metadata = DictBuilder::new();
//! metadata.insert_bytes(COMPOSEFS_DIGEST_KEY, &digest);
//! let opts = CommitOptions {
//!     metadata: Some(metadata.build()),
//!     attachments: vec![(COMPOSEFS_RELATION.to_owned(), image)],
//!     ..CommitOptions::default()
//! };
//! txn.write_commit(opts, &root).await?;
//! txn.commit().await?;
//! # Ok(()) }
//! ```
//!
//! [`CommitOptions::attachments`]: crate::commit::CommitOptions::attachments
//! [`CommitOptions::metadata`]: crate::commit::CommitOptions::metadata
//! [`COMPOSEFS_RELATION`]: crate::COMPOSEFS_RELATION

use std::collections::{HashMap, btree_map};
use std::future::Future;
use std::io::{BufWriter, Seek, SeekFrom};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::path::{Path, PathBuf};
use std::pin::Pin;

use ostrya_composefs::{
    Content, Directory, Error as WriterError, FsVerityHasher, Image, Metadata, Node, Regular,
    Symlink, build_image, write_image_bounded_to, write_image_to, write_image_unhashed_to,
};
use ostrya_core::{
    Checksum, Commit, DirMeta, DirTree, ObjectType, RepoMode, Type, Value, Xattrs, loose_path,
};
use ostrya_rt::FileReader;

use crate::commit::append_dict_entry;
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::related::{self, RelationField};
use crate::repo::Repo;
use crate::repo_fs::{RepoDir, TempFile};
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::FileMeta;

/// The empty top-level directories that the `ostree` command adds to each
/// exported image.
const INJECTED_DIRS: [&str; 5] = ["boot", "etc", "sysroot", "usr", "var"];
/// The mode that the `ostree` command gives each added top-level directory
/// (`040755`).
const INJECTED_DIR_MODE: u32 = 0o040755;
/// The commit metadata key that holds the fs-verity digest of the composefs
/// image of the commit.
///
/// The value is the 32-byte digest as an `ay`.
/// The key records the digest of the image with no hook.
/// [`Repo::commit_add_composefs_metadata`] writes the key with this digest,
/// and [`Transaction::composefs_digest`] gives it. A commit with a labeled
/// image also records this digest, or carries no key. The module
/// documentation, "Labeled images", gives the steps.
pub const COMPOSEFS_DIGEST_KEY: &str = "ostree.composefs.digest.v0";
/// The GVariant type of the digest value, a 32-byte `ay`.
const DIGEST_SIGNATURE: &str = "ay";
/// The size of each chunk that the hasher reads from a backing object.
pub(crate) const DIGEST_CHUNK: usize = 128 * 1024;
/// The bytes that one xattr spends from the composefs xattr budget of an
/// inode, in addition to its name and its value.
const XATTR_ENTRY_COST: usize = 7;
/// The composefs xattr budget of one inode, in bytes.
const MAX_XATTR_TOTAL: usize = 32755;
/// The longest xattr name that the length field of an EROFS entry can state.
/// The entry stores the name without its prefix, and this suffix is not longer
/// than the full name. The check holds the full name to this bound, so the
/// prefix table stays in the writer.
const MAX_XATTR_NAME: usize = u8::MAX as usize;
/// The repository mode of the loose path that each backing redirect names. The
/// image points at the `.file` objects of a composefs backing store, whatever
/// the mode of the repository that the image comes from.
const BACKING_MODE: RepoMode = RepoMode::BareUser;

/// A boxed `Send` future for the recursive tree walk. Async recursion needs
/// this indirection.
type TreeFuture<'a> = Pin<Box<dyn Future<Output = Result<Directory>> + Send + 'a>>;

/// The place where the composefs walk reads the objects of the tree.
#[derive(Clone, Copy)]
enum ObjectSource<'a> {
    /// A published repository: each object is a loose object under `objects/`.
    Repo(&'a Repo),
    /// A transaction: an object that it staged comes from the staging
    /// directory. An object that deduplicated comes from `objects/`.
    Staged(&'a Transaction),
}

impl ObjectSource<'_> {
    async fn dirtree(&self, checksum: &Checksum) -> Result<DirTree> {
        match self {
            ObjectSource::Repo(repo) => repo.load_dirtree(checksum).await,
            ObjectSource::Staged(txn) => txn.load_dirtree_staged_first(checksum).await,
        }
    }

    async fn dirmeta(&self, checksum: &Checksum) -> Result<DirMeta> {
        match self {
            ObjectSource::Repo(repo) => repo.load_dirmeta(checksum).await,
            ObjectSource::Staged(txn) => txn.load_dirmeta_staged_first(checksum).await,
        }
    }

    /// Loads a file object. If `measure` is set, the same load also reads the
    /// fs-verity digest that the kernel holds for a sealed raw-payload object.
    async fn file(&self, checksum: &Checksum, measure: bool) -> Result<FileObject> {
        match self {
            ObjectSource::Repo(repo) => repo.load_file_with(checksum, measure).await,
            ObjectSource::Staged(txn) => txn.load_file_staged_first_with(checksum, measure).await,
        }
    }
}

/// The verity form of an exported composefs image.
///
/// The policy selects if each backed file carries the fs-verity digest of its
/// content. The export opens each backing object under both policies. The
/// size of the inode comes from the file object. The mode, the owner, and the
/// xattrs come from the file object, and the mtime is 0. An entry hook
/// ([`ComposefsEntryFn`]) can change the mode, the owner, the mtime, and the
/// xattrs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerityPolicy {
    /// Each backed file carries the 36-byte metacopy record with the fs-verity
    /// digest of its content.
    ///
    /// This policy is the default.
    ///
    /// If a backing object is sealed with the parameters that
    /// [`Repo::export_composefs`] states, the export reads the digest from the
    /// kernel. For each other backing object, the export streams the payload
    /// to compute the digest.
    #[default]
    Computed,
    /// Each backed file carries the metacopy xattr with an empty value.
    ///
    /// The export reads no payload.
    ///
    /// The image has its own fs-verity digest. This digest is different from
    /// the value that a commit records under `ostree.composefs.digest.v0`.
    /// The recorded value is the digest of the image with verity digests.
    /// [`ComposefsOptions::RECORDED`] gives the options of that image.
    Disabled,
}

/// The options of a composefs export.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ComposefsOptions {
    /// The verity policy of the image.
    ///
    /// The default is [`VerityPolicy::Computed`].
    pub verity: VerityPolicy,
}

impl ComposefsOptions {
    /// The options of the image whose fs-verity digest a commit records.
    ///
    /// `ostree.composefs.digest.v0` holds the fs-verity digest of the image
    /// that [`Repo::export_composefs`] and [`Repo::export_composefs_to`] write
    /// with these options and no hook. A target machine computes the same
    /// digest at boot.
    ///
    /// The policy is [`VerityPolicy::Computed`]. Each backed file in the image
    /// carries the fs-verity digest of its content, so the image digest covers
    /// the content of each backed file.
    /// [`Repo::commit_add_composefs_metadata`] and
    /// [`Transaction::composefs_digest`] use these options, so a change of the
    /// default does not change the recorded digest.
    /// [`Transaction::write_composefs_commit`] also uses these options, with
    /// the hook of its caller.
    pub const RECORDED: ComposefsOptions = ComposefsOptions {
        verity: VerityPolicy::Computed,
    };
}

/// The kind of a node that an entry hook gets.
///
/// The export gives the kind to each call of a [`ComposefsEntryFn`]. The image
/// takes the file type of the inode from the kind, and the hook cannot change
/// it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryKind {
    /// A directory.
    Directory,
    /// A regular file.
    Regular,
    /// A symbolic link.
    Symlink,
}

/// A hook that a composefs export calls for each node of the image.
///
/// [`Repo::export_composefs`], [`Repo::export_composefs_to`],
/// [`Transaction::write_composefs_content`], and
/// [`Transaction::write_composefs_commit`] take the hook as `filter`. The
/// export calls the hook one time for each node of the tree, and one time for
/// each top-level directory that it adds. A hook must not depend on the order
/// of the calls.
///
/// Each call gets these arguments:
///
/// - The absolute path of the node in the image. The path of the root is `/`.
/// - The [`EntryKind`] of the node.
/// - The [`Metadata`] of the node. For a node of the tree, the mode, the
///   owner, and the xattrs come from the tree. For a top-level directory that
///   the export adds, the mode is `040755`, the owner is 0:0, and the node
///   has no xattrs. The mtime is `(0, 0)`. An xattr name has no NUL byte at
///   its end, and each value is the stored value.
///
/// The hook can change the mode, the uid, the gid, the mtime, and the xattrs.
/// The image holds the metadata that the hook leaves, with these rules:
///
/// - The image takes the file type from the [`EntryKind`]. A change to the
///   file-type bits of the mode has no effect.
/// - The export adds no byte to a value and removes none. If a SELinux label
///   must end in a NUL byte, the hook adds the NUL.
/// - A file capability is the xattr `security.capability` with a binary
///   value. The hook sets it as any other xattr.
/// - The hook does not see the xattrs that the image writer adds:
///   `trusted.overlay.redirect` and `trusted.overlay.metacopy` of a backed
///   file, and `trusted.overlay.opaque` of the root.
/// - The image writer escapes a name `trusted.overlay.X` as
///   `trusted.overlay.overlay.X`, so a hook cannot set an overlay xattr of
///   the image.
///
/// After each call, the export checks the xattrs of the node against the
/// first two limits of the image ([`Repo::export_composefs`], "Limits"): the
/// length of a name and the xattr budget of the inode. It also refuses an
/// empty name, a name with a NUL byte, and a name that occurs two times. Each
/// refusal is [`Error::Unsupported`]. The check also covers the added
/// top-level directories, so a hook cannot make the image writer panic.
///
/// The xattrs of a symlink share the block of the inode with the target. The
/// image writer refuses with [`Error::Unsupported`] a symlink whose xattrs and
/// target do not fit in the block.
///
/// The image writer adds a whiteout stub to the root for each name `00` to
/// `ff` that the root does not hold. The stubs are not nodes of the tree, so
/// the hook gets no call for them. Each stub is a character device 0:0 with
/// the mode `0644`. It takes the uid, the gid, the mtime, and the
/// `security.selinux` xattr that the root has after the hook. A stub has no
/// other xattr.
///
/// The export calls the hook on the thread of its async task, one time for
/// each node, between the reads of the objects. The export does not call the
/// hook on the blocking pool. A hook that blocks or runs for a long time stops
/// the other tasks on that thread. The caller therefore loads the policy
/// before the export, and the hook does no I/O.
///
/// The export keeps the metadata of each node, with its xattrs, in memory
/// until it writes the image. Each xattr that the hook adds thus uses memory
/// for each node that gets it.
///
/// If the hook returns an error, the export stops and returns that error
/// unchanged. The hook is `Sync`, so several exports can share one hook at the
/// same time.
pub type ComposefsEntryFn<'a> = &'a (dyn Fn(&Path, EntryKind, &mut Metadata) -> Result<()> + Sync);

/// The inputs of one walk of a tree that are the same for each node.
#[derive(Clone, Copy)]
struct Walk<'a> {
    /// The place where the walk reads the objects of the tree.
    source: ObjectSource<'a>,
    /// The way the walk gets the fs-verity digest of each backed file.
    digests: Digests,
    /// The hook of the caller, if it gave one.
    filter: Option<ComposefsEntryFn<'a>>,
}

impl Walk<'_> {
    /// Gives `meta` of the node at `path` to the hook, if the walk has one,
    /// and then checks the xattrs of the result. An error of the hook goes
    /// back unchanged.
    fn entry(&self, path: &Path, kind: EntryKind, meta: &mut Metadata) -> Result<()> {
        if let Some(filter) = self.filter {
            filter(path, kind, meta)?;
        }
        check_xattrs(&meta.xattrs)
    }
}

/// The way the export gets the fs-verity digest of each backed file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Digests {
    /// The digest that the kernel holds for a sealed object, or else the
    /// digest of the streamed payload. [`VerityPolicy::Computed`] gives it.
    Computed,
    /// The digest that the kernel holds for a sealed object. An object with
    /// no seal is refused, and no payload is read.
    Sealed,
    /// No digest. [`VerityPolicy::Disabled`] gives it.
    Disabled,
}

/// The fs-verity digests that one walk of a tree computed for one image
/// model, keyed by the checksum of the file object.
///
/// When several paths of the tree name one object, the walk reads and hashes
/// the object one time. A digest that the kernel gives for a sealed object
/// does not go into the cache, because the load of the object reads it at no
/// cost.
#[derive(Default)]
struct VerityCache {
    digests: HashMap<Checksum, [u8; 32]>,
    /// The number of objects that the cache read and hashed.
    #[cfg(test)]
    hashed: usize,
}

impl From<VerityPolicy> for Digests {
    fn from(policy: VerityPolicy) -> Digests {
        match policy {
            VerityPolicy::Computed => Digests::Computed,
            VerityPolicy::Disabled => Digests::Disabled,
        }
    }
}

/// Methods that compute the composefs digest of a staged tree and stage its
/// image as a content object.
impl Transaction {
    /// Returns the composefs image digest of a tree that this transaction
    /// staged.
    ///
    /// The value is the one that `ostree.composefs.digest.v0` holds: the
    /// fs-verity digest of the image that an export with
    /// [`ComposefsOptions::RECORDED`] and no hook writes for the same tree.
    /// [`Repo::export_composefs`] describes the image.
    ///
    /// The call reads each object that this transaction staged from the
    /// staging directory, and each other object from `objects/`. The digest is
    /// available before the transaction commit, so it can go into the metadata
    /// of the commit that the tree belongs to. The value depends on the tree
    /// alone, so a repository of any mode that holds the tree gives the same
    /// digest.
    ///
    /// The image goes to [`std::io::sink`], so the digest needs no image-sized
    /// buffer.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if a dirtree, dirmeta, or file object of the
    ///   tree is in neither the staging directory nor the object store.
    /// - [`Error::Core`] if a dirtree object, a dirmeta object, or the header
    ///   of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    ///   [`Repo::export_composefs`] lists the limits.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if a file system operation fails, or if an `archive`
    ///   payload does not inflate.
    pub async fn composefs_digest(&self, root: &RepoTree) -> Result<[u8; 32]> {
        let walk = Walk {
            source: ObjectSource::Staged(self),
            digests: ComposefsOptions::RECORDED.verity.into(),
            filter: None,
        };
        let dir = composefs_model(walk, root, &mut VerityCache::default()).await?;
        image_digest(dir).await
    }

    /// Writes the composefs image of a tree that this transaction staged as a
    /// regular content object.
    ///
    /// The call returns the checksum of the content object and the fs-verity
    /// digest of the image. The image is the image that an export with `opts`
    /// and the hook `filter` writes for the same tree
    /// ([`Repo::export_composefs`]). The call reads the objects of the tree as
    /// [`composefs_digest`](Transaction::composefs_digest) reads them.
    ///
    /// `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. With `None`, the call uses no hook.
    ///
    /// `meta` is the owner, the mode, and the xattrs of the content object.
    /// The caller sets them.
    ///
    /// The call writes the image in two steps, and no step holds a buffer of
    /// the image bytes:
    ///
    /// 1. On the blocking pool, the writer writes the image to an unnamed temp
    ///    file of the staging directory and computes the fs-verity digest as
    ///    it writes. The call does not seal and does not sync this file.
    /// 2. The call streams the temp file into a content object with
    ///    [`write_content`](Transaction::write_content). The content writer
    ///    applies the form of the repository mode, the fs-verity seal, and
    ///    the sync of the transaction, and counts the object in the
    ///    free-space budget.
    ///
    /// The image therefore goes to disk two times. The temp file does not
    /// count in the free-space budget. During step 2, the disk holds the temp
    /// file and the content object at the same time. The temp file goes away
    /// before the call returns. In an `archive` repository, the content object
    /// is a `.filez` object.
    ///
    /// The model of the tree, with the metadata and the xattrs of each node,
    /// stays in memory until step 1 writes the image.
    ///
    /// # Errors
    ///
    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`.
    ///   The call refuses this mode before it reads the tree.
    /// - The errors of [`composefs_digest`](Transaction::composefs_digest).
    /// - [`Error::Unsupported`] if the xattrs of an inode after `filter` do
    ///   not fit a limit of the image, or if they hold an empty name, a name
    ///   with a NUL byte, or one name two times.
    /// - The error that `filter` returns.
    /// - The errors of [`write_content`](Transaction::write_content).
    /// - [`Error::Io`] if the create of the temp file, a write to it, or a
    ///   read from it fails.
    pub async fn write_composefs_content(
        &self,
        root: &RepoTree,
        opts: &ComposefsOptions,
        filter: Option<ComposefsEntryFn<'_>>,
        meta: &FileMeta,
    ) -> Result<(Checksum, [u8; 32])> {
        if self.repo().mode() == RepoMode::BareSplitXattrs {
            return Err(Error::Unsupported(
                "bare-split-xattrs is read-only; the port does not write it".into(),
            ));
        }
        let walk = Walk {
            source: ObjectSource::Staged(self),
            digests: opts.verity.into(),
            filter,
        };
        let dir = composefs_model(walk, root, &mut VerityCache::default()).await?;
        let staging = self.staging_dir().clone();
        let (file, size, digest) = self
            .unblock(move || write_scratch_image_blocking(&staging, &dir))
            .await?;
        let checksum = self
            .write_content(None, meta, FileReader::with_len_hint(file, size))
            .await?;
        Ok((checksum, digest))
    }
}

/// Methods that export a commit as a composefs image.
impl Repo {
    /// Builds the composefs EROFS image of `commit` in memory.
    ///
    /// The returned [`Image`] holds the bytes of the image and its fs-verity
    /// digest. With [`ComposefsOptions::RECORDED`] and no hook (`filter` is
    /// `None`), the digest is the value that
    /// [`commit_add_composefs_metadata`](Repo::commit_add_composefs_metadata)
    /// records for the tree of the commit. Under [`VerityPolicy::Disabled`],
    /// the digest is different from that value. The image assembly runs on the
    /// blocking pool.
    ///
    /// `filter` is an entry hook. The export calls it one time for each node of
    /// the tree, and for each top-level directory that it adds. The whiteout
    /// stubs of the image get no call. [`ComposefsEntryFn`] states the rules of
    /// the hook. With `None`, the export calls no hook.
    ///
    /// # Tree model
    ///
    /// The export reads the root tree of the commit. It turns each entry into
    /// a node of the image:
    ///
    /// - A directory gets the mode, the owner, and the xattrs of its dirmeta
    ///   object.
    /// - A symlink stores its target inline.
    /// - An empty regular file has no backing.
    /// - A regular file with content redirects to the loose path of its
    ///   `.file` object, with a leading `/`. Under
    ///   [`VerityPolicy::Computed`], it also carries the fs-verity digest of
    ///   its content.
    ///
    /// The export sets the mtime of each inode to 0, as the `ostree` command
    /// does. It adds the five empty top-level directories that the `ostree`
    /// command adds: `boot`, `etc`, `sysroot`, `usr`, and `var`. Each one has
    /// the mode `040755` and the uid and gid 0. If the root of the commit
    /// already holds one of these names, the entry of the commit stays.
    ///
    /// The export gives the metadata of each node to the hook `filter`, the
    /// added top-level directories included. The hook can change the mode, the
    /// owner, the mtime, and the xattrs. The image holds the metadata after the
    /// hook. The image writer escapes an xattr name `trusted.overlay.X` as
    /// `trusted.overlay.overlay.X`.
    ///
    /// The image writer adds a whiteout stub to the root for each name `00` to
    /// `ff` that the root does not hold, and sets `trusted.overlay.opaque` to
    /// `y` on the root. Each stub takes the owner, the mtime, and the
    /// `security.selinux` xattr of the root after the hook.
    /// [`ComposefsEntryFn`] states the rules.
    ///
    /// # Verity digests
    ///
    /// Under [`VerityPolicy::Computed`], the export gets the fs-verity digest
    /// of each backed file in one of two ways:
    ///
    /// - If the object file is the raw payload and `statx` reports its inode
    ///   as sealed, the export reads the digest from the kernel. The seal must
    ///   name SHA-256, 4096-byte blocks, no salt, and the payload size. A
    ///   repository with `[ex-integrity] fsverity` seals with these parameters.
    ///   The read occurs in the blocking-pool call that loads the metadata of
    ///   the object.
    /// - In all other cases, and if the kernel read fails, the export streams
    ///   the payload through the fs-verity hasher in chunks of 128 KiB. It
    ///   buffers no unconstrained blob.
    ///
    /// The export never reads the digest of an `archive` object from the
    /// kernel. The digest of a `.filez` file covers the stored form of the
    /// object, and the image needs the digest of the content.
    ///
    /// The kernel read takes no payload byte, so it does not find damage to
    /// the data or the verity metadata of a sealed object. [`Repo::fsck`] is
    /// the check for object integrity.
    ///
    /// # Repository modes
    ///
    /// The export runs in every repository mode. The EROFS metadata of each
    /// file comes from the file object, as [`Repo::load_file`] reads it in the
    /// mode of the repository. The hook `filter` can change this metadata. The
    /// image stores the logical uid and gid of each file, whoever runs the
    /// export. composefs presents the ownership through uid mapping at mount.
    ///
    /// The image depends on the committed tree and the hook alone. Each regular
    /// file redirects to its `.file` loose path, the form that a composefs
    /// backing store holds. Each digest covers the content of the file, so a
    /// repository of any mode that holds the tree gives the same image and
    /// digest.
    ///
    /// An `archive` repository holds its content objects in `.filez` form. An
    /// image exported from it mounts over a store that holds the same objects
    /// in `.file` form. A `bare-user` repository that pulls the tree is an
    /// example.
    ///
    /// # Limits
    ///
    /// The image cannot hold some trees. The export refuses each of these trees
    /// with [`Error::Unsupported`]:
    ///
    /// - An inode with too many bytes of extended attributes. Each attribute
    ///   spends its name, its value, and 7 bytes from a budget of 32755 bytes
    ///   for the inode. The `ostree` command refuses a tree that spends more.
    ///   At boot, the `ostree` command cannot reproduce a composefs digest of
    ///   such a tree.
    ///   The budget is less than the 65535 bytes that the value-length field
    ///   of an EROFS xattr entry can state, so that field never limits first.
    /// - An xattr name longer than 255 bytes, the limit of the name-length
    ///   field of an EROFS xattr entry. The budget alone does not hold a name
    ///   to this length.
    /// - A symlink target that does not fit in the block of its inode. The
    ///   image stores the target inline, next to the inode header and the
    ///   xattrs of the inode. For a symlink with no xattrs, the limit is 4063
    ///   bytes. The `ostree` command aborts on the same trees. `PATH_MAX` keeps
    ///   a target this long out of a tree that a checkout produces. A tar
    ///   import can produce one.
    /// - A child name longer than 255 bytes. The `ostree` command refuses the
    ///   same trees with `File name too long`. A file system holds no name
    ///   this long. A tar import can produce one.
    /// - A child name that is empty, is `.` or `..`, or holds `/`.
    ///
    /// The export checks the first two limits on the xattrs of each node after
    /// the hook `filter`, the added top-level directories included.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object, or a dirtree,
    ///   dirmeta, or file object of its tree, is not in the object store.
    /// - [`Error::Core`] if the commit object, a dirtree object, a dirmeta
    ///   object, or the header of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    /// - [`Error::Unsupported`] if the xattrs of an inode after `filter` do
    ///   not fit a limit of the image, or if they hold an empty name, a name
    ///   with a NUL byte, or one name two times.
    /// - The error that `filter` returns.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if a file system operation fails, or if an `archive`
    ///   payload does not inflate.
    pub async fn export_composefs(
        &self,
        commit: &Checksum,
        opts: &ComposefsOptions,
        filter: Option<ComposefsEntryFn<'_>>,
    ) -> Result<Image> {
        let dir = self
            .composefs_export_model(commit, opts.verity.into(), filter)
            .await?;
        ostrya_rt::unblock(move || build_image(&dir))
            .await
            .map_err(writer_error)
    }

    /// Writes the composefs image of `commit` to `out` and returns its digest.
    ///
    /// The image and its fs-verity digest are the same as those of
    /// [`export_composefs`](Repo::export_composefs), with the same options,
    /// the same hook `filter`, the same repository modes, and the same limits.
    ///
    /// The call writes the image to the file descriptor as it serializes it.
    /// The output is append-only, so the call holds no buffer of the image
    /// bytes. The model of the tree, with the metadata and the xattrs of each
    /// node, stays in memory until the image is written. The call writes `out`
    /// from its current offset and never seeks it. If the call
    /// fails, the bytes that it already wrote stay in `out`.
    ///
    /// # Errors
    ///
    /// - [`Error::ObjectNotFound`] if the commit object, or a dirtree,
    ///   dirmeta, or file object of its tree, is not in the object store.
    /// - [`Error::Core`] if the commit object, a dirtree object, a dirmeta
    ///   object, or the header of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    ///   [`export_composefs`](Repo::export_composefs) lists the limits.
    /// - [`Error::Unsupported`] if the xattrs of an inode after `filter` do
    ///   not fit a limit of the image, or if they hold an empty name, a name
    ///   with a NUL byte, or one name two times.
    /// - The error that `filter` returns.
    /// - [`Error::Io`] if the duplicate of `out` fails, or if a write to `out`
    ///   or its flush fails.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if another file system operation fails, or if an
    ///   `archive` payload does not inflate.
    pub async fn export_composefs_to(
        &self,
        commit: &Checksum,
        opts: &ComposefsOptions,
        filter: Option<ComposefsEntryFn<'_>>,
        out: BorrowedFd<'_>,
    ) -> Result<[u8; 32]> {
        let dir = self
            .composefs_export_model(commit, opts.verity.into(), filter)
            .await?;
        // The blocking pool needs an owned handle, so the call duplicates the
        // descriptor of the caller for the closure to move.
        let fd = out.try_clone_to_owned()?;
        ostrya_rt::unblock(move || write_image_to_fd(&dir, fd))
            .await
            .map_err(writer_error)
    }

    /// Writes the composefs image of `commit` to `out` for a mount, and
    /// returns the size of the image in bytes.
    ///
    /// The image is the image of
    /// [`export_composefs_to`](Repo::export_composefs_to) with `verity` and
    /// no hook, with these changes:
    ///
    /// - Under [`VerityPolicy::Computed`], the call takes the fs-verity digest
    ///   of each backed file from the kernel alone, and reads no payload. An
    ///   object with no seal, or with a seal of other parameters, fails the
    ///   call. An overlay with `verity=require` cannot open such an object.
    /// - Under [`VerityPolicy::Computed`], if the commit carries the key
    ///   `ostree.composefs.digest.v0`, the call computes the fs-verity digest
    ///   of the image as it writes the image, and compares the digest with
    ///   the key. A digest other than the key fails the call after the write,
    ///   and the bytes stay in `out`. The call reads the key before it walks
    ///   the tree.
    /// - Under [`VerityPolicy::Disabled`], or if the commit carries no key,
    ///   the call computes no fs-verity digest of the image. Under
    ///   [`VerityPolicy::Disabled`] the call does not read the key.
    /// - The call computes the size of the image before it writes, and
    ///   refuses an image larger than `max_size` bytes with no write.
    ///
    /// The function is not a stable API.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] under [`VerityPolicy::Computed`] if the
    ///   value of the key is not a variant of type `ay` with 32 bytes.
    /// - [`Error::Unsupported`] if a backed file has no seal under
    ///   [`VerityPolicy::Computed`], or if the image is larger than
    ///   `max_size` bytes.
    /// - [`Error::ComposefsDigestMismatch`] under [`VerityPolicy::Computed`]
    ///   if the fs-verity digest of the image is not the key.
    /// - The errors of [`export_composefs_to`](Repo::export_composefs_to).
    #[doc(hidden)]
    pub async fn export_composefs_for_mount(
        &self,
        commit: &Checksum,
        verity: VerityPolicy,
        out: BorrowedFd<'_>,
        max_size: u64,
    ) -> Result<u64> {
        let (commit_obj, _) = self.load_commit(commit).await?;
        let (digests, key) = match verity {
            VerityPolicy::Computed => (Digests::Sealed, recorded_digest(&commit_obj)?),
            VerityPolicy::Disabled => (Digests::Disabled, None),
        };
        let dir = self
            .composefs_commit_model(&commit_obj, digests, None)
            .await?;
        let fd = out.try_clone_to_owned()?;
        let hash = key.is_some();
        let (size, actual) = ostrya_rt::unblock(move || {
            let mut out = BufWriter::with_capacity(DIGEST_CHUNK, std::fs::File::from(fd));
            if hash {
                write_image_bounded_to(&dir, &mut out, max_size)
                    .map(|(size, digest)| (size, Some(digest)))
            } else {
                write_image_unhashed_to(&dir, &mut out, max_size).map(|size| (size, None))
            }
        })
        .await
        .map_err(writer_error)?;
        if let (Some(expected), Some(actual)) = (key, actual)
            && expected != actual
        {
            return Err(Error::ComposefsDigestMismatch {
                commit: *commit,
                expected,
                actual,
            });
        }
        Ok(size)
    }

    /// Returns the composefs tree model of the root of `commit`. The two
    /// export entry points share this step.
    async fn composefs_export_model(
        &self,
        commit: &Checksum,
        digests: Digests,
        filter: Option<ComposefsEntryFn<'_>>,
    ) -> Result<Directory> {
        let (commit_obj, _) = self.load_commit(commit).await?;
        self.composefs_commit_model(&commit_obj, digests, filter)
            .await
    }

    /// Returns the composefs tree model of the root of a loaded commit.
    async fn composefs_commit_model(
        &self,
        commit_obj: &Commit,
        digests: Digests,
        filter: Option<ComposefsEntryFn<'_>>,
    ) -> Result<Directory> {
        let tree = RepoTree::from_parts(
            self.clone(),
            commit_obj.root_dirtree,
            commit_obj.root_dirmeta,
        );
        let walk = Walk {
            source: ObjectSource::Repo(self),
            digests,
            filter,
        };
        composefs_model(walk, &tree, &mut VerityCache::default()).await
    }

    /// Stages a new commit that records the composefs image digest of
    /// `commit`.
    ///
    /// The digest is the fs-verity digest of the image that
    /// [`export_composefs`](Repo::export_composefs) writes with
    /// [`ComposefsOptions::RECORDED`] and no hook. The `ostree` command stores
    /// this value and verifies it at boot.
    ///
    /// The call appends the key `ostree.composefs.digest.v0` to the metadata
    /// dict of `commit`, with the 32-byte digest as an `ay` value. The other
    /// fields of the commit stay the same. The call stages the new commit in
    /// `txn` and returns its checksum. The new commit publishes when `txn`
    /// commits.
    ///
    /// The new commit keeps field 2 of `commit`, the attachments, with no
    /// change. Before the call builds the image, it checks field 2 with the
    /// rules of [`write_commit`](Transaction::write_commit): each entry has a
    /// name that is not empty and a checksum of 32 bytes, the entries are
    /// sorted by name in byte order with no name two times, and each
    /// attachment is complete in the repository or in `txn`. The check reads
    /// no attachment of an attachment.
    ///
    /// The image depends on the tree of the commit alone, so the metadata of
    /// the commit and the repository mode do not change the digest. The image
    /// goes to [`std::io::sink`], so the digest needs no image-sized buffer.
    ///
    /// # Errors
    ///
    /// - [`Error::InvalidFormat`] if `commit` already carries
    ///   `ostree.composefs.digest.v0`.
    /// - [`Error::InvalidRelations`] with `commit` if field 2 of `commit` is
    ///   defective, if its entries are not sorted or have a name two times,
    ///   or if an attachment is absent or partial.
    /// - [`Error::Core`] if the commit tuple of an attachment does not frame,
    ///   or if its field 2 does not decode.
    /// - [`Error::ObjectNotFound`] if the commit object, or a dirtree,
    ///   dirmeta, or file object of its tree, is not in the object store.
    /// - [`Error::Core`] if the commit object, a dirtree object, a dirmeta
    ///   object, or the header of a file object does not parse.
    /// - [`Error::InvalidFormat`] if a file object does not have the form of
    ///   the repository mode. [`Repo::load_file`] lists the cases.
    /// - [`Error::Unsupported`] if the tree does not fit a limit of the image.
    ///   [`export_composefs`](Repo::export_composefs) lists the limits.
    /// - [`Error::Unsupported`] if the repository mode is `bare-split-xattrs`,
    ///   or if `[ex-integrity] fsverity` is `yes` and the fs-verity seal of
    ///   the new commit object fails.
    /// - [`Error::InsufficientFreeSpace`] if the new commit object needs more
    ///   space than the free-space budget of the transaction holds.
    /// - [`Error::Core`] if `[core] fsync` or `[core] per-object-fsync` in the
    ///   repository config is malformed.
    /// - [`Error::InvalidFormat`] if `[ex-integrity] fsverity` or
    ///   `[ex-integrity] composefs` in the repository config is malformed.
    /// - [`Error::InvalidFormat`] if a metadata object is larger than
    ///   [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
    ///   file, or if a symlink is on its path.
    /// - [`Error::Io`] if a file system operation fails, or if an `archive`
    ///   payload does not inflate.
    pub async fn commit_add_composefs_metadata(
        &self,
        txn: &Transaction,
        commit: &Checksum,
    ) -> Result<Checksum> {
        let (mut commit_obj, _) = self.load_commit(commit).await?;
        if commit_obj.metadata.dict_get(COMPOSEFS_DIGEST_KEY).is_some() {
            return Err(Error::InvalidFormat(format!(
                "commit already carries {COMPOSEFS_DIGEST_KEY}"
            )));
        }
        let atts = related::checked_entries(
            RelationField::Attachments,
            Some(*commit),
            related::entries_of(&commit_obj.related),
        )?;
        related::check_order(Some(*commit), atts.iter().map(|(name, _)| name.as_str()))?;
        related::check_attachments(txn, Some(*commit), &atts).await?;
        let dir = self
            .composefs_commit_model(&commit_obj, ComposefsOptions::RECORDED.verity.into(), None)
            .await?;
        let fs_verity = image_digest(dir).await?;
        let digest_type = Type::parse(DIGEST_SIGNATURE).map_err(ostrya_core::Error::from)?;
        let value = Value::variant(digest_type, Value::Bytes(fs_verity.to_vec()));
        append_dict_entry(&mut commit_obj.metadata, COMPOSEFS_DIGEST_KEY, value)?;
        let bytes = commit_obj.serialize()?;
        txn.write_metadata(ObjectType::Commit, None, &bytes).await
    }
}

/// Returns the fs-verity digest of the bytes of `file` from its current
/// offset to its end.
///
/// The function reads the file in chunks of 128 KiB and feeds each chunk to
/// the fs-verity hasher, so it holds no image-sized buffer.
pub(crate) fn image_file_digest(file: &mut std::fs::File) -> std::io::Result<[u8; 32]> {
    use std::io::Read;

    let mut hasher = FsVerityHasher::new();
    let mut buf = vec![0u8; DIGEST_CHUNK];
    loop {
        match file.read(&mut buf) {
            Ok(0) => break,
            Ok(n) => hasher.update(&buf[..n]),
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(e),
        }
    }
    Ok(hasher.finalize())
}

/// Returns the digest that `commit` records under
/// `ostree.composefs.digest.v0`, or `None` if the commit does not carry the
/// key.
///
/// The value is the first entry of the key. It must be a variant of type `ay`
/// with 32 bytes, or the call fails with [`Error::InvalidFormat`].
pub(crate) fn recorded_digest(commit: &Commit) -> Result<Option<[u8; 32]>> {
    let Some(entry) = commit.metadata.dict_get(COMPOSEFS_DIGEST_KEY) else {
        return Ok(None);
    };
    entry_digest(entry).map(Some)
}

/// Returns the digest that `entry`, the value of an entry under
/// `ostree.composefs.digest.v0`, holds: a variant of type `ay` with 32 bytes.
/// Each other value fails with [`Error::InvalidFormat`].
fn entry_digest(entry: &Value) -> Result<[u8; 32]> {
    entry
        .as_variant()
        .filter(|(ty, _)| ty.signature() == DIGEST_SIGNATURE)
        .and_then(|(_, value)| value.as_bytes())
        .and_then(|bytes| <[u8; 32]>::try_from(bytes).ok())
        .ok_or_else(|| {
            Error::InvalidFormat(format!(
                "the value of {COMPOSEFS_DIGEST_KEY} is not a variant of type \
                 {DIGEST_SIGNATURE} with 32 bytes"
            ))
        })
}

/// Returns the lowercase hex form of a 32-byte digest.
pub(crate) fn digest_hex(digest: &[u8; 32]) -> String {
    use std::fmt::Write;

    digest
        .iter()
        .fold(String::with_capacity(64), |mut out, byte| {
            let _ = write!(out, "{byte:02x}");
            out
        })
}

/// Builds the composefs tree model of `root` from the objects in `source`.
/// The model holds the metadata and the backing redirect of each file, and no
/// file content, so the shape of the tree bounds its size. The walk takes the
/// fs-verity digest of each object with no seal from `cache` if it holds one.
/// The walk gives each node to the hook of `walk`, if it has one, and checks
/// the xattrs of the node after the hook.
async fn composefs_model(
    walk: Walk<'_>,
    root: &RepoTree,
    cache: &mut VerityCache,
) -> Result<Directory> {
    let mut path = PathBuf::from("/");
    let mut dir = build_directory(
        walk,
        &mut path,
        *root.dirtree_checksum(),
        *root.dirmeta_checksum(),
        cache,
    )
    .await?;
    inject_top_level_dirs(&mut dir, walk)?;
    Ok(dir)
}

/// Serializes `dir` through `fd` and returns the fs-verity digest of the
/// image. A buffer wraps the descriptor, because the writer emits the image in
/// many small writes.
fn write_image_to_fd(dir: &Directory, fd: OwnedFd) -> std::result::Result<[u8; 32], WriterError> {
    let mut out = BufWriter::with_capacity(DIGEST_CHUNK, std::fs::File::from(fd));
    write_image_to(dir, &mut out)
}

/// Writes the image of `dir` to an unnamed temp file of the staging directory
/// `staging`, and returns the file at offset 0, its size in bytes, and the
/// fs-verity digest of the image.
///
/// The writer computes the digest as it writes through a buffer of 128 KiB,
/// so no step holds the whole image. The function sets no mode, does not sync
/// the file, and does not seal it. The file goes away when it closes.
fn write_scratch_image_blocking(
    staging: &RepoDir,
    dir: &Directory,
) -> Result<(std::fs::File, u64, [u8; 32])> {
    let mut file = TempFile::create(staging)?.into_file()?;
    let mut out = BufWriter::with_capacity(DIGEST_CHUNK, &mut file);
    let digest = write_image_to(dir, &mut out).map_err(writer_error)?;
    out.into_inner().map_err(|e| Error::Io(e.into_error()))?;
    let size = crate::repo_fs::stat_fd(file.as_fd())?.size;
    file.seek(SeekFrom::Start(0))?;
    Ok((file, size, digest))
}

/// Returns the fs-verity digest of the image of `dir`, for a caller that needs
/// the digest alone. The image goes to [`std::io::sink`], so the call never
/// holds it.
async fn image_digest(dir: Directory) -> Result<[u8; 32]> {
    ostrya_rt::unblock(move || write_image_to(&dir, &mut std::io::sink()))
        .await
        .map_err(writer_error)
}

/// Returns the library error for an error of the writer. The writer holds the
/// bounds that the image format states. The tree reaches these bounds, so a
/// refusal of the writer is a refusal of the tree.
pub(crate) fn writer_error(err: WriterError) -> Error {
    match err {
        WriterError::Unsupported(msg) => Error::Unsupported(msg),
        WriterError::Io(err) => Error::Io(err),
    }
}

/// Builds the composefs [`Directory`] model of one directory of a committed
/// tree, and recurses into its subdirectories. `path` is the absolute path of
/// the directory in the image. The call gives the directory to the hook before
/// its children. The future is boxed because the recursion is async.
fn build_directory<'a>(
    walk: Walk<'a>,
    path: &'a mut PathBuf,
    dirtree: Checksum,
    dirmeta: Checksum,
    cache: &'a mut VerityCache,
) -> TreeFuture<'a> {
    Box::pin(async move {
        let object = walk.source.dirmeta(&dirmeta).await?;
        let mut meta = dirmeta_to_metadata(&object);
        walk.entry(path, EntryKind::Directory, &mut meta)?;
        let mut dir = Directory::new(meta);
        let tree = walk.source.dirtree(&dirtree).await?;
        for (name, checksum) in tree.files {
            path.push(&name);
            let node = file_node(walk, path, &checksum, &mut *cache).await?;
            path.pop();
            dir.children.insert(name.into_bytes(), node);
        }
        for (name, subtree, submeta) in tree.dirs {
            path.push(&name);
            let sub = build_directory(walk, &mut *path, subtree, submeta, &mut *cache).await?;
            path.pop();
            dir.children.insert(name.into_bytes(), Node::Directory(sub));
        }
        Ok(dir)
    })
}

/// Builds the composefs [`Node`] of a file object.
///
/// - A symlink stores its target inline.
/// - An empty regular file has no backing.
/// - A regular file with content redirects to its `.file` loose path. Under
///   [`Digests::Computed`] and [`Digests::Sealed`], it carries the fs-verity
///   digest of its content.
///
/// The call reads the file object in each mode, because the metadata of the
/// inode comes from it. Under [`Digests::Computed`], it takes the digest of an
/// object with no seal from `cache` if it holds one. `path` is the absolute
/// path of the file in the image. The call gives the file to the hook before
/// it gets the digest of the content.
async fn file_node(
    walk: Walk<'_>,
    path: &Path,
    checksum: &Checksum,
    cache: &mut VerityCache,
) -> Result<Node> {
    let digests = walk.digests;
    let file = walk
        .source
        .file(checksum, digests != Digests::Disabled)
        .await?;
    let mut meta = file_to_metadata(&file);
    let kind = match &file.kind {
        FileKind::Symlink { .. } => EntryKind::Symlink,
        FileKind::Regular { .. } => EntryKind::Regular,
    };
    walk.entry(path, kind, &mut meta)?;
    match &file.kind {
        FileKind::Symlink { target } => Ok(Node::Symlink(Symlink {
            meta,
            target: target.clone().into_bytes(),
        })),
        FileKind::Regular { size } => {
            let content = if *size == 0 {
                Content::Empty
            } else {
                let digest = match digests {
                    Digests::Computed => Some(content_fs_verity(&file, cache).await?),
                    Digests::Sealed => Some(file.kernel_fs_verity().ok_or_else(|| {
                        Error::Unsupported(format!(
                            "the file object {checksum} has no fs-verity seal with SHA-256, \
                             4096-byte blocks, and no salt"
                        ))
                    })?),
                    Digests::Disabled => None,
                };
                Content::Backed {
                    size: *size,
                    redirect: format!("/{}", loose_path(checksum, ObjectType::File, BACKING_MODE)),
                    verity: digest,
                }
            };
            Ok(Node::Regular(Regular { meta, content }))
        }
    }
}

/// Returns the fs-verity digest of the content of a regular file.
///
/// If the object file is a sealed raw payload, the value is the digest that
/// the kernel gave at load. The call then reads no payload byte, and it does
/// not put the digest in `cache`. The seal must name SHA-256, 4096-byte
/// blocks, no salt, and the payload size.
///
/// In all other cases, the call looks for the checksum of the file object in
/// `cache`, and gives the digest that the cache holds. If the cache holds no
/// digest of the object, the call streams the payload of the object through
/// the hasher in bounded chunks, and puts the digest in `cache`. The checksum
/// of the file object covers the content, so it is a key of the digest. The
/// digest covers the content, so a repository that stores the object
/// compressed gives the same value as one that stores it raw.
async fn content_fs_verity(file: &FileObject, cache: &mut VerityCache) -> Result<[u8; 32]> {
    use futures_lite::AsyncReadExt;

    if let Some(digest) = file.kernel_fs_verity() {
        return Ok(digest);
    }
    if let Some(digest) = cache.digests.get(file.checksum()) {
        return Ok(*digest);
    }
    let mut reader = file.reader().await?;
    let mut hasher = FsVerityHasher::new();
    let mut buf = vec![0u8; DIGEST_CHUNK];
    loop {
        let n = reader.read(&mut buf).await.map_err(Error::Io)?;
        if n == 0 {
            break;
        }
        hasher.update(&buf[..n]);
    }
    let digest = hasher.finalize();
    cache.digests.insert(*file.checksum(), digest);
    #[cfg(test)]
    {
        cache.hashed += 1;
    }
    Ok(digest)
}

/// Inserts the five top-level directories that the `ostree` command adds. If
/// the root of the commit already holds one of these names, its entry stays,
/// and the call does not give the name to the hook a second time.
fn inject_top_level_dirs(root: &mut Directory, walk: Walk<'_>) -> Result<()> {
    for name in INJECTED_DIRS {
        let key = name.as_bytes().to_vec();
        if let btree_map::Entry::Vacant(slot) = root.children.entry(key) {
            let mut meta = Metadata {
                mode: INJECTED_DIR_MODE,
                uid: 0,
                gid: 0,
                mtime: (0, 0),
                xattrs: Vec::new(),
            };
            walk.entry(&Path::new("/").join(name), EntryKind::Directory, &mut meta)?;
            slot.insert(Node::Directory(Directory::new(meta)));
        }
    }
    Ok(())
}

/// Returns the composefs [`Metadata`] of a directory. The `ostree` command
/// sets the mtime of each exported inode to 0.
fn dirmeta_to_metadata(dirmeta: &DirMeta) -> Metadata {
    Metadata {
        mode: dirmeta.mode,
        uid: dirmeta.uid,
        gid: dirmeta.gid,
        mtime: (0, 0),
        xattrs: xattrs_to_model(&dirmeta.xattrs),
    }
}

/// Returns the composefs [`Metadata`] of a file object. The `ostree` command
/// sets the mtime of each exported inode to 0.
fn file_to_metadata(file: &FileObject) -> Metadata {
    Metadata {
        mode: file.mode,
        uid: file.uid,
        gid: file.gid,
        mtime: (0, 0),
        xattrs: xattrs_to_model(&file.xattrs),
    }
}

/// Converts an [`Xattrs`] set to the `(name, value)` pairs of the writer. A
/// stored name ends in a NUL byte. The writer indexes raw names, so the call
/// drops the NUL.
fn xattrs_to_model(xattrs: &Xattrs) -> Vec<(Vec<u8>, Vec<u8>)> {
    xattrs
        .iter()
        .map(|(name, value)| {
            let name = name.strip_suffix(&[0]).unwrap_or(name);
            (name.to_vec(), value.to_vec())
        })
        .collect()
}

/// Checks the final xattrs of one inode of the image model.
///
/// Each attribute spends its name, its value, and [`XATTR_ENTRY_COST`] bytes
/// from the budget of [`MAX_XATTR_TOTAL`] bytes of the inode. The call refuses
/// an inode that spends more. It holds each name to [`MAX_XATTR_NAME`] bytes,
/// the one EROFS length field that the budget does not bind. It also refuses
/// an empty name, a name that holds a NUL byte, and a name that occurs two
/// times. A stored [`Xattrs`] set holds none of these three, so only a hook
/// can give one. The writer panics on a value or an area above its limits, so
/// the walk runs this check on each node after the hook.
fn check_xattrs(xattrs: &[(Vec<u8>, Vec<u8>)]) -> Result<()> {
    let mut spent = 0usize;
    for (name, value) in xattrs {
        if name.is_empty() {
            return Err(Error::Unsupported("an xattr name is empty".into()));
        }
        if name.contains(&0) {
            return Err(Error::Unsupported(format!(
                "xattr {} holds a NUL byte",
                name.escape_ascii(),
            )));
        }
        if name.len() > MAX_XATTR_NAME {
            return Err(Error::Unsupported(format!(
                "xattr {} is {} bytes long, above the {MAX_XATTR_NAME} \
                 bytes a composefs image states a name in",
                String::from_utf8_lossy(name),
                name.len(),
            )));
        }
        spent += XATTR_ENTRY_COST + name.len() + value.len();
        if spent > MAX_XATTR_TOTAL {
            return Err(Error::Unsupported(format!(
                "xattr {} takes the inode to {spent} bytes of extended \
                 attributes, above the {MAX_XATTR_TOTAL} bytes a composefs \
                 image holds",
                String::from_utf8_lossy(name),
            )));
        }
    }
    // A stored set holds its names in strictly increasing order, so with no
    // hook the check needs no sorted copy.
    if !xattrs.windows(2).all(|pair| pair[0].0 < pair[1].0) {
        let mut names: Vec<&[u8]> = xattrs.iter().map(|(name, _)| name.as_slice()).collect();
        names.sort_unstable();
        if let Some(pair) = names.windows(2).find(|pair| pair[0] == pair[1]) {
            return Err(Error::Unsupported(format!(
                "xattr {} is on the inode two times",
                String::from_utf8_lossy(pair[0]),
            )));
        }
    }
    Ok(())
}

/// Compile-time checks that the futures of the exports with a hook are
/// `Send`.
const _: fn() = || {
    fn assert_send<T: Send>(_: &T) {}
    let _ = |repo: &Repo, commit: &Checksum, filter: ComposefsEntryFn<'_>| {
        assert_send(&repo.export_composefs(commit, &ComposefsOptions::RECORDED, Some(filter)));
    };
    let _ = |repo: &Repo, commit: &Checksum, filter: ComposefsEntryFn<'_>, out: BorrowedFd<'_>| {
        assert_send(&repo.export_composefs_to(
            commit,
            &ComposefsOptions::RECORDED,
            Some(filter),
            out,
        ));
    };
};

#[cfg(test)]
mod tests {
    use std::os::fd::AsFd;
    use std::os::unix::fs::PermissionsExt;
    use std::path::{Path, PathBuf};

    use std::sync::Mutex;

    use ostrya_composefs::{Metadata, Node};
    use ostrya_core::{DirMeta, ObjectType, RepoMode, Xattrs};
    use ostrya_rt::block_on;

    use super::{
        ComposefsEntryFn, Digests, EntryKind, ObjectSource, VerityCache, Walk, composefs_model,
    };
    use crate::{CreateOptions, FileMeta, MutableTree, Repo, Transaction};

    /// A scratch directory that the drop removes.
    struct Scratch {
        path: PathBuf,
    }

    impl Scratch {
        fn new(tag: &str) -> Scratch {
            let path = std::env::temp_dir().join(format!(
                "ostrya-composefs-{tag}-{}-{}",
                std::process::id(),
                crate::write::unique()
            ));
            let _ = std::fs::remove_dir_all(&path);
            std::fs::create_dir_all(&path).unwrap();
            Scratch { path }
        }
    }

    impl Drop for Scratch {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.path);
        }
    }

    /// Writes the regular file `name` under `dir` with `bytes` and the mode
    /// 0644.
    fn write_file(dir: &Path, name: &str, bytes: &[u8]) {
        let path = dir.join(name);
        std::fs::write(&path, bytes).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
    }

    /// One tree walk reads and hashes each object with no seal one time. Two
    /// paths of the tree name one object. An empty file has no backing, so
    /// the walk hashes no empty object.
    #[test]
    fn one_tree_walk_hashes_each_unsealed_object_one_time() {
        let scratch = Scratch::new("verity-cache");
        let root = scratch.path.join("repo");
        block_on(async {
            drop(
                Repo::create(&root, CreateOptions::new(RepoMode::BareUser))
                    .await
                    .unwrap(),
            );
            let cfg = root.join("config");
            let mut text = std::fs::read_to_string(&cfg).unwrap();
            text.push_str("[ex-integrity]\nfsverity=no\n");
            std::fs::write(&cfg, text).unwrap();
            let repo = Repo::open(&root).await.unwrap();

            let src = scratch.path.join("tree").join("src");
            std::fs::create_dir_all(&src).unwrap();
            write_file(&src, "a", b"shared bytes\n");
            write_file(&src, "b", b"shared bytes\n");
            write_file(&src, "empty", b"");

            let txn = repo.transaction().await.unwrap();
            let mut mtree = MutableTree::new();
            let dfd = std::fs::File::open(scratch.path.join("tree")).unwrap();
            txn.write_dfd_to_mtree(dfd.as_fd(), Path::new("src"), &mut mtree, None)
                .await
                .unwrap();
            let tree = txn.write_mtree(&mut mtree).await.unwrap();
            let mut cache = VerityCache::default();
            let walk = Walk {
                source: ObjectSource::Staged(&txn),
                digests: Digests::Computed,
                filter: None,
            };
            composefs_model(walk, &tree, &mut cache).await.unwrap();
            assert_eq!(cache.hashed, 1);
        });
    }

    /// The stored xattrs of the test tree: `security.selinux` with `label`.
    /// A stored name ends in a NUL byte.
    fn selinux(label: &[u8]) -> Xattrs {
        Xattrs::new([(b"security.selinux\0".to_vec(), label.to_vec())]).unwrap()
    }

    /// Stages a dirmeta with the mode 040755, the owner 0:0, and `xattrs`.
    async fn stage_dirmeta(txn: &Transaction, xattrs: Xattrs) -> ostrya_core::Checksum {
        let bytes = DirMeta {
            uid: 0,
            gid: 0,
            mode: 0o040755,
            xattrs,
        }
        .serialize()
        .unwrap();
        txn.write_metadata(ObjectType::DirMeta, None, &bytes)
            .await
            .unwrap()
    }

    /// One call of the hook: the path, the kind, the mtime, and the xattr
    /// names that the hook got.
    type Call = (PathBuf, EntryKind, (u64, u32), Vec<Vec<u8>>);

    /// The walk gives each node of the tree to the hook one time, before the
    /// children of a directory. The hook gets the mtime 0 and the xattr names
    /// with no NUL byte. A change of the hook is in the model. A top-level
    /// name that the tree holds gets one call with the kind of the tree
    /// entry, and the walk adds no directory in its place.
    #[test]
    fn the_walk_gives_each_node_to_the_hook() {
        let scratch = Scratch::new("hook-model");
        let calls: Mutex<Vec<Call>> = Mutex::new(Vec::new());
        let hook: ComposefsEntryFn<'_> = &|path, kind, meta: &mut Metadata| {
            let names = meta.xattrs.iter().map(|(name, _)| name.clone()).collect();
            calls
                .lock()
                .unwrap()
                .push((path.to_path_buf(), kind, meta.mtime, names));
            if path == Path::new("/sub/f") {
                meta.mode = 0o100600;
                meta.uid = 7;
                meta.gid = 8;
                meta.mtime = (5, 6);
            }
            Ok(())
        };
        let model = block_on(async {
            let repo = Repo::create(
                &scratch.path.join("repo"),
                CreateOptions::new(RepoMode::Archive),
            )
            .await
            .unwrap();
            let txn = repo.transaction().await.unwrap();
            let file = |xattrs: Xattrs| FileMeta {
                uid: 0,
                gid: 0,
                mode: 0o100644,
                xattrs,
            };
            let etc = txn
                .write_regfile_inline(None, &file(selinux(b"etc_t\0")), b"a file\n")
                .await
                .unwrap();
            let f = txn
                .write_regfile_inline(None, &file(Xattrs::empty()), b"")
                .await
                .unwrap();
            let mut mtree = MutableTree::new();
            mtree.replace_file("etc", etc).unwrap();
            let sub = mtree.ensure_dir("sub").await.unwrap();
            sub.replace_file("f", f).unwrap();
            sub.set_metadata_checksum(stage_dirmeta(&txn, Xattrs::empty()).await);
            mtree.set_metadata_checksum(stage_dirmeta(&txn, selinux(b"root_t\0")).await);
            let tree = txn.write_mtree(&mut mtree).await.unwrap();
            let walk = Walk {
                source: ObjectSource::Staged(&txn),
                digests: Digests::Disabled,
                filter: Some(hook),
            };
            composefs_model(walk, &tree, &mut VerityCache::default())
                .await
                .unwrap()
        });

        let calls = calls.into_inner().unwrap();
        let paths: Vec<&Path> = calls.iter().map(|call| call.0.as_path()).collect();
        let at = |path: &str| {
            paths
                .iter()
                .position(|seen| *seen == Path::new(path))
                .unwrap()
        };
        for want in [
            "/", "/etc", "/sub", "/sub/f", "/boot", "/sysroot", "/usr", "/var",
        ] {
            let count = paths
                .iter()
                .filter(|seen| **seen == Path::new(want))
                .count();
            assert_eq!(count, 1, "{want} gets one call: {paths:?}");
        }
        assert_eq!(
            paths.len(),
            8,
            "the hook gets one call for each node: {paths:?}"
        );
        assert!(at("/") < at("/etc") && at("/") < at("/sub") && at("/sub") < at("/sub/f"));

        let selinux_name = [b"security.selinux".to_vec()];
        for (path, kind, mtime, names) in &calls {
            assert_eq!(*mtime, (0, 0), "the mtime of {}", path.display());
            let want: &[Vec<u8>] = match path.to_str().unwrap() {
                "/" | "/etc" => &selinux_name,
                _ => &[],
            };
            assert_eq!(names, want, "the xattr names of {}", path.display());
            let want_kind = match path.to_str().unwrap() {
                "/etc" | "/sub/f" => EntryKind::Regular,
                _ => EntryKind::Directory,
            };
            assert_eq!(*kind, want_kind, "the kind of {}", path.display());
        }

        assert!(matches!(
            model.children.get(&b"etc"[..]),
            Some(Node::Regular(_))
        ));
        let Some(Node::Directory(sub)) = model.children.get(&b"sub"[..]) else {
            panic!("the model holds the directory sub");
        };
        let Some(Node::Regular(f)) = sub.children.get(&b"f"[..]) else {
            panic!("the model holds the file sub/f");
        };
        assert_eq!(
            (f.meta.mode, f.meta.uid, f.meta.gid, f.meta.mtime),
            (0o100600, 7, 8, (5, 6)),
        );
    }
}