ostrya/image_commit.rs
1//! The composefs image commit.
2//!
3//! The image commit holds the composefs image of the tree of another commit.
4//! Its tree holds one regular file, `/root.cfs`, which is the EROFS image.
5//! A commit names its image commit by the name [`COMPOSEFS_RELATION`], as an
6//! attachment (field 2 of the commit object) or as a supplement (the key
7//! `ostrya.related` of the detached metadata).
8//!
9//! - [`Transaction::write_composefs_commit`] stages the image commit of a
10//! tree.
11//! - [`Repo::open_composefs_image`] finds the image commit that a commit
12//! names, checks it, and opens its `/root.cfs`.
13//! - [`Repo::add_composefs_supplement`] writes the image commit of a commit
14//! and names it as the supplement [`COMPOSEFS_RELATION`] of the commit.
15//!
16//! The key [`COMPOSEFS_DIGEST_KEY`] of a commit records the fs-verity digest
17//! of the image that a build of its tree with no hook gives. The lookup
18//! compares the key with the image of a supplement, and refuses a supplement
19//! of a commit with no key. The lookup does not read the key for an
20//! attachment.
21//!
22//! The shape of the image commit is fixed:
23//!
24//! - The root directory is `0:0` with the mode `040755` and no xattrs.
25//! - The root directory holds the file `root.cfs` alone. The file is `0:0`
26//! with the mode `0100400` and no xattrs. Its content is the image that an
27//! export with [`ComposefsOptions::RECORDED`] writes for the tree, with the
28//! hook that the caller gives or with no hook.
29//! - The commit has the subject `composefs image`, an empty body, the
30//! timestamp 0, no parent, no metadata key, and no related entry.
31//!
32//! The same image therefore gives the same image commit.
33
34use ostrya_core::{Checksum, Commit, DirMeta, DirTree, ObjectType, Value, Xattrs};
35
36use async_compression::futures::bufread::DeflateDecoder;
37
38use crate::composefs::{
39 COMPOSEFS_DIGEST_KEY, ComposefsEntryFn, ComposefsOptions, DIGEST_CHUNK, digest_hex,
40 image_file_digest, recorded_digest,
41};
42use crate::config::Tristate;
43use crate::error::{Error, Result};
44use crate::file::{FileKind, FileObject, Payload};
45use crate::inflate::BufSource;
46use crate::read::CommitState;
47use crate::related::{self, RelationField};
48use crate::repo::Repo;
49use crate::transaction::Transaction;
50use crate::tree::RepoTree;
51use crate::write::FileMeta;
52
53/// The name of the attachment and of the supplement that names the
54/// composefs image commit of a commit.
55pub const COMPOSEFS_RELATION: &str = "composefs";
56
57/// The name of the image file in the root directory of the image commit.
58const IMAGE_FILE: &str = "root.cfs";
59
60/// The subject of the image commit.
61const IMAGE_SUBJECT: &str = "composefs image";
62
63/// The permission bits of the image file.
64const IMAGE_PERM: u32 = 0o400;
65
66/// The mode of the root directory of the image commit.
67const ROOT_DIR_MODE: u32 = 0o040755;
68
69/// The field of a commit that names the image commit that
70/// [`Repo::open_composefs_image`] opens.
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum ComposefsImageSource {
73 /// The attachment [`COMPOSEFS_RELATION`]: an entry of field 2 of the
74 /// commit object.
75 Attachment,
76 /// The supplement [`COMPOSEFS_RELATION`]: an entry of the key
77 /// `ostrya.related` of the detached metadata.
78 Supplement,
79}
80
81impl std::fmt::Display for ComposefsImageSource {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83 f.write_str(match self {
84 ComposefsImageSource::Attachment => "attachment",
85 ComposefsImageSource::Supplement => "supplement",
86 })
87 }
88}
89
90/// The open composefs image of a commit, from
91/// [`Repo::open_composefs_image`].
92#[derive(Debug)]
93pub struct ComposefsImage {
94 /// The loose object of `/root.cfs` in the image commit, open read-only at
95 /// offset 0.
96 pub file: std::fs::File,
97 /// The size of the image in bytes.
98 pub size: u64,
99 /// The field of the commit that names the image commit.
100 pub source: ComposefsImageSource,
101 /// The checksum of the image commit.
102 pub commit: Checksum,
103}
104
105/// The result of [`Repo::add_composefs_supplement`].
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107pub enum ComposefsSupplementAdd {
108 /// The commit has the supplement [`COMPOSEFS_RELATION`], and its image
109 /// commit passes the checks of [`Repo::open_composefs_image`]. The call
110 /// writes nothing.
111 Valid {
112 /// The checksum of the image commit.
113 image: Checksum,
114 },
115 /// The call wrote the image commit and set the supplement
116 /// [`COMPOSEFS_RELATION`] of the commit to it.
117 Written {
118 /// The checksum of the image commit.
119 image: Checksum,
120 /// The image commit that the supplement named before the call, if
121 /// the commit had the supplement and its image commit failed a
122 /// check. It can be equal to `image`: for example, a partial image
123 /// commit that the call completes.
124 replaced: Option<Checksum>,
125 },
126}
127
128/// The defect of an image commit, or of the way that a commit names it, that
129/// [`Repo::open_composefs_image`] refuses with
130/// [`Error::InvalidComposefsImage`].
131///
132/// The text of each defect is a clause that follows the checksum of the image
133/// commit in the text of the error.
134#[derive(Debug, Clone, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum ComposefsImageDefect {
137 /// The commit names the image commit as a supplement and carries no key
138 /// `ostree.composefs.digest.v0`.
139 NoKey,
140 /// The repository does not hold the image commit.
141 Absent,
142 /// The repository marks the image commit partial.
143 Partial,
144 /// The root directory of the image commit holds no entry `root.cfs`.
145 NoImageFile,
146 /// The entry `root.cfs` is a directory or a symlink.
147 NotRegular,
148 /// The root directory of the image commit holds an entry other than
149 /// `root.cfs`. The value is the name of the entry.
150 ExtraEntry(String),
151 /// The repository sets `[ex-integrity] fsverity=yes`, and the file object
152 /// of `root.cfs` has no fs-verity seal with SHA-256, 4096-byte blocks, no
153 /// salt, and its full size.
154 NotSealed,
155 /// The fs-verity digest of `/root.cfs` is not the value of the key
156 /// `ostree.composefs.digest.v0` of the commit.
157 DigestMismatch {
158 /// The digest that the commit records.
159 expected: [u8; 32],
160 /// The fs-verity digest of `/root.cfs`.
161 actual: [u8; 32],
162 },
163}
164
165impl std::fmt::Display for ComposefsImageDefect {
166 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167 match self {
168 ComposefsImageDefect::NoKey => {
169 f.write_str("and the commit carries no ostree.composefs.digest.v0")
170 }
171 ComposefsImageDefect::Absent => f.write_str(related::ABSENT_REASON),
172 ComposefsImageDefect::Partial => f.write_str(related::PARTIAL_REASON),
173 ComposefsImageDefect::NoImageFile => write!(f, "whose tree holds no /{IMAGE_FILE}"),
174 ComposefsImageDefect::NotRegular => {
175 write!(f, "whose /{IMAGE_FILE} is not a regular file")
176 }
177 ComposefsImageDefect::ExtraEntry(name) => {
178 write!(f, "whose tree holds the entry {name} next to /{IMAGE_FILE}")
179 }
180 ComposefsImageDefect::NotSealed => write!(
181 f,
182 "whose /{IMAGE_FILE} has no fs-verity seal with SHA-256, 4096-byte blocks, \
183 no salt, and its full size"
184 ),
185 ComposefsImageDefect::DigestMismatch { expected, actual } => write!(
186 f,
187 "whose /{IMAGE_FILE} has the fs-verity digest {}, and the commit records {}",
188 digest_hex(actual),
189 digest_hex(expected)
190 ),
191 }
192 }
193}
194
195/// Methods that write the composefs image commit.
196impl Transaction {
197 /// Stages the composefs image commit of a tree that this transaction
198 /// staged.
199 ///
200 /// The call returns the checksum of the image commit and the fs-verity
201 /// digest of the image. The image is the image that
202 /// [`Repo::export_composefs_to`] writes for the tree with
203 /// [`ComposefsOptions::RECORDED`] and the hook `filter`. With `None`, the
204 /// digest is the value that
205 /// [`composefs_digest`](Transaction::composefs_digest) gives.
206 ///
207 /// The call takes no [`ComposefsOptions`]. It always uses
208 /// [`ComposefsOptions::RECORDED`], so each backed file of the image carries
209 /// the fs-verity digest of its content.
210 ///
211 /// `filter` is an entry hook. [`ComposefsEntryFn`] states its rules. The
212 /// hook gets one call for each node of the tree, and for each top-level
213 /// directory that the call adds to the image. The whiteout stubs of the
214 /// image get no call. Each stub takes the owner, the mtime, and the
215 /// `security.selinux` xattr of the root after the hook. With `None`, the
216 /// call uses no hook.
217 ///
218 /// The image commit has a fixed shape:
219 ///
220 /// - The root directory is `0:0` with the mode `040755` and no xattrs.
221 /// - The root directory holds the file `root.cfs` alone. The file is the
222 /// image, `0:0` with the mode `0100400` and no xattrs.
223 /// - The commit has the subject `composefs image`, an empty body, the
224 /// timestamp 0, no parent, no metadata key, and no related entry.
225 ///
226 /// So the same image gives the same image commit.
227 ///
228 /// The call writes the image file with
229 /// [`write_composefs_content`](Transaction::write_composefs_content). It
230 /// then stages the root dirmeta, the root dirtree, and the commit object
231 /// with no `ostree.sizes` key. The image commit
232 /// does not name the commit of the tree. The caller names the image commit
233 /// from that commit as the attachment or the supplement
234 /// [`COMPOSEFS_RELATION`].
235 ///
236 /// The key [`COMPOSEFS_DIGEST_KEY`] of the commit of the tree records the
237 /// digest of the image that the call gives with no hook. With a hook, the
238 /// caller writes the value of
239 /// [`composefs_digest`](Transaction::composefs_digest) under the key, or
240 /// no key, and names the image commit as an attachment.
241 /// [`Repo::open_composefs_image`] compares the key with the digest of
242 /// `/root.cfs` for a supplement alone, so it refuses a supplement whose
243 /// image a hook changed.
244 ///
245 /// In an `archive` repository, the image file is a `.filez` object.
246 /// [`Repo::open_composefs_image`] refuses an `archive` repository.
247 ///
248 /// If the repository already holds the image commit and marks it partial,
249 /// the call does not remove the partial marker. The image commit then
250 /// stays partial, and [`Repo::open_composefs_image`] refuses it.
251 ///
252 /// # Errors
253 ///
254 /// - The errors of
255 /// [`write_composefs_content`](Transaction::write_composefs_content).
256 /// - The errors of [`write_dirmeta`](Transaction::write_dirmeta) and of
257 /// [`write_metadata`](Transaction::write_metadata).
258 pub async fn write_composefs_commit(
259 &self,
260 root: &RepoTree,
261 filter: Option<ComposefsEntryFn<'_>>,
262 ) -> Result<(Checksum, [u8; 32])> {
263 let (commit, _, digest) = self.stage_image_commit(root, filter).await?;
264 Ok((commit, digest))
265 }
266
267 /// Stages the image commit of `root` as
268 /// [`write_composefs_commit`](Transaction::write_composefs_commit) does,
269 /// and returns the checksum of the image commit, the checksum of the file
270 /// object of `root.cfs`, and the fs-verity digest of the image.
271 async fn stage_image_commit(
272 &self,
273 root: &RepoTree,
274 filter: Option<ComposefsEntryFn<'_>>,
275 ) -> Result<(Checksum, Checksum, [u8; 32])> {
276 let meta = FileMeta::regular(0, 0, IMAGE_PERM);
277 let (image, digest) = self
278 .write_composefs_content(root, &ComposefsOptions::RECORDED, filter, &meta)
279 .await?;
280 let root_dirmeta = self
281 .write_dirmeta(&DirMeta {
282 uid: 0,
283 gid: 0,
284 mode: ROOT_DIR_MODE,
285 xattrs: Xattrs::empty(),
286 })
287 .await?;
288 let tree = DirTree {
289 files: vec![(IMAGE_FILE.to_owned(), image)],
290 dirs: Vec::new(),
291 };
292 let root_dirtree = self
293 .write_metadata(ObjectType::DirTree, None, &tree.serialize()?)
294 .await?;
295 let commit = Commit {
296 metadata: Value::Array(Vec::new()),
297 parent: None,
298 related: Vec::new(),
299 subject: IMAGE_SUBJECT.to_owned(),
300 body: String::new(),
301 timestamp: 0,
302 root_dirtree,
303 root_dirmeta,
304 };
305 let checksum = self
306 .write_metadata(ObjectType::Commit, None, &commit.serialize()?)
307 .await?;
308 Ok((checksum, image, digest))
309 }
310}
311
312/// Methods that find and open the composefs image of a commit.
313impl Repo {
314 /// Opens the composefs image of the image commit that `commit` names.
315 ///
316 /// The call returns `None` if `commit` names no image commit.
317 ///
318 /// # Lookup
319 ///
320 /// The call reads the commit object and finds the image commit in this
321 /// order:
322 ///
323 /// 1. The attachment [`COMPOSEFS_RELATION`] of field 2. If the commit has
324 /// it, the call does not read the detached metadata.
325 /// 2. Else the supplement [`COMPOSEFS_RELATION`] of the key
326 /// `ostrya.related` of the detached metadata.
327 ///
328 /// The call checks each entry of field 2, and each entry of
329 /// `ostrya.related` if it reads that key. A
330 /// defective entry fails the call, also if its name is not
331 /// [`COMPOSEFS_RELATION`]. Two entries of the name in one field fail the
332 /// call. If the image commit of the selected entry has a defect, the call
333 /// fails and does not try the other field.
334 ///
335 /// The call does not check the state of `commit`. A partial commit gives
336 /// its image as a complete commit does.
337 ///
338 /// # Checks
339 ///
340 /// The call checks the image commit in this order:
341 ///
342 /// 1. For a supplement, `commit` carries the key
343 /// `ostree.composefs.digest.v0`. The call reads no part of the image
344 /// commit before this check.
345 /// 2. The repository holds the image commit.
346 /// 3. The repository does not mark the image commit partial.
347 /// 4. The root directory holds the entry `root.cfs`.
348 /// 5. The entry `root.cfs` is not a directory.
349 /// 6. The root directory holds no other entry.
350 /// 7. The file object of `root.cfs` is not a symlink.
351 /// 8. If the repository sets `[ex-integrity] fsverity=yes`, the file
352 /// object of `root.cfs` is sealed with fs-verity with SHA-256,
353 /// 4096-byte blocks, no salt, and its full size. This applies to an
354 /// attachment and to a supplement.
355 /// 9. For a supplement, the fs-verity digest of `/root.cfs` is the value
356 /// of the key.
357 ///
358 /// The call does not check the owners, the modes, or the xattrs of the
359 /// image commit.
360 ///
361 /// For an attachment, the call does not read the key and does not
362 /// compare it with the image. The checksum chain from `commit` to the
363 /// image commit, its tree, and `/root.cfs` binds the image to `commit`,
364 /// and the repository checked each object when it wrote it. A labeled
365 /// image, which an entry hook changed, can therefore be an attachment.
366 ///
367 /// The key records the digest of the image that a build of the tree of
368 /// `commit` with no hook gives. For a supplement, the call compares that
369 /// key with the image. It builds no image to check the key. If the file
370 /// object has the seal of step 8, the call reads the digest from the
371 /// kernel. Otherwise it streams the file through the fs-verity hasher in
372 /// chunks of 128 KiB, one time. The call measures the digest through the
373 /// descriptor that it returns. A process that can write the unsealed file
374 /// can change it after the call returns, so the check holds only for the
375 /// bytes that the call read.
376 ///
377 /// The checks guard against damage and against a writer of the
378 /// repository other than the caller. They do not guard against the
379 /// caller, who can write the commit and the image commit.
380 ///
381 /// # Errors
382 ///
383 /// - [`Error::Unsupported`] if the repository is in `archive` mode. The
384 /// call refuses this mode before it reads a file.
385 /// - [`Error::ObjectNotFound`] if the repository does not hold the commit
386 /// object of `commit`.
387 /// - [`Error::Core`] if the commit tuple does not frame, if field 2 does
388 /// not decode, if the detached metadata does not parse, or if a commit
389 /// object or the root dirtree of the image commit does not parse.
390 /// - [`Error::InvalidRelations`] with `commit` and the field, if an entry
391 /// of field 2 or of `ostrya.related` has an empty name or a checksum
392 /// that is not 32 bytes, if the value of `ostrya.related` is not a
393 /// variant of type `a(say)`, or if two entries of one field have the
394 /// name [`COMPOSEFS_RELATION`].
395 /// - [`Error::InvalidFormat`] if `commit` names a supplement and the
396 /// first entry of `ostree.composefs.digest.v0` is not a variant of type
397 /// `ay` with 32 bytes.
398 /// - The errors of [`RepoConfig::fsverity`](crate::RepoConfig::fsverity),
399 /// if `commit` names an image commit. If `commit` names no image commit,
400 /// the call does not read `[ex-integrity] fsverity`.
401 /// - [`Error::InvalidComposefsImage`] with `commit`, the source, the
402 /// image commit, and the [`ComposefsImageDefect`], if a check fails.
403 /// - [`Error::ObjectNotFound`] if the repository holds the image commit
404 /// complete and does not hold its root dirtree or the file object of
405 /// `root.cfs`.
406 /// - [`Error::InvalidFormat`] if a metadata object is larger than
407 /// [`MAX_METADATA_SIZE`](crate::MAX_METADATA_SIZE) or is not a regular
408 /// file, if a symlink is on its path, or if the file object does not
409 /// have the form of the repository mode. [`Repo::load_file`] lists the
410 /// cases.
411 /// - [`Error::Io`] if a read of the image or another file system
412 /// operation fails.
413 pub async fn open_composefs_image(&self, commit: &Checksum) -> Result<Option<ComposefsImage>> {
414 if self.mode().is_archive() {
415 return Err(archive_refusal());
416 }
417 let repo = self.clone();
418 let key = *commit;
419 ostrya_rt::unblock(move || {
420 let Some(named) = repo.named_image_blocking(&key)? else {
421 return Ok(None);
422 };
423 let require_seal = repo.requires_sealed_image()?;
424 let (file, size) = repo.check_raw_image_blocking(
425 &key,
426 named.source,
427 &named.image,
428 named.key,
429 require_seal,
430 )?;
431 Ok(Some(ComposefsImage {
432 file,
433 size,
434 source: named.source,
435 commit: named.image,
436 }))
437 })
438 .await
439 }
440
441 /// Writes the composefs image commit of `commit` and names it as the
442 /// supplement [`COMPOSEFS_RELATION`] of `commit`, if the commit has no
443 /// valid image commit.
444 ///
445 /// The call begins a transaction before it reads the commit, so a prune
446 /// cannot remove the commit or its objects during the build. It then
447 /// makes these steps in this order:
448 ///
449 /// 1. If field 2 of the commit has the attachment
450 /// [`COMPOSEFS_RELATION`], the call refuses the commit. It does not
451 /// check the attachment.
452 /// 2. If the commit carries no key `ostree.composefs.digest.v0`, the call
453 /// refuses the commit. [`open_composefs_image`](Repo::open_composefs_image)
454 /// refuses a supplement of such a commit.
455 /// [`Repo::commit_add_composefs_metadata`] stages a commit that carries
456 /// the key.
457 /// 3. If the commit has the supplement [`COMPOSEFS_RELATION`], the call
458 /// checks its image commit with the checks of
459 /// [`open_composefs_image`](Repo::open_composefs_image). If the image
460 /// commit passes, the call writes nothing and gives
461 /// [`ComposefsSupplementAdd::Valid`]. If a check fails with
462 /// [`Error::InvalidComposefsImage`], the call writes the entry again in
463 /// step 7. Thus the call replaces an entry that names another image
464 /// commit, an image commit that the repository does not hold or holds
465 /// partial, or an image commit whose tree has a defect. For the defect
466 /// [`ComposefsImageDefect::NotSealed`], the call first streams the file
467 /// through the fs-verity hasher. If the digest is the value of the key,
468 /// the build gives the same object, so the call refuses the commit with
469 /// this defect.
470 /// 4. The call builds the image of the tree of the commit with
471 /// [`ComposefsOptions::RECORDED`] and stages the image commit with
472 /// [`Transaction::write_composefs_commit`].
473 /// 5. If the fs-verity digest of the image is not the value of the key,
474 /// the call refuses the commit with [`Error::ComposefsDigestMismatch`].
475 /// The call builds the image with no hook, so it refuses a commit whose
476 /// key records the digest of an image that a hook changed.
477 /// 6. If the repository sets `[ex-integrity] fsverity=yes`, the file
478 /// object of `/root.cfs` of the built image commit must have the seal
479 /// of [`open_composefs_image`](Repo::open_composefs_image). If it has
480 /// no seal, the call refuses the commit with
481 /// [`Error::InvalidComposefsImage`] and
482 /// [`ComposefsImageDefect::NotSealed`].
483 /// 7. The call sets the supplement [`COMPOSEFS_RELATION`] of the commit
484 /// to the image commit, as [`Transaction::add_supplement`] does, and
485 /// commits the transaction.
486 /// 8. If the repository marked the image commit partial before the call,
487 /// the call removes the partial marker. After the commit of the
488 /// transaction, the repository holds each object of the image commit.
489 ///
490 /// The transaction does not write an object that the repository already
491 /// holds. If the entry names the image commit that the build gives, and
492 /// the file object of its `/root.cfs` is changed on disk, the check of
493 /// step 3 fails and the build gives the same image commit. The call then
494 /// gives [`ComposefsSupplementAdd::Written`] with this image commit as
495 /// `replaced`, and the changed object stays. A changed object is a defect
496 /// that [`Repo::fsck`] reports. With `[ex-integrity] fsverity=yes`, step 6
497 /// refuses such an object if it has no seal.
498 ///
499 /// An object that the repository wrote before it set `fsverity=yes` can
500 /// have no seal. The transaction does not write such an object again, so
501 /// the build does not seal it. With `fsverity=yes`, step 3 or step 6
502 /// refuses it, and the call writes nothing.
503 ///
504 /// The checks of step 3 work in each repository mode. In `archive` mode,
505 /// the call inflates the image and streams it through the fs-verity
506 /// hasher. Steps 3 and 6 apply no seal rule in `archive` mode. The call
507 /// writes the image commit in each mode. In `archive` mode, the image
508 /// file is a `.filez` object, and
509 /// [`open_composefs_image`](Repo::open_composefs_image) refuses the
510 /// repository.
511 ///
512 /// The call does not check the state of `commit`. If an object of its
513 /// tree is absent, the build fails.
514 ///
515 /// On a refusal or an error before the commit of the transaction, the
516 /// call writes nothing.
517 ///
518 /// # Errors
519 ///
520 /// - The errors of [`Repo::transaction`].
521 /// - The errors of [`RepoConfig::fsverity`](crate::RepoConfig::fsverity).
522 /// - The errors of [`Repo::load_object_bytes`] for the commit object.
523 /// - [`Error::Core`] if the commit object does not parse.
524 /// - [`Error::InvalidFormat`] if the first entry of
525 /// `ostree.composefs.digest.v0` is not a variant of type `ay` with 32
526 /// bytes.
527 /// - [`Error::InvalidRelations`] with `commit` and the field, if an entry
528 /// of field 2 or of `ostrya.related` is defective, or if two entries of
529 /// one field have the name [`COMPOSEFS_RELATION`].
530 /// - [`Error::InvalidInput`] if field 2 of the commit has the attachment
531 /// [`COMPOSEFS_RELATION`], or if the commit carries no key
532 /// `ostree.composefs.digest.v0`.
533 /// - [`Error::InvalidComposefsImage`] with
534 /// [`ComposefsImageDefect::NotSealed`] if the check of step 3 finds a
535 /// `/root.cfs` with no seal whose digest is the value of the key, under
536 /// `[ex-integrity] fsverity=yes`.
537 /// - The errors of the checks of step 3 other than
538 /// [`Error::InvalidComposefsImage`], as
539 /// [`open_composefs_image`](Repo::open_composefs_image) lists them.
540 /// - The errors of [`Transaction::write_composefs_commit`]. The build
541 /// fails with [`Error::ObjectNotFound`] if an object of the tree is
542 /// absent.
543 /// - [`Error::ComposefsDigestMismatch`] if the digest of the image is not
544 /// the value of the key.
545 /// - [`Error::InvalidComposefsImage`] with
546 /// [`ComposefsImageDefect::NotSealed`] if the check of step 6 finds a
547 /// `/root.cfs` with no seal.
548 /// - The errors of [`Repo::load_file`] for the file object of `/root.cfs`
549 /// in step 6.
550 /// - The errors of [`Transaction::commit`].
551 /// - The error of the removal of the partial marker.
552 pub async fn add_composefs_supplement(
553 &self,
554 commit: &Checksum,
555 ) -> Result<ComposefsSupplementAdd> {
556 let txn = self.transaction().await?;
557 let (result, was_partial) = match self.stage_composefs_supplement(&txn, commit).await {
558 Ok(staged) => staged,
559 Err(e) => {
560 txn.abort().await?;
561 return Err(e);
562 }
563 };
564 let ComposefsSupplementAdd::Written { image, .. } = result else {
565 txn.abort().await?;
566 return Ok(result);
567 };
568 let fsync = txn.fsync_flags().0;
569 txn.commit().await?;
570 if was_partial {
571 let failed = self.remove_partial_markers(vec![image], fsync).await?;
572 if let Some((_, e)) = failed.into_iter().next() {
573 return Err(e);
574 }
575 }
576 Ok(result)
577 }
578
579 /// Runs the steps of
580 /// [`add_composefs_supplement`](Repo::add_composefs_supplement) up to the
581 /// commit of `txn`.
582 ///
583 /// For [`ComposefsSupplementAdd::Written`], the call stages the image
584 /// commit and queues the supplement in `txn`. The second value is `true`
585 /// if the repository marked the image commit partial before the call.
586 /// For [`ComposefsSupplementAdd::Valid`], the call stages nothing.
587 async fn stage_composefs_supplement(
588 &self,
589 txn: &Transaction,
590 commit: &Checksum,
591 ) -> Result<(ComposefsSupplementAdd, bool)> {
592 let repo = self.clone();
593 let read_commit = *commit;
594 let read = ostrya_rt::unblock(move || repo.supplement_state_blocking(&read_commit)).await?;
595 let replaced = match read.state {
596 SupplementState::Valid(image) => {
597 return Ok((ComposefsSupplementAdd::Valid { image }, false));
598 }
599 SupplementState::Build { replaced } => replaced,
600 };
601 let root = RepoTree::from_parts(self.clone(), read.root_dirtree, read.root_dirmeta);
602 let (image, file, digest) = txn.stage_image_commit(&root, None).await?;
603 if read.key != digest {
604 return Err(Error::ComposefsDigestMismatch {
605 commit: *commit,
606 expected: read.key,
607 actual: digest,
608 });
609 }
610 if read.require_seal && !self.mode().is_archive() {
611 let object = txn.load_file_staged_first_with(&file, true).await?;
612 if object.kernel_fs_verity().is_none() {
613 return Err(invalid_image(
614 commit,
615 ComposefsImageSource::Supplement,
616 &image,
617 ComposefsImageDefect::NotSealed,
618 ));
619 }
620 }
621 let was_partial = self.commit_state(&image).await? == CommitState::Partial;
622 txn.add_supplement(commit, COMPOSEFS_RELATION, &image)?;
623 Ok((
624 ComposefsSupplementAdd::Written { image, replaced },
625 was_partial,
626 ))
627 }
628
629 /// Reads the commit object of `commit` one time and gives the parts of it
630 /// that [`add_composefs_supplement`](Repo::add_composefs_supplement) uses:
631 /// the root of its tree, the value of the key
632 /// `ostree.composefs.digest.v0`, and the state of its supplement
633 /// [`COMPOSEFS_RELATION`].
634 ///
635 /// The call checks the attachments of the parsed commit and refuses a
636 /// commit whose field 2 has the attachment [`COMPOSEFS_RELATION`]. It
637 /// then refuses a commit that carries no key. Only then does it read the
638 /// detached metadata. If the commit has the supplement, the call checks
639 /// its image commit with
640 /// [`check_composefs_commit_blocking`](Repo::check_composefs_commit_blocking).
641 /// A defect gives [`SupplementState::Build`]. For
642 /// [`ComposefsImageDefect::NotSealed`], the call checks the image again
643 /// with no seal rule, which hashes the file. If the digest is the value
644 /// of the key, the call gives the `NotSealed` error. The reads block the
645 /// thread, so an async caller runs this call on the blocking pool.
646 fn supplement_state_blocking(&self, commit: &Checksum) -> Result<SupplementRead> {
647 let require_seal = self.requires_sealed_image()?;
648 let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
649 let parsed = Commit::parse(&bytes)?;
650 let key = recorded_digest(&parsed)?;
651 if let Some(image) = attached_image(commit, related::entries_of(&parsed.related))? {
652 return Err(Error::InvalidInput(format!(
653 "commit {commit} names its composefs image commit {image} as an \
654 attachment; a supplement is not written"
655 )));
656 }
657 let Some(key) = key else {
658 return Err(Error::InvalidInput(format!(
659 "commit {commit} carries no {COMPOSEFS_DIGEST_KEY}; a supplement is not \
660 written (Repo::commit_add_composefs_metadata stages a commit that carries \
661 the key)"
662 )));
663 };
664 let read = |state| SupplementRead {
665 root_dirtree: parsed.root_dirtree,
666 root_dirmeta: parsed.root_dirmeta,
667 key,
668 require_seal,
669 state,
670 };
671 let Some(image) = self.supplemented_image_blocking(commit)? else {
672 return Ok(read(SupplementState::Build { replaced: None }));
673 };
674 let source = ComposefsImageSource::Supplement;
675 let check =
676 |seal| self.check_composefs_commit_blocking(commit, source, &image, Some(key), seal);
677 let replace = || {
678 read(SupplementState::Build {
679 replaced: Some(image),
680 })
681 };
682 match check(require_seal) {
683 Ok(_) => Ok(read(SupplementState::Valid(image))),
684 // The hash of the file tells a wrong image, which the build
685 // replaces, from the image of the key, which the build gives again
686 // with the same object.
687 Err(e) if is_not_sealed(&e) => match check(false) {
688 Ok(_) => Err(e),
689 Err(Error::InvalidComposefsImage { .. }) => Ok(replace()),
690 Err(other) => Err(other),
691 },
692 Err(Error::InvalidComposefsImage { .. }) => Ok(replace()),
693 Err(e) => Err(e),
694 }
695 }
696
697 /// Reads the commit `commit` and returns the image commit that it names,
698 /// as [`open_composefs_image`](Repo::open_composefs_image) selects it,
699 /// with the value of the key `ostree.composefs.digest.v0` of `commit`.
700 ///
701 /// The call parses the key only if `commit` names a supplement. For an
702 /// attachment, the key of the result is `None`. The reads and the parse
703 /// block the thread, so an async caller runs this call on the blocking
704 /// pool.
705 fn named_image_blocking(&self, commit: &Checksum) -> Result<Option<NamedImage>> {
706 let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
707 let Some((source, image)) = self.named_entry_blocking(commit, &bytes)? else {
708 return Ok(None);
709 };
710 let key = match source {
711 ComposefsImageSource::Attachment => None,
712 ComposefsImageSource::Supplement => recorded_digest(&Commit::parse(&bytes)?)?,
713 };
714 Ok(Some(NamedImage { source, image, key }))
715 }
716
717 /// Returns the field and the checksum of the image commit that the commit
718 /// `commit` names, as
719 /// [`open_composefs_image`](Repo::open_composefs_image) selects it.
720 /// `bytes` are the bytes of the commit object of `commit`.
721 ///
722 /// The call reads the detached metadata only if field 2 has no entry
723 /// [`COMPOSEFS_RELATION`]. The read blocks the thread, so an async caller
724 /// runs this call on the blocking pool.
725 fn named_entry_blocking(
726 &self,
727 commit: &Checksum,
728 bytes: &[u8],
729 ) -> Result<Option<(ComposefsImageSource, Checksum)>> {
730 if let Some(image) = attached_image(commit, related::parse_attachments(bytes)?)? {
731 return Ok(Some((ComposefsImageSource::Attachment, image)));
732 }
733 Ok(self
734 .supplemented_image_blocking(commit)?
735 .map(|image| (ComposefsImageSource::Supplement, image)))
736 }
737
738 /// Returns the checksum of the image commit that the supplement
739 /// [`COMPOSEFS_RELATION`] of `commit` names, or `None` if `commit` has no
740 /// such supplement.
741 ///
742 /// The call reads the detached metadata of `commit` and checks each entry
743 /// of `ostrya.related`. The read blocks the thread, so an async caller
744 /// runs this call on the blocking pool.
745 fn supplemented_image_blocking(&self, commit: &Checksum) -> Result<Option<Checksum>> {
746 let detached = self.read_supplement_dict_blocking(commit)?;
747 let supplements = related::supplements(detached.as_ref())
748 .map_err(|reason| Error::InvalidRelations {
749 commit: Some(*commit),
750 field: RelationField::Supplements,
751 reason,
752 })?
753 .map(|entries| {
754 related::checked_entries(RelationField::Supplements, Some(*commit), entries)
755 })
756 .transpose()?
757 .unwrap_or_default();
758 composefs_entry(commit, RelationField::Supplements, &supplements)
759 }
760
761 /// Checks the image commit `image`, which `commit` names in the field
762 /// `relation`, by the checks of
763 /// [`open_composefs_image`](Repo::open_composefs_image). `key` is the
764 /// value of the key `ostree.composefs.digest.v0` of `commit`, or `None`
765 /// if `commit` carries no key. The call uses `key` for a supplement
766 /// alone. `require_seal` is the seal rule of `[ex-integrity]
767 /// fsverity=yes`.
768 ///
769 /// The call works in each repository mode. In a mode other than
770 /// `archive`, it returns the file object of `root.cfs`, open read-only at
771 /// offset 0, and its size. In `archive` mode, it returns `None` and
772 /// applies no seal rule. For a supplement, it first streams the inflated
773 /// payload through the fs-verity hasher in chunks of 128 KiB. For an
774 /// attachment, it reads no byte of the payload. The reads block the
775 /// thread, so an async caller runs this call on the blocking pool.
776 ///
777 /// # Errors
778 ///
779 /// [`Error::InvalidComposefsImage`] with `commit`, `relation`, `image`,
780 /// and the defect, and the errors of the reads that
781 /// [`open_composefs_image`](Repo::open_composefs_image) lists.
782 fn check_composefs_commit_blocking(
783 &self,
784 commit: &Checksum,
785 relation: ComposefsImageSource,
786 image: &Checksum,
787 key: Option<[u8; 32]>,
788 require_seal: bool,
789 ) -> Result<Option<(std::fs::File, u64)>> {
790 if !self.mode().is_archive() {
791 return self
792 .check_raw_image_blocking(commit, relation, image, key, require_seal)
793 .map(Some);
794 }
795 let expected = expected_digest(commit, relation, image, key)?;
796 let (object, payload) = self.image_file_blocking(commit, relation, image, false)?;
797 let Some(expected) = expected else {
798 return Ok(None);
799 };
800 let Some((file, len)) = payload else {
801 return Err(no_payload(&object));
802 };
803 let actual = inflated_digest_blocking(file, len)?;
804 check_digest(&expected, &actual)
805 .map_err(|defect| invalid_image(commit, relation, image, defect))?;
806 Ok(None)
807 }
808
809 /// Checks the image commit `image` as
810 /// [`check_composefs_commit_blocking`](Repo::check_composefs_commit_blocking) does in a mode
811 /// other than `archive`, and returns the file object of `root.cfs`, open
812 /// read-only at offset 0, and its size.
813 ///
814 /// If `require_seal` is set, the file object must have the fs-verity
815 /// seal that the kernel gives the digest of. For a supplement, the digest
816 /// of the file comes from the kernel when the load of the object gives
817 /// one. Else the call streams the file through the fs-verity hasher in
818 /// chunks of 128 KiB and seeks back to offset 0. The reads block the
819 /// thread, so an async caller runs this call on the blocking pool.
820 fn check_raw_image_blocking(
821 &self,
822 commit: &Checksum,
823 relation: ComposefsImageSource,
824 image: &Checksum,
825 key: Option<[u8; 32]>,
826 require_seal: bool,
827 ) -> Result<(std::fs::File, u64)> {
828 use std::io::{Seek, SeekFrom};
829
830 let expected = expected_digest(commit, relation, image, key)?;
831 let measure = require_seal || expected.is_some();
832 let (object, payload) = self.image_file_blocking(commit, relation, image, measure)?;
833 let Some((mut file, size)) = payload else {
834 return Err(no_payload(&object));
835 };
836 if require_seal && object.kernel_fs_verity().is_none() {
837 return Err(invalid_image(
838 commit,
839 relation,
840 image,
841 ComposefsImageDefect::NotSealed,
842 ));
843 }
844 let Some(expected) = expected else {
845 return Ok((file, size));
846 };
847 let actual = match object.kernel_fs_verity() {
848 Some(digest) => digest,
849 None => {
850 let digest = image_file_digest(&mut file)?;
851 file.seek(SeekFrom::Start(0))?;
852 digest
853 }
854 };
855 check_digest(&expected, &actual)
856 .map_err(|defect| invalid_image(commit, relation, image, defect))?;
857 Ok((file, size))
858 }
859
860 /// Returns `true` if the repository sets `[ex-integrity] fsverity=yes`.
861 /// The lookup then requires a sealed `/root.cfs`.
862 ///
863 /// # Errors
864 ///
865 /// The errors of [`RepoConfig::fsverity`](crate::RepoConfig::fsverity).
866 fn requires_sealed_image(&self) -> Result<bool> {
867 Ok(self.config().fsverity()? == Tristate::Yes)
868 }
869
870 /// Runs the checks of the image commit `image` up to the type of the file
871 /// object of `root.cfs`, and returns that object with its object file,
872 /// open at the start of its payload.
873 ///
874 /// If `measure` is set, the load of the object also reads the fs-verity
875 /// digest that the kernel holds for it. The reads block the thread, so an
876 /// async caller runs this call on the blocking pool.
877 fn image_file_blocking(
878 &self,
879 commit: &Checksum,
880 relation: ComposefsImageSource,
881 image: &Checksum,
882 measure: bool,
883 ) -> Result<(FileObject, Option<Payload>)> {
884 let invalid = |defect| invalid_image(commit, relation, image, defect);
885 let Some(bytes) = self.held_object_bytes_blocking(ObjectType::Commit, image)? else {
886 return Err(invalid(ComposefsImageDefect::Absent));
887 };
888 if self.commit_state_blocking(image)? == CommitState::Partial {
889 return Err(invalid(ComposefsImageDefect::Partial));
890 }
891 let root = Commit::parse(&bytes)?.root_dirtree;
892 let tree = DirTree::parse(&self.load_object_bytes_blocking(ObjectType::DirTree, &root)?)?;
893 let file = image_entry(&tree).map_err(invalid)?;
894 let (object, payload) = self.open_file_blocking(&file, measure)?;
895 if !matches!(object.kind, FileKind::Regular { .. }) {
896 return Err(invalid(ComposefsImageDefect::NotRegular));
897 }
898 Ok((object, payload))
899 }
900}
901
902/// The parts of a commit that [`Repo::add_composefs_supplement`] uses, from
903/// [`Repo::supplement_state_blocking`].
904struct SupplementRead {
905 /// The checksum of the root dirtree of the commit.
906 root_dirtree: Checksum,
907 /// The checksum of the root dirmeta of the commit.
908 root_dirmeta: Checksum,
909 /// The value of the key `ostree.composefs.digest.v0` of the commit.
910 key: [u8; 32],
911 /// `true` if the repository sets `[ex-integrity] fsverity=yes`.
912 require_seal: bool,
913 /// The state of the supplement [`COMPOSEFS_RELATION`] of the commit.
914 state: SupplementState,
915}
916
917/// The state of the supplement [`COMPOSEFS_RELATION`] of a commit, from
918/// [`Repo::supplement_state_blocking`].
919enum SupplementState {
920 /// The supplement names this image commit, and the image commit passes
921 /// the checks.
922 Valid(Checksum),
923 /// The call builds the image commit. `replaced` is the image commit that
924 /// the supplement names and that fails a check, or `None` if the commit
925 /// has no supplement.
926 Build { replaced: Option<Checksum> },
927}
928
929/// The image commit that a commit names, from
930/// [`Repo::named_image_blocking`].
931struct NamedImage {
932 /// The field of the commit that names the image commit.
933 source: ComposefsImageSource,
934 /// The checksum of the image commit.
935 image: Checksum,
936 /// The value of the key `ostree.composefs.digest.v0` of the commit for a
937 /// supplement, or `None` if the commit does not carry the key or names
938 /// an attachment.
939 key: Option<[u8; 32]>,
940}
941
942/// Returns the error of the defect `defect` of the image commit `image`,
943/// which `commit` names in the field `relation`.
944fn invalid_image(
945 commit: &Checksum,
946 relation: ComposefsImageSource,
947 image: &Checksum,
948 defect: ComposefsImageDefect,
949) -> Error {
950 Error::InvalidComposefsImage {
951 commit: *commit,
952 relation,
953 image: *image,
954 defect: Box::new(defect),
955 }
956}
957
958/// Returns the error of the file object `object` of `/root.cfs` that the load
959/// gives with no payload.
960fn no_payload(object: &FileObject) -> Error {
961 Error::InvalidFormat(format!(
962 "the file object {} of /{IMAGE_FILE} has no payload",
963 object.checksum()
964 ))
965}
966
967/// Returns the error of a lookup of the composefs image in an `archive`
968/// repository.
969fn archive_refusal() -> Error {
970 Error::Unsupported(
971 "the lookup of a composefs image refuses an archive repository: it stores \
972 /root.cfs compressed, and a mount needs the raw image"
973 .into(),
974 )
975}
976
977/// Returns the checksum of the image commit that the attachment
978/// [`COMPOSEFS_RELATION`] of `commit` names, or `None` if `commit` has no
979/// such attachment. `entries` are the entries of field 2 of `commit`.
980///
981/// # Errors
982///
983/// [`Error::InvalidRelations`] with `commit` and
984/// [`RelationField::Attachments`] if an entry is defective, or if two or more
985/// entries have the name.
986fn attached_image(
987 commit: &Checksum,
988 entries: Vec<related::RelatedEntry>,
989) -> Result<Option<Checksum>> {
990 let attachments = related::checked_entries(RelationField::Attachments, Some(*commit), entries)?;
991 composefs_entry(commit, RelationField::Attachments, &attachments)
992}
993
994/// Returns `true` if `error` is the refusal of an image commit whose
995/// `/root.cfs` has no fs-verity seal.
996fn is_not_sealed(error: &Error) -> bool {
997 matches!(
998 error,
999 Error::InvalidComposefsImage { defect, .. } if **defect == ComposefsImageDefect::NotSealed
1000 )
1001}
1002
1003/// Returns the checksum of the entry [`COMPOSEFS_RELATION`] of `entries`, the
1004/// checked entries of the field `field` of `commit`, or `None` if no entry
1005/// has the name.
1006///
1007/// # Errors
1008///
1009/// [`Error::InvalidRelations`] with `commit` and `field` if two or more
1010/// entries have the name.
1011fn composefs_entry(
1012 commit: &Checksum,
1013 field: RelationField,
1014 entries: &[(String, Checksum)],
1015) -> Result<Option<Checksum>> {
1016 let mut named = entries
1017 .iter()
1018 .filter(|(name, _)| name == COMPOSEFS_RELATION);
1019 let first = named.next().map(|(_, checksum)| *checksum);
1020 if named.next().is_some() {
1021 return Err(Error::InvalidRelations {
1022 commit: Some(*commit),
1023 field,
1024 reason: format!("two or more entries have the name {COMPOSEFS_RELATION}"),
1025 });
1026 }
1027 Ok(first)
1028}
1029
1030/// Returns the checksum of the file object of `root.cfs` in `tree`, the root
1031/// dirtree of an image commit, or the structural defect of the tree.
1032///
1033/// A tree with no entry `root.cfs` gives [`ComposefsImageDefect::NoImageFile`],
1034/// a directory `root.cfs` gives [`ComposefsImageDefect::NotRegular`], and
1035/// each other entry gives [`ComposefsImageDefect::ExtraEntry`], in this order.
1036fn image_entry(tree: &DirTree) -> std::result::Result<Checksum, ComposefsImageDefect> {
1037 let file = tree
1038 .files
1039 .iter()
1040 .find(|(name, _)| name == IMAGE_FILE)
1041 .map(|(_, checksum)| *checksum);
1042 let dir = tree.dirs.iter().any(|(name, _, _)| name == IMAGE_FILE);
1043 if file.is_none() && !dir {
1044 return Err(ComposefsImageDefect::NoImageFile);
1045 }
1046 if dir {
1047 return Err(ComposefsImageDefect::NotRegular);
1048 }
1049 let extra = tree
1050 .files
1051 .iter()
1052 .map(|(name, _)| name)
1053 .chain(tree.dirs.iter().map(|(name, _, _)| name))
1054 .find(|name| *name != IMAGE_FILE);
1055 if let Some(name) = extra {
1056 return Err(ComposefsImageDefect::ExtraEntry(name.clone()));
1057 }
1058 Ok(file.expect("the tree holds the file root.cfs"))
1059}
1060
1061/// Returns the digest that the lookup compares with the digest of
1062/// `/root.cfs` of the image commit `image`, which `commit` names in the field
1063/// `relation`. `key` is the value of the key `ostree.composefs.digest.v0` of
1064/// `commit`.
1065///
1066/// An attachment gives `None`: the lookup does not compare the key with an
1067/// attachment. A supplement gives the key.
1068///
1069/// # Errors
1070///
1071/// [`Error::InvalidComposefsImage`] with [`ComposefsImageDefect::NoKey`] for
1072/// a supplement and no key.
1073fn expected_digest(
1074 commit: &Checksum,
1075 relation: ComposefsImageSource,
1076 image: &Checksum,
1077 key: Option<[u8; 32]>,
1078) -> Result<Option<[u8; 32]>> {
1079 match relation {
1080 ComposefsImageSource::Attachment => Ok(None),
1081 ComposefsImageSource::Supplement => key
1082 .map(Some)
1083 .ok_or_else(|| invalid_image(commit, relation, image, ComposefsImageDefect::NoKey)),
1084 }
1085}
1086
1087/// Refuses `actual`, the fs-verity digest of `/root.cfs`, with
1088/// [`ComposefsImageDefect::DigestMismatch`] if it is not `expected`.
1089fn check_digest(
1090 expected: &[u8; 32],
1091 actual: &[u8; 32],
1092) -> std::result::Result<(), ComposefsImageDefect> {
1093 if actual == expected {
1094 return Ok(());
1095 }
1096 Err(ComposefsImageDefect::DigestMismatch {
1097 expected: *expected,
1098 actual: *actual,
1099 })
1100}
1101
1102/// Returns the fs-verity digest of the inflated payload of an `archive`
1103/// object. `file` is open at the start of the raw-DEFLATE stream, and `len`
1104/// is the number of bytes from there to the end of the file.
1105///
1106/// The call reads the stream in bounded chunks and hashes the inflated bytes
1107/// in chunks of 128 KiB. The reads block the thread, so an async caller runs
1108/// this call on the blocking pool.
1109fn inflated_digest_blocking(file: std::fs::File, len: u64) -> Result<[u8; 32]> {
1110 use futures_lite::AsyncReadExt;
1111
1112 let source = BufSource::with_len_hint(futures_lite::io::AssertAsync::new(file), len);
1113 let mut decoder = DeflateDecoder::new(source);
1114 let mut hasher = ostrya_composefs::FsVerityHasher::new();
1115 let mut buf = vec![0u8; DIGEST_CHUNK];
1116 // The reader over a blocking file never returns `Pending`, so `block_on`
1117 // drives it on this thread with no executor.
1118 futures_lite::future::block_on(async {
1119 loop {
1120 let n = decoder.read(&mut buf).await.map_err(Error::Io)?;
1121 if n == 0 {
1122 return Ok::<(), Error>(());
1123 }
1124 hasher.update(&buf[..n]);
1125 }
1126 })?;
1127 Ok(hasher.finalize())
1128}
1129
1130/// Compile-time checks that [`ComposefsImage`] is `Send + Sync` and that the
1131/// futures of the calls of this module are `Send`.
1132const _: fn() = || {
1133 fn assert_send_sync<T: Send + Sync>() {}
1134 fn assert_send<T: Send>(_: &T) {}
1135 assert_send_sync::<ComposefsImage>();
1136 assert_send_sync::<ComposefsImageDefect>();
1137 let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.open_composefs_image(commit));
1138 let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.add_composefs_supplement(commit));
1139 let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>| {
1140 assert_send(&txn.write_composefs_commit(root, Some(filter)));
1141 };
1142 let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>, meta: &FileMeta| {
1143 assert_send(&txn.write_composefs_content(
1144 root,
1145 &ComposefsOptions::RECORDED,
1146 Some(filter),
1147 meta,
1148 ));
1149 };
1150};
1151
1152#[cfg(test)]
1153mod tests {
1154 use ostrya_core::{Checksum, DirMeta, DirTree, ObjectType, RepoMode, Xattrs};
1155 use ostrya_rt::block_on;
1156
1157 use super::{ComposefsImageDefect, ComposefsImageSource, ROOT_DIR_MODE};
1158 use crate::tree::RepoTree;
1159 use crate::{CreateOptions, Error, FileMeta, Repo};
1160
1161 /// In an `archive` repository, the check of a supplement hashes the
1162 /// inflated payload of `root.cfs`, refuses a key that is not its digest
1163 /// and a commit with no key, and gives no descriptor.
1164 #[test]
1165 fn the_check_hashes_the_inflated_image_in_archive_mode() {
1166 let path = std::env::temp_dir().join(format!(
1167 "ostrya-image-commit-archive-{}-{}",
1168 std::process::id(),
1169 crate::write::unique()
1170 ));
1171 let _ = std::fs::remove_dir_all(&path);
1172 block_on(async {
1173 let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
1174 .await
1175 .unwrap();
1176 let txn = repo.transaction().await.unwrap();
1177 let file = txn
1178 .write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"payload\n")
1179 .await
1180 .unwrap();
1181 let dirmeta = txn
1182 .write_dirmeta(&DirMeta {
1183 uid: 0,
1184 gid: 0,
1185 mode: ROOT_DIR_MODE,
1186 xattrs: Xattrs::empty(),
1187 })
1188 .await
1189 .unwrap();
1190 let tree = DirTree {
1191 files: vec![("a".to_owned(), file)],
1192 dirs: Vec::new(),
1193 };
1194 let dirtree = txn
1195 .write_metadata(ObjectType::DirTree, None, &tree.serialize().unwrap())
1196 .await
1197 .unwrap();
1198 let root = RepoTree::from_parts(repo.clone(), dirtree, dirmeta);
1199 let (image, digest) = txn.write_composefs_commit(&root, None).await.unwrap();
1200 txn.commit().await.unwrap();
1201
1202 let commit = Checksum::from_bytes([1; 32]);
1203 let source = ComposefsImageSource::Supplement;
1204 let checked = repo
1205 .check_composefs_commit_blocking(&commit, source, &image, Some(digest), false)
1206 .unwrap();
1207 assert!(checked.is_none());
1208 let wrong = [0x11; 32];
1209 let refusals = [
1210 (
1211 Some(wrong),
1212 ComposefsImageDefect::DigestMismatch {
1213 expected: wrong,
1214 actual: digest,
1215 },
1216 ),
1217 (None, ComposefsImageDefect::NoKey),
1218 ];
1219 for (key, expected) in refusals {
1220 match repo
1221 .check_composefs_commit_blocking(&commit, source, &image, key, false)
1222 .unwrap_err()
1223 {
1224 Error::InvalidComposefsImage { defect, .. } => assert_eq!(*defect, expected),
1225 other => panic!("expected InvalidComposefsImage, got {other:?}"),
1226 }
1227 }
1228 });
1229 let _ = std::fs::remove_dir_all(&path);
1230 }
1231}