mod common;
use std::os::fd::AsFd;
use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};
use std::path::{Path, PathBuf};
use std::process::Command;
use common::{TmpDir, ostree_available};
use ostrya::{
Checksum, CommitModifier, CommitModifierFlags, CommitOptions, CommitState, CreateOptions,
Ed25519Signer, Error, MutableTree, PullFlags, PullOptions, PullVerify, Repo, RepoMode, Type,
Value,
};
use ostrya_rt::block_on;
const FIXED_TS: u64 = 1_700_000_000;
fn ostree(args: &[&str]) -> Vec<u8> {
let out = Command::new("ostree")
.args(args)
.output()
.expect("run ostree");
assert!(
out.status.success(),
"ostree {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr)
);
out.stdout
}
fn build_tree(dir: &Path, marker: &[u8]) {
std::fs::create_dir_all(dir.join("subdir")).unwrap();
std::fs::write(dir.join("hello.txt"), marker).unwrap();
std::fs::write(dir.join("exec.sh"), b"#!/bin/sh\necho hi\n").unwrap();
std::fs::write(dir.join("subdir/nested.txt"), b"nested\n").unwrap();
symlink("hello.txt", dir.join("link")).unwrap();
std::fs::set_permissions(
dir.join("hello.txt"),
std::fs::Permissions::from_mode(0o644),
)
.unwrap();
std::fs::set_permissions(dir.join("exec.sh"), std::fs::Permissions::from_mode(0o755)).unwrap();
}
fn ref_binding(branch: &str) -> Value {
Value::Array(vec![Value::Tuple(vec![
Value::Str("ostree.ref-binding".to_owned()),
Value::Variant(Box::new((
Type::parse("as").unwrap(),
Value::Array(vec![Value::Str(branch.to_owned())]),
))),
])])
}
async fn commit_tree(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
) -> Checksum {
commit_tree_with(
repo,
base,
sub,
branch,
parent,
CommitModifierFlags::SKIP_XATTRS,
None,
)
.await
}
async fn commit_tree_with(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
flags: CommitModifierFlags,
owner: Option<(u32, u32)>,
) -> Checksum {
let txn = repo.transaction().await.unwrap();
let mut mtree = MutableTree::new();
let mut modifier = CommitModifier::new(flags);
if let Some((uid, gid)) = owner {
modifier.owner_uid = Some(uid);
modifier.owner_gid = Some(gid);
}
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(dfd.as_fd(), Path::new(sub), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
parent,
subject: Some(format!("{branch} {sub}")),
timestamp: Some(FIXED_TS),
metadata: Some(ref_binding(branch)),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(branch, Some(&commit));
txn.commit().await.unwrap();
commit
}
async fn make_repo(base: &Path, name: &str, mode: RepoMode) -> (PathBuf, Repo) {
let path = base.join(name);
let repo = Repo::create(&path, CreateOptions::new(mode)).await.unwrap();
(path, repo)
}
async fn make_repo_in_group(base: &Path, name: &str, mode: RepoMode, gid: u32) -> (PathBuf, Repo) {
let parent = base.join(format!("{name}-group"));
std::fs::create_dir(&parent).unwrap();
std::os::unix::fs::chown(&parent, None, Some(gid)).unwrap();
std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o2775)).unwrap();
let path = parent.join(name);
let repo = Repo::create(&path, CreateOptions::new(mode)).await.unwrap();
(path, repo)
}
async fn source_repo(base: &Path, mode: RepoMode) -> (PathBuf, Repo, Checksum, Checksum) {
build_tree(&base.join("v1"), b"hello one\n");
build_tree(&base.join("v2"), b"hello two\n");
let (path, repo) = make_repo(base, "src", mode).await;
let c1 = commit_tree(&repo, base, "v1", "main", None).await;
let c2 = commit_tree(&repo, base, "v2", "main", Some(c1)).await;
(path, repo, c1, c2)
}
async fn canonical_source_repo(base: &Path, mode: RepoMode) -> (PathBuf, Repo, Checksum, Checksum) {
build_tree(&base.join("v1"), b"hello one\n");
build_tree(&base.join("v2"), b"hello two\n");
let (path, repo) = make_repo(base, "src", mode).await;
let flags = CommitModifierFlags::SKIP_XATTRS | CommitModifierFlags::CANONICAL_PERMISSIONS;
let c1 = commit_tree_with(&repo, base, "v1", "main", None, flags, None).await;
let c2 = commit_tree_with(&repo, base, "v2", "main", Some(c1), flags, None).await;
(path, repo, c1, c2)
}
async fn owned_source_repo(base: &Path, mode: RepoMode) -> (PathBuf, Repo, Checksum, Checksum) {
build_tree(&base.join("v1"), b"hello one\n");
build_tree(&base.join("v2"), b"hello two\n");
let (path, repo) = make_repo(base, "src", mode).await;
let flags = CommitModifierFlags::SKIP_XATTRS;
let owner = Some((1000, 1000));
let c1 = commit_tree_with(&repo, base, "v1", "main", None, flags, owner).await;
let c2 = commit_tree_with(&repo, base, "v2", "main", Some(c1), flags, owner).await;
(path, repo, c1, c2)
}
fn object_ino(repo_dir: &Path, name: &str) -> Option<(u64, u64)> {
let path = repo_dir.join("objects").join(&name[..2]).join(&name[2..]);
std::fs::symlink_metadata(path)
.ok()
.map(|m| (m.dev(), m.ino()))
}
fn object_mode(repo_dir: &Path, name: &str) -> Option<u32> {
let path = repo_dir.join("objects").join(&name[..2]).join(&name[2..]);
std::fs::symlink_metadata(path)
.ok()
.map(|m| m.mode() & 0o7777)
}
async fn pull_main(dst: &Repo, src: &Repo, flags: PullFlags) {
dst.pull_local(
src,
PullOptions {
refs: vec!["main".to_owned()],
flags,
..PullOptions::default()
},
)
.await
.unwrap();
}
fn object_names(repo_dir: &Path) -> Vec<String> {
let mut out = Vec::new();
let objects = repo_dir.join("objects");
let Ok(fanouts) = std::fs::read_dir(&objects) else {
return out;
};
for fanout in fanouts.flatten() {
let prefix = fanout.file_name().to_string_lossy().into_owned();
if prefix.len() != 2 {
continue;
}
for entry in std::fs::read_dir(fanout.path()).unwrap().flatten() {
out.push(format!("{prefix}{}", entry.file_name().to_string_lossy()));
}
}
out.sort();
out
}
async fn first_regular_content(repo: &Repo, commit: &Checksum) -> ostrya::ObjectName {
let mut names: Vec<ostrya::ObjectName> = repo
.traverse_commit(commit, 0)
.await
.unwrap()
.into_iter()
.filter(|name| name.ty == ostrya::ObjectType::File)
.collect();
names.sort_by_key(|name| name.checksum.to_hex());
for name in names {
let file = repo.load_file(&name.checksum).await.unwrap();
if let ostrya::FileKind::Regular { size } = file.kind
&& size > 0
{
return name;
}
}
panic!("the commit holds no regular content object with a payload");
}
async fn symlink_content(repo: &Repo, commit: &Checksum) -> ostrya::ObjectName {
let mut names: Vec<ostrya::ObjectName> = repo
.traverse_commit(commit, 0)
.await
.unwrap()
.into_iter()
.filter(|name| name.ty == ostrya::ObjectType::File)
.collect();
names.sort_by_key(|name| name.checksum.to_hex());
for name in names {
if repo.load_file(&name.checksum).await.unwrap().is_symlink() {
return name;
}
}
panic!("the commit holds no symlink content object");
}
async fn subdir_dirtree(repo: &Repo, commit: &Checksum) -> ostrya::ObjectName {
let bytes = repo
.load_object_bytes(ostrya::ObjectType::Commit, commit)
.await
.unwrap();
let root = ostrya::Commit::parse(&bytes).unwrap().root_dirtree;
repo.traverse_commit(commit, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ostrya::ObjectType::DirTree && name.checksum != root)
.expect("the commit holds a subdirectory dirtree")
}
fn object_path(repo_dir: &Path, name: &ostrya::ObjectName, mode: RepoMode) -> PathBuf {
repo_dir.join("objects").join(name.loose_path(mode))
}
fn has_xattr(path: &Path, name: &str) -> bool {
let mut buf = [0u8; 256];
rustix::fs::getxattr(path, name, &mut buf).is_ok()
}
fn has_ostreemeta(path: &Path) -> bool {
has_xattr(path, "user.ostreemeta")
}
fn other_group(own: u32) -> Option<u32> {
let out = Command::new("id").arg("-G").output().ok()?;
String::from_utf8_lossy(&out.stdout)
.split_whitespace()
.filter_map(|g| g.parse::<u32>().ok())
.find(|g| *g != own)
}
const REQUIRE_MULTIGROUP: &str = "OSTRYA_REQUIRE_MULTIGROUP";
fn required_other_group(own: u32) -> Option<u32> {
if let Some(gid) = other_group(own) {
return Some(gid);
}
assert!(
std::env::var_os(REQUIRE_MULTIGROUP).is_none(),
"{REQUIRE_MULTIGROUP} is set and the process belongs to a single group, \
so the ownership gate cannot be exercised"
);
eprintln!("skipped: the process belongs to a single group");
None
}
fn flat_object_path(repo_dir: &Path, flat: &str) -> PathBuf {
repo_dir.join("objects").join(&flat[..2]).join(&flat[2..])
}
async fn verity_repo(base: &Path, name: &str, mode: RepoMode, fsverity: &str) -> (PathBuf, Repo) {
let (path, repo) = make_repo(base, name, mode).await;
drop(repo);
let config = path.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!("[ex-integrity]\nfsverity={fsverity}\n"));
std::fs::write(&config, text).unwrap();
let repo = Repo::open(&path).await.unwrap();
(path, repo)
}
fn is_sealed(path: &Path) -> bool {
std::fs::OpenOptions::new().write(true).open(path).is_err()
}
async fn fs_supports_verity(base: &Path) -> bool {
build_tree(&base.join("verity-probe"), b"probe\n");
let (path, repo) = verity_repo(base, "verity-probe-repo", RepoMode::BareUser, "maybe").await;
commit_tree(&repo, base, "verity-probe", "probe", None).await;
object_names(&path)
.iter()
.any(|flat| is_sealed(&flat_object_path(&path, flat)))
}
async fn zero_budget_repo(base: &Path, name: &str, mode: RepoMode) -> (PathBuf, Repo) {
let (path, repo) = make_repo(base, name, mode).await;
drop(repo);
let config = path.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str("min-free-space-percent=100\n");
std::fs::write(&config, text).unwrap();
let repo = Repo::open(&path).await.unwrap();
(path, repo)
}
fn has_partial_marker(repo_dir: &Path, commit: &Checksum) -> bool {
repo_dir
.join("state")
.join(format!("{}.commitpartial", commit.to_hex()))
.exists()
}
#[test]
fn pulls_a_ref_its_commit_and_its_tree() {
let tmp = TmpDir::new("pull-basic");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let stats = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
assert!(
dst.has_object(ostrya::ObjectType::Commit, &c2)
.await
.unwrap()
);
assert!(
!dst.has_object(ostrya::ObjectType::Commit, &c1)
.await
.unwrap()
);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
assert!(stats.metadata_imported > 0 && stats.content_imported > 0);
let reached = src.traverse_commit(&c2, 0).await.unwrap();
for name in &reached {
assert!(
dst.has_object(name.ty, &name.checksum).await.unwrap(),
"{name} missing from the destination"
);
}
assert_eq!(object_names(&dst_dir).len(), reached.len());
assert!(object_names(&src_dir).len() > reached.len());
let again = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(again.metadata_imported, 0);
assert_eq!(again.content_imported, 0);
});
}
#[test]
fn an_empty_ref_list_pulls_every_ref() {
let tmp = TmpDir::new("pull-all-refs");
block_on(async {
let base = tmp.path();
build_tree(&base.join("v1"), b"hello\n");
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let a = commit_tree(&src, base, "v1", "a", None).await;
let b = commit_tree(&src, base, "v1", "team/b", None).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, PullOptions::default()).await.unwrap();
assert_eq!(dst.resolve_rev("a", false).await.unwrap(), Some(a));
assert_eq!(dst.resolve_rev("team/b", false).await.unwrap(), Some(b));
});
}
#[test]
fn a_remote_name_writes_the_ref_under_refs_remotes() {
let tmp = TmpDir::new("pull-remote");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
..PullOptions::default()
},
)
.await
.unwrap();
assert!(dst_dir.join("refs/remotes/origin/main").exists());
assert!(!dst_dir.join("refs/heads/main").exists());
assert_eq!(
dst.resolve_rev("origin:main", false).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn a_local_pull_ignores_the_mirror_flag() {
let tmp = TmpDir::new("pull-mirror");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
flags: PullFlags::MIRROR,
..PullOptions::default()
},
)
.await
.unwrap();
assert!(dst_dir.join("refs/remotes/origin/main").exists());
assert!(!dst_dir.join("refs/heads/main").exists());
assert_eq!(
dst.resolve_rev("origin:main", false).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn depth_follows_parent_commits() {
let tmp = TmpDir::new("pull-depth");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
depth: -1,
..PullOptions::default()
},
)
.await
.unwrap();
for commit in [c1, c2] {
assert!(
dst.has_object(ostrya::ObjectType::Commit, &commit)
.await
.unwrap()
);
assert_eq!(
dst.commit_state(&commit).await.unwrap(),
CommitState::Normal
);
}
});
}
#[test]
fn depth_does_not_depend_on_ref_order() {
let tmp = TmpDir::new("pull-depth-order");
block_on(async {
let base = tmp.path();
for (sub, marker) in [
("v1", "one\n"),
("v2", "two\n"),
("v3", "three\n"),
("v4", "four\n"),
] {
build_tree(&base.join(sub), marker.as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let c1 = commit_tree(&src, base, "v1", "main", None).await;
let c2 = commit_tree(&src, base, "v2", "main", Some(c1)).await;
let c3 = commit_tree(&src, base, "v3", "old", Some(c2)).await;
let c4 = commit_tree(&src, base, "v4", "main", Some(c3)).await;
for (name, refs) in [
("forward", vec!["main".to_owned(), "old".to_owned()]),
("reverse", vec!["old".to_owned(), "main".to_owned()]),
] {
let (_dst_dir, dst) = make_repo(base, name, RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs,
depth: 1,
..PullOptions::default()
},
)
.await
.unwrap();
for commit in [c4, c3, c2] {
assert!(
dst.has_object(ostrya::ObjectType::Commit, &commit)
.await
.unwrap(),
"{name}: commit {commit} missing"
);
}
assert!(
!dst.has_object(ostrya::ObjectType::Commit, &c1)
.await
.unwrap(),
"{name}: commit {c1} is past the requested depth"
);
}
});
}
#[test]
fn a_deep_pull_imports_every_commits_tree() {
let tmp = TmpDir::new("pull-deep-tree");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
depth: -1,
..PullOptions::default()
},
)
.await
.unwrap();
let reached = src.traverse_commit(&c2, -1).await.unwrap();
for name in &reached {
assert!(
dst.has_object(name.ty, &name.checksum).await.unwrap(),
"{name} missing from the destination"
);
}
assert_eq!(object_names(&dst_dir).len(), reached.len());
});
}
#[test]
fn a_parent_the_source_lacks_ends_the_chain() {
let tmp = TmpDir::new("pull-truncated");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
std::fs::remove_file(
src_dir
.join("objects")
.join(&c1.to_hex()[..2])
.join(format!("{}.commit", &c1.to_hex()[2..])),
)
.unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
depth: -1,
..PullOptions::default()
},
)
.await
.unwrap();
assert!(
dst.has_object(ostrya::ObjectType::Commit, &c2)
.await
.unwrap()
);
assert!(
!dst.has_object(ostrya::ObjectType::Commit, &c1)
.await
.unwrap()
);
});
}
#[test]
fn a_missing_ref_fails_before_anything_is_imported() {
let tmp = TmpDir::new("pull-missing-ref");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, _c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["nosuch".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::RefNotFound(ref name) if name == "nosuch"));
assert!(object_names(&dst_dir).is_empty());
});
}
#[test]
fn a_same_mode_import_hardlinks_the_loose_object() {
let tmp = TmpDir::new("pull-hardlink");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let reached = src.traverse_commit(&c2, 0).await.unwrap();
assert!(!reached.is_empty());
for name in &reached {
let object = name.loose_path(RepoMode::Archive).replace('/', "");
assert_eq!(
object_ino(&src_dir, &object),
object_ino(&dst_dir, &object),
"{name} should share the source inode"
);
}
});
}
#[test]
fn force_copy_clones_the_object_instead_of_linking() {
let tmp = TmpDir::new("pull-force-copy");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::FORCE_COPY,
..PullOptions::default()
},
)
.await
.unwrap();
let reached = src.traverse_commit(&c2, 0).await.unwrap();
for name in &reached {
let object = name.loose_path(RepoMode::BareUser).replace('/', "");
let src_ino = object_ino(&src_dir, &object).unwrap();
let dst_ino = object_ino(&dst_dir, &object).unwrap();
assert_ne!(src_ino, dst_ino, "{name} should be a fresh inode");
let src_path = src_dir
.join("objects")
.join(&object[..2])
.join(&object[2..]);
let dst_path = dst_dir
.join("objects")
.join(&object[..2])
.join(&object[2..]);
let src_meta = std::fs::symlink_metadata(&src_path).unwrap();
let dst_meta = std::fs::symlink_metadata(&dst_path).unwrap();
assert_eq!(
src_meta.permissions().mode(),
dst_meta.permissions().mode(),
"{name} should carry the bare-user mode"
);
if src_meta.is_file() {
assert_eq!(
std::fs::read(&src_path).unwrap(),
std::fs::read(&dst_path).unwrap()
);
}
}
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_refused_link_imports_a_content_object_through_its_header() {
let tmp = TmpDir::new("pull-refused-link");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let content = first_regular_content(&src, &c2).await;
let src_path = object_path(&src_dir, &content, RepoMode::BareUser);
std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o600)).unwrap();
rustix::fs::setxattr(
&src_path,
"user.stray",
b"1",
rustix::fs::XattrFlags::empty(),
)
.unwrap();
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::FORCE_COPY,
..PullOptions::default()
},
)
.await
.unwrap();
let dst_path = object_path(&dst_dir, &content, RepoMode::BareUser);
let logical = src.load_file(&content.checksum).await.unwrap().mode;
assert_eq!(
std::fs::symlink_metadata(&dst_path)
.unwrap()
.permissions()
.mode()
& 0o7777,
(logical & 0o775) | 0o400
);
assert!(has_ostreemeta(&dst_path));
assert!(!has_xattr(&dst_path, "user.stray"));
assert_eq!(
std::fs::read(&src_path).unwrap(),
std::fs::read(&dst_path).unwrap()
);
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_cloned_metadata_object_takes_the_destination_policy() {
let tmp = TmpDir::new("pull-clone-metadata");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Bare).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Bare).await;
build_tree(&base.join("baseline"), b"baseline\n");
let baseline = commit_tree(&dst, base, "baseline", "baseline", None).await;
let want = std::fs::symlink_metadata(object_path(
&dst_dir,
&ostrya::ObjectName::new(baseline, ostrya::ObjectType::Commit),
RepoMode::Bare,
))
.unwrap();
let name = ostrya::ObjectName::new(c2, ostrya::ObjectType::Commit);
let src_path = object_path(&src_dir, &name, RepoMode::Bare);
std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o600)).unwrap();
rustix::fs::setxattr(
&src_path,
"user.stray",
b"1",
rustix::fs::XattrFlags::empty(),
)
.unwrap();
if let Some(gid) = other_group(want.gid()) {
std::os::unix::fs::chown(&src_path, None, Some(gid)).unwrap();
}
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::FORCE_COPY,
..PullOptions::default()
},
)
.await
.unwrap();
let dst_path = object_path(&dst_dir, &name, RepoMode::Bare);
let got = std::fs::symlink_metadata(&dst_path).unwrap();
assert_eq!(
got.permissions().mode() & 0o7777,
want.permissions().mode() & 0o7777
);
assert_eq!((got.uid(), got.gid()), (want.uid(), want.gid()));
assert!(!has_xattr(&dst_path, "user.stray"));
assert_eq!(
std::fs::read(&src_path).unwrap(),
std::fs::read(&dst_path).unwrap()
);
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn differing_ownership_refuses_the_link_and_writes_the_destinations_own() {
let tmp = TmpDir::new("pull-owner-gate");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUserShared).await;
let own = std::fs::symlink_metadata(&src_dir).unwrap().gid();
let Some(gid) = required_other_group(own) else {
return;
};
let (dst_dir, dst) = make_repo_in_group(base, "dst", RepoMode::BareUserShared, gid).await;
build_tree(&base.join("baseline"), b"baseline\n");
let baseline = commit_tree(&dst, base, "baseline", "baseline", None).await;
let want = std::fs::symlink_metadata(object_path(
&dst_dir,
&ostrya::ObjectName::new(baseline, ostrya::ObjectType::Commit),
RepoMode::BareUserShared,
))
.unwrap();
assert_eq!(want.gid(), gid);
assert_ne!(want.gid(), own);
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let reached = src.traverse_commit(&c2, 0).await.unwrap();
assert!(!reached.is_empty());
for name in &reached {
let object = name.loose_path(RepoMode::BareUserShared).replace('/', "");
assert_ne!(
object_ino(&src_dir, &object),
object_ino(&dst_dir, &object),
"{name} should be a fresh inode"
);
let got =
std::fs::symlink_metadata(object_path(&dst_dir, name, RepoMode::BareUserShared))
.unwrap();
assert_eq!(
(got.uid(), got.gid()),
(want.uid(), want.gid()),
"{name} should carry the destination's ownership"
);
}
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_bare_content_object_links_whatever_the_repositories_ownership() {
let tmp = TmpDir::new("pull-bare-owner-gate");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Bare).await;
let own = std::fs::symlink_metadata(&src_dir).unwrap().gid();
let Some(gid) = required_other_group(own) else {
return;
};
let (dst_dir, dst) = make_repo_in_group(base, "dst", RepoMode::Bare, gid).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let reached = src.traverse_commit(&c2, 0).await.unwrap();
assert!(!reached.is_empty());
let mut content = 0;
let mut metadata = 0;
for name in &reached {
let object = name.loose_path(RepoMode::Bare).replace('/', "");
let got =
std::fs::symlink_metadata(object_path(&dst_dir, name, RepoMode::Bare)).unwrap();
if name.ty == ostrya::ObjectType::File {
content += 1;
assert_eq!(
object_ino(&src_dir, &object),
object_ino(&dst_dir, &object),
"{name} should share the source inode"
);
assert_eq!(got.gid(), own, "{name} should carry the header's group");
} else {
metadata += 1;
assert_ne!(
object_ino(&src_dir, &object),
object_ino(&dst_dir, &object),
"{name} should be a fresh inode"
);
assert_eq!(
got.gid(),
gid,
"{name} should carry the destination's group"
);
}
}
assert!(content > 0 && metadata > 0);
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
if ostree_available() {
ostree(&[&format!("--repo={}", dst_dir.display()), "fsck"]);
}
});
}
#[test]
fn crossing_repository_modes_reingests_the_content() {
let tmp = TmpDir::new("pull-cross-mode");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
for name in src.traverse_commit(&c2, 0).await.unwrap() {
assert!(dst.has_object(name.ty, &name.checksum).await.unwrap());
}
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_bare_family_cross_mode_pull_clones_the_content() {
let tmp = TmpDir::new("pull-bare-family");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = canonical_source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUserOnly).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let content = first_regular_content(&src, &c2).await;
let src_path = object_path(&src_dir, &content, RepoMode::BareUser);
let dst_path = object_path(&dst_dir, &content, RepoMode::BareUserOnly);
let flat = content.loose_path(RepoMode::BareUser).replace('/', "");
assert_ne!(
object_ino(&src_dir, &flat),
object_ino(&dst_dir, &flat),
"{content} should be a fresh inode"
);
assert_eq!(
std::fs::read(&src_path).unwrap(),
std::fs::read(&dst_path).unwrap()
);
assert!(has_ostreemeta(&src_path));
assert!(!has_ostreemeta(&dst_path));
let logical = src.load_file(&content.checksum).await.unwrap().mode;
assert_eq!(
std::fs::symlink_metadata(&dst_path)
.unwrap()
.permissions()
.mode()
& 0o7777,
logical & 0o755
);
let landed = dst.load_file(&content.checksum).await.unwrap();
assert_eq!((landed.uid, landed.gid), (0, 0));
assert_eq!(landed.mode, (logical & 0o755) | 0o100000);
assert!(landed.xattrs.is_empty());
for name in src.traverse_commit(&c2, 0).await.unwrap() {
assert!(dst.has_object(name.ty, &name.checksum).await.unwrap());
}
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_bare_user_only_destination_refuses_a_header_it_cannot_store() {
let tmp = TmpDir::new("pull-buo-header");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, _c2) = owned_source_repo(base, RepoMode::BareUser).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUserOnly).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err}");
assert!(
err.to_string()
.contains("cannot be imported under its own name"),
"{err}"
);
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), None);
});
}
#[test]
fn a_symlink_object_is_shared_between_bare_user_and_bare_user_shared() {
let tmp = TmpDir::new("pull-symlink-share");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUserShared).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let link = symlink_content(&src, &c2).await;
let link_flat = link.loose_path(RepoMode::BareUser).replace('/', "");
assert_eq!(
object_ino(&src_dir, &link_flat),
object_ino(&dst_dir, &link_flat),
"{link} should share the source inode"
);
let content = first_regular_content(&src, &c2).await;
let content_flat = content.loose_path(RepoMode::BareUser).replace('/', "");
assert_ne!(
object_ino(&src_dir, &content_flat),
object_ino(&dst_dir, &content_flat),
"{content} should be a fresh inode"
);
assert_eq!(
std::fs::symlink_metadata(object_path(&dst_dir, &content, RepoMode::BareUserShared))
.unwrap()
.permissions()
.mode()
& 0o7777,
0o644
);
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_verity_destination_seals_every_imported_object() {
let tmp = TmpDir::new("pull-verity");
block_on(async {
let base = tmp.path();
if !fs_supports_verity(base).await {
eprintln!("skipping: filesystem does not support fs-verity");
return;
}
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = verity_repo(base, "dst", RepoMode::BareUser, "yes").await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let names = object_names(&dst_dir);
assert!(!names.is_empty(), "the pull imported nothing");
for flat in &names {
assert!(
is_sealed(&flat_object_path(&dst_dir, flat)),
"imported object not sealed: {flat}"
);
assert_ne!(
object_ino(&src_dir, flat),
object_ino(&dst_dir, flat),
"{flat} should be a fresh inode"
);
assert!(
!is_sealed(&flat_object_path(&src_dir, flat)),
"the pull sealed the source's copy: {flat}"
);
}
for name in src.traverse_commit(&c2, 0).await.unwrap() {
assert!(dst.has_object(name.ty, &name.checksum).await.unwrap());
}
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(report.is_ok(), "fsck reported {:?}", report.errors);
});
}
#[test]
fn a_bare_split_xattrs_destination_is_refused() {
let tmp = TmpDir::new("pull-split-xattrs-dst");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, _c2) = source_repo(base, RepoMode::BareUser).await;
std::fs::create_dir(base.join("flat")).unwrap();
std::fs::write(base.join("flat/only.txt"), b"only\n").unwrap();
commit_tree(&src, base, "flat", "flat", None).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareSplitXattrs).await;
for (ref_name, flags) in [("main", PullFlags::COMMIT_ONLY), ("flat", PullFlags::NONE)] {
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec![ref_name.to_owned()],
flags,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::Unsupported(_)),
"bare-split-xattrs is read-only, got {err:?}"
);
assert!(object_names(&dst_dir).is_empty());
assert!(dst.resolve_rev(ref_name, true).await.unwrap().is_none());
}
});
}
#[test]
fn a_read_only_file_imports_on_every_path() {
let tmp = TmpDir::new("pull-readonly");
block_on(async {
let base = tmp.path();
let tree = base.join("ro");
std::fs::create_dir_all(&tree).unwrap();
std::fs::write(tree.join("ro.txt"), b"read only\n").unwrap();
std::fs::set_permissions(tree.join("ro.txt"), std::fs::Permissions::from_mode(0o444))
.unwrap();
let (src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let commit = commit_tree(&src, base, "ro", "main", None).await;
let (_archive_dir, archive) = make_repo(base, "src-archive", RepoMode::Archive).await;
let archived = commit_tree(&archive, base, "ro", "main", None).await;
assert_eq!(commit, archived, "the commit identity is mode-independent");
let content = first_regular_content(&src, &commit).await;
let object = content.loose_path(RepoMode::BareUser).replace('/', "");
let (link_dir, link_dst) = make_repo(base, "link", RepoMode::BareUser).await;
pull_main(&link_dst, &src, PullFlags::NONE).await;
assert_eq!(
object_ino(&src_dir, &object),
object_ino(&link_dir, &object),
"the link path shares the inode"
);
let (copy_dir, copy_dst) = make_repo(base, "copy", RepoMode::BareUser).await;
pull_main(©_dst, &src, PullFlags::FORCE_COPY).await;
assert_ne!(
object_ino(&src_dir, &object),
object_ino(©_dir, &object),
"force_copy writes a fresh inode"
);
let (ingest_dir, ingest_dst) = make_repo(base, "ingest", RepoMode::BareUser).await;
pull_main(&ingest_dst, &archive, PullFlags::NONE).await;
for (dir, dst) in [
(&link_dir, &link_dst),
(©_dir, ©_dst),
(&ingest_dir, &ingest_dst),
] {
assert_eq!(
object_mode(dir, &object),
Some(0o444),
"stored mode in {}",
dir.display()
);
let file = dst.load_file(&content.checksum).await.unwrap();
assert_eq!(
file.mode & 0o7777,
0o444,
"logical mode in {}",
dir.display()
);
}
});
}
#[test]
fn a_shared_import_debits_no_free_space() {
let tmp = TmpDir::new("pull-budget-shared");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = zero_budget_repo(base, "dst", RepoMode::BareUser).await;
let stats = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let reached = src.traverse_commit(&c2, 0).await.unwrap();
assert!(!reached.is_empty());
for name in &reached {
let object = name.loose_path(RepoMode::BareUser).replace('/', "");
assert_eq!(
object_ino(&src_dir, &object),
object_ino(&dst_dir, &object),
"{name} should share the source inode"
);
}
assert!(stats.content_bytes_written > 0);
assert!(!has_partial_marker(&dst_dir, &c2));
});
}
#[test]
fn a_reingested_import_debits_the_free_space_budget() {
let tmp = TmpDir::new("pull-budget-reingest");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let (dst_dir, dst) = zero_budget_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::InsufficientFreeSpace { shortfall } if shortfall > 0),
"expected a free-space error, got {err:?}"
);
assert!(object_names(&dst_dir).is_empty());
assert!(dst.resolve_rev("main", true).await.unwrap().is_none());
assert!(!has_partial_marker(&dst_dir, &c2));
});
}
#[test]
fn commit_metadata_only_leaves_the_commit_partial() {
let tmp = TmpDir::new("pull-commit-only");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let stats = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::COMMIT_ONLY,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(stats.metadata_imported, 1);
assert_eq!(stats.content_imported, 0);
assert_eq!(
object_names(&dst_dir),
vec![format!("{}.commit", c2.to_hex())]
);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Partial);
let marker = dst_dir
.join("state")
.join(format!("{}.commitpartial", c2.to_hex()));
assert_eq!(std::fs::metadata(&marker).unwrap().len(), 0);
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
});
}
#[test]
fn a_failed_pull_publishes_nothing_and_clears_the_marker() {
let tmp = TmpDir::new("pull-failed");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let content = src
.traverse_commit(&c2, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ostrya::ObjectType::File)
.unwrap();
let object = content.loose_path(RepoMode::Archive);
std::fs::remove_file(src_dir.join("objects").join(&object)).unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::ObjectNotFound { .. }));
assert!(object_names(&dst_dir).is_empty());
assert!(dst.resolve_rev("main", true).await.unwrap().is_none());
assert!(!has_partial_marker(&dst_dir, &c2));
});
}
#[test]
fn a_pull_leaves_an_fsck_marker_as_it_found_it() {
let tmp = TmpDir::new("pull-fsck-marker");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let opts = || PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
};
dst.pull_local(&src, opts()).await.unwrap();
let content = dst
.traverse_commit(&c2, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ostrya::ObjectType::File)
.unwrap();
let object = content.loose_path(RepoMode::Archive);
std::fs::remove_file(dst_dir.join("objects").join(&object)).unwrap();
let report = dst.fsck(&ostrya::FsckOptions::new()).await.unwrap();
assert!(!report.is_ok());
let marker = dst_dir
.join("state")
.join(format!("{}.commitpartial", c2.to_hex()));
assert_eq!(std::fs::read(&marker).unwrap(), b"f");
std::fs::remove_file(src_dir.join("objects").join(&object)).unwrap();
let err = dst.pull_local(&src, opts()).await.unwrap_err();
assert!(matches!(err, Error::ObjectNotFound { .. }));
assert_eq!(std::fs::read(&marker).unwrap(), b"f");
});
}
#[test]
fn untrusted_rejects_a_corrupt_source_object() {
let tmp = TmpDir::new("pull-untrusted");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let content = first_regular_content(&src, &c2).await;
let path = src_dir
.join("objects")
.join(content.loose_path(RepoMode::BareUser));
let mut bytes = std::fs::read(&path).unwrap();
bytes[0] ^= 0xff;
std::fs::write(&path, &bytes).unwrap();
let (_trusted_dir, trusted) = make_repo(base, "trusted", RepoMode::BareUser).await;
trusted
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert!(
trusted
.has_object(content.ty, &content.checksum)
.await
.unwrap()
);
let (untrusted_dir, untrusted) = make_repo(base, "untrusted", RepoMode::BareUser).await;
let err = untrusted
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::UNTRUSTED,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ChecksumMismatch { expected, .. } if expected == content.checksum),
"unexpected error: {err}"
);
assert!(object_names(&untrusted_dir).is_empty());
});
}
#[test]
fn a_cross_mode_clone_is_trusted_and_untrusted_verifies_it() {
let tmp = TmpDir::new("pull-clone-trust");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let content = first_regular_content(&src, &c2).await;
let path = object_path(&src_dir, &content, RepoMode::BareUser);
let mut bytes = std::fs::read(&path).unwrap();
bytes[0] ^= 0xff;
std::fs::write(&path, &bytes).unwrap();
let (trusted_dir, trusted) = make_repo(base, "trusted", RepoMode::BareUserShared).await;
trusted
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
std::fs::read(object_path(
&trusted_dir,
&content,
RepoMode::BareUserShared
))
.unwrap(),
bytes
);
let (untrusted_dir, untrusted) =
make_repo(base, "untrusted", RepoMode::BareUserShared).await;
let err = untrusted
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::UNTRUSTED,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ChecksumMismatch { expected, .. } if expected == content.checksum),
"unexpected error: {err}"
);
assert!(object_names(&untrusted_dir).is_empty());
});
}
#[test]
fn a_reingest_rejects_a_corrupt_payload_with_or_without_untrusted() {
let tmp = TmpDir::new("pull-reingest-trust");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
let content = first_regular_content(&src, &c2).await;
let path = object_path(&src_dir, &content, RepoMode::BareUser);
let mut bytes = std::fs::read(&path).unwrap();
bytes[0] ^= 0xff;
std::fs::write(&path, &bytes).unwrap();
for flags in [PullFlags::NONE, PullFlags::UNTRUSTED] {
let (dst_dir, dst) =
make_repo(base, &format!("dst-{}", flags.bits()), RepoMode::Archive).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ChecksumMismatch { expected, .. } if expected == content.checksum),
"flags {flags:?}: unexpected error: {err}"
);
assert!(object_names(&dst_dir).is_empty());
}
});
}
#[test]
fn untrusted_rejects_a_corrupt_metadata_object() {
let tmp = TmpDir::new("pull-untrusted-meta");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let path = src_dir.join("objects").join(
ostrya::ObjectName::new(c2, ostrya::ObjectType::Commit).loose_path(RepoMode::Archive),
);
let mut bytes = std::fs::read(&path).unwrap();
let subject = b"main v2";
let at = bytes
.windows(subject.len())
.position(|w| w == subject)
.expect("the commit carries its subject verbatim");
bytes[at] = b'M';
std::fs::write(&path, &bytes).unwrap();
let (_untrusted_dir, untrusted) = make_repo(base, "untrusted", RepoMode::Archive).await;
let err = untrusted
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::UNTRUSTED,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ChecksumMismatch { expected, .. } if expected == c2),
"unexpected error: {err}"
);
let (_trusted_dir, trusted) = make_repo(base, "trusted", RepoMode::Archive).await;
trusted
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert!(
trusted
.has_object(ostrya::ObjectType::Commit, &c2)
.await
.unwrap()
);
});
}
#[test]
fn a_ref_binding_that_omits_the_pulled_ref_is_rejected() {
let tmp = TmpDir::new("pull-binding");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.set_ref_immediate("other", Some(&c2)).await.unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["other".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err}");
assert!(err.to_string().contains("other"));
dst.pull_local(
&src,
PullOptions {
refs: vec!["other".to_owned()],
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.resolve_rev("other", false).await.unwrap(), Some(c2));
});
}
#[test]
fn a_commit_with_no_binding_key_is_accepted() {
let tmp = TmpDir::new("pull-no-binding");
block_on(async {
let base = tmp.path();
build_tree(&base.join("v1"), b"hello\n");
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let commit = {
let txn = src.transaction().await.unwrap();
let mut mtree = MutableTree::new();
let mut modifier = CommitModifier::new(CommitModifierFlags::SKIP_XATTRS);
let dfd = std::fs::File::open(base).unwrap();
txn.write_dfd_to_mtree(
dfd.as_fd(),
Path::new("v1"),
&mut mtree,
Some(&mut modifier),
)
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
timestamp: Some(FIXED_TS),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref("free", Some(&commit));
txn.commit().await.unwrap();
commit
};
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["free".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.resolve_rev("free", false).await.unwrap(), Some(commit));
});
}
#[test]
fn bareuseronly_files_rejects_a_world_writable_mode() {
let tmp = TmpDir::new("pull-bareuseronly");
block_on(async {
let base = tmp.path();
let tree = base.join("v1");
build_tree(&tree, b"hello\n");
std::fs::set_permissions(
tree.join("hello.txt"),
std::fs::Permissions::from_mode(0o777),
)
.unwrap();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
commit_tree(&src, base, "v1", "main", None).await;
let (_flagged_dir, flagged) = make_repo(base, "flagged", RepoMode::Archive).await;
let err = flagged
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::BAREUSERONLY_FILES,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err}");
assert!(err.to_string().contains("invalid mode"));
let (_buo_dir, buo) = make_repo(base, "buo", RepoMode::BareUserOnly).await;
let err = buo
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err}");
let (_plain_dir, plain) = make_repo(base, "plain", RepoMode::Archive).await;
plain
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
});
}
#[test]
fn detached_metadata_travels_with_the_commit() {
let tmp = TmpDir::new("pull-detached");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let meta = Value::Array(vec![Value::Tuple(vec![
Value::Str("demo".to_owned()),
Value::Variant(Box::new((
Type::parse("s").unwrap(),
Value::Str("value".to_owned()),
))),
])]);
src.write_commit_detached_metadata(&c2, Some(&meta))
.await
.unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
dst.read_commit_detached_metadata(&c2).await.unwrap(),
Some(meta)
);
});
}
#[test]
fn a_localcache_repo_supplies_an_object_the_source_lacks() {
let tmp = TmpDir::new("pull-localcache");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (_cache_dir, cache) = make_repo(base, "cache", RepoMode::Archive).await;
cache
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::FORCE_COPY,
..PullOptions::default()
},
)
.await
.unwrap();
let content = src
.traverse_commit(&c2, 0)
.await
.unwrap()
.into_iter()
.find(|name| name.ty == ostrya::ObjectType::File)
.unwrap();
std::fs::remove_file(
src_dir
.join("objects")
.join(content.loose_path(RepoMode::Archive)),
)
.unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
localcache_repos: vec![cache.clone()],
..PullOptions::default()
},
)
.await
.unwrap();
assert!(dst.has_object(content.ty, &content.checksum).await.unwrap());
});
}
#[test]
fn a_localcache_supplied_dirtree_is_descended_into() {
let tmp = TmpDir::new("pull-cache-dirtree");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (_cache_dir, cache) = make_repo(base, "cache", RepoMode::Archive).await;
cache
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::FORCE_COPY,
..PullOptions::default()
},
)
.await
.unwrap();
let dirtree = subdir_dirtree(&src, &c2).await;
std::fs::remove_file(object_path(&src_dir, &dirtree, RepoMode::Archive)).unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
localcache_repos: vec![cache.clone()],
..PullOptions::default()
},
)
.await
.unwrap();
let reached = cache.traverse_commit(&c2, 0).await.unwrap();
for name in &reached {
assert!(
dst.has_object(name.ty, &name.checksum).await.unwrap(),
"{name} missing from the destination"
);
}
assert_eq!(object_names(&dst_dir).len(), reached.len());
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
let (bare_dir, bare) = make_repo(base, "dst2", RepoMode::Archive).await;
let err = bare
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::ObjectNotFound { .. }));
assert!(bare.resolve_rev("main", true).await.unwrap().is_none());
assert!(!has_partial_marker(&bare_dir, &c2));
});
}
#[test]
fn pulls_from_a_tool_built_repository_and_the_tool_reads_the_result() {
if !ostree_available() {
eprintln!("skipping: ostree tool not available");
return;
}
let tmp = TmpDir::new("pull-interop");
block_on(async {
let base = tmp.path();
let tree = base.join("v1");
build_tree(&tree, b"hello interop\n");
let src_dir = base.join("src");
let src_arg = format!("--repo={}", src_dir.display());
ostree(&[&src_arg, "init", "--mode=archive"]);
let tip = String::from_utf8(ostree(&[
&src_arg,
"commit",
"-b",
"main",
"--timestamp=2020-01-01 00:00:00 +0000",
&format!("--tree=dir={}", tree.display()),
]))
.unwrap()
.trim()
.to_owned();
for (name, mode) in [
("dst-archive", RepoMode::Archive),
("dst-bare-user", RepoMode::BareUser),
] {
let src = Repo::open(&src_dir).await.unwrap();
let (dst_dir, dst) = make_repo(base, name, mode).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let dst_arg = format!("--repo={}", dst_dir.display());
let resolved = String::from_utf8(ostree(&[&dst_arg, "rev-parse", "main"])).unwrap();
assert_eq!(resolved.trim(), tip, "{name}");
ostree(&[&dst_arg, "fsck"]);
let listing = String::from_utf8(ostree(&[&dst_arg, "ls", "-R", "main"])).unwrap();
assert!(listing.contains("/hello.txt"), "{name}: {listing}");
let content = ostree(&[&dst_arg, "cat", "main", "/hello.txt"]);
assert_eq!(content, b"hello interop\n", "{name}");
}
});
}
#[test]
fn the_tool_validates_a_bare_family_cross_mode_clone() {
if !ostree_available() {
eprintln!("skipping: ostree tool not available");
return;
}
let tmp = TmpDir::new("pull-interop-clone");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Bare).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
let dst_arg = format!("--repo={}", dst_dir.display());
let resolved = String::from_utf8(ostree(&[&dst_arg, "rev-parse", "main"])).unwrap();
assert_eq!(resolved.trim(), c2.to_hex());
ostree(&[&dst_arg, "fsck"]);
assert_eq!(
ostree(&[&dst_arg, "cat", "main", "/hello.txt"]),
b"hello two\n"
);
let listing = String::from_utf8(ostree(&[&dst_arg, "ls", "-R", "main"])).unwrap();
assert!(listing.contains("/link -> hello.txt"), "{listing}");
});
}
#[test]
fn the_tool_pulls_from_a_repository_the_port_wrote() {
if !ostree_available() {
eprintln!("skipping: ostree tool not available");
return;
}
let tmp = TmpDir::new("pull-interop-reverse");
block_on(async {
let base = tmp.path();
let (src_dir, _src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let dst_dir = base.join("tool-dst");
let dst_arg = format!("--repo={}", dst_dir.display());
ostree(&[&dst_arg, "init", "--mode=bare-user"]);
ostree(&[&dst_arg, "pull-local", &src_dir.to_string_lossy(), "main"]);
let resolved = String::from_utf8(ostree(&[&dst_arg, "rev-parse", "main"])).unwrap();
assert_eq!(resolved.trim(), c2.to_hex());
ostree(&[&dst_arg, "fsck"]);
});
}
const SECRET_B64: &str =
"o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
const OTHER_PUBLIC_B64: &str = "8+dqdDZWIesQQO95CRCSoSm2543BNK7FgOVwPyuUquU=";
async fn dest_with_remote(base: &Path, extra: &str) -> Repo {
let (path, repo) = make_repo(base, "dst", RepoMode::Archive).await;
drop(repo);
let config = path.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!(
"\n[remote \"origin\"]\nurl=file:///dev/null\n{extra}"
));
std::fs::write(&config, text).unwrap();
Repo::open(&path).await.unwrap()
}
async fn pull_main_with(dst: &Repo, src: &Repo, opts: PullOptions) -> Result<(), Error> {
dst.pull_local(
src,
PullOptions {
refs: vec!["main".to_owned()],
..opts
},
)
.await
.map(|_| ())
}
#[test]
fn a_local_pull_checks_nothing_by_default() {
let tmp = TmpDir::new("pull-local-verify-default");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let dst = dest_with_remote(base, "gpg-verify=true\nsign-verify=true\n").await;
pull_main_with(
&dst,
&src,
PullOptions {
remote: Some("origin".to_owned()),
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn a_local_pull_checks_the_commits_when_asked() {
let tmp = TmpDir::new("pull-local-verify-asked");
let base = tmp.path();
block_on(async {
let (_src_path, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
src.sign_commit(&c1, &signer).await.unwrap();
src.sign_commit(&c2, &signer).await.unwrap();
let dst = dest_with_remote(base, &format!("verification-ed25519-key={PUBLIC_B64}\n")).await;
let asked = PullOptions {
remote: Some("origin".to_owned()),
verify: PullVerify {
sign: Some(true),
..PullVerify::default()
},
depth: -1,
..PullOptions::default()
};
pull_main_with(&dst, &src, asked.clone()).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
let dst = dest_with_remote(
base,
&format!("verification-ed25519-key={OTHER_PUBLIC_B64}\n"),
)
.await;
let err = pull_main_with(&dst, &src, asked).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(
!dst.has_object(ostrya::ObjectType::Commit, &c2)
.await
.unwrap()
);
});
}
#[test]
fn a_local_pull_checks_the_source_summary_when_asked() {
let tmp = TmpDir::new("pull-local-verify-summary");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.regenerate_summary(&ostrya::SummaryOptions {
last_modified: Some(FIXED_TS),
..ostrya::SummaryOptions::default()
})
.await
.unwrap();
let dst = dest_with_remote(base, &format!("verification-ed25519-key={PUBLIC_B64}\n")).await;
let asked = PullOptions {
remote: Some("origin".to_owned()),
verify: PullVerify {
sign_summary: Some(true),
..PullVerify::default()
},
..PullOptions::default()
};
let err = pull_main_with(&dst, &src, asked.clone()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no summary.sig")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
src.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
.await
.unwrap();
pull_main_with(&dst, &src, asked).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn a_local_pull_checks_the_metadata_it_leaves_in_place() {
let tmp = TmpDir::new("pull-local-verify-stored-meta");
let base = tmp.path();
block_on(async {
let (src_path, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
src.sign_commit(&c1, &signer).await.unwrap();
src.sign_commit(&c2, &signer).await.unwrap();
let dst = dest_with_remote(base, &format!("verification-ed25519-key={PUBLIC_B64}\n")).await;
let asked = PullOptions {
remote: Some("origin".to_owned()),
verify: PullVerify {
sign: Some(true),
..PullVerify::default()
},
depth: -1,
..PullOptions::default()
};
pull_main_with(&dst, &src, asked.clone()).await.unwrap();
assert!(
dst.read_commit_detached_metadata(&c2)
.await
.unwrap()
.is_some()
);
for commit in [c1, c2] {
let hex = commit.to_hex();
let path = src_path
.join("objects")
.join(&hex[..2])
.join(format!("{}.commitmeta", &hex[2..]));
std::fs::remove_file(&path).unwrap();
}
pull_main_with(&dst, &src, asked.clone()).await.unwrap();
assert!(
dst.read_commit_detached_metadata(&c2)
.await
.unwrap()
.is_some()
);
src.write_commit_detached_metadata(&c2, None).await.unwrap();
let err = pull_main_with(&dst, &src, asked).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("carries no signature")),
"{err}"
);
});
}
#[test]
fn a_check_without_a_remote_name_is_refused() {
let tmp = TmpDir::new("pull-local-verify-no-remote");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, _c2) = source_repo(base, RepoMode::Archive).await;
let (_dst_path, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = pull_main_with(
&dst,
&src,
PullOptions {
verify: PullVerify {
sign: Some(true),
..PullVerify::default()
},
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("name a remote")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}