use std::fs::File;
use std::io;
use std::os::fd::AsFd;
use std::pin::Pin;
use std::task::{Context, Poll};
use ostrya_core::{Checksum, FileHeader, ObjectType, RepoMode, Xattrs, loose_path};
use ostrya_rt::FileReader;
use rustix::fs::FileType;
use crate::error::{Error, Result};
use crate::inflate::{ArchiveDecoder, archive_decoder};
use crate::object::{MAX_FILE_HEADER_SIZE, MAX_METADATA_SIZE};
use crate::read::object_path_error;
use crate::repo::Repo;
use crate::repo_fs::{self, FsError, FsResultExt, ObjectEntry, Opened, Reason, RepoDir, Stat};
use crate::write::FileMeta;
const SYMLINK_READ_CAP: u64 = 64 * 1024;
const LINK_TARGET_CAP: u64 = 4095;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FileKind {
Regular {
size: u64,
},
Symlink {
target: String,
},
}
#[derive(Debug, Clone)]
enum ReaderSource {
None,
Plain,
Archive { payload_offset: u64 },
}
impl ReaderSource {
fn reader_over(&self, payload: Option<Payload>) -> ContentReader {
let inner = match (self, payload) {
(ReaderSource::Plain, Some((file, len))) => {
ContentReaderInner::Plain(FileReader::with_len_hint(file, len))
}
(ReaderSource::Archive { .. }, Some((file, len))) => ContentReaderInner::Inflate(
Box::new(archive_decoder(FileReader::with_len_hint(file, len), len)),
),
_ => ContentReaderInner::Empty,
};
ContentReader { inner }
}
}
#[derive(Debug, Clone)]
enum ObjectStore {
Repo,
Staging {
dir: RepoDir,
name: String,
},
}
#[derive(Debug, Clone)]
pub struct FileObject {
repo: Repo,
checksum: Checksum,
pub uid: u32,
pub gid: u32,
pub mode: u32,
pub xattrs: Xattrs,
pub kind: FileKind,
source: ReaderSource,
store: ObjectStore,
kernel_verity: Option<[u8; 32]>,
stored_size: u64,
}
impl FileObject {
pub fn checksum(&self) -> &Checksum {
&self.checksum
}
pub fn is_symlink(&self) -> bool {
matches!(self.kind, FileKind::Symlink { .. })
}
pub fn header(&self) -> FileHeader {
FileHeader {
uid: self.uid,
gid: self.gid,
mode: self.mode,
symlink_target: match &self.kind {
FileKind::Symlink { target } => target.clone(),
FileKind::Regular { .. } => String::new(),
},
xattrs: self.xattrs.clone(),
}
}
pub(crate) fn meta(&self) -> FileMeta {
FileMeta {
uid: self.uid,
gid: self.gid,
mode: self.mode,
xattrs: self.xattrs.clone(),
}
}
pub async fn reader(&self) -> Result<ContentReader> {
let payload = match &self.source {
ReaderSource::None => None,
ReaderSource::Plain => {
let len = match self.kind {
FileKind::Regular { size } => size,
FileKind::Symlink { .. } => 0,
};
Some((self.open_payload(0, false).await?.0, len))
}
ReaderSource::Archive { payload_offset } => {
Some(self.open_payload(*payload_offset, true).await?)
}
};
Ok(self.source.reader_over(payload))
}
pub async fn write_to<W: futures_io::AsyncWrite + Unpin>(&self, writer: &mut W) -> Result<()> {
let reader = self.reader().await?;
crate::write::copy_stream(reader, writer)
.await
.map_err(Error::Io)
}
pub(crate) fn kernel_fs_verity(&self) -> Option<[u8; 32]> {
self.kernel_verity
}
pub(crate) fn stored_size(&self) -> u64 {
self.stored_size
}
pub(crate) fn reader_over(&self, payload: Option<Payload>) -> ContentReader {
self.source.reader_over(payload)
}
fn payload_location(&self) -> (RepoDir, String) {
match &self.store {
ObjectStore::Repo => {
let path = loose_path(&self.checksum, ObjectType::File, self.repo.mode());
(self.repo.objects().clone(), path)
}
ObjectStore::Staging { dir, name } => (dir.clone(), name.clone()),
}
}
async fn open_payload(&self, payload_offset: u64, measure: bool) -> Result<Payload> {
let (dir, path) = self.payload_location();
let checksum = self.checksum;
ostrya_rt::unblock(move || {
let Opened { file, stat } = dir
.open_regular_at(&path, payload_offset)
.map_err(|e| e.into_object_error(&checksum, ObjectType::File))?;
let len = if measure {
stat.size.saturating_sub(payload_offset)
} else {
0
};
Ok((file, len))
})
.await
}
}
impl Repo {
pub async fn load_file(&self, checksum: &Checksum) -> Result<FileObject> {
self.load_file_with(checksum, false).await
}
pub(crate) async fn load_file_with(
&self,
checksum: &Checksum,
measure: bool,
) -> Result<FileObject> {
let loaded = self.load_loose(checksum, measure, false).await?;
Ok(self.file_object(checksum, loaded).0)
}
pub(crate) async fn open_file(
&self,
checksum: &Checksum,
) -> Result<(FileObject, Option<Payload>)> {
let loaded = self.load_loose(checksum, false, true).await?;
Ok(self.file_object(checksum, loaded))
}
async fn load_loose(&self, checksum: &Checksum, measure: bool, keep: bool) -> Result<Loaded> {
let mode = self.mode();
let path = loose_path(checksum, ObjectType::File, mode);
let repo = self.clone();
let key = *checksum;
ostrya_rt::unblock(move || {
load_by_mode(repo.objects(), &path, mode, measure, keep).map_err(|e| e.into_error(&key))
})
.await
}
#[cfg_attr(not(feature = "push"), allow(dead_code))]
pub(crate) fn content_size_blocking(
&self,
checksums: &[Checksum],
stored: bool,
) -> Result<u64> {
let mut total = 0u64;
for checksum in checksums {
total = total.saturating_add(self.object_content_size_blocking(checksum, stored)?);
}
Ok(total)
}
#[cfg_attr(not(feature = "push"), allow(dead_code))]
pub(crate) fn object_content_size_blocking(
&self,
checksum: &Checksum,
stored: bool,
) -> Result<u64> {
let mode = self.mode();
let dir = self.objects();
let path = loose_path(checksum, ObjectType::File, mode);
let size = (|| -> std::result::Result<u64, LoadError> {
Ok(match mode {
RepoMode::Archive if stored => {
let stat = dir.lstat(&path)?;
if stat.file_type == FileType::RegularFile {
stat.size
} else {
dir.open_regular(&path)?.stat.size
}
}
RepoMode::Archive => match load_archive(dir, &path, false)?.kind {
FileKind::Regular { size } => size,
FileKind::Symlink { .. } => 0,
},
RepoMode::BareUser | RepoMode::BareUserShared => {
bare_user_payload_size(dir, &path)?
}
RepoMode::Bare | RepoMode::BareUserOnly | RepoMode::BareSplitXattrs => {
let stat = dir.lstat(&path)?;
match stat.file_type {
FileType::Symlink => 0,
FileType::RegularFile => stat.size,
_ => match dir.open_object(&path)? {
ObjectEntry::Regular(opened) => opened.stat.size,
ObjectEntry::Symlink(_) => 0,
},
}
}
})
})();
size.map_err(|e| e.into_error(checksum))
}
pub(crate) fn load_contained_blocking(
&self,
checksum: &Checksum,
) -> Result<Contained<ContainedFile>> {
let mode = self.mode();
let path = loose_path(checksum, ObjectType::File, mode);
match load_by_mode(self.objects(), &path, mode, false, true) {
Ok(loaded) => Ok(Contained::Found(ContainedFile { loaded })),
Err(e) => e.into_contained(checksum),
}
}
pub(crate) fn contained_file(
&self,
checksum: &Checksum,
contained: ContainedFile,
) -> (FileObject, ContentReader) {
let (file, payload) = self.file_object(checksum, contained.loaded);
let reader = file.reader_over(payload);
(file, reader)
}
pub(crate) fn probe_contained_blocking(&self, checksum: &Checksum) -> Result<Contained<()>> {
let mode = self.mode();
let path = loose_path(checksum, ObjectType::File, mode);
let objects = self.objects();
let probed = (|| -> std::result::Result<(), LoadError> {
match mode {
RepoMode::Bare | RepoMode::BareUserOnly => {
objects.open_object(&path)?;
}
RepoMode::BareSplitXattrs => {
objects.open_object(&path)?;
probe_split_xattrs_link(objects, &path)?;
}
RepoMode::Archive | RepoMode::BareUser | RepoMode::BareUserShared => {
objects.open_regular(&path)?;
}
}
Ok(())
})();
match probed {
Ok(()) => Ok(Contained::Found(())),
Err(e) => e.into_contained(checksum),
}
}
fn file_object(&self, checksum: &Checksum, loaded: Loaded) -> (FileObject, Option<Payload>) {
let file = FileObject {
repo: self.clone(),
checksum: *checksum,
uid: loaded.uid,
gid: loaded.gid,
mode: loaded.mode,
xattrs: loaded.xattrs,
kind: loaded.kind,
source: loaded.source,
store: ObjectStore::Repo,
kernel_verity: loaded.kernel_verity,
stored_size: loaded.stored_size,
};
(file, loaded.payload)
}
}
pub(crate) async fn load_staged_file(
repo: &Repo,
staging: &RepoDir,
checksum: &Checksum,
measure: bool,
) -> Result<FileObject> {
let mode = repo.mode();
let name = crate::write::flat_name(checksum, ObjectType::File, mode);
let key = *checksum;
let load_dir = staging.clone();
let load_name = name.clone();
let loaded = ostrya_rt::unblock(move || {
load_by_mode(&load_dir, &load_name, mode, measure, false).map_err(|e| e.into_error(&key))
})
.await?;
Ok(FileObject {
repo: repo.clone(),
checksum: *checksum,
uid: loaded.uid,
gid: loaded.gid,
mode: loaded.mode,
xattrs: loaded.xattrs,
kind: loaded.kind,
source: loaded.source,
store: ObjectStore::Staging {
dir: staging.clone(),
name,
},
kernel_verity: loaded.kernel_verity,
stored_size: loaded.stored_size,
})
}
pub(crate) enum Contained<T> {
Found(T),
NotFound,
Refused,
}
pub(crate) struct ContainedFile {
loaded: Loaded,
}
enum LoadError {
Fs(FsError),
Other(Error),
}
impl From<FsError> for LoadError {
fn from(err: FsError) -> LoadError {
LoadError::Fs(err)
}
}
impl From<Error> for LoadError {
fn from(err: Error) -> LoadError {
LoadError::Other(err)
}
}
impl From<io::Error> for LoadError {
fn from(err: io::Error) -> LoadError {
LoadError::Other(Error::Io(err))
}
}
impl From<ostrya_core::Error> for LoadError {
fn from(err: ostrya_core::Error) -> LoadError {
LoadError::Other(err.into())
}
}
impl LoadError {
fn into_error(self, checksum: &Checksum) -> Error {
match self {
LoadError::Fs(err) => err.into_object_error(checksum, ObjectType::File),
LoadError::Other(err) => err,
}
}
fn into_contained<T>(self, checksum: &Checksum) -> Result<Contained<T>> {
match self {
LoadError::Fs(
FsError::Absent { .. }
| FsError::Invalid {
reason: Reason::NotDirectory,
..
},
) => Ok(Contained::NotFound),
LoadError::Fs(FsError::Invalid {
reason: Reason::Symlink,
..
}) => Ok(Contained::Refused),
other => Err(other.into_error(checksum)),
}
}
}
struct Loaded {
uid: u32,
gid: u32,
mode: u32,
xattrs: Xattrs,
kind: FileKind,
source: ReaderSource,
kernel_verity: Option<[u8; 32]>,
stored_size: u64,
payload: Option<Payload>,
}
pub(crate) type Payload = (File, u64);
fn load_by_mode(
dir: &RepoDir,
object_path: &str,
mode: RepoMode,
measure: bool,
keep: bool,
) -> std::result::Result<Loaded, LoadError> {
match mode {
RepoMode::Archive => load_archive(dir, object_path, keep),
RepoMode::BareUser | RepoMode::BareUserShared => {
load_bare_user(dir, object_path, measure, keep)
}
RepoMode::Bare => load_bare(dir, object_path, measure, keep),
RepoMode::BareUserOnly => load_bare_user_only(dir, object_path, measure, keep),
RepoMode::BareSplitXattrs => load_bare_split_xattrs(dir, object_path, measure, keep),
}
}
fn kernel_digest(file: &File, stat: &Stat, measure: bool) -> Option<[u8; 32]> {
if !(measure && stat.verity) {
return None;
}
repo_fs::verity_digest(file.as_fd(), stat.size)
}
fn link_target(target: Vec<u8>) -> Result<String> {
String::from_utf8(target)
.map_err(|_| Error::InvalidFormat("symlink target is not valid UTF-8".into()))
}
fn symlink_target_from_content(content: &[u8]) -> Result<String> {
let bytes = content.strip_suffix(&[0]).unwrap_or(content);
if bytes.contains(&0) {
return Err(Error::InvalidFormat(
"symlink target has an interior NUL".into(),
));
}
std::str::from_utf8(bytes)
.map(str::to_owned)
.map_err(|_| Error::InvalidFormat("symlink target is not valid UTF-8".into()))
}
fn bare_user_header(file: &File) -> std::result::Result<FileHeader, LoadError> {
let meta = repo_fs::xattr(file.as_fd(), "user.ostreemeta")?.ok_or_else(|| {
Error::InvalidFormat("bare-user .file is missing its user.ostreemeta xattr".into())
})?;
Ok(FileHeader::parse_stat_metadata(&meta)?)
}
fn load_archive(dir: &RepoDir, path: &str, keep: bool) -> std::result::Result<Loaded, LoadError> {
use std::io::Read;
let Opened { mut file, stat } = dir.open_regular(path)?;
let mut prefix = [0u8; 8];
file.read_exact(&mut prefix)?;
if prefix[4..8] != [0u8; 4] {
return Err(Error::InvalidFormat("content framing padding is not zero".into()).into());
}
let header_len = u32::from_be_bytes(prefix[..4].try_into().unwrap()) as u64;
if header_len > MAX_FILE_HEADER_SIZE {
return Err(Error::InvalidFormat("content header exceeds the size cap".into()).into());
}
let mut header_bytes = vec![0u8; header_len as usize];
file.read_exact(&mut header_bytes)?;
let (header, uncompressed_size) = FileHeader::parse_archive(&header_bytes)?;
let (kind, source, payload) = if header.is_symlink() {
(
FileKind::Symlink {
target: header.symlink_target,
},
ReaderSource::None,
None,
)
} else {
(
FileKind::Regular {
size: uncompressed_size,
},
ReaderSource::Archive {
payload_offset: 8 + header_len,
},
keep.then(|| (file, stat.size.saturating_sub(8 + header_len))),
)
};
Ok(Loaded {
uid: header.uid,
gid: header.gid,
mode: header.mode,
xattrs: header.xattrs,
kind,
source,
kernel_verity: None,
stored_size: stat.size,
payload,
})
}
fn load_bare_user(
dir: &RepoDir,
path: &str,
measure: bool,
keep: bool,
) -> std::result::Result<Loaded, LoadError> {
let Opened { file, stat } = dir.open_regular(path)?;
let header = bare_user_header(&file)?;
let stored_size = stat.size;
let (kind, source, kernel_verity, payload) = if header.is_symlink() {
drop(file);
let content = dir.read_capped(path, SYMLINK_READ_CAP)?;
(
FileKind::Symlink {
target: symlink_target_from_content(&content)?,
},
ReaderSource::None,
None,
None,
)
} else {
let size = stat.size;
let kernel_verity = kernel_digest(&file, &stat, measure);
(
FileKind::Regular { size },
ReaderSource::Plain,
kernel_verity,
keep.then_some((file, size)),
)
};
Ok(Loaded {
uid: header.uid,
gid: header.gid,
mode: header.mode,
xattrs: header.xattrs,
kind,
source,
kernel_verity,
stored_size,
payload,
})
}
fn bare_user_payload_size(dir: &RepoDir, path: &str) -> std::result::Result<u64, LoadError> {
let Opened { file, stat } = dir.open_regular(path)?;
if bare_user_header(&file)?.is_symlink() {
return Ok(0);
}
Ok(stat.size)
}
enum BareEntry {
Regular(Stat, Option<File>),
Symlink(Stat, Vec<u8>, Xattrs),
}
fn bare_entry(
dir: &RepoDir,
path: &str,
open: bool,
measure: bool,
link_xattrs: bool,
) -> std::result::Result<BareEntry, LoadError> {
let opened = if open {
match dir.open_object(path)? {
ObjectEntry::Regular(Opened { file, stat }) => {
return Ok(BareEntry::Regular(stat, Some(file)));
}
ObjectEntry::Symlink(target) => Some(target),
}
} else {
None
};
let stat = dir.lstat(path)?;
let target = match opened {
Some(target) => target,
None => match stat.file_type {
FileType::Symlink => dir.read_link(path, LINK_TARGET_CAP)?,
FileType::RegularFile if !(measure && stat.verity) => {
return Ok(BareEntry::Regular(stat, None));
}
_ => return bare_entry(dir, path, true, measure, link_xattrs),
},
};
let xattrs = if link_xattrs {
dir.link_xattrs(path)
.map_err(|e| object_path_error(e, path))?
} else {
Xattrs::empty()
};
Ok(BareEntry::Symlink(stat, target, xattrs))
}
fn symlink_loaded(
stat: &Stat,
uid: u32,
gid: u32,
xattrs: Xattrs,
target: Vec<u8>,
) -> std::result::Result<Loaded, LoadError> {
Ok(Loaded {
uid,
gid,
mode: stat.mode,
xattrs,
kind: FileKind::Symlink {
target: link_target(target)?,
},
source: ReaderSource::None,
kernel_verity: None,
stored_size: stat.size,
payload: None,
})
}
fn regular_loaded(
stat: &Stat,
file: Option<File>,
uid: u32,
gid: u32,
xattrs: Xattrs,
measure: bool,
keep: bool,
) -> Loaded {
Loaded {
uid,
gid,
mode: stat.mode,
xattrs,
kind: FileKind::Regular { size: stat.size },
source: ReaderSource::Plain,
kernel_verity: file.as_ref().and_then(|f| kernel_digest(f, stat, measure)),
stored_size: stat.size,
payload: file.filter(|_| keep).map(|f| (f, stat.size)),
}
}
fn load_bare(
dir: &RepoDir,
path: &str,
measure: bool,
keep: bool,
) -> std::result::Result<Loaded, LoadError> {
Ok(match bare_entry(dir, path, true, measure, true)? {
BareEntry::Symlink(stat, target, xattrs) => {
symlink_loaded(&stat, stat.uid, stat.gid, xattrs, target)?
}
BareEntry::Regular(stat, file) => {
let xattrs = match &file {
Some(file) => repo_fs::xattrs(file.as_fd())?,
None => Xattrs::empty(),
};
regular_loaded(&stat, file, stat.uid, stat.gid, xattrs, measure, keep)
}
})
}
fn load_bare_user_only(
dir: &RepoDir,
path: &str,
measure: bool,
keep: bool,
) -> std::result::Result<Loaded, LoadError> {
Ok(match bare_entry(dir, path, keep, measure, false)? {
BareEntry::Symlink(stat, target, _) => {
symlink_loaded(&stat, 0, 0, Xattrs::empty(), target)?
}
BareEntry::Regular(stat, file) => {
regular_loaded(&stat, file, 0, 0, Xattrs::empty(), measure, keep)
}
})
}
fn load_bare_split_xattrs(
dir: &RepoDir,
path: &str,
measure: bool,
keep: bool,
) -> std::result::Result<Loaded, LoadError> {
let entry = bare_entry(dir, path, keep, measure, false)?;
let xattrs = load_split_xattrs(dir, path)?;
Ok(match entry {
BareEntry::Symlink(stat, target, _) => {
symlink_loaded(&stat, stat.uid, stat.gid, xattrs, target)?
}
BareEntry::Regular(stat, file) => {
regular_loaded(&stat, file, stat.uid, stat.gid, xattrs, measure, keep)
}
})
}
fn missing_xattrs_link() -> LoadError {
Error::InvalidFormat("bare-split-xattrs .file is missing its .file-xattrs-link".into()).into()
}
fn load_split_xattrs(dir: &RepoDir, file_path: &str) -> std::result::Result<Xattrs, LoadError> {
let path = format!("{file_path}-xattrs-link");
let bytes = dir
.read_capped(&path, MAX_METADATA_SIZE)
.optional()?
.ok_or_else(missing_xattrs_link)?;
Ok(Xattrs::from_gvariant(&bytes)?)
}
fn probe_split_xattrs_link(dir: &RepoDir, file_path: &str) -> std::result::Result<(), LoadError> {
let path = format!("{file_path}-xattrs-link");
dir.open_regular(&path)
.optional()?
.map(drop)
.ok_or_else(missing_xattrs_link)
}
pub struct ContentReader {
inner: ContentReaderInner,
}
enum ContentReaderInner {
Empty,
Plain(FileReader),
Inflate(Box<ArchiveDecoder>),
}
impl ContentReader {
pub(crate) fn empty() -> ContentReader {
ContentReader {
inner: ContentReaderInner::Empty,
}
}
fn poll_read_bytes(&mut self, cx: &mut Context<'_>, out: &mut [u8]) -> Poll<io::Result<usize>> {
use futures_io::AsyncRead;
match &mut self.inner {
ContentReaderInner::Empty => Poll::Ready(Ok(0)),
ContentReaderInner::Plain(inner) => Pin::new(inner).poll_read(cx, out),
ContentReaderInner::Inflate(inner) => Pin::new(&mut **inner).poll_read(cx, out),
}
}
}
impl futures_io::AsyncRead for ContentReader {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
self.get_mut().poll_read_bytes(cx, buf)
}
}
#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncRead for ContentReader {
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ostrya_rt::tokio_io::ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let out = buf.initialize_unfilled();
match self.get_mut().poll_read_bytes(cx, out) {
Poll::Ready(Ok(n)) => {
buf.advance(n);
Poll::Ready(Ok(()))
}
Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
Poll::Pending => Poll::Pending,
}
}
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<FileObject>();
assert_send_sync::<ContentReader>();
};
#[cfg(feature = "tokio")]
const _: fn() = || {
fn assert_tokio_read<T: ostrya_rt::tokio_io::AsyncRead>() {}
assert_tokio_read::<ContentReader>();
};
#[cfg(test)]
mod sealed_verity_tests {
use std::os::fd::AsFd;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use super::FileKind;
use crate::repo_fs::verity_digest;
use crate::{CreateOptions, FileMeta, Repo, Transaction};
use ostrya_composefs::FsVerityHasher;
use ostrya_core::{Checksum, ObjectType, RepoMode, loose_path};
use ostrya_rt::block_on;
fn payload() -> Vec<u8> {
b"sealed fs-verity fast path payload\n".repeat(300)
}
fn scratch(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"ostrya-sealed-{tag}-{}-{}",
std::process::id(),
crate::write::unique()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
fn verity_supported(dir: &Path) -> bool {
let probe = dir.join("probe");
std::fs::write(&probe, b"probe").unwrap();
let ro = std::fs::File::open(&probe).unwrap();
let ok = ostrya_sys::enable_verity(ro.as_fd()).is_ok();
drop(ro);
let _ = std::fs::remove_file(&probe);
ok
}
async fn repo_in(dir: &Path, mode: RepoMode, fsverity: &str) -> Repo {
let root = dir.join("repo");
drop(Repo::create(&root, CreateOptions::new(mode)).await.unwrap());
let cfg = root.join("config");
let mut text = std::fs::read_to_string(&cfg).unwrap();
text.push_str(&format!("[ex-integrity]\nfsverity={fsverity}\n"));
std::fs::write(&cfg, text).unwrap();
Repo::open(&root).await.unwrap()
}
async fn stage_payload(txn: &Transaction, dir: &Path) -> Checksum {
let owner = std::fs::metadata(dir).unwrap();
txn.write_regfile_inline(
None,
&FileMeta::regular(owner.uid(), owner.gid(), 0o644),
&payload(),
)
.await
.unwrap()
}
async fn repo_with_object(dir: &Path, mode: RepoMode, fsverity: &str) -> (Repo, Checksum) {
let repo = repo_in(dir, mode, fsverity).await;
let txn = repo.transaction().await.unwrap();
let checksum = stage_payload(&txn, dir).await;
txn.commit().await.unwrap();
(repo, checksum)
}
fn object_path(dir: &Path, checksum: &Checksum, mode: RepoMode) -> PathBuf {
dir.join("repo/objects")
.join(loose_path(checksum, ObjectType::File, mode))
}
fn sealed(repo: &Repo, checksum: &Checksum) -> bool {
let path = loose_path(checksum, ObjectType::File, repo.mode());
repo.objects().lstat(&path).unwrap().verity
}
fn check_sealed_object_yields_the_kernel_digest(tag: &str, mode: RepoMode) {
let dir = scratch(tag);
if !verity_supported(&dir) {
eprintln!("skipping sealed digest check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
block_on(async {
let (repo, checksum) = repo_with_object(&dir, mode, "yes").await;
let file = repo.load_file_with(&checksum, true).await.unwrap();
assert_eq!(
file.kernel_fs_verity(),
Some(FsVerityHasher::hash(&payload())),
"the kernel digest equals the computed digest"
);
let plain = repo.load_file(&checksum).await.unwrap();
assert_eq!(plain.kernel_fs_verity(), None, "a plain load reads none");
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_sealed_bare_user_object_yields_the_kernel_digest() {
check_sealed_object_yields_the_kernel_digest("bare-user", RepoMode::BareUser);
}
#[test]
fn a_sealed_bare_user_only_object_yields_the_kernel_digest() {
check_sealed_object_yields_the_kernel_digest("bare-user-only", RepoMode::BareUserOnly);
}
#[test]
fn a_sealed_bare_object_yields_the_kernel_digest() {
check_sealed_object_yields_the_kernel_digest("bare", RepoMode::Bare);
}
#[test]
fn a_sealed_staged_object_yields_the_kernel_digest() {
let dir = scratch("staged");
if !verity_supported(&dir) {
eprintln!("skipping staged digest check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
block_on(async {
let repo = repo_in(&dir, RepoMode::BareUser, "yes").await;
let txn = repo.transaction().await.unwrap();
let checksum = stage_payload(&txn, &dir).await;
assert!(txn.is_staged(&checksum, ObjectType::File));
let file = txn
.load_file_staged_first_with(&checksum, true)
.await
.unwrap();
assert_eq!(
file.kernel_fs_verity(),
Some(FsVerityHasher::hash(&payload())),
"the staged object gives the kernel digest"
);
txn.abort().await.unwrap();
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn statx_gates_the_kernel_read() {
let dir = scratch("gate");
if !verity_supported(&dir) {
eprintln!("skipping statx gate check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
block_on(async {
let sealed_dir = dir.join("sealed");
let open_dir = dir.join("open");
std::fs::create_dir_all(&sealed_dir).unwrap();
std::fs::create_dir_all(&open_dir).unwrap();
let (sealed_repo, sealed_sum) =
repo_with_object(&sealed_dir, RepoMode::BareUser, "yes").await;
let (open, open_sum) = repo_with_object(&open_dir, RepoMode::BareUser, "no").await;
assert!(sealed(&sealed_repo, &sealed_sum));
assert!(!sealed(&open, &open_sum));
let file = open.load_file_with(&open_sum, true).await.unwrap();
assert_eq!(file.kernel_fs_verity(), None);
let path = loose_path(&sealed_sum, ObjectType::File, RepoMode::BareUser);
let size = payload().len() as u64;
let opened = sealed_repo.objects().open_regular(&path).unwrap();
assert!(opened.stat.verity);
assert_eq!(
verity_digest(opened.file.as_fd(), size),
Some(FsVerityHasher::hash(&payload()))
);
assert_eq!(
verity_digest(opened.file.as_fd(), size + 1),
None,
"another size gives no digest"
);
});
let _ = std::fs::remove_dir_all(&dir);
}
fn unpack_bare_user_fixture(dir: &Path) -> Option<PathBuf> {
let tar = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/generated/bare-user.tar");
if !tar.exists() {
return None;
}
let status = std::process::Command::new("tar")
.args(["--xattrs", "--xattrs-include=user.*", "-xf"])
.arg(&tar)
.arg("-C")
.arg(dir)
.status()
.expect("run tar to unpack the fixture");
assert!(status.success(), "tar failed to unpack {}", tar.display());
Some(dir.join("repo"))
}
#[test]
fn every_sealed_fixture_object_yields_the_kernel_digest() {
use futures_lite::AsyncReadExt;
let dir = scratch("fixture");
if !verity_supported(&dir) {
eprintln!("skipping fixture digest check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
let Some(root) = unpack_bare_user_fixture(&dir) else {
eprintln!("skipping fixture digest check: fixture absent");
let _ = std::fs::remove_dir_all(&dir);
return;
};
let mut objects = Vec::new();
for fanout in std::fs::read_dir(root.join("objects")).unwrap() {
let fanout = fanout.unwrap().path();
if !fanout.is_dir() {
continue;
}
let prefix = fanout.file_name().unwrap().to_str().unwrap().to_owned();
for entry in std::fs::read_dir(&fanout).unwrap() {
let path = entry.unwrap().path();
let name = path.file_name().unwrap().to_str().unwrap();
let Some(rest) = name.strip_suffix(".file") else {
continue;
};
let checksum = Checksum::from_hex(&format!("{prefix}{rest}")).unwrap();
let ro = std::fs::File::open(&path).unwrap();
ostrya_sys::enable_verity(ro.as_fd()).unwrap();
objects.push(checksum);
}
}
block_on(async {
let repo = Repo::open(&root).await.unwrap();
let mut backed = 0;
for checksum in &objects {
let file = repo.load_file_with(checksum, true).await.unwrap();
if !matches!(file.kind, FileKind::Regular { size } if size > 0) {
continue;
}
let mut reader = file.reader().await.unwrap();
let mut hasher = FsVerityHasher::new();
let mut buf = vec![0u8; 64 * 1024];
loop {
let n = reader.read(&mut buf).await.unwrap();
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
assert_eq!(
file.kernel_fs_verity(),
Some(hasher.finalize()),
"{checksum} gives the kernel digest"
);
backed += 1;
}
assert!(backed > 0, "the fixture holds backed objects");
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_sealed_archive_object_yields_none() {
let dir = scratch("archive");
if !verity_supported(&dir) {
eprintln!("skipping archive check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
block_on(async {
let (repo, checksum) = repo_with_object(&dir, RepoMode::Archive, "yes").await;
let object = object_path(&dir, &checksum, RepoMode::Archive);
let fd = std::fs::File::open(&object).unwrap();
assert!(
ostrya_sys::measure_verity(fd.as_fd()).is_ok(),
"the write path sealed the archive object"
);
let file = repo.load_file_with(&checksum, true).await.unwrap();
assert_eq!(file.kernel_fs_verity(), None);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn an_unsealed_object_yields_none() {
let dir = scratch("unsealed");
block_on(async {
let (repo, checksum) = repo_with_object(&dir, RepoMode::BareUser, "no").await;
let file = repo.load_file_with(&checksum, true).await.unwrap();
assert_eq!(file.kernel_fs_verity(), None);
});
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_salted_object_yields_none() {
let dir = scratch("salted");
if !verity_supported(&dir) {
eprintln!("skipping salted check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
block_on(async {
let (repo, checksum) = repo_with_object(&dir, RepoMode::BareUser, "no").await;
let object = object_path(&dir, &checksum, RepoMode::BareUser);
let ro = std::fs::File::open(&object).unwrap();
ostrya_sys::enable_verity_with_salt(ro.as_fd(), &[0x5a; 8]).unwrap();
drop(ro);
let file = repo.load_file_with(&checksum, true).await.unwrap();
assert_eq!(file.kernel_fs_verity(), None);
});
let _ = std::fs::remove_dir_all(&dir);
}
async fn write_one(
dir: &Path,
mode: RepoMode,
fsverity: &str,
meta: &FileMeta,
) -> crate::Result<(Repo, Checksum)> {
std::fs::create_dir_all(dir).unwrap();
let repo = repo_in(dir, mode, fsverity).await;
let txn = repo.transaction().await?;
let checksum = txn.write_regfile_inline(None, meta, &payload()).await?;
txn.commit().await?;
Ok((repo, checksum))
}
const SEAL_XATTR: &str = "user.ostrya-seal";
#[derive(Debug)]
struct Inode {
perm: u32,
uid: u32,
gid: u32,
sealed: bool,
ostreemeta: Option<Vec<u8>>,
seal_xattr: Option<Vec<u8>>,
}
fn inode_of(repo: &Repo, checksum: &Checksum) -> Inode {
use rustix::fs::{Mode, OFlags};
let path = loose_path(checksum, ObjectType::File, repo.mode());
let stat = repo.objects().lstat(&path).unwrap();
let fd = rustix::fs::openat(
repo.objects_fd(),
path.as_str(),
OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::empty(),
)
.ok();
let xattr = |name: &str| {
fd.as_ref()
.and_then(|fd| crate::repo_fs::xattr(fd.as_fd(), name).unwrap())
};
Inode {
perm: stat.mode & 0o7777,
uid: stat.uid,
gid: stat.gid,
sealed: stat.verity,
ostreemeta: xattr("user.ostreemeta"),
seal_xattr: xattr(SEAL_XATTR),
}
}
fn check_like_unsealed(
tag: &str,
mode: RepoMode,
fsverity: &str,
metas: &[FileMeta],
) -> Option<Vec<Inode>> {
let dir = scratch(tag);
if !verity_supported(&dir) {
eprintln!("skipping {tag} seal-order check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return None;
}
let mut failures = Vec::new();
let mut sealed_side = Vec::new();
block_on(async {
for meta in metas {
let name = format!("{:o}", meta.mode);
let on = write_one(&dir.join(format!("on-{name}")), mode, fsverity, meta).await;
let (on_repo, on_sum) = match on {
Ok(pair) => pair,
Err(e) => {
failures.push(format!("{name} with fsverity={fsverity}: {e}"));
continue;
}
};
let (off_repo, off_sum) =
write_one(&dir.join(format!("off-{name}")), mode, "no", meta)
.await
.unwrap();
assert_eq!(on_sum, off_sum, "{name}: the checksums agree");
let on = inode_of(&on_repo, &on_sum);
let off = inode_of(&off_repo, &off_sum);
assert_eq!(on.perm, off.perm, "{name}: the inode modes agree");
assert_eq!(
(on.uid, on.gid),
(off.uid, off.gid),
"{name}: the owners agree"
);
assert_eq!(
on.ostreemeta, off.ostreemeta,
"{name}: user.ostreemeta agrees"
);
assert_eq!(on.seal_xattr, off.seal_xattr, "{name}: {SEAL_XATTR} agrees");
assert!(
!off.sealed,
"{name}: the object with verity off is unsealed"
);
if !on.sealed {
failures.push(format!("{name} with fsverity={fsverity}: object unsealed"));
continue;
}
if mode != RepoMode::Archive && on.perm & 0o400 != 0 {
let file = on_repo.load_file_with(&on_sum, true).await.unwrap();
assert_eq!(
file.kernel_fs_verity(),
Some(FsVerityHasher::hash(&payload())),
"{name}: the kernel digest equals the computed digest"
);
}
sealed_side.push(on);
}
});
let _ = std::fs::remove_dir_all(&dir);
assert!(failures.is_empty(), "{tag}: {failures:#?}");
Some(sealed_side)
}
fn metas(perms: &[u32]) -> Vec<FileMeta> {
perms.iter().map(|&p| FileMeta::regular(0, 0, p)).collect()
}
#[test]
fn a_bare_user_object_without_owner_write_is_sealed() {
check_like_unsealed(
"bu-nowrite",
RepoMode::BareUser,
"yes",
&metas(&[0o444, 0o555, 0o400]),
);
}
#[test]
fn a_bare_user_only_object_without_owner_write_is_sealed() {
check_like_unsealed(
"buo-nowrite",
RepoMode::BareUserOnly,
"yes",
&metas(&[0o444, 0o555, 0o400, 0o200]),
);
}
#[test]
fn maybe_seals_a_bare_user_object_without_owner_write() {
check_like_unsealed("bu-maybe", RepoMode::BareUser, "maybe", &metas(&[0o444]));
}
#[test]
fn an_owner_writable_object_is_sealed_with_an_unchanged_inode() {
let perms = [0o644, 0o755];
let Some(inodes) =
check_like_unsealed("bu-write", RepoMode::BareUser, "yes", &metas(&perms))
else {
return;
};
for (inode, (perm, meta)) in inodes.iter().zip(perms.iter().zip(metas(&perms))) {
assert_eq!(inode.perm, perm | 0o400);
let expected = meta.regular_header().serialize_stat_metadata().unwrap();
assert_eq!(inode.ostreemeta.as_deref(), Some(&expected[..]));
}
let inodes = check_like_unsealed("ar-write", RepoMode::Archive, "yes", &metas(&perms))
.expect("the archive check runs where the bare-user check ran");
for inode in inodes {
assert_eq!(inode.perm, 0o644);
}
}
#[test]
fn a_bare_object_with_a_foreign_owner_is_sealed_as_root() {
if !rustix::process::geteuid().is_root() {
eprintln!("skipping bare foreign-owner seal check: not running as root");
return;
}
let xattrs =
ostrya_core::Xattrs::new([(format!("{SEAL_XATTR}\0").into_bytes(), b"v".to_vec())])
.unwrap();
let metas: Vec<FileMeta> = [0o100444, 0o104555]
.into_iter()
.map(|mode| FileMeta {
uid: 1234,
gid: 5678,
mode,
xattrs: xattrs.clone(),
})
.collect();
let Some(inodes) = check_like_unsealed("bare-owner", RepoMode::Bare, "yes", &metas) else {
return;
};
for (inode, perm) in inodes.iter().zip([0o444, 0o4555]) {
assert_eq!((inode.uid, inode.gid), (1234, 5678));
assert_eq!(inode.perm, perm);
assert_eq!(inode.seal_xattr.as_deref(), Some(&b"v"[..]));
}
}
#[test]
fn a_bare_object_owned_by_the_writer_without_owner_write_is_sealed() {
let uid = rustix::process::geteuid().as_raw();
let gid = rustix::process::getegid().as_raw();
let xattrs =
ostrya_core::Xattrs::new([(format!("{SEAL_XATTR}\0").into_bytes(), b"v".to_vec())])
.unwrap();
let metas: Vec<FileMeta> = [0o100444, 0o100555, 0o100400]
.into_iter()
.map(|mode| FileMeta {
uid,
gid,
mode,
xattrs: xattrs.clone(),
})
.collect();
let Some(inodes) = check_like_unsealed("bare-self", RepoMode::Bare, "yes", &metas) else {
return;
};
for (inode, perm) in inodes.iter().zip([0o444, 0o555, 0o400]) {
assert_eq!((inode.uid, inode.gid), (uid, gid));
assert_eq!(inode.perm, perm);
assert_eq!(inode.seal_xattr.as_deref(), Some(&b"v"[..]));
}
}
#[test]
fn a_bare_object_keeps_its_file_capability_as_root() {
use rustix::fs::{Mode, OFlags};
if !rustix::process::geteuid().is_root() {
eprintln!("skipping bare file-capability check: not running as root");
return;
}
let cap: Vec<u8> = [0x0200_0001u32, 1 << 13, 0, 0, 0]
.iter()
.flat_map(|word| word.to_le_bytes())
.collect();
let cap_xattr = (b"security.capability\0".to_vec(), cap.clone());
let seal_xattr = (format!("{SEAL_XATTR}\0").into_bytes(), b"v".to_vec());
let cases = [
(
"self",
FileMeta {
uid: rustix::process::geteuid().as_raw(),
gid: rustix::process::getegid().as_raw(),
mode: 0o100755,
xattrs: ostrya_core::Xattrs::new([cap_xattr.clone()]).unwrap(),
},
0o755,
None,
),
(
"foreign",
FileMeta {
uid: 1234,
gid: 5678,
mode: 0o104755,
xattrs: ostrya_core::Xattrs::new([cap_xattr, seal_xattr]).unwrap(),
},
0o4755,
Some(b"v".to_vec()),
),
];
let dir = scratch("bare-cap");
let verity = verity_supported(&dir);
let mut failures = Vec::new();
block_on(async {
for fsverity in ["no", "yes"] {
if fsverity == "yes" && !verity {
eprintln!("skipping the verity side: filesystem lacks fs-verity");
continue;
}
for (tag, meta, perm, seal) in &cases {
let (repo, checksum) = write_one(
&dir.join(format!("{fsverity}-{tag}")),
RepoMode::Bare,
fsverity,
meta,
)
.await
.unwrap();
let path = loose_path(&checksum, ObjectType::File, repo.mode());
let fd = rustix::fs::openat(
repo.objects_fd(),
path.as_str(),
OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::empty(),
)
.unwrap();
let stored = crate::repo_fs::xattr(fd.as_fd(), "security.capability").unwrap();
if stored.as_deref() != Some(&cap[..]) {
failures.push(format!(
"fsverity={fsverity} {tag}: security.capability is {stored:02x?}"
));
}
let inode = inode_of(&repo, &checksum);
let what = format!("fsverity={fsverity} {tag}");
assert_eq!(inode.perm, *perm, "{what}: the inode mode");
assert_eq!(
(inode.uid, inode.gid),
(meta.uid, meta.gid),
"{what}: owner"
);
assert_eq!(&inode.seal_xattr, seal, "{what}: {SEAL_XATTR}");
assert_eq!(inode.sealed, fsverity == "yes", "{what}: the seal");
}
}
});
let _ = std::fs::remove_dir_all(&dir);
assert!(failures.is_empty(), "{failures:#?}");
}
const SEAL_UMASK_CHILD: &str = "OSTRYA_SEAL_UMASK_CHILD";
#[test]
fn an_object_written_under_a_umask_without_owner_write_is_sealed() {
if let Some(marker) = std::env::var_os(SEAL_UMASK_CHILD) {
let marker = PathBuf::from(marker);
write_under_umask(&marker.with_file_name("child"));
std::fs::write(marker, b"written").expect("record that the write ran");
return;
}
let dir = scratch("umask");
if !verity_supported(&dir) {
eprintln!("skipping umask seal check: filesystem lacks fs-verity");
let _ = std::fs::remove_dir_all(&dir);
return;
}
let marker = dir.join("written");
let exe = std::env::current_exe().expect("the path of the running test binary");
let status = std::process::Command::new(&exe)
.arg("--exact")
.arg("file::sealed_verity_tests::an_object_written_under_a_umask_without_owner_write_is_sealed")
.arg("--nocapture")
.env(SEAL_UMASK_CHILD, &marker)
.status()
.expect("re-run the test binary for the umask write");
let written = marker.exists();
let _ = std::fs::remove_dir_all(&dir);
assert!(
status.success(),
"the write under umask 0222 failed: {status}"
);
assert!(
written,
"the child ran no write: the test name the filter names is stale"
);
}
fn write_under_umask(dir: &Path) {
use rustix::fs::Mode;
use std::os::unix::fs::PermissionsExt;
std::fs::create_dir_all(dir).unwrap();
let meta = FileMeta::regular(0, 0, 0o644);
block_on(async {
let repo = repo_in(dir, RepoMode::BareUser, "yes").await;
let txn = repo.transaction().await.unwrap();
let old = rustix::process::umask(Mode::from_raw_mode(0o222));
let probe = dir.join("umask-probe");
std::fs::write(&probe, b"probe").unwrap();
let probe_mode = std::fs::metadata(&probe).unwrap().permissions().mode() & 0o7777;
let written = txn.write_regfile_inline(None, &meta, &payload()).await;
rustix::process::umask(old);
assert_eq!(probe_mode, 0o444, "umask 0222 clears the owner-write bit");
let checksum = written.unwrap();
txn.commit().await.unwrap();
let inode = inode_of(&repo, &checksum);
assert!(inode.sealed, "the object is sealed");
assert_eq!(inode.perm, 0o644);
let expected = meta.regular_header().serialize_stat_metadata().unwrap();
assert_eq!(inode.ostreemeta.as_deref(), Some(&expected[..]));
});
}
}
#[cfg(test)]
mod content_size_tests {
use std::path::Path;
use ostrya_core::{Checksum, ObjectType, RepoMode, loose_path};
use ostrya_rt::block_on;
use crate::repo_fs::TestDir;
use crate::{CreateOptions, Error, Repo};
const SYMLINK_TEXT: &str =
"passes through a symlink; ostrya refuses a symlink in the repository";
#[derive(Debug, Clone, Copy)]
enum Kind {
Symlink,
Fifo,
}
fn size_of_entry(dir: &Path, mode: RepoMode, kind: Kind, stored: bool) -> (Error, String) {
let root = dir.join(format!("{mode:?}-{kind:?}-{stored}"));
let repo = block_on(Repo::create(&root, CreateOptions::new(mode))).unwrap();
let checksum = Checksum::from_hex(&format!("ab{}", "c".repeat(62))).unwrap();
let rel = loose_path(&checksum, ObjectType::File, mode);
let path = root.join("objects").join(&rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
match kind {
Kind::Symlink => std::os::unix::fs::symlink("../../config", &path).unwrap(),
Kind::Fifo => rustix::fs::mknodat(
rustix::fs::CWD,
&path,
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o600),
0,
)
.unwrap(),
}
let err = repo.content_size_blocking(&[checksum], stored).unwrap_err();
(err, format!("objects/{rel}"))
}
#[test]
fn content_size_refuses_a_type_that_the_mode_does_not_store() {
let dir = TestDir::new("content-size-type");
let cases = [
(RepoMode::Archive, Kind::Symlink, true, SYMLINK_TEXT),
(RepoMode::Archive, Kind::Fifo, true, "is not a regular file"),
(
RepoMode::Archive,
Kind::Fifo,
false,
"is not a regular file",
),
(RepoMode::BareUser, Kind::Symlink, false, SYMLINK_TEXT),
(
RepoMode::BareUser,
Kind::Fifo,
false,
"is not a regular file",
),
(
RepoMode::BareUserOnly,
Kind::Fifo,
false,
"is not a regular file",
),
(RepoMode::Bare, Kind::Fifo, false, "is not a regular file"),
];
for (mode, kind, stored, text) in cases {
let (err, path) = size_of_entry(dir.path(), mode, kind, stored);
match err {
Error::InvalidFormat(m) => {
assert_eq!(m, format!("{path} {text}"), "{mode:?} {kind:?} {stored}")
}
other => panic!("{mode:?} {kind:?} {stored}: {other}"),
}
}
let root = dir.path().join("buo-link");
let repo = block_on(Repo::create(
&root,
CreateOptions::new(RepoMode::BareUserOnly),
))
.unwrap();
let checksum = Checksum::from_hex(&format!("ab{}", "d".repeat(62))).unwrap();
let rel = loose_path(&checksum, ObjectType::File, RepoMode::BareUserOnly);
let path = root.join("objects").join(rel);
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::os::unix::fs::symlink("target", &path).unwrap();
assert_eq!(repo.content_size_blocking(&[checksum], false).unwrap(), 0);
}
}