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;
const INJECTED_DIRS: [&str; 5] = ["boot", "etc", "sysroot", "usr", "var"];
const INJECTED_DIR_MODE: u32 = 0o040755;
pub const COMPOSEFS_DIGEST_KEY: &str = "ostree.composefs.digest.v0";
const DIGEST_SIGNATURE: &str = "ay";
pub(crate) const DIGEST_CHUNK: usize = 128 * 1024;
const XATTR_ENTRY_COST: usize = 7;
const MAX_XATTR_TOTAL: usize = 32755;
const MAX_XATTR_NAME: usize = u8::MAX as usize;
const BACKING_MODE: RepoMode = RepoMode::BareUser;
type TreeFuture<'a> = Pin<Box<dyn Future<Output = Result<Directory>> + Send + 'a>>;
#[derive(Clone, Copy)]
enum ObjectSource<'a> {
Repo(&'a Repo),
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,
}
}
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,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum VerityPolicy {
#[default]
Computed,
Disabled,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ComposefsOptions {
pub verity: VerityPolicy,
}
impl ComposefsOptions {
pub const RECORDED: ComposefsOptions = ComposefsOptions {
verity: VerityPolicy::Computed,
};
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryKind {
Directory,
Regular,
Symlink,
}
pub type ComposefsEntryFn<'a> = &'a (dyn Fn(&Path, EntryKind, &mut Metadata) -> Result<()> + Sync);
#[derive(Clone, Copy)]
struct Walk<'a> {
source: ObjectSource<'a>,
digests: Digests,
filter: Option<ComposefsEntryFn<'a>>,
}
impl Walk<'_> {
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)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Digests {
Computed,
Sealed,
Disabled,
}
#[derive(Default)]
struct VerityCache {
digests: HashMap<Checksum, [u8; 32]>,
#[cfg(test)]
hashed: usize,
}
impl From<VerityPolicy> for Digests {
fn from(policy: VerityPolicy) -> Digests {
match policy {
VerityPolicy::Computed => Digests::Computed,
VerityPolicy::Disabled => Digests::Disabled,
}
}
}
impl Transaction {
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
}
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))
}
}
impl Repo {
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)
}
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?;
let fd = out.try_clone_to_owned()?;
ostrya_rt::unblock(move || write_image_to_fd(&dir, fd))
.await
.map_err(writer_error)
}
#[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)
}
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
}
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
}
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
}
}
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())
}
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)
}
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"
))
})
}
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
})
}
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)
}
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)
}
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))
}
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)
}
pub(crate) fn writer_error(err: WriterError) -> Error {
match err {
WriterError::Unsupported(msg) => Error::Unsupported(msg),
WriterError::Io(err) => Error::Io(err),
}
}
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)
})
}
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 }))
}
}
}
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)
}
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(())
}
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),
}
}
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),
}
}
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()
}
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),
)));
}
}
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(())
}
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};
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);
}
}
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();
}
#[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);
});
}
fn selinux(label: &[u8]) -> Xattrs {
Xattrs::new([(b"security.selinux\0".to_vec(), label.to_vec())]).unwrap()
}
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()
}
type Call = (PathBuf, EntryKind, (u64, u32), Vec<Vec<u8>>);
#[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)),
);
}
}