use ostrya_core::{Checksum, Commit, DirMeta, DirTree, ObjectType, Value, Xattrs};
use async_compression::futures::bufread::DeflateDecoder;
use crate::composefs::{
COMPOSEFS_DIGEST_KEY, ComposefsEntryFn, ComposefsOptions, DIGEST_CHUNK, digest_hex,
image_file_digest, recorded_digest,
};
use crate::config::Tristate;
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject, Payload};
use crate::inflate::BufSource;
use crate::read::CommitState;
use crate::related::{self, RelationField};
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::tree::RepoTree;
use crate::write::FileMeta;
pub const COMPOSEFS_RELATION: &str = "composefs";
const IMAGE_FILE: &str = "root.cfs";
const IMAGE_SUBJECT: &str = "composefs image";
const IMAGE_PERM: u32 = 0o400;
const ROOT_DIR_MODE: u32 = 0o040755;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsImageSource {
Attachment,
Supplement,
}
impl std::fmt::Display for ComposefsImageSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
ComposefsImageSource::Attachment => "attachment",
ComposefsImageSource::Supplement => "supplement",
})
}
}
#[derive(Debug)]
pub struct ComposefsImage {
pub file: std::fs::File,
pub size: u64,
pub source: ComposefsImageSource,
pub commit: Checksum,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposefsSupplementAdd {
Valid {
image: Checksum,
},
Written {
image: Checksum,
replaced: Option<Checksum>,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ComposefsImageDefect {
NoKey,
Absent,
Partial,
NoImageFile,
NotRegular,
ExtraEntry(String),
NotSealed,
DigestMismatch {
expected: [u8; 32],
actual: [u8; 32],
},
}
impl std::fmt::Display for ComposefsImageDefect {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ComposefsImageDefect::NoKey => {
f.write_str("and the commit carries no ostree.composefs.digest.v0")
}
ComposefsImageDefect::Absent => f.write_str(related::ABSENT_REASON),
ComposefsImageDefect::Partial => f.write_str(related::PARTIAL_REASON),
ComposefsImageDefect::NoImageFile => write!(f, "whose tree holds no /{IMAGE_FILE}"),
ComposefsImageDefect::NotRegular => {
write!(f, "whose /{IMAGE_FILE} is not a regular file")
}
ComposefsImageDefect::ExtraEntry(name) => {
write!(f, "whose tree holds the entry {name} next to /{IMAGE_FILE}")
}
ComposefsImageDefect::NotSealed => write!(
f,
"whose /{IMAGE_FILE} has no fs-verity seal with SHA-256, 4096-byte blocks, \
no salt, and its full size"
),
ComposefsImageDefect::DigestMismatch { expected, actual } => write!(
f,
"whose /{IMAGE_FILE} has the fs-verity digest {}, and the commit records {}",
digest_hex(actual),
digest_hex(expected)
),
}
}
}
impl Transaction {
pub async fn write_composefs_commit(
&self,
root: &RepoTree,
filter: Option<ComposefsEntryFn<'_>>,
) -> Result<(Checksum, [u8; 32])> {
let (commit, _, digest) = self.stage_image_commit(root, filter).await?;
Ok((commit, digest))
}
async fn stage_image_commit(
&self,
root: &RepoTree,
filter: Option<ComposefsEntryFn<'_>>,
) -> Result<(Checksum, Checksum, [u8; 32])> {
let meta = FileMeta::regular(0, 0, IMAGE_PERM);
let (image, digest) = self
.write_composefs_content(root, &ComposefsOptions::RECORDED, filter, &meta)
.await?;
let root_dirmeta = self
.write_dirmeta(&DirMeta {
uid: 0,
gid: 0,
mode: ROOT_DIR_MODE,
xattrs: Xattrs::empty(),
})
.await?;
let tree = DirTree {
files: vec![(IMAGE_FILE.to_owned(), image)],
dirs: Vec::new(),
};
let root_dirtree = self
.write_metadata(ObjectType::DirTree, None, &tree.serialize()?)
.await?;
let commit = Commit {
metadata: Value::Array(Vec::new()),
parent: None,
related: Vec::new(),
subject: IMAGE_SUBJECT.to_owned(),
body: String::new(),
timestamp: 0,
root_dirtree,
root_dirmeta,
};
let checksum = self
.write_metadata(ObjectType::Commit, None, &commit.serialize()?)
.await?;
Ok((checksum, image, digest))
}
}
impl Repo {
pub async fn open_composefs_image(&self, commit: &Checksum) -> Result<Option<ComposefsImage>> {
if self.mode().is_archive() {
return Err(archive_refusal());
}
let repo = self.clone();
let key = *commit;
ostrya_rt::unblock(move || {
let Some(named) = repo.named_image_blocking(&key)? else {
return Ok(None);
};
let require_seal = repo.requires_sealed_image()?;
let (file, size) = repo.check_raw_image_blocking(
&key,
named.source,
&named.image,
named.key,
require_seal,
)?;
Ok(Some(ComposefsImage {
file,
size,
source: named.source,
commit: named.image,
}))
})
.await
}
pub async fn add_composefs_supplement(
&self,
commit: &Checksum,
) -> Result<ComposefsSupplementAdd> {
let txn = self.transaction().await?;
let (result, was_partial) = match self.stage_composefs_supplement(&txn, commit).await {
Ok(staged) => staged,
Err(e) => {
txn.abort().await?;
return Err(e);
}
};
let ComposefsSupplementAdd::Written { image, .. } = result else {
txn.abort().await?;
return Ok(result);
};
let fsync = txn.fsync_flags()?.0;
txn.commit().await?;
if was_partial {
let failed = self.remove_partial_markers(vec![image], fsync).await?;
if let Some((_, e)) = failed.into_iter().next() {
return Err(e);
}
}
Ok(result)
}
async fn stage_composefs_supplement(
&self,
txn: &Transaction,
commit: &Checksum,
) -> Result<(ComposefsSupplementAdd, bool)> {
let repo = self.clone();
let read_commit = *commit;
let read = ostrya_rt::unblock(move || repo.supplement_state_blocking(&read_commit)).await?;
let replaced = match read.state {
SupplementState::Valid(image) => {
return Ok((ComposefsSupplementAdd::Valid { image }, false));
}
SupplementState::Build { replaced } => replaced,
};
let root = RepoTree::from_parts(self.clone(), read.root_dirtree, read.root_dirmeta);
let (image, file, digest) = txn.stage_image_commit(&root, None).await?;
if read.key != digest {
return Err(Error::ComposefsDigestMismatch {
commit: *commit,
expected: read.key,
actual: digest,
});
}
if read.require_seal && !self.mode().is_archive() {
let object = txn.load_file_staged_first_with(&file, true).await?;
if object.kernel_fs_verity().is_none() {
return Err(invalid_image(
commit,
ComposefsImageSource::Supplement,
&image,
ComposefsImageDefect::NotSealed,
));
}
}
let was_partial = self.commit_state(&image).await? == CommitState::Partial;
txn.add_supplement(commit, COMPOSEFS_RELATION, &image)?;
Ok((
ComposefsSupplementAdd::Written { image, replaced },
was_partial,
))
}
fn supplement_state_blocking(&self, commit: &Checksum) -> Result<SupplementRead> {
let require_seal = self.requires_sealed_image()?;
let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
let parsed = Commit::parse(&bytes)?;
let key = recorded_digest(&parsed)?;
if let Some(image) = attached_image(commit, related::entries_of(&parsed.related))? {
return Err(Error::InvalidInput(format!(
"commit {commit} names its composefs image commit {image} as an \
attachment; a supplement is not written"
)));
}
let Some(key) = key else {
return Err(Error::InvalidInput(format!(
"commit {commit} carries no {COMPOSEFS_DIGEST_KEY}; a supplement is not \
written (Repo::commit_add_composefs_metadata stages a commit that carries \
the key)"
)));
};
let read = |state| SupplementRead {
root_dirtree: parsed.root_dirtree,
root_dirmeta: parsed.root_dirmeta,
key,
require_seal,
state,
};
let Some(image) = self.supplemented_image_blocking(commit)? else {
return Ok(read(SupplementState::Build { replaced: None }));
};
let source = ComposefsImageSource::Supplement;
let check =
|seal| self.check_composefs_commit_blocking(commit, source, &image, Some(key), seal);
let replace = || {
read(SupplementState::Build {
replaced: Some(image),
})
};
match check(require_seal) {
Ok(_) => Ok(read(SupplementState::Valid(image))),
Err(e) if is_not_sealed(&e) => match check(false) {
Ok(_) => Err(e),
Err(Error::InvalidComposefsImage { .. }) => Ok(replace()),
Err(other) => Err(other),
},
Err(Error::InvalidComposefsImage { .. }) => Ok(replace()),
Err(e) => Err(e),
}
}
fn named_image_blocking(&self, commit: &Checksum) -> Result<Option<NamedImage>> {
let bytes = self.load_object_bytes_blocking(ObjectType::Commit, commit)?;
let Some((source, image)) = self.named_entry_blocking(commit, &bytes)? else {
return Ok(None);
};
let key = match source {
ComposefsImageSource::Attachment => None,
ComposefsImageSource::Supplement => recorded_digest(&Commit::parse(&bytes)?)?,
};
Ok(Some(NamedImage { source, image, key }))
}
fn named_entry_blocking(
&self,
commit: &Checksum,
bytes: &[u8],
) -> Result<Option<(ComposefsImageSource, Checksum)>> {
if let Some(image) = attached_image(commit, related::parse_attachments(bytes)?)? {
return Ok(Some((ComposefsImageSource::Attachment, image)));
}
Ok(self
.supplemented_image_blocking(commit)?
.map(|image| (ComposefsImageSource::Supplement, image)))
}
fn supplemented_image_blocking(&self, commit: &Checksum) -> Result<Option<Checksum>> {
let detached = self.read_supplement_dict_blocking(commit)?;
let supplements = related::supplements(detached.as_ref())
.map_err(|reason| Error::InvalidRelations {
commit: Some(*commit),
field: RelationField::Supplements,
reason,
})?
.map(|entries| {
related::checked_entries(RelationField::Supplements, Some(*commit), entries)
})
.transpose()?
.unwrap_or_default();
composefs_entry(commit, RelationField::Supplements, &supplements)
}
fn check_composefs_commit_blocking(
&self,
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
key: Option<[u8; 32]>,
require_seal: bool,
) -> Result<Option<(std::fs::File, u64)>> {
if !self.mode().is_archive() {
return self
.check_raw_image_blocking(commit, relation, image, key, require_seal)
.map(Some);
}
let expected = expected_digest(commit, relation, image, key)?;
let (object, payload) = self.image_file_blocking(commit, relation, image, false)?;
let Some(expected) = expected else {
return Ok(None);
};
let Some((file, len)) = payload else {
return Err(no_payload(&object));
};
let actual = inflated_digest_blocking(file, len)?;
check_digest(&expected, &actual)
.map_err(|defect| invalid_image(commit, relation, image, defect))?;
Ok(None)
}
fn check_raw_image_blocking(
&self,
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
key: Option<[u8; 32]>,
require_seal: bool,
) -> Result<(std::fs::File, u64)> {
use std::io::{Seek, SeekFrom};
let expected = expected_digest(commit, relation, image, key)?;
let measure = require_seal || expected.is_some();
let (object, payload) = self.image_file_blocking(commit, relation, image, measure)?;
let Some((mut file, size)) = payload else {
return Err(no_payload(&object));
};
if require_seal && object.kernel_fs_verity().is_none() {
return Err(invalid_image(
commit,
relation,
image,
ComposefsImageDefect::NotSealed,
));
}
let Some(expected) = expected else {
return Ok((file, size));
};
let actual = match object.kernel_fs_verity() {
Some(digest) => digest,
None => {
let digest = image_file_digest(&mut file)?;
file.seek(SeekFrom::Start(0))?;
digest
}
};
check_digest(&expected, &actual)
.map_err(|defect| invalid_image(commit, relation, image, defect))?;
Ok((file, size))
}
fn requires_sealed_image(&self) -> Result<bool> {
Ok(self.config().fsverity()? == Tristate::Yes)
}
fn image_file_blocking(
&self,
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
measure: bool,
) -> Result<(FileObject, Option<Payload>)> {
let invalid = |defect| invalid_image(commit, relation, image, defect);
let Some(bytes) = self.held_object_bytes_blocking(ObjectType::Commit, image)? else {
return Err(invalid(ComposefsImageDefect::Absent));
};
if self.commit_state_blocking(image)? == CommitState::Partial {
return Err(invalid(ComposefsImageDefect::Partial));
}
let root = Commit::parse(&bytes)?.root_dirtree;
let tree = DirTree::parse(&self.load_object_bytes_blocking(ObjectType::DirTree, &root)?)?;
let file = image_entry(&tree).map_err(invalid)?;
let (object, payload) = self.open_file_blocking(&file, measure)?;
if !matches!(object.kind, FileKind::Regular { .. }) {
return Err(invalid(ComposefsImageDefect::NotRegular));
}
Ok((object, payload))
}
}
struct SupplementRead {
root_dirtree: Checksum,
root_dirmeta: Checksum,
key: [u8; 32],
require_seal: bool,
state: SupplementState,
}
enum SupplementState {
Valid(Checksum),
Build { replaced: Option<Checksum> },
}
struct NamedImage {
source: ComposefsImageSource,
image: Checksum,
key: Option<[u8; 32]>,
}
fn invalid_image(
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
defect: ComposefsImageDefect,
) -> Error {
Error::InvalidComposefsImage {
commit: *commit,
relation,
image: *image,
defect: Box::new(defect),
}
}
fn no_payload(object: &FileObject) -> Error {
Error::InvalidFormat(format!(
"the file object {} of /{IMAGE_FILE} has no payload",
object.checksum()
))
}
fn archive_refusal() -> Error {
Error::Unsupported(
"the lookup of a composefs image refuses an archive repository: it stores \
/root.cfs compressed, and a mount needs the raw image"
.into(),
)
}
fn attached_image(
commit: &Checksum,
entries: Vec<related::RelatedEntry>,
) -> Result<Option<Checksum>> {
let attachments = related::checked_entries(RelationField::Attachments, Some(*commit), entries)?;
composefs_entry(commit, RelationField::Attachments, &attachments)
}
fn is_not_sealed(error: &Error) -> bool {
matches!(
error,
Error::InvalidComposefsImage { defect, .. } if **defect == ComposefsImageDefect::NotSealed
)
}
fn composefs_entry(
commit: &Checksum,
field: RelationField,
entries: &[(String, Checksum)],
) -> Result<Option<Checksum>> {
let mut named = entries
.iter()
.filter(|(name, _)| name == COMPOSEFS_RELATION);
let first = named.next().map(|(_, checksum)| *checksum);
if named.next().is_some() {
return Err(Error::InvalidRelations {
commit: Some(*commit),
field,
reason: format!("two or more entries have the name {COMPOSEFS_RELATION}"),
});
}
Ok(first)
}
fn image_entry(tree: &DirTree) -> std::result::Result<Checksum, ComposefsImageDefect> {
let file = tree
.files
.iter()
.find(|(name, _)| name == IMAGE_FILE)
.map(|(_, checksum)| *checksum);
let dir = tree.dirs.iter().any(|(name, _, _)| name == IMAGE_FILE);
if file.is_none() && !dir {
return Err(ComposefsImageDefect::NoImageFile);
}
if dir {
return Err(ComposefsImageDefect::NotRegular);
}
let extra = tree
.files
.iter()
.map(|(name, _)| name)
.chain(tree.dirs.iter().map(|(name, _, _)| name))
.find(|name| *name != IMAGE_FILE);
if let Some(name) = extra {
return Err(ComposefsImageDefect::ExtraEntry(name.clone()));
}
Ok(file.expect("the tree holds the file root.cfs"))
}
fn expected_digest(
commit: &Checksum,
relation: ComposefsImageSource,
image: &Checksum,
key: Option<[u8; 32]>,
) -> Result<Option<[u8; 32]>> {
match relation {
ComposefsImageSource::Attachment => Ok(None),
ComposefsImageSource::Supplement => key
.map(Some)
.ok_or_else(|| invalid_image(commit, relation, image, ComposefsImageDefect::NoKey)),
}
}
fn check_digest(
expected: &[u8; 32],
actual: &[u8; 32],
) -> std::result::Result<(), ComposefsImageDefect> {
if actual == expected {
return Ok(());
}
Err(ComposefsImageDefect::DigestMismatch {
expected: *expected,
actual: *actual,
})
}
fn inflated_digest_blocking(file: std::fs::File, len: u64) -> Result<[u8; 32]> {
use futures_lite::AsyncReadExt;
let source = BufSource::with_len_hint(futures_lite::io::AssertAsync::new(file), len);
let mut decoder = DeflateDecoder::new(source);
let mut hasher = ostrya_composefs::FsVerityHasher::new();
let mut buf = vec![0u8; DIGEST_CHUNK];
futures_lite::future::block_on(async {
loop {
let n = decoder.read(&mut buf).await.map_err(Error::Io)?;
if n == 0 {
return Ok::<(), Error>(());
}
hasher.update(&buf[..n]);
}
})?;
Ok(hasher.finalize())
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
fn assert_send<T: Send>(_: &T) {}
assert_send_sync::<ComposefsImage>();
assert_send_sync::<ComposefsImageDefect>();
let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.open_composefs_image(commit));
let _ = |repo: &Repo, commit: &Checksum| assert_send(&repo.add_composefs_supplement(commit));
let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>| {
assert_send(&txn.write_composefs_commit(root, Some(filter)));
};
let _ = |txn: &Transaction, root: &RepoTree, filter: ComposefsEntryFn<'_>, meta: &FileMeta| {
assert_send(&txn.write_composefs_content(
root,
&ComposefsOptions::RECORDED,
Some(filter),
meta,
));
};
};
#[cfg(test)]
mod tests {
use ostrya_core::{Checksum, DirMeta, DirTree, ObjectType, RepoMode, Xattrs};
use ostrya_rt::block_on;
use super::{ComposefsImageDefect, ComposefsImageSource, ROOT_DIR_MODE};
use crate::tree::RepoTree;
use crate::{CreateOptions, Error, FileMeta, Repo};
#[test]
fn the_check_hashes_the_inflated_image_in_archive_mode() {
let path = std::env::temp_dir().join(format!(
"ostrya-image-commit-archive-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&path);
block_on(async {
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let file = txn
.write_regfile_inline(None, &FileMeta::regular(0, 0, 0o644), b"payload\n")
.await
.unwrap();
let dirmeta = txn
.write_dirmeta(&DirMeta {
uid: 0,
gid: 0,
mode: ROOT_DIR_MODE,
xattrs: Xattrs::empty(),
})
.await
.unwrap();
let tree = DirTree {
files: vec![("a".to_owned(), file)],
dirs: Vec::new(),
};
let dirtree = txn
.write_metadata(ObjectType::DirTree, None, &tree.serialize().unwrap())
.await
.unwrap();
let root = RepoTree::from_parts(repo.clone(), dirtree, dirmeta);
let (image, digest) = txn.write_composefs_commit(&root, None).await.unwrap();
txn.commit().await.unwrap();
let commit = Checksum::from_bytes([1; 32]);
let source = ComposefsImageSource::Supplement;
let checked = repo
.check_composefs_commit_blocking(&commit, source, &image, Some(digest), false)
.unwrap();
assert!(checked.is_none());
let wrong = [0x11; 32];
let refusals = [
(
Some(wrong),
ComposefsImageDefect::DigestMismatch {
expected: wrong,
actual: digest,
},
),
(None, ComposefsImageDefect::NoKey),
];
for (key, expected) in refusals {
match repo
.check_composefs_commit_blocking(&commit, source, &image, key, false)
.unwrap_err()
{
Error::InvalidComposefsImage { defect, .. } => assert_eq!(*defect, expected),
other => panic!("expected InvalidComposefsImage, got {other:?}"),
}
}
});
let _ = std::fs::remove_dir_all(&path);
}
}