mod common;
use std::collections::HashSet;
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, dependency_error, file_inventory, ostree_available, store_with_field2,
wait_for_commit_under_guard, within,
};
use futures_lite::future::poll_once;
use ostrya::{
AdvertisedDelta, Checksum, CollectionRef, CommitModifier, CommitModifierFlags, CommitOptions,
CommitState, CreateOptions, DeltaOptions, DeltaSuperblock, Ed25519Signer, Error, FsckOptions,
MutableTree, ObjectName, ObjectType, PullFlags, PullOptions, PullStats, PullVerify,
RefSelector, Repo, RepoMode, Signer, SummaryOptions, TimestampCheck, Type, Value,
};
use ostrya_rt::{block_on, spawn};
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 {
commit_tree_full(repo, base, sub, branch, parent, flags, owner, &[]).await
}
async fn commit_tree_related(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
related: &[(&str, Checksum)],
) -> Checksum {
commit_tree_full(
repo,
base,
sub,
branch,
parent,
CommitModifierFlags::SKIP_XATTRS,
None,
related,
)
.await
}
#[allow(clippy::too_many_arguments)]
async fn commit_tree_full(
repo: &Repo,
base: &Path,
sub: &str,
branch: &str,
parent: Option<Checksum>,
flags: CommitModifierFlags,
owner: Option<(u32, u32)>,
related: &[(&str, Checksum)],
) -> 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)),
related: related
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect(),
..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 commitmeta_path(repo_dir: &Path, commit: &Checksum) -> PathBuf {
let hex = commit.to_hex();
repo_dir
.join("objects")
.join(&hex[..2])
.join(format!("{}.commitmeta", &hex[2..]))
}
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 a_local_pull_refuses_an_invalid_remote_name() {
let tmp = TmpDir::new("pull-invalid-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;
let decoy = base.join("x.trustedkeys.gpg");
std::fs::create_dir(&decoy).unwrap();
let cases = [
PullOptions::default(),
PullOptions {
verify: PullVerify {
gpg: Some(true),
..Default::default()
},
..PullOptions::default()
},
PullOptions {
no_ref_writes: true,
..PullOptions::default()
},
];
for (i, opts) in cases.into_iter().enumerate() {
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".into()],
remote: Some("../x".into()),
..opts
},
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidInput(m) if m == "invalid remote name: ../x"),
"case {i}: {err:?}"
);
}
assert!(object_names(&dst_dir).is_empty());
assert!(decoy.is_dir());
});
}
#[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_eq!(stats.content_bytes_unpacked, 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 each_ref_that_names_one_commit_gets_the_ref_binding_check() {
let tmp = TmpDir::new("pull-binding-shared");
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 refs = vec!["main".to_owned(), "other".to_owned()];
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: refs.clone(),
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err}");
assert!(err.to_string().contains("other"), "{err}");
assert!(
!dst.has_object(ostrya::ObjectType::Commit, &c2)
.await
.unwrap()
);
dst.pull_local(
&src,
PullOptions {
refs,
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
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)
);
});
}
fn two_property_metadata() -> Value {
let entry = |key: &str, value: &str| {
Value::Tuple(vec![
Value::Str(key.to_owned()),
Value::Variant(Box::new((
Type::parse("s").unwrap(),
Value::Str(value.to_owned()),
))),
])
};
Value::Array(vec![
entry("ostree.gpgsigs", "a signature"),
entry("build.gc-roots", "repository-local"),
])
}
async fn detached_property(repo: &Repo, commit: &Checksum, key: &str) -> Option<Value> {
repo.read_commit_detached_metadata(commit)
.await
.unwrap()
.and_then(|dict| dict.dict_get(key).cloned())
}
#[test]
fn the_switch_stores_nothing_for_a_dict_that_holds_the_related_key_alone() {
let tmp = TmpDir::new("pull-keep-related-alone");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
src.add_detached_related(&c2, "layer/base", &c1)
.await
.unwrap();
assert_eq!(detached_keys(&src, &c2).await, ["ostrya.related"]);
let (dst_dir, _dst) = make_repo(base, "dst", RepoMode::Archive).await;
let dst = with_keep_related(&dst_dir, "false").await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert!(
!commitmeta_path(&dst_dir, &c2).exists(),
"no detached metadata is written"
);
assert_eq!(
dst.read_commit_detached_metadata(&c2).await.unwrap(),
None,
"which reads back as no metadata at all"
);
});
}
#[test]
fn a_pull_that_times_out_at_the_ref_step_keeps_its_markers() {
let tmp = TmpDir::new("pull-ref-step-timeout");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.write_commit_detached_metadata(&c2, Some(&two_property_metadata()))
.await
.unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
drop(dst);
let config = dst_dir.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str("lock-timeout-secs=0\n");
std::fs::write(&config, text).unwrap();
let dst = Repo::open(&dst_dir).await.unwrap();
let guard = dst.begin_update().await.unwrap();
let opts = || PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
};
let err = dst.pull_local(&src, opts()).await.unwrap_err();
assert!(matches!(err, Error::LockTimeout { secs: 0 }), "{err:?}");
assert!(
dst.has_object(ostrya::ObjectType::Commit, &c2)
.await
.unwrap()
);
assert!(has_partial_marker(&dst_dir, &c2), "the marker stays");
assert!(
!commitmeta_path(&dst_dir, &c2).exists(),
"no detached metadata"
);
assert_eq!(dst.resolve_ref_tip("main").await.unwrap(), None);
guard.finish().await.unwrap();
dst.pull_local(&src, opts()).await.unwrap();
assert!(!has_partial_marker(&dst_dir, &c2));
assert_eq!(
std::fs::read(commitmeta_path(&dst_dir, &c2)).unwrap(),
std::fs::read(commitmeta_path(&src_dir, &c2)).unwrap()
);
assert_eq!(dst.resolve_ref_tip("main").await.unwrap(), Some(c2));
});
}
#[test]
fn a_pull_under_a_guard_publishes_its_objects_and_waits_at_the_ref_step() {
let tmp = TmpDir::new("pull-under-guard");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.write_commit_detached_metadata(&c2, Some(&two_property_metadata()))
.await
.unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
drop(dst);
let config = dst_dir.join("config");
let text = std::fs::read_to_string(&config).unwrap();
std::fs::write(
&config,
text.replacen("[core]\n", "[core]\nlock-timeout-secs=-1\n", 1),
)
.unwrap();
let a = Repo::open(&dst_dir).await.unwrap();
let b = Repo::open(&dst_dir).await.unwrap();
let guard = a.begin_update().await.unwrap();
let mut task = spawn(async move {
let opts = PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
};
b.pull_local(&src, opts).await
});
wait_for_commit_under_guard(&a, &c2, &mut task).await;
assert_eq!(a.resolve_ref_tip("main").await.unwrap(), None);
assert!(has_partial_marker(&dst_dir, &c2), "the marker stays");
assert!(
!commitmeta_path(&dst_dir, &c2).exists(),
"no detached metadata"
);
assert!(poll_once(&mut task).await.is_none(), "the pull waits");
guard.finish().await.unwrap();
within("the pull", task).await.unwrap();
assert_eq!(a.resolve_ref_tip("main").await.unwrap(), Some(c2));
assert!(!has_partial_marker(&dst_dir, &c2));
assert_eq!(
std::fs::read(commitmeta_path(&dst_dir, &c2)).unwrap(),
std::fs::read(commitmeta_path(&src_dir, &c2)).unwrap()
);
});
}
async fn with_keep_related(dir: &Path, value: &str) -> Repo {
let config = dir.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!("\n[ex-ostrya]\nkeep-detached-related={value}\n"));
std::fs::write(&config, text).unwrap();
Repo::open(dir).await.unwrap()
}
async fn detached_keys(repo: &Repo, commit: &Checksum) -> Vec<String> {
let Some(Value::Array(entries)) = repo.read_commit_detached_metadata(commit).await.unwrap()
else {
return Vec::new();
};
entries
.iter()
.map(|entry| entry.as_tuple().unwrap()[0].as_str().unwrap().to_owned())
.collect()
}
#[test]
fn the_switch_drops_the_related_key_and_keeps_the_rest() {
let tmp = TmpDir::new("pull-keep-related-false");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
src.write_commit_detached_metadata(&c2, Some(&two_property_metadata()))
.await
.unwrap();
src.add_detached_related(&c2, "layer/base", &c1)
.await
.unwrap();
assert_eq!(
detached_keys(&src, &c2).await,
["ostree.gpgsigs", "build.gc-roots", "ostrya.related"]
);
let (dst_dir, _dst) = make_repo(base, "dst", RepoMode::Archive).await;
let dst = with_keep_related(&dst_dir, "false").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(two_property_metadata())
);
});
}
#[test]
fn the_switch_keeps_the_destinations_own_metadata() {
let tmp = TmpDir::new("pull-keep-related-own");
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 local = dict_of("local.signature", "the destination's own");
dst.write_commit_detached_metadata(&c2, Some(&local))
.await
.unwrap();
let before = std::fs::read(commitmeta_path(&dst_dir, &c2)).unwrap();
src.add_detached_related(&c2, "layer/base", &c1)
.await
.unwrap();
assert_eq!(detached_keys(&src, &c2).await, ["ostrya.related"]);
let dst = with_keep_related(&dst_dir, "false").await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
std::fs::read(commitmeta_path(&dst_dir, &c2)).unwrap(),
before,
"the destination's own detached metadata stands"
);
});
}
#[test]
fn the_default_switch_keeps_the_related_key() {
for value in [None, Some("true")] {
let tmp = TmpDir::new("pull-keep-related-default");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
src.write_commit_detached_metadata(&c2, Some(&two_property_metadata()))
.await
.unwrap();
src.add_detached_related(&c2, "layer/base", &c1)
.await
.unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let dst = match value {
Some(value) => with_keep_related(&dst_dir, value).await,
None => dst,
};
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
std::fs::read(commitmeta_path(&dst_dir, &c2)).unwrap(),
std::fs::read(commitmeta_path(&src_dir, &c2)).unwrap(),
"{value:?}: the stored bytes are the source's, byte for byte"
);
});
}
}
#[test]
fn a_switch_that_is_no_boolean_refuses_the_pull() {
let tmp = TmpDir::new("pull-keep-related-malformed");
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 dst = with_keep_related(&dst_dir, "maybe").await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Core(_)), "{err}");
assert!(err.to_string().contains("keep-detached-related"), "{err}");
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_objects().await.unwrap().is_empty());
});
}
fn dict_of(key: &str, value: &str) -> Value {
Value::Array(vec![Value::Tuple(vec![
Value::Str(key.to_owned()),
Value::Variant(Box::new((
Type::parse("s").unwrap(),
Value::Str(value.to_owned()),
))),
])])
}
#[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(|_| ())
}
async fn dest_trusting(base: &Path, public: &str) -> Repo {
dest_with_remote(
base,
&format!("gpg-verify=false\nverification-ed25519-key={public}\n"),
)
.await
}
fn origin_pull(verify: PullVerify) -> PullOptions {
PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
verify,
..PullOptions::default()
}
}
async fn assert_nothing_pulled(dst: &Repo, commit: &Checksum) {
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), None);
assert!(!dst.has_object(ObjectType::Commit, commit).await.unwrap());
assert!(dst.list_objects().await.unwrap().is_empty());
}
#[test]
fn a_remote_with_no_section_checks_nothing() {
let tmp = TmpDir::new("pull-local-verify-no-section");
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;
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn the_gpg_verify_of_a_section_checks_the_commits() {
let tmp = TmpDir::new("pull-local-verify-section-gpg");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
for extra in ["", "gpg-verify=true\n"] {
let dst = dest_with_remote(base, extra).await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
#[cfg(feature = "verify-gpg")]
assert!(
matches!(&err, Error::Signature(m)
if m.contains("GPG verification is enabled, but it carries no signature")),
"{extra:?}: {err}"
);
#[cfg(not(feature = "verify-gpg"))]
assert!(
matches!(&err, Error::Unsupported(m) if m.contains("verify-gpg")),
"{extra:?}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
}
});
}
#[test]
fn gpg_verify_summary_of_a_section_checks_the_summary() {
let tmp = TmpDir::new("pull-local-verify-section-gpg-summary");
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=false\ngpg-verify-summary=true\n").await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
#[cfg(feature = "verify-gpg")]
assert!(
matches!(&err, Error::Signature(m) if m.contains("no summary is published")),
"{err}"
);
#[cfg(not(feature = "verify-gpg"))]
assert!(
matches!(&err, Error::Unsupported(m) if m.contains("verify-gpg")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
});
}
#[test]
fn sign_verify_of_a_section_checks_the_commits() {
let tmp = TmpDir::new("pull-local-verify-section-sign");
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,
&format!(
"gpg-verify=false\nsign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
),
)
.await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m.contains("sign-api verification is enabled, but it carries no signature")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
src.sign_commit(&c2, &signer).await.unwrap();
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn sign_verify_summary_of_a_section_checks_the_summary() {
let tmp = TmpDir::new("pull-local-verify-section-sign-summary");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
let dst = dest_with_remote(
base,
&format!(
"gpg-verify=false\nsign-verify-summary=ed25519\n\
verification-ed25519-key={PUBLIC_B64}\n"
),
)
.await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no summary.sig")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
src.sign_summary(&Ed25519Signer::from_base64(SECRET_B64).unwrap())
.await
.unwrap();
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn a_set_field_wins_over_the_section() {
let tmp = TmpDir::new("pull-local-verify-field-wins");
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,
&format!(
"gpg-verify=true\nsign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
),
)
.await;
let off = PullVerify {
gpg: Some(false),
sign: Some(false),
..PullVerify::default()
};
pull_main_with(&dst, &src, origin_pull(off)).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!(
"gpg-verify=false\nsign-verify=false\nverification-ed25519-key={PUBLIC_B64}\n"
),
)
.await;
let on = PullVerify {
sign: Some(true),
..PullVerify::default()
};
let err = pull_main_with(&dst, &src, origin_pull(on))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m.contains("sign-api verification is enabled, but it carries no signature")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
let dst = dest_with_remote(
base,
&format!(
"gpg-verify=false\ngpg-verify-summary=true\nsign-verify-summary=ed25519\n\
verification-ed25519-key={PUBLIC_B64}\n"
),
)
.await;
let off = PullVerify {
gpg_summary: Some(false),
sign_summary: Some(false),
..PullVerify::default()
};
pull_main_with(&dst, &src, origin_pull(off)).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_trusting(base, PUBLIC_B64).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_trusting(base, OTHER_PUBLIC_B64).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 the_switch_applies_after_the_signature_check() {
let tmp = TmpDir::new("pull-local-switch-after-verify");
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();
src.add_detached_related(&c2, "layer/base", &c1)
.await
.unwrap();
assert_eq!(
detached_keys(&src, &c2).await,
["ostree.sign.ed25519", "ostrya.related"]
);
let dst = dest_trusting(base, PUBLIC_B64).await;
drop(dst);
let dst = with_keep_related(&base.join("dst"), "false").await;
let opts = PullOptions {
remote: Some("origin".to_owned()),
verify: PullVerify {
sign: Some(true),
..PullVerify::default()
},
depth: -1,
..PullOptions::default()
};
pull_main_with(&dst, &src, opts).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2),
"the pull verified the signature and published the ref"
);
assert_eq!(
detached_keys(&dst, &c2).await,
["ostree.sign.ed25519"],
"and stored the signature without the related key"
);
});
}
#[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_trusting(base, PUBLIC_B64).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_summary_check_refuses_a_missing_file_before_it_reads_the_other() {
let tmp = TmpDir::new("pull-local-verify-summary-missing");
let base = tmp.path();
block_on(async {
let (src_path, src, _c1, _c2) = source_repo(base, RepoMode::Archive).await;
let dst = dest_trusting(base, PUBLIC_B64).await;
let asked = PullOptions {
remote: Some("origin".to_owned()),
verify: PullVerify {
sign_summary: Some(true),
..PullVerify::default()
},
..PullOptions::default()
};
std::fs::create_dir(src_path.join("summary.sig")).unwrap();
let err = pull_main_with(&dst, &src, asked.clone()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no summary is published")),
"{err}"
);
std::fs::remove_dir(src_path.join("summary.sig")).unwrap();
let summary = std::fs::File::create(src_path.join("summary")).unwrap();
summary.set_len((64 << 20) + 1).unwrap();
drop(summary);
let err = pull_main_with(&dst, &src, asked).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no summary.sig is published")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}
#[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_trusting(base, PUBLIC_B64).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());
});
}
const OTHER_SECRET_B64: &str =
"5ILWxT+l9G/u3h0BptRpmSi35C9uog7YDdD+Fp1Xk+Hz52p0NlYh6xBA73kJEJKhKbbnjcE0rsWA5XA/K5Sq5Q==";
fn ed25519_group() -> String {
format!("sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n")
}
async fn dest_with_trust(base: &Path, extra: &str, group: &str) -> Repo {
dest_with_remote(
base,
&format!("trust=t\n{extra}[ex-ostrya trust \"t\"]\n{group}"),
)
.await
}
fn remove_dst(dst: Repo, base: &Path) {
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
}
async fn assert_the_group_checks_the_commits(
base: &Path,
group: &str,
own: &dyn Signer,
other: &dyn Signer,
) {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let pull = || origin_pull(PullVerify::default());
let dst = dest_with_trust(base, "", group).await;
let err = pull_main_with(&dst, &src, pull()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m.contains("sign-api verification is enabled, but it carries no signature")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
src.sign_commit(&c2, other).await.unwrap();
let err = pull_main_with(&dst, &src, pull()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
src.write_commit_detached_metadata(&c2, None).await.unwrap();
src.sign_commit(&c2, own).await.unwrap();
pull_main_with(&dst, &src, pull()).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
}
#[test]
fn a_trust_group_checks_the_commits_of_a_local_pull() {
let tmp = TmpDir::new("pull-local-trust-commits");
let base = tmp.path();
block_on(async {
let own = Ed25519Signer::from_base64(SECRET_B64).unwrap();
let other = Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap();
assert_the_group_checks_the_commits(base, &ed25519_group(), &own, &other).await;
});
#[cfg(feature = "sign-spki")]
{
use ostrya::SpkiSigner;
let base = base.join("spki");
std::fs::create_dir(&base).unwrap();
block_on(async {
let own = SpkiSigner::from_base64(SPKI_SECRET_B64).unwrap();
let other = SpkiSigner::from_base64(SPKI_OTHER_SECRET_B64).unwrap();
let group = format!(
"sign-verify=spki\nverification-spki-key={}\n",
ostrya::base64::encode(&own.public_key_der())
);
assert_the_group_checks_the_commits(&base, &group, &own, &other).await;
});
}
}
#[cfg(feature = "sign-spki")]
const SPKI_SECRET_B64: &str = concat!(
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg2L708EsnnzHER0SYasMNIUcG",
"v63QapC/3kVsoPerzKGhRANCAATxfzfHKUPeJtyLTGMUoxHhvBS1NT9guWhUQPGiZRLZIcB8Wc3",
"csdVU1iOiTRmbZGKJTtekOdEAbVRrx5HxIpst",
);
#[cfg(feature = "sign-spki")]
const SPKI_OTHER_SECRET_B64: &str = concat!(
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU5tYPz/hTTxfsSTPOxD/H9U+",
"IkBj5qWV4/H3D1NBfRChRANCAAQPyTr9rh2d6WiYOi3oxNiE3ppTP2g5JP2xX9D7rEKnzixp",
"MqVuqA9XnzQr5GlCYd71m/D7BnYIqS4MytNawYrR",
);
#[test]
fn a_trust_value_that_names_no_group_is_refused() {
let tmp = TmpDir::new("pull-local-trust-value");
let base = tmp.path();
block_on(async {
let (src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
std::fs::rename(src_path.join("refs"), base.join("refs-aside")).unwrap();
for (value, reason) in [
(
"nope",
"[remote \"origin\"] trust=nope names no [ex-ostrya trust \"nope\"] group"
.to_owned(),
),
(
"",
"malformed [remote \"origin\"] trust value '': the value names a trust \
group, is not empty, and holds no '\"' and no control character"
.to_owned(),
),
(
"a\"b",
"malformed [remote \"origin\"] trust value 'a\"b': the value names a trust \
group, is not empty, and holds no '\"' and no control character"
.to_owned(),
),
] {
let dst = dest_with_remote(
base,
&format!(
"trust={value}\n[ex-ostrya trust \"t\"]\n{}",
ed25519_group()
),
)
.await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if *m == reason),
"{value:?}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
remove_dst(dst, base);
}
});
}
#[test]
fn a_trust_group_takes_no_switch_that_turns_on_a_commit_check() {
let tmp = TmpDir::new("pull-local-trust-switches");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let dst = dest_with_trust(base, "", &ed25519_group()).await;
let gpg = PullVerify {
gpg: Some(true),
..PullVerify::default()
};
let sign = PullVerify {
sign: Some(true),
..PullVerify::default()
};
for (verify, check) in [(gpg, "the GPG check"), (sign, "the sign-api check")] {
let err = pull_main_with(&dst, &src, origin_pull(verify))
.await
.unwrap_err();
let reason = format!(
"remote 'origin' takes its commit keys from [ex-ostrya trust \"t\"], so a \
pull cannot turn on {check} of the commits"
);
assert!(
matches!(&err, Error::InvalidInput(m) if *m == reason),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
}
let off = PullVerify {
sign: Some(false),
..PullVerify::default()
};
pull_main_with(&dst, &src, origin_pull(off)).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn a_trust_group_refuses_the_commit_keys_of_the_remote() {
let tmp = TmpDir::new("pull-local-trust-remote-keys");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let head = "[remote \"origin\"] sets trust=t and";
let commit_check = "the trust group sets the commit checks";
for (extra, reason) in [
(
"gpg-verify=true\n".to_owned(),
format!(
"{head} gpg-verify=true: {commit_check}, so set gpg-verify=false or remove the key"
),
),
(
"sign-verify=true\n".to_owned(),
format!("{head} sign-verify=true: {commit_check}, so remove sign-verify"),
),
(
"sign-verify=ed25519\n".to_owned(),
format!("{head} sign-verify=ed25519: {commit_check}, so remove sign-verify"),
),
(
"gpgkeypath=/nonexistent.gpg\n".to_owned(),
format!(
"{head} gpgkeypath, and gpg-verify-summary is not true, so no check \
reads it"
),
),
(
format!("verification-ed25519-key={OTHER_PUBLIC_B64}\n"),
format!(
"{head} holds 'verification-ed25519-key', and sign-verify-summary does \
not select ed25519, so no check reads it"
),
),
(
"sign-verify-summary=spki\nverification-ed25519-file=/nonexistent.keys\n"
.to_owned(),
format!(
"{head} holds 'verification-ed25519-file', and sign-verify-summary does \
not select ed25519, so no check reads it"
),
),
] {
let dst = dest_with_trust(base, &extra, &ed25519_group()).await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if *m == reason),
"{extra:?}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
remove_dst(dst, base);
}
src.sign_commit(&c2, &Ed25519Signer::from_base64(SECRET_B64).unwrap())
.await
.unwrap();
for extra in [
"gpg-verify=false\n",
"sign-verify=false\n",
"sign-verify=\n",
] {
let dst = dest_with_trust(base, extra, &ed25519_group()).await;
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2),
"{extra:?}"
);
remove_dst(dst, base);
}
});
}
#[test]
fn a_trust_group_keeps_the_summary_check_of_the_remote() {
let tmp = TmpDir::new("pull-local-trust-summary");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let own = Ed25519Signer::from_base64(SECRET_B64).unwrap();
let other = Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap();
src.sign_commit(&c2, &own).await.unwrap();
let summarize = || async {
src.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
};
summarize().await;
src.sign_summary(&other).await.unwrap();
let summary_keys =
format!("sign-verify-summary=ed25519\nverification-ed25519-key={OTHER_PUBLIC_B64}\n");
let dst = dest_with_trust(base, &summary_keys, &ed25519_group()).await;
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
remove_dst(dst, base);
summarize().await;
src.sign_summary(&own).await.unwrap();
let dst = dest_with_trust(base, &summary_keys, &ed25519_group()).await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
remove_dst(dst, base);
summarize().await;
let dst = dest_with_trust(
base,
&format!("sign-verify-summary=true\nverification-ed25519-key={OTHER_PUBLIC_B64}\n"),
&ed25519_group(),
)
.await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no summary.sig")),
"{err}"
);
let off = PullVerify {
sign_summary: Some(false),
..PullVerify::default()
};
pull_main_with(&dst, &src, origin_pull(off)).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
});
}
#[test]
fn a_trust_group_refuses_a_malformed_summary_key_before_it_reads_keys() {
let tmp = TmpDir::new("pull-local-trust-summary-key");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let dst = dest_with_trust(
base,
"gpg-verify=false\ngpg-verify-summary=maybe\n",
"sign-verify=ed25519\nverification-ed25519-file=/nonexistent/keys\n",
)
.await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Core(_))
&& err.to_string().contains(
"value 'maybe' for remote \"origin\".gpg-verify-summary is not a boolean"
),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
});
}
async fn dest_with_group(base: &Path, group: &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[ex-ostrya trust \"t\"]\n{group}"));
std::fs::write(&config, text).unwrap();
Repo::open(&path).await.unwrap()
}
fn group_pull(group: &str, remote: Option<&str>, verify: PullVerify) -> PullOptions {
PullOptions {
refs: vec!["main".to_owned()],
remote: remote.map(str::to_owned),
verify,
trust_group: Some(group.to_owned()),
..PullOptions::default()
}
}
async fn assert_the_option_checks_the_commits(
base: &Path,
group: &str,
own: &dyn Signer,
other: &dyn Signer,
) {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let pull = || group_pull("t", None, PullVerify::default());
let dst = dest_with_group(base, group).await;
let err = pull_main_with(&dst, &src, pull()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m.contains("sign-api verification is enabled, but it carries no signature")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
src.sign_commit(&c2, other).await.unwrap();
let err = pull_main_with(&dst, &src, pull()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
src.write_commit_detached_metadata(&c2, None).await.unwrap();
src.sign_commit(&c2, own).await.unwrap();
pull_main_with(&dst, &src, pull()).await.unwrap();
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), Some(c2));
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), None);
remove_dst(dst, base);
let dst = dest_with_group(base, group).await;
pull_main_with(
&dst,
&src,
group_pull("t", Some("origin"), PullVerify::default()),
)
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), None);
}
#[test]
fn the_trust_group_option_checks_the_commits_of_a_local_pull() {
let tmp = TmpDir::new("pull-local-trust-option-commits");
let base = tmp.path();
block_on(async {
let own = Ed25519Signer::from_base64(SECRET_B64).unwrap();
let other = Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap();
assert_the_option_checks_the_commits(base, &ed25519_group(), &own, &other).await;
});
#[cfg(feature = "sign-spki")]
{
use ostrya::SpkiSigner;
let base = base.join("spki");
std::fs::create_dir(&base).unwrap();
block_on(async {
let own = SpkiSigner::from_base64(SPKI_SECRET_B64).unwrap();
let other = SpkiSigner::from_base64(SPKI_OTHER_SECRET_B64).unwrap();
let group = format!(
"sign-verify=spki\nverification-spki-key={}\n",
ostrya::base64::encode(&own.public_key_der())
);
assert_the_option_checks_the_commits(&base, &group, &own, &other).await;
});
}
}
#[test]
fn the_trust_group_option_wins_over_the_remote_key() {
let tmp = TmpDir::new("pull-local-trust-option-wins");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.sign_commit(&c2, &Ed25519Signer::from_base64(SECRET_B64).unwrap())
.await
.unwrap();
let groups = format!(
"[ex-ostrya trust \"other\"]\nsign-verify=ed25519\n\
verification-ed25519-key={OTHER_PUBLIC_B64}\n\
[ex-ostrya trust \"t\"]\n{}",
ed25519_group()
);
let dst = dest_with_remote(base, &format!("gpg-verify=false\ntrust=other\n{groups}")).await;
let err = pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
pull_main_with(
&dst,
&src,
group_pull("t", Some("origin"), PullVerify::default()),
)
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
remove_dst(dst, base);
for key in ["trust=nope\n", "trust=\n"] {
let dst = dest_with_remote(base, &format!("{key}{groups}")).await;
pull_main_with(
&dst,
&src,
group_pull("t", Some("origin"), PullVerify::default()),
)
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2),
"{key:?}"
);
remove_dst(dst, base);
}
});
}
#[test]
fn the_trust_group_option_refuses_a_bad_name() {
let tmp = TmpDir::new("pull-local-trust-option-name");
let base = tmp.path();
block_on(async {
let (src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
std::fs::rename(src_path.join("refs"), base.join("refs-aside")).unwrap();
let dst = dest_with_group(base, &ed25519_group()).await;
let malformed = |name: &str| {
format!(
"malformed trust group name '{name}': the name is not empty, and holds no \
'\"' and no control character"
)
};
for (name, reason) in [
(
"nope",
"the pull names the trust group 'nope', and the config has no \
[ex-ostrya trust \"nope\"] group"
.to_owned(),
),
("", malformed("")),
("a\"b", malformed("a\"b")),
("a\nb", malformed("a\nb")),
] {
for remote in [None, Some("origin")] {
let err =
pull_main_with(&dst, &src, group_pull(name, remote, PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidInput(m) if *m == reason),
"{name:?} {remote:?}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
}
}
remove_dst(dst, base);
let dst = dest_with_group(
base,
&format!("{}gpg-verify-summary=true\n", ed25519_group()),
)
.await;
let err = pull_main_with(&dst, &src, group_pull("t", None, PullVerify::default()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m)
if m == "[ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a trust \
group sets a commit policy alone"),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
});
}
#[test]
fn the_trust_group_option_takes_no_switch_that_turns_on_a_commit_check() {
let tmp = TmpDir::new("pull-local-trust-option-switches");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let dst = dest_with_group(base, &ed25519_group()).await;
let gpg = PullVerify {
gpg: Some(true),
..PullVerify::default()
};
let sign = PullVerify {
sign: Some(true),
..PullVerify::default()
};
for (verify, check) in [(gpg, "the GPG check"), (sign, "the sign-api check")] {
for remote in [None, Some("origin")] {
let err = pull_main_with(&dst, &src, group_pull("t", remote, verify))
.await
.unwrap_err();
let reason = format!(
"the pull takes its commit keys from [ex-ostrya trust \"t\"], so it \
cannot turn on {check} of the commits"
);
assert!(
matches!(&err, Error::InvalidInput(m) if *m == reason),
"{remote:?}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
}
}
let off = PullVerify {
sign: Some(false),
..PullVerify::default()
};
pull_main_with(&dst, &src, group_pull("t", None, off))
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), Some(c2));
});
}
#[test]
fn the_trust_group_option_refuses_the_commit_keys_of_the_remote() {
let tmp = TmpDir::new("pull-local-trust-option-remote-keys");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let group = format!("[ex-ostrya trust \"t\"]\n{}", ed25519_group());
let head = "the pull takes its commit keys from [ex-ostrya trust \"t\"], and \
[remote \"origin\"]";
let commit_check = "the trust group sets the commit checks";
for (extra, reason) in [
(
"gpg-verify=true\n".to_owned(),
format!(
"{head} sets gpg-verify=true: {commit_check}, so set gpg-verify=false or \
remove the key"
),
),
(
"sign-verify=true\n".to_owned(),
format!("{head} sets sign-verify=true: {commit_check}, so remove sign-verify"),
),
(
"sign-verify=ed25519\n".to_owned(),
format!("{head} sets sign-verify=ed25519: {commit_check}, so remove sign-verify"),
),
(
"gpgkeypath=/nonexistent.gpg\n".to_owned(),
format!(
"{head} sets gpgkeypath, and gpg-verify-summary is not true, so no check \
reads it"
),
),
(
format!("verification-ed25519-key={OTHER_PUBLIC_B64}\n"),
format!(
"{head} holds 'verification-ed25519-key', and sign-verify-summary does \
not select ed25519, so no check reads it"
),
),
(
"sign-verify-summary=spki\nverification-ed25519-file=/nonexistent.keys\n"
.to_owned(),
format!(
"{head} holds 'verification-ed25519-file', and sign-verify-summary does \
not select ed25519, so no check reads it"
),
),
] {
let dst = dest_with_remote(base, &format!("{extra}{group}")).await;
let err = pull_main_with(
&dst,
&src,
group_pull("t", Some("origin"), PullVerify::default()),
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if *m == reason),
"{extra:?}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
remove_dst(dst, base);
}
src.sign_commit(&c2, &Ed25519Signer::from_base64(SECRET_B64).unwrap())
.await
.unwrap();
for extra in ["", "gpg-verify=false\n", "sign-verify=false\n"] {
let dst = dest_with_remote(base, &format!("{extra}{group}")).await;
pull_main_with(
&dst,
&src,
group_pull("t", Some("origin"), PullVerify::default()),
)
.await
.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2),
"{extra:?}"
);
remove_dst(dst, base);
}
});
}
#[test]
fn the_trust_group_option_with_no_remote_checks_no_summary() {
let tmp = TmpDir::new("pull-local-trust-option-no-summary");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
src.sign_commit(&c2, &Ed25519Signer::from_base64(SECRET_B64).unwrap())
.await
.unwrap();
src.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
let dst = dest_with_group(base, &ed25519_group()).await;
for (field, verify) in [
(
"gpg_summary",
PullVerify {
gpg_summary: Some(true),
..PullVerify::default()
},
),
(
"sign_summary",
PullVerify {
sign_summary: Some(true),
..PullVerify::default()
},
),
] {
let err = pull_main_with(&dst, &src, group_pull("t", None, verify))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Pull(m)
if m == "a signature check takes its keys from a remote's \
configuration, so the pull has to name a remote"),
"{field}: {err}"
);
assert_nothing_pulled(&dst, &c2).await;
}
pull_main_with(&dst, &src, group_pull("t", None, PullVerify::default()))
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), Some(c2));
remove_dst(dst, base);
src.sign_summary(&Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap())
.await
.unwrap();
let dst = dest_with_group(base, &ed25519_group()).await;
pull_main_with(&dst, &src, group_pull("t", None, PullVerify::default()))
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), Some(c2));
remove_dst(dst, base);
let dst = dest_with_group(base, &ed25519_group()).await;
let off = PullVerify {
sign_summary: Some(false),
..PullVerify::default()
};
pull_main_with(&dst, &src, group_pull("t", None, off))
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), Some(c2));
});
}
#[test]
fn the_trust_group_option_keeps_the_summary_check_of_the_remote() {
let tmp = TmpDir::new("pull-local-trust-option-summary");
let base = tmp.path();
block_on(async {
let (_src_path, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let own = Ed25519Signer::from_base64(SECRET_B64).unwrap();
let other = Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap();
src.sign_commit(&c2, &own).await.unwrap();
let summarize = || async {
src.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
};
let remote = format!(
"sign-verify-summary=ed25519\nverification-ed25519-key={OTHER_PUBLIC_B64}\n\
[ex-ostrya trust \"t\"]\n{}",
ed25519_group()
);
let pull = || group_pull("t", Some("origin"), PullVerify::default());
summarize().await;
src.sign_summary(&other).await.unwrap();
let dst = dest_with_remote(base, &remote).await;
pull_main_with(&dst, &src, pull()).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(c2)
);
remove_dst(dst, base);
summarize().await;
src.sign_summary(&own).await.unwrap();
let dst = dest_with_remote(base, &remote).await;
let err = pull_main_with(&dst, &src, pull()).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
assert_nothing_pulled(&dst, &c2).await;
});
}
#[test]
fn pull_local_durability_options_change_no_byte() {
let tmp = TmpDir::new("pull-durability");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, _c2) = source_repo(base, RepoMode::Archive).await;
for mode in [RepoMode::Archive, RepoMode::BareUser] {
let mut answer = None;
for (disable_fsync, per_object_fsync) in
[(false, false), (true, false), (false, true), (true, true)]
{
let name = format!("dst-{mode:?}-{disable_fsync}-{per_object_fsync}");
let (dst_dir, dst) = make_repo(base, &name, mode).await;
let stats = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
disable_fsync,
per_object_fsync,
..PullOptions::default()
},
)
.await
.unwrap();
let seen = (
file_inventory(&dst_dir, "objects"),
dst.list_refs(None).await.unwrap(),
ostrya::PullStats {
elapsed: std::time::Duration::ZERO,
..stats
},
);
match &answer {
None => answer = Some(seen),
Some(first) => assert_eq!(
&seen, first,
"{mode:?} disable_fsync={disable_fsync} \
per_object_fsync={per_object_fsync} changed what the pull wrote",
),
}
}
}
});
}
#[test]
fn a_local_pull_refuses_subpaths() {
let tmp = TmpDir::new("pull-subpath-refused");
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!["main".to_owned()],
subpaths: vec!["/".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_objects().await.unwrap().is_empty());
});
}
#[test]
fn a_local_pull_refuses_a_depth_below_minus_one() {
let tmp = TmpDir::new("pull-depth-refused");
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;
for depth in [-2, -3, i32::MIN] {
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
depth,
..PullOptions::default()
},
)
.await
.unwrap_err();
match &err {
Error::InvalidInput(msg) => {
assert!(msg.contains(&format!("depth {depth} is below -1")), "{msg}")
}
other => panic!("{depth}: {other:?}"),
}
}
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_objects().await.unwrap().is_empty());
});
}
fn listed_delta(from: Option<u8>, to: u8, digest: u8) -> AdvertisedDelta {
AdvertisedDelta {
from: from.map(|byte| Checksum::from_bytes([byte; 32])),
to: Checksum::from_bytes([to; 32]),
superblock: Checksum::from_bytes([digest; 32]),
}
}
#[test]
fn a_local_pull_refuses_a_static_delta_list_it_cannot_take() {
let tmp = TmpDir::new("pull-static-delta-list-refused");
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 inventory = |dir: &Path| {
let mut out = file_inventory(dir, "objects");
out.extend(file_inventory(dir, "refs"));
out.extend(file_inventory(dir, "state"));
out
};
let before = inventory(&dst_dir);
let main = || PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
};
let two_digests = format!(
"static delta {}-{} is listed with two superblock digests",
Checksum::from_bytes([1; 32]).to_hex(),
Checksum::from_bytes([2; 32]).to_hex()
);
let cases = [
(
PullOptions {
static_deltas: Some(vec![
listed_delta(Some(1), 2, 3),
listed_delta(Some(1), 2, 4),
]),
..main()
},
Error::InvalidInput(two_digests),
),
(
PullOptions {
static_deltas: Some(vec![listed_delta(Some(1), 2, 3)]),
disable_static_deltas: true,
..main()
},
Error::InvalidInput(
"a pull with static_deltas takes no disable_static_deltas option".to_owned(),
),
),
(
PullOptions {
static_deltas: Some(vec![
listed_delta(Some(1), 2, 3),
listed_delta(Some(1), 2, 4),
]),
subpaths: vec!["/".to_owned()],
..main()
},
Error::Unsupported("a local pull takes no subpath".to_owned()),
),
(
PullOptions {
refs: vec!["a:b".to_owned()],
collection_id: Some(COLLECTION.to_owned()),
no_ref_writes: true,
static_deltas: Some(vec![listed_delta(Some(1), 2, 3)]),
..PullOptions::default()
},
Error::InvalidRefspec(format!("{COLLECTION}:a:b")),
),
];
for (opts, expected) in cases {
let err = dst.pull_local(&src, opts).await.unwrap_err();
match (&expected, &err) {
(Error::InvalidInput(want), Error::InvalidInput(got))
| (Error::Unsupported(want), Error::Unsupported(got))
| (Error::InvalidRefspec(want), Error::InvalidRefspec(got)) => {
assert_eq!(got, want)
}
_ => panic!("{expected:?}: {err:?}"),
}
}
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_objects().await.unwrap().is_empty());
assert_eq!(inventory(&dst_dir), before);
let staging = std::fs::read_dir(dst_dir.join("tmp"))
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.starts_with("staging-"))
.collect::<Vec<_>>();
assert!(staging.is_empty(), "{staging:?}");
});
}
#[test]
fn a_local_pull_refuses_a_requested_name_outside_the_ref_name_rule() {
let tmp = TmpDir::new("pull-name-rule");
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 inventory = |dir: &Path| {
let mut out = file_inventory(dir, "objects");
out.extend(file_inventory(dir, "refs"));
out.extend(file_inventory(dir, "state"));
out
};
let before = inventory(&dst_dir);
for name in ["a b", "a*", "-a", "a/.b", "a:b:c"] {
let opts = PullOptions {
refs: vec![name.to_owned()],
..PullOptions::default()
};
match dst.pull_local(&src, opts).await {
Err(Error::InvalidRefspec(got)) => assert_eq!(got, name),
other => panic!("{name:?}: {other:?}"),
}
assert_eq!(inventory(&dst_dir), before, "{name:?}");
}
});
}
async fn delta_with(
repo: &Repo,
from: Option<&Checksum>,
to: &Checksum,
opts: DeltaOptions,
) -> PathBuf {
let dir = repo
.generate_static_delta(
from,
to,
&DeltaOptions {
timestamp: Some(FIXED_TS),
..opts
},
)
.await
.unwrap();
repo.path().join(dir)
}
async fn summarize(repo: &Repo) {
repo.regenerate_summary(&SummaryOptions {
last_modified: Some(FIXED_TS),
..SummaryOptions::default()
})
.await
.unwrap();
}
async fn delta_source(base: &Path) -> (PathBuf, Repo, Checksum, Checksum, PathBuf) {
let (path, repo, c1, c2) = source_repo(base, RepoMode::Archive).await;
let dir = delta_with(&repo, None, &c2, DeltaOptions::default()).await;
repo.reindex_static_deltas().await.unwrap();
summarize(&repo).await;
(path, repo, c1, c2, dir)
}
fn required(flags: PullFlags) -> PullOptions {
PullOptions {
refs: vec!["main".to_owned()],
flags,
require_static_deltas: true,
..PullOptions::default()
}
}
async fn dst_holding(base: &Path, name: &str, src: &Repo, commit: &Checksum) -> (PathBuf, Repo) {
let (path, dst) = make_repo(base, name, RepoMode::BareUser).await;
hold_commit(&dst, src, commit).await;
(path, dst)
}
async fn hold_commit(dst: &Repo, src: &Repo, commit: &Checksum) {
dst.pull_local(
src,
PullOptions {
refs: vec![commit.to_hex()],
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..PullOptions::default()
},
)
.await
.unwrap();
let txn = dst.transaction().await.unwrap();
txn.set_ref(&commit.to_hex(), None);
txn.commit().await.unwrap();
assert!(dst.list_refs(None).await.unwrap().is_empty());
}
fn tree_size(dir: &Path) -> u64 {
let mut total = 0;
for entry in std::fs::read_dir(dir).unwrap().flatten() {
let meta = entry.metadata().unwrap();
total += if meta.is_dir() {
tree_size(&entry.path())
} else {
meta.len()
};
}
total
}
async fn assert_nothing_left(dst_dir: &Path, dst: &Repo, commit: &Checksum) {
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_objects().await.unwrap().is_empty());
assert!(!has_partial_marker(dst_dir, commit));
}
#[test]
fn a_local_pull_reads_no_delta_by_default() {
let tmp = TmpDir::new("pull-delta-default");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2, dir) = delta_source(base).await;
std::fs::write(dir.join("superblock"), b"not a superblock").unwrap();
let deltas = src_dir.join("deltas");
std::fs::set_permissions(&deltas, std::fs::Permissions::from_mode(0o000)).unwrap();
for (name, disable_static_deltas) in [("plain", false), ("disabled", true)] {
let (_dst_dir, dst) = make_repo(base, name, RepoMode::BareUser).await;
let stats = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
disable_static_deltas,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(stats.delta_parts, 0, "{name}");
assert_eq!(stats.metadata_fetched, 0, "{name}");
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
}
std::fs::set_permissions(&deltas, std::fs::Permissions::from_mode(0o755)).unwrap();
});
}
#[test]
fn a_required_delta_applies_from_scratch() {
let tmp = TmpDir::new("pull-delta-scratch");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2, dir) = delta_source(base).await;
let (_plain_dir, plain) = make_repo(base, "plain", RepoMode::BareUser).await;
pull_main(&plain, &src, PullFlags::empty()).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(
dst.list_objects().await.unwrap(),
plain.list_objects().await.unwrap()
);
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
let index_dir = src_dir.join("delta-indexes");
assert_eq!(
PullStats {
elapsed: std::time::Duration::ZERO,
..stats
},
PullStats {
metadata_imported: stats.metadata_imported,
content_imported: stats.content_imported,
content_bytes_written: stats.content_bytes_written,
metadata_fetched: 2,
content_fetched: 0,
delta_parts: 1,
bytes_transferred: tree_size(&dir) + tree_size(&index_dir),
..PullStats::default()
}
);
});
}
#[test]
fn a_required_from_to_delta_applies() {
let tmp = TmpDir::new("pull-delta-from-to");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let dir = delta_with(&src, Some(&c1), &c2, DeltaOptions::default()).await;
summarize(&src).await;
for remote in [None, Some("origin")] {
let name = format!("dst-{}", remote.unwrap_or("local"));
let (_dst_dir, dst) = dst_holding(base, &name, &src, &c1).await;
let stats = dst
.pull_local(
&src,
PullOptions {
remote: remote.map(str::to_owned),
..required(PullFlags::empty())
},
)
.await
.unwrap();
assert_eq!(stats.delta_parts, 1, "{remote:?}");
assert_eq!(stats.metadata_fetched, 2, "{remote:?}");
assert_eq!(stats.bytes_transferred, tree_size(&dir), "{remote:?}");
assert_eq!(stats.content_bytes_unpacked, 0, "{remote:?}");
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
}
});
}
#[test]
fn a_required_delta_that_is_not_published_is_refused() {
let tmp = TmpDir::new("pull-delta-none-found");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
delta_with(&src, Some(&c1), &c2, DeltaOptions::default()).await;
summarize(&src).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert_eq!(
err.to_string(),
format!("pull: Static deltas required, but none found for main to {c2}")
);
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_required_delta_needs_a_summary() {
let tmp = TmpDir::new("pull-delta-no-summary");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
delta_with(&src, None, &c2, DeltaOptions::default()).await;
src.reindex_static_deltas().await.unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert_eq!(
err.to_string(),
"pull: Fetch configured to require static deltas, but no summary deltas or \
delta index found"
);
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_required_delta_refuses_a_source_outside_archive_mode() {
let tmp = TmpDir::new("pull-delta-bare-source");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::BareUser).await;
delta_with(&src, None, &c2, DeltaOptions::default()).await;
summarize(&src).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
assert!(err.to_string().contains("bare-user"), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_tampered_delta_fails_and_publishes_nothing() {
let tmp = TmpDir::new("pull-delta-tampered");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2, dir) = delta_source(base).await;
let superblock = dir.join("superblock");
let original = std::fs::read(&superblock).unwrap();
let mut changed = original.clone();
*changed.last_mut().unwrap() ^= 0xff;
std::fs::write(&superblock, &changed).unwrap();
let (dst_dir, dst) = make_repo(base, "sb", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert!(matches!(err, Error::ChecksumMismatch { .. }), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
std::fs::write(&superblock, &original).unwrap();
let part = dir.join("0");
let mut bytes = std::fs::read(&part).unwrap();
let middle = bytes.len() / 2;
bytes[middle] ^= 0xff;
std::fs::write(&part, &bytes).unwrap();
let (dst_dir, dst) = make_repo(base, "part", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_required_delta_pull_of_a_held_commit_is_not_refused() {
let tmp = TmpDir::new("pull-delta-held");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
delta_with(&src, Some(&c1), &c2, DeltaOptions::default()).await;
summarize(&src).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
pull_main(&dst, &src, PullFlags::empty()).await;
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.delta_parts, 0);
assert_eq!(stats.metadata_fetched, 0);
});
}
#[test]
fn a_required_delta_commit_only_pull_takes_the_commit_loose() {
let tmp = TmpDir::new("pull-delta-commit-only");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
summarize(&src).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let stats = dst
.pull_local(&src, required(PullFlags::COMMIT_ONLY))
.await
.unwrap();
let hex = c2.to_hex();
let commit_file = src_dir
.join("objects")
.join(&hex[..2])
.join(format!("{}.commit", &hex[2..]));
assert_eq!(stats.metadata_fetched, 1);
assert_eq!(
stats.bytes_transferred,
std::fs::metadata(commit_file).unwrap().len()
);
assert!(has_partial_marker(&dst_dir, &c2));
});
}
#[test]
fn a_required_delta_applies_into_archive() {
let tmp = TmpDir::new("pull-delta-archive");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2, _dir) = delta_source(base).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.delta_parts, 1);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn bareuseronly_files_rejects_a_local_delta_object_outside_0775() {
let tmp = TmpDir::new("pull-delta-mode-bits");
block_on(async {
let base = tmp.path();
build_tree(&base.join("v1"), b"hello\n");
std::fs::set_permissions(
base.join("v1/exec.sh"),
std::fs::Permissions::from_mode(0o4755),
)
.unwrap();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let c1 = commit_tree_with(
&src,
base,
"v1",
"main",
None,
CommitModifierFlags::SKIP_XATTRS,
None,
)
.await;
delta_with(&src, None, &c1, DeltaOptions::default()).await;
summarize(&src).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::BAREUSERONLY_FILES))
.await
.unwrap_err();
assert!(err.to_string().contains("invalid mode"), "{err}");
assert_nothing_left(&dst_dir, &dst, &c1).await;
});
}
#[test]
fn multi_part_and_inline_deltas_apply() {
let tmp = TmpDir::new("pull-delta-parts");
block_on(async {
let base = tmp.path();
build_tree(&base.join("v1"), b"hello\n");
let mut big = Vec::with_capacity(256 * 1024);
let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
while big.len() < 256 * 1024 {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
big.extend_from_slice(&state.to_le_bytes());
}
std::fs::write(base.join("v1/big"), &big).unwrap();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let c1 = commit_tree(&src, base, "v1", "main", None).await;
summarize(&src).await;
for (name, inline) in [("parts", false), ("inline", true)] {
delta_with(
&src,
None,
&c1,
DeltaOptions {
max_chunk_size: 1,
inline,
..DeltaOptions::default()
},
)
.await;
summarize(&src).await;
let (_dst_dir, dst) = make_repo(base, name, RepoMode::BareUser).await;
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
if inline {
assert_eq!(stats.delta_parts, 0, "{name}");
} else {
assert!(stats.delta_parts > 1, "{name}: {stats:?}");
}
assert_eq!(dst.commit_state(&c1).await.unwrap(), CommitState::Normal);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
assert_eq!(
dst.list_objects().await.unwrap(),
src.traverse_commit(&c1, 0).await.unwrap()
);
}
});
}
#[test]
fn a_required_delta_pull_of_a_partial_commit_looks_for_a_delta() {
let tmp = TmpDir::new("pull-delta-partial");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
summarize(&src).await;
let (dst_dir, dst) = make_repo(base, "none", RepoMode::BareUser).await;
pull_main(&dst, &src, PullFlags::COMMIT_ONLY).await;
let held = dst.list_objects().await.unwrap();
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert_eq!(
err.to_string(),
format!("pull: Static deltas required, but none found for main to {c2}")
);
assert_eq!(dst.list_objects().await.unwrap(), held);
assert!(has_partial_marker(&dst_dir, &c2));
delta_with(&src, None, &c2, DeltaOptions::default()).await;
src.reindex_static_deltas().await.unwrap();
summarize(&src).await;
let (dst_dir, dst) = make_repo(base, "scratch", RepoMode::BareUser).await;
pull_main(&dst, &src, PullFlags::COMMIT_ONLY).await;
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.delta_parts, 0);
assert!(stats.content_fetched > 0, "{stats:?}");
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
});
}
#[test]
fn a_required_delta_pull_refuses_in_the_tool_order() {
let tmp = TmpDir::new("pull-delta-refusal-order");
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 absent = PullOptions {
refs: vec!["absent".to_owned()],
..required(PullFlags::empty())
};
let err = dst.pull_local(&src, absent.clone()).await.unwrap_err();
assert_eq!(
err.to_string(),
"pull: Fetch configured to require static deltas, but no summary deltas or \
delta index found"
);
summarize(&src).await;
let err = dst.pull_local(&src, absent).await.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
});
}
#[test]
fn a_required_delta_pull_refuses_a_summary_that_is_not_a_regular_file() {
let tmp = TmpDir::new("pull-delta-summary-fifo");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let status = Command::new("mkfifo")
.arg(src_dir.join("summary"))
.status()
.unwrap();
assert!(status.success());
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert!(err.to_string().contains("not a regular file"), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_part_file_past_its_declared_size_is_refused() {
let tmp = TmpDir::new("pull-delta-grown-part");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2, dir) = delta_source(base).await;
let mut part = std::fs::OpenOptions::new()
.append(true)
.open(dir.join("0"))
.unwrap();
std::io::Write::write_all(&mut part, &[0u8; 4096]).unwrap();
drop(part);
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
assert!(err.to_string().contains("declared for it"), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
async fn assert_complete(src: &Repo, dst: &Repo, dst_dir: &Path, commit: &Checksum) {
assert_eq!(dst.commit_state(commit).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(dst_dir, commit));
for name in &src.traverse_commit(commit, 0).await.unwrap() {
assert!(
dst.has_object(name.ty, &name.checksum).await.unwrap(),
"{name} missing from the destination"
);
}
}
#[test]
fn a_pull_with_no_ref_writes_keeps_the_ref_and_completes_the_commit() {
let tmp = TmpDir::new("pull-no-ref-writes");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
src.write_commit_detached_metadata(&c2, Some(&two_property_metadata()))
.await
.unwrap();
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let txn = dst.transaction().await.unwrap();
txn.set_ref("main", Some(&c1));
txn.commit().await.unwrap();
let refs = file_inventory(&dst_dir, "refs");
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
no_ref_writes: true,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(file_inventory(&dst_dir, "refs"), refs);
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c1));
assert_complete(&src, &dst, &dst_dir, &c2).await;
assert_eq!(
dst.read_commit_detached_metadata(&c2).await.unwrap(),
Some(two_property_metadata())
);
});
}
#[test]
fn a_pull_with_no_ref_writes_writes_no_remote_ref() {
let tmp = TmpDir::new("pull-no-ref-writes-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;
let refs = file_inventory(&dst_dir, "refs");
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
no_ref_writes: true,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(file_inventory(&dst_dir, "refs"), refs);
assert!(!dst_dir.join("refs/remotes/origin").exists());
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), None);
assert_complete(&src, &dst, &dst_dir, &c2).await;
});
}
#[test]
fn a_pull_with_no_ref_writes_completes_every_parent_under_depth() {
let tmp = TmpDir::new("pull-no-ref-writes-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::BareUser).await;
let refs = file_inventory(&dst_dir, "refs");
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
depth: -1,
no_ref_writes: true,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(file_inventory(&dst_dir, "refs"), refs);
assert_eq!(dst.resolve_rev("main", true).await.unwrap(), None);
for commit in [&c1, &c2] {
assert_complete(&src, &dst, &dst_dir, commit).await;
}
});
}
const COLLECTION: &str = "org.example.Os";
fn collection_pull(refs: &[&str]) -> PullOptions {
PullOptions {
refs: refs.iter().map(|name| (*name).to_owned()).collect(),
remote: Some("origin".to_owned()),
collection_id: Some(COLLECTION.to_owned()),
no_ref_writes: true,
..PullOptions::default()
}
}
async fn set_collection_ref(repo: &Repo, collection: &str, name: &str, commit: &Checksum) {
let txn = repo.transaction().await.unwrap();
txn.set_collection_ref(&CollectionRef::new(collection, name), Some(commit));
txn.commit().await.unwrap();
}
async fn thin_source(
base: &Path,
src_dir: &Path,
src: &Repo,
c1: &Checksum,
c2: &Checksum,
) -> (PathBuf, Repo, HashSet<ObjectName>) {
let old = src.traverse_commit(c1, 0).await.unwrap();
let new = src.traverse_commit(c2, 0).await.unwrap();
let (path, thin) = make_repo(base, "thin", RepoMode::Archive).await;
for name in new.difference(&old) {
let to = object_path(&path, name, RepoMode::Archive);
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
std::fs::copy(object_path(src_dir, name, RepoMode::Archive), &to).unwrap();
}
set_collection_ref(&thin, COLLECTION, "main", c2).await;
drop(thin);
let thin = Repo::open(&path).await.unwrap();
let shared = old.intersection(&new).copied().collect();
(path, thin, shared)
}
fn copy_tree(from: &Path, to: &Path) {
std::fs::create_dir_all(to).unwrap();
for entry in std::fs::read_dir(from).unwrap().flatten() {
let target = to.join(entry.file_name());
if entry.file_type().unwrap().is_dir() {
copy_tree(&entry.path(), &target);
} else {
std::fs::copy(entry.path(), &target).unwrap();
}
}
}
#[test]
fn a_collection_pull_takes_the_shared_objects_from_the_destination() {
let tmp = TmpDir::new("pull-collection-thin");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (_thin_dir, thin, shared) = thin_source(base, &src_dir, &src, &c1, &c2).await;
assert!(shared.contains(&subdir_dirtree(&src, &c2).await));
assert!(shared.iter().any(|name| name.ty == ObjectType::File));
for name in &shared {
assert!(!thin.has_object(name.ty, &name.checksum).await.unwrap());
}
let held = thin.list_objects().await.unwrap();
let (dst_dir, dst) = dst_holding(base, "dst", &src, &c1).await;
let refs = file_inventory(&dst_dir, "refs");
let stats = dst
.pull_local(&thin, collection_pull(&["main"]))
.await
.unwrap();
assert_eq!(file_inventory(&dst_dir, "refs"), refs);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
let mut expected = src.traverse_commit(&c1, 0).await.unwrap();
expected.extend(src.traverse_commit(&c2, 0).await.unwrap());
assert_eq!(dst.list_objects().await.unwrap(), expected);
let content = held.iter().filter(|n| n.ty == ObjectType::File).count();
assert_eq!(stats.content_imported as usize, content);
assert_eq!(stats.metadata_imported as usize, held.len() - content);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_collection_pull_from_a_thin_source_into_an_empty_destination_fails() {
let tmp = TmpDir::new("pull-collection-thin-empty");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (_thin_dir, thin, _shared) = thin_source(base, &src_dir, &src, &c1, &c2).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let err = dst
.pull_local(&thin, collection_pull(&["main"]))
.await
.unwrap_err();
assert!(matches!(err, Error::ObjectNotFound { .. }), "{err:?}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_collection_pull_reads_the_ref_under_refs_mirrors() {
let tmp = TmpDir::new("pull-collection-mirrors");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
assert_eq!(src.resolve_rev("main", false).await.unwrap(), Some(c2));
set_collection_ref(&src, COLLECTION, "main", &c1).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, collection_pull(&["main"]))
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &c1).await;
assert!(!dst.has_object(ObjectType::Commit, &c2).await.unwrap());
});
}
#[test]
fn an_absent_collection_ref_is_not_found() {
let tmp = TmpDir::new("pull-collection-absent");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
set_collection_ref(&src, "org.example.Other", "main", &c2).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let hex = c2.to_hex();
for name in ["main", hex.as_str()] {
let err = dst
.pull_local(&src, collection_pull(&[name]))
.await
.unwrap_err();
match err {
Error::RefNotFound(pair) => assert_eq!(pair, format!("{COLLECTION}:{name}")),
other => panic!("{name}: {other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &c2).await;
}
});
}
async fn own_collection_source(base: &Path, name: &str) -> (PathBuf, Repo, Checksum) {
let path = base.join("src");
let src = Repo::create(
&path,
CreateOptions {
mode: RepoMode::Archive,
collection_id: Some(COLLECTION.to_owned()),
},
)
.await
.unwrap();
let commit = commit_collection_ref(
&src,
base,
"va",
name,
None,
bound_to(COLLECTION),
Some(&[name]),
)
.await;
let txn = src.transaction().await.unwrap();
txn.set_collection_ref(&CollectionRef::new(COLLECTION, name), None);
txn.set_ref(name, Some(&commit));
txn.commit().await.unwrap();
assert!(
!path
.join(format!("refs/mirrors/{COLLECTION}/{name}"))
.exists()
);
assert!(path.join(format!("refs/heads/{name}")).is_file());
(path, src, commit)
}
#[test]
fn a_collection_pull_reads_the_local_ref_of_a_source_of_the_collection() {
let tmp = TmpDir::new("pull-collection-own-source");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commit) = own_collection_source(base, "app/a").await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, collection_write_pull(&["app/a"]))
.await
.unwrap();
let cref = CollectionRef::new(COLLECTION, "app/a");
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(commit)
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_complete(&src, &dst, &dst_dir, &commit).await;
});
}
#[test]
fn the_collection_ref_of_a_source_of_the_collection_wins_over_its_local_ref() {
let tmp = TmpDir::new("pull-collection-own-source-mirror");
block_on(async {
let base = tmp.path();
let (_src_dir, src, local) = own_collection_source(base, "app/a").await;
let mirrored = commit_collection_ref(
&src,
base,
"vb",
"app/a",
None,
bound_to(COLLECTION),
Some(&["app/a"]),
)
.await;
assert_ne!(mirrored, local);
assert_eq!(src.resolve_rev("app/a", false).await.unwrap(), Some(local));
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(&src, collection_write_pull(&["app/none"]))
.await
.unwrap_err();
match err {
Error::RefNotFound(pair) => assert_eq!(pair, format!("{COLLECTION}:app/none")),
other => panic!("{other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &mirrored).await;
assert!(dst.list_mirror_refs().await.unwrap().is_empty());
dst.pull_local(&src, collection_write_pull(&["app/a"]))
.await
.unwrap();
let cref = CollectionRef::new(COLLECTION, "app/a");
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(mirrored)
);
assert_complete(&src, &dst, &dst_dir, &mirrored).await;
assert!(!dst.has_object(ObjectType::Commit, &local).await.unwrap());
});
}
#[test]
fn an_unreadable_local_ref_of_a_source_of_the_collection_fails_the_pull() {
if is_root() {
eprintln!("skipping: root reads a directory of mode 0000");
return;
}
let tmp = TmpDir::new("pull-collection-own-source-eacces");
block_on(async {
let base = tmp.path();
let (src_dir, src, commit) = own_collection_source(base, "app/a").await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let dir = src_dir.join("refs/heads/app");
let mode = std::fs::metadata(&dir).unwrap().permissions();
std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o000)).unwrap();
let result = dst
.pull_local(&src, collection_write_pull(&["app/a"]))
.await;
std::fs::set_permissions(&dir, mode).unwrap();
match result {
Err(Error::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied),
other => panic!("{other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &commit).await;
assert!(dst.list_mirror_refs().await.unwrap().is_empty());
});
}
#[test]
fn a_collection_pull_takes_a_required_delta() {
let tmp = TmpDir::new("pull-collection-delta");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let delta = delta_with(&src, Some(&c1), &c2, DeltaOptions::default()).await;
let (thin_dir, thin, _shared) = thin_source(base, &src_dir, &src, &c1, &c2).await;
copy_tree(
&delta,
&thin_dir.join(delta.strip_prefix(&src_dir).unwrap()),
);
thin.reindex_static_deltas().await.unwrap();
summarize(&thin).await;
let (_dst_dir, dst) = dst_holding(base, "dst", &src, &c1).await;
let txn = dst.transaction().await.unwrap();
txn.set_ref("origin:main", Some(&c1));
txn.commit().await.unwrap();
let stats = dst
.pull_local(
&thin,
PullOptions {
remote: Some("origin".to_owned()),
collection_id: Some(COLLECTION.to_owned()),
no_ref_writes: true,
..required(PullFlags::empty())
},
)
.await
.unwrap();
assert_eq!(stats.delta_parts, 1);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert_eq!(
dst.resolve_rev("origin:main", false).await.unwrap(),
Some(c1)
);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_collection_pull_checks_the_ref_binding_against_the_name() {
let tmp = TmpDir::new("pull-collection-binding");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
set_collection_ref(&src, COLLECTION, "other", &c2).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(&src, collection_pull(&["other"]))
.await
.unwrap_err();
assert!(matches!(err, Error::Pull(_)), "{err}");
assert!(err.to_string().contains("other"), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
dst.pull_local(
&src,
PullOptions {
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..collection_pull(&["other"])
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &c2).await;
});
}
fn metadata_entry(key: &str, ty: &str, value: Value) -> Value {
Value::Tuple(vec![
Value::Str(key.to_owned()),
Value::Variant(Box::new((Type::parse(ty).unwrap(), value))),
])
}
fn bound_to(id: &str) -> Option<(&'static str, Value)> {
Some(("s", Value::Str(id.to_owned())))
}
async fn commit_collection_ref(
repo: &Repo,
base: &Path,
sub: &str,
name: &str,
parent: Option<Checksum>,
collection: Option<(&str, Value)>,
refs: Option<&[&str]>,
) -> Checksum {
commit_collection_ref_full(repo, base, sub, name, parent, collection, refs, &[]).await
}
#[allow(clippy::too_many_arguments)]
async fn commit_collection_ref_full(
repo: &Repo,
base: &Path,
sub: &str,
name: &str,
parent: Option<Checksum>,
collection: Option<(&str, Value)>,
refs: Option<&[&str]>,
related: &[(&str, Checksum)],
) -> Checksum {
build_tree(&base.join(sub), sub.as_bytes());
let txn = repo.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(sub), &mut mtree, Some(&mut modifier))
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let mut metadata = Vec::new();
if let Some((ty, value)) = collection {
metadata.push(metadata_entry("ostree.collection-binding", ty, value));
}
if let Some(refs) = refs {
let refs = refs.iter().map(|r| Value::Str((*r).to_owned())).collect();
metadata.push(metadata_entry(
"ostree.ref-binding",
"as",
Value::Array(refs),
));
}
let commit = txn
.write_commit(
CommitOptions {
parent,
subject: Some(format!("{name} {sub}")),
timestamp: Some(FIXED_TS),
metadata: Some(Value::Array(metadata)),
related: related
.iter()
.map(|(name, checksum)| ((*name).to_owned(), *checksum))
.collect(),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_collection_ref(&CollectionRef::new(COLLECTION, name), Some(&commit));
txn.commit().await.unwrap();
commit
}
fn collection_write_pull(refs: &[&str]) -> PullOptions {
PullOptions {
no_ref_writes: false,
..collection_pull(refs)
}
}
fn repo_inventory(dir: &Path) -> Vec<(String, Vec<u8>)> {
let mut out = file_inventory(dir, "objects");
out.extend(file_inventory(dir, "refs"));
out.extend(file_inventory(dir, "state"));
out
}
struct ReadOnlyStore {
held: Vec<(PathBuf, std::fs::Permissions)>,
}
impl ReadOnlyStore {
fn new(repo_dir: &Path) -> ReadOnlyStore {
let mut held = Vec::new();
if is_root() {
eprintln!("not checking the write order: root writes a directory of mode 0555");
return ReadOnlyStore { held };
}
for dir in ["objects", "state"] {
let path = repo_dir.join(dir);
let mode = std::fs::metadata(&path).unwrap().permissions();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o555)).unwrap();
held.push((path, mode));
}
ReadOnlyStore { held }
}
}
impl Drop for ReadOnlyStore {
fn drop(&mut self) {
for (path, mode) in self.held.drain(..) {
let _ = std::fs::set_permissions(path, mode);
}
}
}
#[test]
fn a_collection_pull_with_ref_writes_writes_the_collection_refs() {
let tmp = TmpDir::new("pull-collection-write");
block_on(async {
let base = tmp.path();
let (src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let mut pulled = Vec::new();
for (sub, name) in [("va", "app/a"), ("vb", "app/b")] {
let commit = commit_collection_ref(
&src,
base,
sub,
name,
None,
bound_to(COLLECTION),
Some(&[name]),
)
.await;
let meta = Value::Array(vec![metadata_entry(
"build.name",
"s",
Value::Str(name.to_owned()),
)]);
src.write_commit_detached_metadata(&commit, Some(&meta))
.await
.unwrap();
pulled.push((name, commit));
}
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
dst.pull_local(&src, collection_write_pull(&["app/a", "app/b"]))
.await
.unwrap();
for (name, commit) in &pulled {
let cref = CollectionRef::new(COLLECTION, *name);
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(*commit)
);
assert_complete(&src, &dst, &dst_dir, commit).await;
assert_eq!(
std::fs::read(commitmeta_path(&dst_dir, commit)).unwrap(),
std::fs::read(commitmeta_path(&src_dir, commit)).unwrap(),
"{name}"
);
}
let mut mirrors = dst.list_mirror_refs().await.unwrap();
mirrors.sort();
let expected: Vec<_> = pulled
.iter()
.map(|(name, commit)| (COLLECTION.to_owned(), (*name).to_owned(), *commit))
.collect();
assert_eq!(mirrors, expected);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(file_inventory(&dst_dir, "refs/remotes").is_empty());
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_collection_pull_into_the_own_collection_writes_refs_heads() {
let tmp = TmpDir::new("pull-collection-own");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let commit = commit_collection_ref(
&src,
base,
"va",
"app/a",
None,
bound_to(COLLECTION),
Some(&["app/a"]),
)
.await;
let dst_dir = base.join("dst");
let dst = Repo::create(
&dst_dir,
CreateOptions {
mode: RepoMode::BareUser,
collection_id: Some(COLLECTION.to_owned()),
},
)
.await
.unwrap();
dst.pull_local(&src, collection_write_pull(&["app/a"]))
.await
.unwrap();
assert_eq!(
dst.list_refs(None).await.unwrap(),
vec![("app/a".to_owned(), commit)]
);
assert!(file_inventory(&dst_dir, "refs/mirrors").is_empty());
assert!(file_inventory(&dst_dir, "refs/remotes").is_empty());
let cref = CollectionRef::new(COLLECTION, "app/a");
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(commit)
);
assert_complete(&src, &dst, &dst_dir, &commit).await;
});
}
#[test]
fn a_collection_pull_into_the_own_collection_writes_an_existing_mirror_ref() {
let tmp = TmpDir::new("pull-collection-own-mirror");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let mut commits = Vec::new();
for (sub, name) in [("vm", "app/m"), ("vh", "app/h"), ("va", "app/a")] {
let refs: &[&str] = &[name];
commits.push(
commit_collection_ref(
&src,
base,
sub,
name,
None,
bound_to(COLLECTION),
Some(refs),
)
.await,
);
}
let (held, local, commit) = (commits[0], commits[1], commits[2]);
let dst_dir = base.join("dst");
let dst = Repo::create(
&dst_dir,
CreateOptions {
mode: RepoMode::BareUser,
collection_id: Some(COLLECTION.to_owned()),
},
)
.await
.unwrap();
for c in [held, local] {
hold_commit(&dst, &src, &c).await;
}
let txn = dst.transaction().await.unwrap();
txn.set_collection_ref(&CollectionRef::new(COLLECTION, "app/a"), Some(&held));
txn.set_ref("app/a", Some(&local));
txn.commit().await.unwrap();
dst.pull_local(&src, collection_write_pull(&["app/a"]))
.await
.unwrap();
assert_eq!(
dst.list_refs(None).await.unwrap(),
vec![("app/a".to_owned(), local)]
);
assert_eq!(
dst.list_mirror_refs().await.unwrap(),
vec![(COLLECTION.to_owned(), "app/a".to_owned(), commit)]
);
let cref = CollectionRef::new(COLLECTION, "app/a");
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(commit)
);
let all = RefSelector::parse([]).unwrap();
assert_eq!(
dst.list_collection_refs_in(COLLECTION, &all).await.unwrap(),
vec![("app/a".to_owned(), commit)]
);
assert_complete(&src, &dst, &dst_dir, &commit).await;
});
}
#[test]
fn a_collection_pull_with_ref_writes_refuses_an_unbound_tip() {
let tmp = TmpDir::new("pull-collection-unbound");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let commit =
commit_collection_ref(&src, base, "va", "app/a", None, None, Some(&["app/a"])).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let before = repo_inventory(&dst_dir);
let _store = ReadOnlyStore::new(&dst_dir);
let err = dst
.pull_local(&src, collection_write_pull(&["app/a"]))
.await
.unwrap_err();
match err {
Error::Pull(msg) => assert_eq!(
msg,
format!(
"commit {commit}: no collection binding metadata for the requested \
collection '{COLLECTION}'"
)
),
other => panic!("{other:?}"),
}
assert_eq!(repo_inventory(&dst_dir), before);
assert!(dst.list_mirror_refs().await.unwrap().is_empty());
assert_nothing_left(&dst_dir, &dst, &commit).await;
});
}
#[test]
fn a_collection_pull_with_ref_writes_refuses_a_tip_bound_elsewhere() {
let tmp = TmpDir::new("pull-collection-bound-elsewhere");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let other = commit_collection_ref(
&src,
base,
"va",
"app/a",
None,
bound_to("org.example.Other"),
Some(&["app/a"]),
)
.await;
let number = commit_collection_ref(
&src,
base,
"vb",
"app/b",
None,
Some(("u", Value::U32(7))),
Some(&["app/b"]),
)
.await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let before = repo_inventory(&dst_dir);
let _store = ReadOnlyStore::new(&dst_dir);
for (name, commit, expected) in [
(
"app/a",
other,
format!(
"commit {other}: collection binding 'org.example.Other' is not the \
requested collection '{COLLECTION}'"
),
),
(
"app/b",
number,
format!("commit {number}: collection binding metadata is not a string"),
),
] {
match dst.pull_local(&src, collection_write_pull(&[name])).await {
Err(Error::Pull(msg)) => assert_eq!(msg, expected, "{name}"),
other => panic!("{name}: {other:?}"),
}
assert_eq!(repo_inventory(&dst_dir), before, "{name}");
assert_nothing_left(&dst_dir, &dst, &commit).await;
}
});
}
#[test]
fn a_collection_pull_with_no_ref_writes_reads_no_collection_binding() {
let tmp = TmpDir::new("pull-collection-no-writes-binding");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let mut tips = Vec::new();
for (sub, name, collection) in [
("va", "app/a", None),
("vb", "app/b", bound_to("org.example.Other")),
("vc", "app/c", Some(("u", Value::U32(7)))),
] {
let commit =
commit_collection_ref(&src, base, sub, name, None, collection, Some(&[name])).await;
tips.push(commit);
}
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let refs = file_inventory(&dst_dir, "refs");
dst.pull_local(&src, collection_pull(&["app/a", "app/b", "app/c"]))
.await
.unwrap();
assert_eq!(file_inventory(&dst_dir, "refs"), refs);
for commit in &tips {
assert_complete(&src, &dst, &dst_dir, commit).await;
}
});
}
#[test]
fn disable_verify_bindings_skips_the_ref_binding_alone_in_a_collection_pull() {
let tmp = TmpDir::new("pull-collection-disable-bindings");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::BareUser).await;
let misnamed = commit_collection_ref(
&src,
base,
"va",
"app/a",
None,
bound_to(COLLECTION),
Some(&["app/other"]),
)
.await;
let unbound =
commit_collection_ref(&src, base, "vb", "app/b", None, None, Some(&["app/b"])).await;
let elsewhere = commit_collection_ref(
&src,
base,
"vc",
"app/c",
None,
bound_to("org.example.Other"),
Some(&["app/c"]),
)
.await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let disabled = |name: &str| PullOptions {
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..collection_write_pull(&[name])
};
for (name, commit, opts, expected) in [
(
"app/a",
misnamed,
collection_write_pull(&["app/a"]),
"ref binding",
),
(
"app/b",
unbound,
disabled("app/b"),
"no collection binding metadata",
),
(
"app/c",
elsewhere,
disabled("app/c"),
"is not the requested collection",
),
] {
match dst.pull_local(&src, opts).await {
Err(Error::Pull(msg)) => assert!(msg.contains(expected), "{name}: {msg}"),
other => panic!("{name}: {other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &commit).await;
}
assert!(dst.list_mirror_refs().await.unwrap().is_empty());
dst.pull_local(&src, disabled("app/a")).await.unwrap();
let cref = CollectionRef::new(COLLECTION, "app/a");
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(misnamed)
);
assert_complete(&src, &dst, &dst_dir, &misnamed).await;
});
}
async fn collection_chain_source(
base: &Path,
tip: Option<(&str, Value)>,
tip_refs: &[&str],
) -> (Repo, Checksum, Checksum) {
let (_path, src) = make_repo(base, "src", RepoMode::Archive).await;
let c1 = commit_collection_ref(
&src,
base,
"v1",
"main",
None,
bound_to(COLLECTION),
Some(&["main"]),
)
.await;
let c2 = commit_collection_ref(&src, base, "v2", "main", Some(c1), tip, Some(tip_refs)).await;
(src, c1, c2)
}
async fn publish_listed(
src: &Repo,
steps: &[(Option<Checksum>, Checksum)],
) -> Vec<AdvertisedDelta> {
let dirs = publish_deltas(src, steps).await;
steps
.iter()
.zip(dirs)
.map(|((from, to), dir)| AdvertisedDelta {
from: *from,
to: *to,
superblock: Checksum::sha256(&std::fs::read(dir.join("superblock")).unwrap()),
})
.collect()
}
fn collection_delta_pulls(list: &[AdvertisedDelta]) -> [(&'static str, PullOptions); 2] {
[
(
"required",
PullOptions {
require_static_deltas: true,
..collection_write_pull(&["main"])
},
),
(
"list",
PullOptions {
static_deltas: Some(list.to_vec()),
..collection_write_pull(&["main"])
},
),
]
}
#[derive(Clone, Copy, Debug)]
enum HeldAt {
Mirror,
Own,
OwnMirror,
OwnBoth,
Elsewhere,
}
fn unheld_commit() -> Checksum {
Checksum::from_bytes([0xa5; 32])
}
async fn dst_with_main(
base: &Path,
name: &str,
src: &Repo,
held: &[Checksum],
at: HeldAt,
tip: &Checksum,
) -> (PathBuf, Repo) {
let path = base.join(name);
let dst = Repo::create(
&path,
CreateOptions {
mode: RepoMode::BareUser,
collection_id: matches!(at, HeldAt::Own | HeldAt::OwnMirror | HeldAt::OwnBoth)
.then(|| COLLECTION.to_owned()),
},
)
.await
.unwrap();
for commit in held {
hold_commit(&dst, src, commit).await;
}
let txn = dst.transaction().await.unwrap();
match at {
HeldAt::Mirror | HeldAt::OwnMirror => {
txn.set_collection_ref(&CollectionRef::new(COLLECTION, "main"), Some(tip));
}
HeldAt::OwnBoth => {
txn.set_collection_ref(&CollectionRef::new(COLLECTION, "main"), Some(tip));
txn.set_ref("main", Some(&unheld_commit()));
}
HeldAt::Own => txn.set_ref("main", Some(tip)),
HeldAt::Elsewhere => {
txn.set_ref("origin:main", Some(tip));
txn.set_ref("main", Some(tip));
}
}
txn.commit().await.unwrap();
(path, dst)
}
async fn clear_unheld_main(dst: &Repo, name: &str) {
assert_eq!(
dst.list_refs(None).await.unwrap(),
vec![("main".to_owned(), unheld_commit())],
"{name}"
);
dst.set_ref_immediate("main", None).await.unwrap();
}
#[test]
fn a_collection_delta_pull_reads_the_from_commit_at_the_written_ref() {
let tmp = TmpDir::new("pull-collection-delta-place");
block_on(async {
let base = tmp.path();
let (src, c1, c2) = collection_chain_source(base, bound_to(COLLECTION), &["main"]).await;
let list = publish_listed(&src, &[(None, c2)]).await;
for (path, opts) in collection_delta_pulls(&list) {
for (at, parts) in [
(HeldAt::Mirror, 0),
(HeldAt::Own, 0),
(HeldAt::OwnMirror, 0),
(HeldAt::OwnBoth, 0),
(HeldAt::Elsewhere, 1),
] {
let name = format!("{path}-{at:?}");
let (dst_dir, dst) = dst_with_main(base, &name, &src, &[c1], at, &c1).await;
let stats = dst.pull_local(&src, opts.clone()).await.unwrap();
assert_eq!(stats.delta_parts, parts, "{name}");
let cref = CollectionRef::new(COLLECTION, "main");
assert_eq!(
dst.resolve_collection_ref(&cref, false).await.unwrap(),
Some(c2),
"{name}"
);
if let HeldAt::Elsewhere = at {
for held in ["origin:main", "main"] {
assert_eq!(
dst.resolve_rev(held, false).await.unwrap(),
Some(c1),
"{name} {held}"
);
}
}
if let HeldAt::OwnBoth = at {
clear_unheld_main(&dst, &name).await;
}
assert_complete(&src, &dst, &dst_dir, &c2).await;
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
}
}
});
}
#[test]
fn a_collection_pull_reads_the_paired_entry_of_a_dependency_at_the_written_ref() {
let tmp = TmpDir::new("pull-collection-dependency-place");
block_on(async {
let base = tmp.path();
for sub in ["uki1", "uki2"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (_path, src) = make_repo(base, "src", RepoMode::Archive).await;
let d1 = commit_tree(&src, base, "uki1", "dep/uki", None).await;
let d2 = commit_tree(&src, base, "uki2", "dep/uki", Some(d1)).await;
let t1 = commit_collection_ref_full(
&src,
base,
"main1",
"main",
None,
bound_to(COLLECTION),
Some(&["main"]),
&[("boot/uki", d1)],
)
.await;
let t2 = commit_collection_ref_full(
&src,
base,
"main2",
"main",
Some(t1),
bound_to(COLLECTION),
Some(&["main"]),
&[("boot/uki", d2)],
)
.await;
let list = publish_listed(&src, &[(Some(t1), t2), (None, d2)]).await;
for (path, opts) in collection_delta_pulls(&list) {
for (at, parts) in [
(HeldAt::Mirror, 1),
(HeldAt::Own, 1),
(HeldAt::OwnMirror, 1),
(HeldAt::OwnBoth, 1),
(HeldAt::Elsewhere, 2),
] {
let name = format!("{path}-{at:?}");
let (dst_dir, dst) = dst_with_main(base, &name, &src, &[t1, d1], at, &t1).await;
let stats = dst.pull_local(&src, opts.clone()).await.unwrap();
assert_eq!(stats.delta_parts, parts, "{name}");
if let HeldAt::OwnBoth = at {
clear_unheld_main(&dst, &name).await;
}
for commit in [t2, d2] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
}
}
});
}
#[test]
fn a_collection_delta_pull_refuses_an_unbound_tip() {
let tmp = TmpDir::new("pull-collection-delta-unbound");
block_on(async {
let base = tmp.path();
let (src, c1, c2) = collection_chain_source(base, None, &["main"]).await;
let list = publish_listed(&src, &[(Some(c1), c2)]).await;
for (case, opts) in collection_delta_pulls(&list) {
let (dst_dir, dst) = dst_holding(base, case, &src, &c1).await;
set_collection_ref(&dst, COLLECTION, "main", &c1).await;
let before = repo_inventory(&dst_dir);
let store = ReadOnlyStore::new(&dst_dir);
match dst.pull_local(&src, opts).await {
Err(Error::Pull(msg)) => assert_eq!(
msg,
format!(
"commit {c2}: no collection binding metadata for the requested \
collection '{COLLECTION}'"
),
"{case}"
),
other => panic!("{case}: {other:?}"),
}
drop(store);
assert_eq!(repo_inventory(&dst_dir), before, "{case}");
}
});
}
#[test]
fn disable_verify_bindings_skips_the_ref_binding_alone_in_a_collection_delta_pull() {
let tmp = TmpDir::new("pull-collection-delta-disable-bindings");
block_on(async {
for (tip, collection, refs) in [
("misnamed", bound_to(COLLECTION), &["other"][..]),
("unbound", None, &["main"][..]),
] {
let base = tmp.path().join(tip);
std::fs::create_dir(&base).unwrap();
let (src, c1, c2) = collection_chain_source(&base, collection, refs).await;
let list = publish_listed(&src, &[(Some(c1), c2)]).await;
for (path, opts) in collection_delta_pulls(&list) {
let (dst_dir, dst) = dst_holding(&base, path, &src, &c1).await;
set_collection_ref(&dst, COLLECTION, "main", &c1).await;
let opts = PullOptions {
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..opts
};
let result = dst.pull_local(&src, opts).await;
let cref = CollectionRef::new(COLLECTION, "main");
let at = dst.resolve_collection_ref(&cref, false).await.unwrap();
match (tip, result) {
("misnamed", Ok(_)) => {
assert_eq!(at, Some(c2), "{tip} {path}");
assert_complete(&src, &dst, &dst_dir, &c2).await;
}
("unbound", Err(Error::Pull(msg))) => {
assert!(
msg.contains("no collection binding metadata"),
"{tip} {path}: {msg}"
);
assert_eq!(at, Some(c1), "{tip} {path}");
}
(_, other) => panic!("{tip} {path}: {other:?}"),
}
}
}
});
}
#[test]
fn a_collection_pull_is_refused_without_a_ref() {
let tmp = TmpDir::new("pull-collection-refused");
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;
let before = repo_inventory(&dst_dir);
for (case, opts) in [
("no ref writes", collection_pull(&[])),
("ref writes", collection_write_pull(&[])),
] {
match dst.pull_local(&src, opts).await {
Err(Error::Unsupported(msg)) => assert_eq!(
msg, "a local pull with a collection id needs at least one ref name",
"{case}"
),
other => panic!("{case}: {other:?}"),
}
assert_eq!(repo_inventory(&dst_dir), before, "{case}");
}
});
}
#[test]
fn a_collection_ref_path_through_a_directory_or_a_file_is_not_found() {
let tmp = TmpDir::new("pull-collection-not-a-ref");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
set_collection_ref(&src, COLLECTION, "main/sub", &c2).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
for name in ["main", "main/sub/x"] {
let err = dst
.pull_local(&src, collection_pull(&[name]))
.await
.unwrap_err();
match err {
Error::RefNotFound(pair) => assert_eq!(pair, format!("{COLLECTION}:{name}")),
other => panic!("{name}: {other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &c2).await;
}
let own_base = base.join("own");
std::fs::create_dir(&own_base).unwrap();
let (_own_dir, own, app) = own_collection_source(&own_base, "app").await;
let err = dst
.pull_local(&own, collection_pull(&["app/a"]))
.await
.unwrap_err();
match err {
Error::RefNotFound(pair) => assert_eq!(pair, format!("{COLLECTION}:app/a")),
other => panic!("app/a: {other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &app).await;
});
}
#[test]
fn a_collection_ref_name_takes_no_revision_syntax() {
let tmp = TmpDir::new("pull-collection-revision");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
set_collection_ref(&src, COLLECTION, "main", &c2).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let hex = c2.to_hex();
let name = &hex[..10];
let err = dst
.pull_local(&src, collection_pull(&[name]))
.await
.unwrap_err();
match err {
Error::RefNotFound(pair) => assert_eq!(pair, format!("{COLLECTION}:{name}")),
other => panic!("{name}: {other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &c2).await;
let name = "main^";
let err = dst
.pull_local(&src, collection_pull(&[name]))
.await
.unwrap_err();
match err {
Error::InvalidRefspec(pair) => assert_eq!(pair, format!("{COLLECTION}:{name}")),
other => panic!("{name}: {other:?}"),
}
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn an_invalid_collection_id_or_name_is_refused_before_the_source_is_read() {
let tmp = TmpDir::new("pull-collection-invalid");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::BareUser).await;
let before = repo_inventory(&dst_dir);
for no_ref_writes in [true, false] {
let opts = |id: &str, name: &str| PullOptions {
refs: vec![name.to_owned()],
collection_id: Some(id.to_owned()),
no_ref_writes,
require_static_deltas: true,
..PullOptions::default()
};
let err = dst.pull_local(&src, opts(COLLECTION, "main")).await;
assert!(
matches!(err, Err(Error::Pull(_))),
"{no_ref_writes}: {err:?}"
);
for (id, name) in [
("", "main"),
("..", "main"),
("a/b", "main"),
("a", "main"),
("1org.x", "main"),
(COLLECTION, "a:b"),
(COLLECTION, "x:"),
(COLLECTION, ":y"),
(COLLECTION, "main^"),
(COLLECTION, "a b"),
(COLLECTION, "-a"),
] {
match dst.pull_local(&src, opts(id, name)).await {
Err(Error::InvalidRefspec(pair)) => assert_eq!(
pair,
format!("{id}:{name}"),
"{no_ref_writes} {id:?} {name:?}"
),
other => panic!("{no_ref_writes} {id:?} {name:?}: {other:?}"),
}
assert_eq!(
repo_inventory(&dst_dir),
before,
"{no_ref_writes} {id:?} {name:?}"
);
}
}
});
}
fn is_root() -> bool {
rustix::process::geteuid().is_root()
}
fn make_unreadable(repo_dir: &Path, name: &ObjectName, mode: RepoMode) {
std::fs::set_permissions(
object_path(repo_dir, name, mode),
std::fs::Permissions::from_mode(0o000),
)
.unwrap();
}
async fn dst_copy_holding(
base: &Path,
name: &str,
mode: RepoMode,
src: &Repo,
commit: &Checksum,
) -> (PathBuf, Repo) {
let (path, dst) = make_repo(base, name, mode).await;
dst.pull_local(
src,
PullOptions {
refs: vec![commit.to_hex()],
flags: PullFlags::DISABLE_VERIFY_BINDINGS | PullFlags::FORCE_COPY,
no_ref_writes: true,
..PullOptions::default()
},
)
.await
.unwrap();
assert!(dst.list_refs(None).await.unwrap().is_empty());
(path, dst)
}
fn assert_own_inode(src_dir: &Path, dst_dir: &Path, dirtree: &ObjectName, dst_mode: RepoMode) {
let ino = |path: PathBuf| {
let meta = std::fs::symlink_metadata(path).unwrap();
(meta.dev(), meta.ino())
};
assert_ne!(
ino(object_path(src_dir, dirtree, RepoMode::Archive)),
ino(object_path(dst_dir, dirtree, dst_mode)),
"{dirtree} is one inode in the source and the destination"
);
}
async fn nested_content(repo: &Repo, commit: &Checksum) -> ObjectName {
let subdir = subdir_dirtree(repo, commit).await;
let dirtree = repo.load_dirtree(&subdir.checksum).await.unwrap();
let (_, file) = dirtree
.files
.into_iter()
.find(|(name, _)| name == "nested.txt")
.expect("the subdirectory holds nested.txt");
ObjectName::new(file, ObjectType::File)
}
#[test]
fn a_commit_the_destination_holds_complete_reads_no_object_of_its_tree() {
if is_root() {
eprintln!("skipping: root reads a file of mode 0000");
return;
}
let tmp = TmpDir::new("pull-held-commit");
block_on(async {
let base = tmp.path();
let (src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = dst_copy_holding(base, "dst", RepoMode::BareUser, &src, &c2).await;
let (partial_dir, partial) = make_repo(base, "partial", RepoMode::BareUser).await;
partial
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
flags: PullFlags::COMMIT_ONLY | PullFlags::FORCE_COPY,
no_ref_writes: true,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
partial.commit_state(&c2).await.unwrap(),
CommitState::Partial
);
src.write_commit_detached_metadata(&c2, Some(&two_property_metadata()))
.await
.unwrap();
let tree = src.traverse_commit(&c2, 0).await.unwrap();
let mut held: Vec<(PathBuf, std::fs::Permissions)> = Vec::new();
for name in tree.iter().filter(|name| name.ty == ObjectType::DirTree) {
assert_own_inode(&src_dir, &dst_dir, name, RepoMode::BareUser);
let path = object_path(&dst_dir, name, RepoMode::BareUser);
held.push((
path.clone(),
std::fs::metadata(&path).unwrap().permissions(),
));
make_unreadable(&dst_dir, name, RepoMode::BareUser);
}
assert!(held.len() > 1, "the commit holds a root and a subdirectory");
for name in &tree {
if name.ty != ObjectType::Commit {
make_unreadable(&src_dir, name, RepoMode::Archive);
}
}
let opts = || PullOptions {
refs: vec!["main".to_owned()],
no_ref_writes: true,
..PullOptions::default()
};
let stats = dst.pull_local(&src, opts()).await.unwrap();
assert_eq!(stats.content_imported, 0);
assert_eq!(
dst.read_commit_detached_metadata(&c2).await.unwrap(),
Some(two_property_metadata())
);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
assert!(dst.list_refs(None).await.unwrap().is_empty());
for (path, permissions) in held {
std::fs::set_permissions(path, permissions).unwrap();
}
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
let err = partial.pull_local(&src, opts()).await.unwrap_err();
match err {
Error::Io(e) => assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied),
other => panic!("{other:?}"),
}
assert!(has_partial_marker(&partial_dir, &c2));
});
}
#[test]
fn a_dirtree_the_destination_holds_is_read_from_the_destination() {
if is_root() {
eprintln!("skipping: root reads a file of mode 0000");
return;
}
for mode in [RepoMode::Archive, RepoMode::BareUser] {
let tmp = TmpDir::new("pull-held-dirtree");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = dst_copy_holding(base, "dst", mode, &src, &c1).await;
let old = src.traverse_commit(&c1, 0).await.unwrap();
let new = src.traverse_commit(&c2, 0).await.unwrap();
let shared: Vec<ObjectName> = old
.intersection(&new)
.filter(|name| name.ty == ObjectType::DirTree)
.copied()
.collect();
assert!(shared.contains(&subdir_dirtree(&src, &c2).await));
for name in &shared {
assert_own_inode(&src_dir, &dst_dir, name, mode);
make_unreadable(&src_dir, name, RepoMode::Archive);
}
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));
for name in &new {
assert!(
dst.has_object(name.ty, &name.checksum).await.unwrap(),
"{mode:?}: {name} missing from the destination"
);
}
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
}
#[test]
fn a_hole_below_a_dirtree_the_destination_holds_is_filled_from_the_source() {
if is_root() {
eprintln!("skipping: root reads a file of mode 0000");
return;
}
let tmp = TmpDir::new("pull-held-dirtree-hole");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = dst_copy_holding(base, "dst", RepoMode::BareUser, &src, &c1).await;
let nested = nested_content(&src, &c2).await;
std::fs::remove_file(object_path(&dst_dir, &nested, RepoMode::BareUser)).unwrap();
let new = src.traverse_commit(&c2, 0).await.unwrap();
let subdir = subdir_dirtree(&src, &c2).await;
assert_own_inode(&src_dir, &dst_dir, &subdir, RepoMode::BareUser);
make_unreadable(&src_dir, &subdir, RepoMode::Archive);
dst.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert!(dst.has_object(nested.ty, &nested.checksum).await.unwrap());
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
for name in &new {
assert!(
dst.has_object(name.ty, &name.checksum).await.unwrap(),
"{name} missing from the destination"
);
}
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_hole_below_a_dirtree_no_source_holds_fails_the_pull() {
let tmp = TmpDir::new("pull-held-dirtree-thin");
block_on(async {
let base = tmp.path();
let (src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (thin_dir, thin, shared) = thin_source(base, &src_dir, &src, &c1, &c2).await;
let subdir = subdir_dirtree(&src, &c2).await;
let nested = nested_content(&src, &c2).await;
assert!(shared.contains(&subdir));
assert!(shared.contains(&nested));
let (dst_dir, dst) = dst_copy_holding(base, "dst", RepoMode::BareUser, &src, &c1).await;
std::fs::remove_file(object_path(&dst_dir, &nested, RepoMode::BareUser)).unwrap();
let before = object_names(&dst_dir);
let err = dst
.pull_local(&thin, collection_pull(&["main"]))
.await
.unwrap_err();
match err {
Error::ObjectNotFound { checksum, ty } => {
assert_eq!(ObjectName::new(checksum, ty), nested)
}
other => panic!("{other:?}"),
}
assert!(!dst.has_object(ObjectType::Commit, &c2).await.unwrap());
assert!(!has_partial_marker(&dst_dir, &c2));
assert_eq!(object_names(&dst_dir), before);
let to = object_path(&thin_dir, &nested, RepoMode::Archive);
std::fs::create_dir_all(to.parent().unwrap()).unwrap();
std::fs::copy(object_path(&src_dir, &nested, RepoMode::Archive), &to).unwrap();
dst.pull_local(&thin, collection_pull(&["main"]))
.await
.unwrap();
assert!(dst.has_object(nested.ty, &nested.checksum).await.unwrap());
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_dangling_symlink_at_a_dirtree_the_destination_holds_fails_the_pull() {
let tmp = TmpDir::new("pull-held-dirtree-symlink");
block_on(async {
let base = tmp.path();
let (_src_dir, src, c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = dst_copy_holding(base, "dst", RepoMode::BareUser, &src, &c1).await;
let subdir = subdir_dirtree(&src, &c2).await;
assert!(src.traverse_commit(&c1, 0).await.unwrap().contains(&subdir));
let path = object_path(&dst_dir, &subdir, RepoMode::BareUser);
std::fs::remove_file(&path).unwrap();
symlink(dst_dir.join("absent"), &path).unwrap();
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
match err {
Error::ObjectNotFound { checksum, ty } => {
assert_eq!(ObjectName::new(checksum, ty), subdir)
}
other => panic!("{other:?}"),
}
assert!(!dst.has_object(ObjectType::Commit, &c2).await.unwrap());
assert!(!has_partial_marker(&dst_dir, &c2));
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}
#[test]
fn a_hole_in_a_commit_held_complete_is_filled_after_fsck_marks_it() {
let tmp = TmpDir::new("pull-held-commit-hole");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
let (dst_dir, dst) = dst_copy_holding(base, "dst", RepoMode::BareUser, &src, &c2).await;
let nested = nested_content(&src, &c2).await;
std::fs::remove_file(object_path(&dst_dir, &nested, RepoMode::BareUser)).unwrap();
let opts = || PullOptions {
refs: vec!["main".to_owned()],
no_ref_writes: true,
..PullOptions::default()
};
let stats = dst.pull_local(&src, opts()).await.unwrap();
assert_eq!(stats.content_imported, 0);
assert!(!dst.has_object(nested.ty, &nested.checksum).await.unwrap());
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Partial);
let stats = dst.pull_local(&src, opts()).await.unwrap();
assert_eq!(stats.content_imported, 1);
assert!(dst.has_object(nested.ty, &nested.checksum).await.unwrap());
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &c2));
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
async fn chain_source(base: &Path, names: &[&str]) -> (PathBuf, Repo, Vec<Checksum>) {
let (path, repo) = make_repo(base, "src", RepoMode::Archive).await;
let mut commits: Vec<Checksum> = Vec::new();
for name in names {
build_tree(&base.join(name), format!("{name}\n").as_bytes());
let parent = commits.last().copied();
commits.push(commit_tree(&repo, base, name, "main", parent).await);
}
(path, repo, commits)
}
async fn chain_list(
src: &Repo,
steps: &[(Checksum, Checksum)],
) -> (Vec<AdvertisedDelta>, Vec<PathBuf>) {
let mut list = Vec::new();
let mut dirs = Vec::new();
for (from, to) in steps {
let (delta, dir) = listed_step(src, from, to, DeltaOptions::default()).await;
list.push(delta);
dirs.push(dir);
}
(list, dirs)
}
async fn listed_step(
src: &Repo,
from: &Checksum,
to: &Checksum,
opts: DeltaOptions,
) -> (AdvertisedDelta, PathBuf) {
let dir = delta_with(src, Some(from), to, opts).await;
let bytes = std::fs::read(dir.join("superblock")).unwrap();
let delta = AdvertisedDelta {
from: Some(*from),
to: *to,
superblock: Checksum::sha256(&bytes),
};
(delta, dir)
}
fn incompressible(len: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(len + 8);
let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
while out.len() < len {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
out.extend_from_slice(&state.to_le_bytes());
}
out.truncate(len);
out
}
fn part_files(dir: &Path) -> usize {
std::fs::read_dir(dir)
.unwrap()
.filter(|entry| {
entry
.as_ref()
.unwrap()
.file_name()
.to_str()
.is_some_and(|name| name.parse::<u32>().is_ok())
})
.count()
}
fn chain_pull(list: Vec<AdvertisedDelta>) -> PullOptions {
PullOptions {
refs: vec!["main".to_owned()],
static_deltas: Some(list),
..PullOptions::default()
}
}
fn signed_chain_pull(list: Vec<AdvertisedDelta>) -> PullOptions {
PullOptions {
remote: Some("origin".to_owned()),
verify: PullVerify {
sign: Some(true),
..PullVerify::default()
},
..chain_pull(list)
}
}
async fn signed_dst_holding(base: &Path, src: &Repo, commit: &Checksum) -> (PathBuf, Repo) {
let dst = dest_trusting(base, PUBLIC_B64).await;
hold_commit(&dst, src, commit).await;
(base.join("dst"), dst)
}
async fn sign_commits(repo: &Repo, commits: &[Checksum]) {
let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
for commit in commits {
repo.sign_commit(commit, &signer).await.unwrap();
}
}
fn assert_no_markers(dst_dir: &Path) {
let markers: Vec<String> = std::fs::read_dir(dst_dir.join("state"))
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.ends_with(".commitpartial"))
.collect();
assert!(markers.is_empty(), "{markers:?}");
let staging: Vec<String> = std::fs::read_dir(dst_dir.join("tmp"))
.unwrap()
.map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.starts_with("staging-"))
.collect();
assert!(staging.is_empty(), "{staging:?}");
}
#[test]
fn a_chain_of_two_steps_is_applied() {
let tmp = TmpDir::new("pull-chain-two-steps");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c"]).await;
let [a, b, c] = commits[..] else {
unreachable!()
};
let (list, dirs) = chain_list(&src, &[(a, b), (b, c)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let stats = dst.pull_local(&src, chain_pull(list)).await.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c));
for commit in [b, c] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.metadata_fetched, 2);
assert_eq!(
stats.delta_parts as usize,
dirs.iter().map(|dir| part_files(dir)).sum::<usize>()
);
assert_eq!(
stats.bytes_transferred,
dirs.iter().map(|dir| tree_size(dir)).sum::<u64>()
);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_missing_superblock_in_the_middle_of_a_local_chain() {
let tmp = TmpDir::new("pull-chain-missing-superblock");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
let (list, dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
std::fs::remove_file(dirs[1].join("superblock")).unwrap();
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let held = dst.list_objects().await.unwrap();
let required = PullOptions {
require_static_deltas: true,
..chain_pull(list.clone())
};
let err = dst.pull_local(&src, required).await.unwrap_err();
assert_eq!(
err.to_string(),
format!("pull: Static deltas required, but none found for main to {d}")
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
let stats = dst.pull_local(&src, chain_pull(list)).await.unwrap();
assert_eq!(stats.delta_parts, 0);
assert!(stats.content_fetched > 0, "{stats:?}");
assert_complete(&src, &dst, &dst_dir, &d).await;
assert_no_markers(&dst_dir);
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(d));
});
}
#[test]
fn a_wrong_listed_digest_fails_a_local_pull() {
let tmp = TmpDir::new("pull-chain-wrong-digest");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
let (mut list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
list[1].superblock = Checksum::from_bytes([0xee; 32]);
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let held = dst.list_objects().await.unwrap();
let err = dst.pull_local(&src, chain_pull(list)).await.unwrap_err();
assert!(matches!(err, Error::ChecksumMismatch { .. }), "{err:?}");
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
});
}
#[test]
fn an_unsigned_intermediate_commit_fails_a_local_pull() {
let tmp = TmpDir::new("pull-chain-unsigned-intermediate");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
sign_commits(&src, &[a, c, d]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let (dst_dir, dst) = signed_dst_holding(base, &src, &a).await;
let held = dst.list_objects().await.unwrap();
let err = dst
.pull_local(&src, signed_chain_pull(list.clone()))
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.starts_with(&format!("commit {b}: "))
&& !m.contains("static delta")),
"{err:?}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
let (off_dir, off) = dst_holding(base, "dst-off", &src, &a).await;
off.pull_local(&src, chain_pull(list.clone()))
.await
.unwrap();
assert_eq!(off.resolve_rev("main", false).await.unwrap(), Some(d));
for commit in [b, c, d] {
assert_complete(&src, &off, &off_dir, &commit).await;
}
assert_no_markers(&off_dir);
sign_commits(&src, &[b]).await;
dst.pull_local(&src, signed_chain_pull(list)).await.unwrap();
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(d));
for commit in [b, c, d] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
});
}
#[test]
fn depth_one_through_a_local_chain_under_verification() {
let tmp = TmpDir::new("pull-chain-depth-verify");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
sign_commits(&src, &[a, b, c, d]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let (dst_dir, dst) = signed_dst_holding(base, &src, &a).await;
let opts = PullOptions {
depth: 1,
..signed_chain_pull(list)
};
let stats = dst.pull_local(&src, opts).await.unwrap();
assert_eq!(stats.metadata_fetched, 6);
assert_eq!(stats.content_fetched, 0);
for commit in [b, c, d] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
let detached = dst.read_commit_detached_metadata(&c).await.unwrap();
assert!(detached.is_some());
assert_eq!(
detached,
src.read_commit_detached_metadata(&c).await.unwrap()
);
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(d));
});
}
#[test]
fn the_switch_applies_through_a_local_chain_under_verification() {
let tmp = TmpDir::new("pull-chain-keep-related");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c"]).await;
let [a, b, c] = commits[..] else {
unreachable!()
};
sign_commits(&src, &[a, b, c]).await;
for commit in [b, c] {
src.add_detached_related(&commit, "layer/base", &a)
.await
.unwrap();
}
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c)]).await;
let (dst_dir, _dst) = signed_dst_holding(base, &src, &a).await;
let dst = with_keep_related(&dst_dir, "false").await;
dst.pull_local(&src, signed_chain_pull(list)).await.unwrap();
for commit in [b, c] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
assert_eq!(
detached_keys(&src, &commit).await,
["ostree.sign.ed25519", "ostrya.related"]
);
assert_eq!(detached_keys(&dst, &commit).await, ["ostree.sign.ed25519"]);
assert_eq!(
detached_property(&dst, &commit, "ostree.sign.ed25519").await,
detached_property(&src, &commit, "ostree.sign.ed25519").await
);
}
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(c));
});
}
#[test]
fn a_local_target_that_is_an_intermediate_commit_of_another_target() {
let tmp = TmpDir::new("pull-chain-target-in-level");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
for name in ["a", "b", "c", "d"] {
build_tree(&base.join(name), format!("{name}\n").as_bytes());
}
let a = commit_tree(&src, base, "a", "main", None).await;
let b = commit_tree(&src, base, "b", "main", Some(a)).await;
let c = commit_tree(&src, base, "c", "mid", Some(b)).await;
let d = commit_tree(&src, base, "d", "main", Some(c)).await;
let txn = src.transaction().await.unwrap();
txn.set_ref("alias", Some(&c));
txn.commit().await.unwrap();
sign_commits(&src, &[a, b, c, d]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let (dst_dir, dst) = signed_dst_holding(base, &src, &a).await;
let held = dst.list_objects().await.unwrap();
let alias = PullOptions {
refs: vec!["main".to_owned(), "alias".to_owned()],
..signed_chain_pull(list.clone())
};
let err = dst.pull_local(&src, alias).await.unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("'alias'")),
"{err:?}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
let opts = PullOptions {
refs: vec!["main".to_owned(), "mid".to_owned()],
..signed_chain_pull(list)
};
dst.pull_local(&src, opts).await.unwrap();
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(d));
assert_eq!(dst.resolve_rev("origin:mid", true).await.unwrap(), Some(c));
for commit in [b, c, d] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
});
}
#[test]
fn a_local_intermediate_commit_bound_to_another_ref_passes() {
let tmp = TmpDir::new("pull-chain-intermediate-binding");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
for name in ["a", "b", "c", "d"] {
build_tree(&base.join(name), format!("{name}\n").as_bytes());
}
let a = commit_tree(&src, base, "a", "main", None).await;
let b = commit_tree(&src, base, "b", "main", Some(a)).await;
let c = commit_tree(&src, base, "c", "mid", Some(b)).await;
let d = commit_tree(&src, base, "d", "main", Some(c)).await;
sign_commits(&src, &[a, b, c, d]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let (dst_dir, dst) = signed_dst_holding(base, &src, &a).await;
dst.pull_local(&src, signed_chain_pull(list)).await.unwrap();
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(d));
assert_eq!(dst.resolve_rev("origin:mid", true).await.unwrap(), None);
for commit in [b, c, d] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
});
}
#[test]
fn a_local_chain_refuses_a_source_outside_archive_mode() {
let tmp = TmpDir::new("pull-chain-bare-source");
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 opts = PullOptions {
refs: vec!["absent".to_owned()],
..chain_pull(vec![listed_delta(Some(1), 2, 3)])
};
let err = dst.pull_local(&src, opts).await.unwrap_err();
assert!(matches!(err, Error::Unsupported(_)), "{err}");
assert!(err.to_string().contains("bare-user"), "{err}");
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn an_empty_local_list_imports_loose_and_counts_the_reads() {
let tmp = TmpDir::new("pull-chain-empty-list");
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;
let stats = dst.pull_local(&src, chain_pull(Vec::new())).await.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
assert_complete(&src, &dst, &dst_dir, &c2).await;
assert_eq!(stats.delta_parts, 0);
assert!(stats.content_fetched > 0, "{stats:?}");
assert_eq!(stats.content_fetched, stats.content_imported);
assert_eq!(stats.metadata_fetched, stats.metadata_imported);
assert!(stats.bytes_transferred > 0, "{stats:?}");
});
}
#[test]
fn an_empty_local_list_fails_under_require() {
let tmp = TmpDir::new("pull-chain-empty-list-required");
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;
let opts = PullOptions {
require_static_deltas: true,
..chain_pull(Vec::new())
};
let err = dst.pull_local(&src, opts).await.unwrap_err();
assert_eq!(
err.to_string(),
format!("pull: Static deltas required, but none found for main to {c2}")
);
assert_nothing_left(&dst_dir, &dst, &c2).await;
});
}
#[test]
fn a_commit_only_local_pull_ignores_the_list() {
let tmp = TmpDir::new("pull-chain-commit-only");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _c1, c2) = source_repo(base, RepoMode::Archive).await;
for require_static_deltas in [false, true] {
let name = format!("dst-{require_static_deltas}");
let (_dst_dir, dst) = make_repo(base, &name, RepoMode::BareUser).await;
let opts = PullOptions {
flags: PullFlags::COMMIT_ONLY,
require_static_deltas,
..chain_pull(vec![listed_delta(Some(1), 2, 3)])
};
let stats = dst.pull_local(&src, opts).await.unwrap();
assert_eq!(stats.delta_parts, 0, "{name}");
assert_eq!(
dst.commit_state(&c2).await.unwrap(),
CommitState::Partial,
"{name}"
);
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
}
});
}
#[test]
fn a_later_local_step_reads_a_fallback_of_an_earlier_step() {
let tmp = TmpDir::new("pull-chain-fallback-barrier");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let big = incompressible(300_000);
let mut edited = big.clone();
edited[150_000..150_016].copy_from_slice(&[0x5a; 16]);
build_tree(&base.join("a"), b"a\n");
build_tree(&base.join("b"), b"a\n");
std::fs::write(base.join("b/big"), &big).unwrap();
build_tree(&base.join("c"), b"a\n");
std::fs::write(base.join("c/big"), &edited).unwrap();
let a = commit_tree(&src, base, "a", "main", None).await;
let b = commit_tree(&src, base, "b", "main", Some(a)).await;
let c = commit_tree(&src, base, "c", "main", Some(b)).await;
let (ab, ab_dir) = listed_step(
&src,
&a,
&b,
DeltaOptions {
min_fallback_size: 100_000,
..DeltaOptions::default()
},
)
.await;
let (bc, bc_dir) = listed_step(
&src,
&b,
&c,
DeltaOptions {
min_fallback_size: 0,
..DeltaOptions::default()
},
)
.await;
let ab_superblock =
DeltaSuperblock::parse(std::fs::read(ab_dir.join("superblock")).unwrap()).unwrap();
assert_eq!(ab_superblock.fallbacks().len(), 1);
let bc_superblock =
DeltaSuperblock::parse(std::fs::read(bc_dir.join("superblock")).unwrap()).unwrap();
let mut reads = 0;
for index in 0..bc_superblock.parts().len() {
reads += bc_superblock
.part_stats(index, &bc_dir)
.await
.unwrap()
.ops
.set_read_source;
}
assert!(reads > 0, "the delta from B to C reads no source object");
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let stats = dst
.pull_local(&src, chain_pull(vec![ab, bc]))
.await
.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c));
for commit in [b, c] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
assert_eq!(stats.content_fetched, 1, "{stats:?}");
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_failure_inside_a_local_level_clears_the_markers() {
let tmp = TmpDir::new("pull-chain-fail-in-level");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
let (list, dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
assert!(part_files(&dirs[1]) > 0);
let part = dirs[1].join("0");
let mut bytes = std::fs::read(&part).unwrap();
let last = bytes.len() - 1;
bytes[last] ^= 0xff;
std::fs::write(&part, bytes).unwrap();
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let held = dst.list_objects().await.unwrap();
let err = dst.pull_local(&src, chain_pull(list)).await.unwrap_err();
assert!(matches!(err, Error::InvalidFormat(_)), "{err:?}");
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
});
}
#[test]
fn an_unsigned_local_target_fails_before_the_transaction() {
let tmp = TmpDir::new("pull-chain-unsigned-target");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
sign_commits(&src, &[a, b, c]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let (dst_dir, dst) = signed_dst_holding(base, &src, &a).await;
let held = dst.list_objects().await.unwrap();
let err = dst
.pull_local(&src, signed_chain_pull(list))
.await
.unwrap_err();
assert!(matches!(err, Error::Signature(_)), "{err:?}");
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
});
}
#[test]
fn a_local_target_refused_by_its_ref_binding_applies_no_part() {
let tmp = TmpDir::new("pull-chain-target-binding");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
let txn = src.transaction().await.unwrap();
txn.set_ref("alias", Some(&d));
txn.commit().await.unwrap();
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let held = dst.list_objects().await.unwrap();
let opts = PullOptions {
refs: vec!["alias".to_owned()],
..chain_pull(list)
};
let err = dst.pull_local(&src, opts).await.unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("'alias'")),
"{err:?}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
});
}
#[test]
fn a_local_target_refused_by_its_ref_binding_reports_before_the_walk() {
let tmp = TmpDir::new("pull-chain-target-binding-first");
block_on(async {
let base = tmp.path();
let (src_dir, src, commits) = chain_source(base, &["a", "b", "c", "d"]).await;
let [a, b, c, d] = commits[..] else {
unreachable!()
};
let txn = src.transaction().await.unwrap();
txn.set_ref("alias", Some(&d));
txn.commit().await.unwrap();
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (c, d)]).await;
let name = ostrya::ObjectName::new(d, ostrya::ObjectType::Commit);
std::fs::remove_file(object_path(&src_dir, &name, RepoMode::Archive)).unwrap();
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let held = dst.list_objects().await.unwrap();
let opts = PullOptions {
refs: vec!["alias".to_owned()],
..chain_pull(list)
};
let err = dst.pull_local(&src, opts).await.unwrap_err();
assert!(
matches!(&err, Error::Pull(m) if m.contains("'alias'")),
"{err:?}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_eq!(dst.list_objects().await.unwrap(), held);
assert_no_markers(&dst_dir);
});
}
#[test]
fn a_local_chain_pull_makes_no_timestamp_check() {
let tmp = TmpDir::new("pull-chain-no-timestamp");
block_on(async {
let base = tmp.path();
let (_src_dir, src, commits) = chain_source(base, &["a", "b", "c"]).await;
let [a, b, c] = commits[..] else {
unreachable!()
};
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
build_tree(&base.join("newer"), b"newer\n");
let newer = {
let txn = dst.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("newer"),
&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 + 100),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.commit().await.unwrap();
commit
};
let opts = PullOptions {
timestamp_check: TimestampCheck::Rev(newer),
..chain_pull(list)
};
let stats = dst.pull_local(&src, opts).await.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c));
assert!(stats.delta_parts > 0, "{stats:?}");
for commit in [b, c] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
});
}
#[test]
fn two_local_targets_share_a_step() {
let tmp = TmpDir::new("pull-chain-shared-step");
block_on(async {
let base = tmp.path();
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
for name in ["a", "b", "c", "d"] {
build_tree(&base.join(name), format!("{name}\n").as_bytes());
}
let a = commit_tree(&src, base, "a", "main", None).await;
let b = commit_tree(&src, base, "b", "main", Some(a)).await;
let c = commit_tree(&src, base, "c", "main", Some(b)).await;
let d = commit_tree(&src, base, "d", "other", Some(b)).await;
let (list, dirs) = chain_list(&src, &[(a, b), (b, c), (b, d)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let opts = PullOptions {
refs: vec!["main".to_owned(), "other".to_owned()],
..chain_pull(list)
};
let stats = dst.pull_local(&src, opts).await.unwrap();
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c));
assert_eq!(dst.resolve_rev("other", false).await.unwrap(), Some(d));
for commit in [b, c, d] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.metadata_fetched, 3);
assert_eq!(
stats.delta_parts as usize,
dirs.iter().map(|dir| part_files(dir)).sum::<usize>()
);
assert_eq!(
stats.bytes_transferred,
dirs.iter().map(|dir| tree_size(dir)).sum::<u64>()
);
});
}
#[test]
fn a_commit_only_local_pull_with_a_list_reads_a_bare_source() {
let tmp = TmpDir::new("pull-chain-commit-only-bare");
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 opts = PullOptions {
flags: PullFlags::COMMIT_ONLY,
..chain_pull(vec![listed_delta(Some(1), 2, 3)])
};
let stats = dst.pull_local(&src, opts).await.unwrap();
assert_eq!(stats.delta_parts, 0);
assert_eq!(dst.commit_state(&c2).await.unwrap(), CommitState::Partial);
assert_eq!(dst.resolve_rev("main", false).await.unwrap(), Some(c2));
});
}
async fn build_dependency_source(base: &Path) -> (PathBuf, Repo, Checksum, Checksum) {
build_tree(&base.join("uki"), b"uki\n");
build_tree(&base.join("main"), b"main\n");
let (path, src) = make_repo(base, "src", RepoMode::Archive).await;
let dep = commit_tree(&src, base, "uki", "dep/uki", None).await;
let tip = commit_tree_related(&src, base, "main", "main", None, &[("boot/uki", dep)]).await;
(path, src, tip, dep)
}
async fn move_ref(repo: &Repo, name: &str, commit: &Checksum) {
let txn = repo.transaction().await.unwrap();
txn.set_ref(name, Some(commit));
txn.commit().await.unwrap();
}
fn remove_commit_object(repo_dir: &Path, commit: &Checksum) {
let name = ObjectName::new(*commit, ObjectType::Commit);
std::fs::remove_file(object_path(repo_dir, &name, RepoMode::Archive)).unwrap();
}
fn spoil_commit_object(repo_dir: &Path, commit: &Checksum) {
remove_commit_object(repo_dir, commit);
let name = ObjectName::new(*commit, ObjectType::Commit);
std::fs::create_dir(object_path(repo_dir, &name, RepoMode::Archive)).unwrap();
}
async fn assert_left_nothing(dst: &Repo) {
assert!(dst.list_objects().await.unwrap().is_empty());
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_remote_refs().await.unwrap().is_empty());
assert_eq!(file_inventory(dst.path(), "state"), Vec::new());
}
fn signed_remote() -> String {
format!("gpg-verify=false\nsign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n")
}
fn assert_commit_not_found(err: &Error, commit: &Checksum) {
assert!(
matches!(
err,
Error::ObjectNotFound {
checksum,
ty: ObjectType::Commit,
} if checksum == commit
),
"{err:?}"
);
}
fn counted_pull() -> PullOptions {
chain_pull(Vec::new())
}
#[test]
fn a_local_pull_imports_the_dependency_of_the_commit() {
let tmp = TmpDir::new("pull-local-dependency");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let main = || PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
};
let stats = dst.pull_local(&src, main()).await.unwrap();
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &dep).await;
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
let mut expected = src.traverse_commit(&tip, 0).await.unwrap();
expected.extend(src.traverse_commit(&dep, 0).await.unwrap());
assert_eq!(dst.list_objects().await.unwrap(), expected);
let content = expected
.iter()
.filter(|name| name.ty == ObjectType::File)
.count();
assert_eq!(stats.content_imported as usize, content);
assert_eq!(stats.metadata_imported as usize, expected.len() - content);
assert_eq!(
dst.list_refs(None).await.unwrap(),
[("main".to_owned(), tip)]
);
let repeated = dst.pull_local(&src, main()).await.unwrap();
assert_eq!(
(repeated.metadata_imported, repeated.content_imported),
(0, 0)
);
});
}
#[test]
fn a_local_pull_follows_the_dependency_of_a_tip_held_complete() {
let tmp = TmpDir::new("pull-local-dependency-tip-held");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap();
remove_commit_object(&dst_dir, &dep);
assert!(!dst.has_object(ObjectType::Commit, &dep).await.unwrap());
assert_eq!(dst.commit_state(&tip).await.unwrap(), CommitState::Normal);
let stats = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!((stats.metadata_imported, stats.content_imported), (1, 0));
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &dep).await;
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_local_pull_with_depth_imports_the_dependencies_of_the_parents() {
let tmp = TmpDir::new("pull-local-dependency-parent");
block_on(async {
let base = tmp.path();
for sub in ["d1", "d2", "p", "t"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let d1 = commit_tree(&src, base, "d1", "dep/d1", None).await;
let d2 = commit_tree(&src, base, "d2", "dep/d2", None).await;
let parent = commit_tree_related(&src, base, "p", "main", None, &[("boot/d1", d1)]).await;
let tip =
commit_tree_related(&src, base, "t", "main", Some(parent), &[("boot/d2", d2)]).await;
for depth in [0, 1] {
let (dst_dir, dst) = make_repo(base, &format!("dst-{depth}"), RepoMode::Archive).await;
pull_main_with(
&dst,
&src,
PullOptions {
depth,
..PullOptions::default()
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &d2).await;
for commit in [parent, d1] {
assert_eq!(
dst.has_object(ObjectType::Commit, &commit).await.unwrap(),
depth == 1,
"depth {depth}: {commit}"
);
}
if depth == 1 {
assert_complete(&src, &dst, &dst_dir, &d1).await;
}
assert_eq!(
dst.list_refs(None).await.unwrap(),
[("main".to_owned(), tip)]
);
}
});
}
#[test]
fn a_dependency_that_two_local_commits_name_is_imported_once() {
let tmp = TmpDir::new("pull-local-dependency-once");
block_on(async {
let base = tmp.path();
for sub in ["uki", "p", "t"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let dep = commit_tree(&src, base, "uki", "dep/uki", None).await;
src.write_commit_detached_metadata(&dep, Some(&two_property_metadata()))
.await
.unwrap();
let parent = commit_tree_related(&src, base, "p", "main", None, &[("boot/uki", dep)]).await;
commit_tree_related(&src, base, "t", "main", Some(parent), &[("boot/uki", dep)]).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let stats = dst
.pull_local(
&src,
PullOptions {
depth: 1,
..counted_pull()
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &dep).await;
assert_eq!(stats.metadata_fetched, stats.metadata_imported + 1);
assert_eq!(
dst.read_commit_detached_metadata(&dep).await.unwrap(),
Some(two_property_metadata())
);
});
}
#[test]
fn a_local_dependency_is_imported_at_depth_zero() {
let tmp = TmpDir::new("pull-local-dependency-depth");
block_on(async {
let base = tmp.path();
for sub in ["old", "uki", "main"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let old = commit_tree(&src, base, "old", "dep/uki", None).await;
let dep = commit_tree(&src, base, "uki", "dep/uki", Some(old)).await;
let tip = commit_tree_related(&src, base, "main", "main", None, &[("boot/uki", dep)]).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
pull_main_with(
&dst,
&src,
PullOptions {
depth: -1,
..PullOptions::default()
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &dep).await;
assert!(!dst.has_object(ObjectType::Commit, &old).await.unwrap());
});
}
#[test]
fn a_local_pull_does_not_import_a_build_source() {
let tmp = TmpDir::new("pull-local-build-source");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, _dep) = build_dependency_source(base).await;
build_tree(&base.join("base"), b"base\n");
let source = commit_tree(&src, base, "base", "other/base", None).await;
src.add_detached_related(&tip, "layer/base", &source)
.await
.unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap();
assert_eq!(
dst.read_commit_related(&tip).await.unwrap().build_sources,
[("layer/base".to_owned(), source)]
);
assert!(!dst.has_object(ObjectType::Commit, &source).await.unwrap());
});
}
#[test]
fn a_commit_only_local_pull_imports_no_dependency() {
let tmp = TmpDir::new("pull-local-dependency-commit-only");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
pull_main(&dst, &src, PullFlags::COMMIT_ONLY).await;
assert!(dst.has_object(ObjectType::Commit, &tip).await.unwrap());
assert!(!dst.has_object(ObjectType::Commit, &dep).await.unwrap());
pull_main(&dst, &src, PullFlags::NONE).await;
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &dep).await;
});
}
#[test]
fn a_commit_only_local_pull_checks_the_format_of_field_2() {
let tmp = TmpDir::new("pull-local-dependency-commit-only-check");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
let short: &[u8] = &dep.as_bytes()[..31];
let defective = store_with_field2(&src, &tip, &[("boot/uki", short)]).await;
move_ref(&src, "main", &defective).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let commit_only = || PullOptions {
flags: PullFlags::COMMIT_ONLY,
..PullOptions::default()
};
let err = pull_main_with(&dst, &src, commit_only()).await.unwrap_err();
assert_eq!(
dependency_error(err),
(
Some(defective),
"entry 0 (boot/uki) has a checksum of 31 bytes, not 32".to_owned()
)
);
assert_left_nothing(&dst).await;
build_tree(&base.join("other"), b"other\n");
let other = commit_tree(&src, base, "other", "other", None).await;
let nested = store_with_field2(&src, &other, &[("lib/c", dep.as_bytes())]).await;
let absent = [7u8; 32];
let entries: [(&str, &[u8]); 2] = [("lib/b", nested.as_bytes()), ("lib/x", &absent)];
for entry in entries {
let head = store_with_field2(&src, &tip, &[entry]).await;
move_ref(&src, "main", &head).await;
pull_main_with(&dst, &src, commit_only()).await.unwrap();
assert!(dst.has_object(ObjectType::Commit, &head).await.unwrap());
}
});
}
#[test]
fn a_local_dependency_with_wrong_bytes_fails_an_untrusted_pull() {
let tmp = TmpDir::new("pull-local-dependency-wrong-bytes");
block_on(async {
let base = tmp.path();
let (src_dir, src, tip, dep) = build_dependency_source(base).await;
sign_commits(&src, &[tip]).await;
build_tree(&base.join("other"), b"other\n");
let donor = commit_tree(&src, base, "other", "other/x", None).await;
let donor_bytes = std::fs::read(object_path(
&src_dir,
&ObjectName::new(donor, ObjectType::Commit),
RepoMode::Archive,
))
.unwrap();
std::fs::write(
object_path(
&src_dir,
&ObjectName::new(dep, ObjectType::Commit),
RepoMode::Archive,
),
donor_bytes,
)
.unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = pull_main_with(
&dst,
&src,
PullOptions {
flags: PullFlags::UNTRUSTED,
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ChecksumMismatch { expected, .. } if expected == dep),
"{err}"
);
assert_left_nothing(&dst).await;
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
let dst = dest_with_remote(base, &signed_remote()).await;
let err = dst
.pull_local(
&src,
PullOptions {
flags: PullFlags::UNTRUSTED,
..origin_pull(PullVerify::default())
},
)
.await
.unwrap_err();
assert!(
matches!(err, Error::ChecksumMismatch { expected, .. } if expected == dep),
"verified: {err}"
);
assert_left_nothing(&dst).await;
});
}
#[test]
fn a_local_dependency_with_no_trusted_signature_passes_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-signature");
block_on(async {
let base = tmp.path();
let (src_dir, src, tip, dep) = build_dependency_source(base).await;
sign_commits(&src, &[tip]).await;
let meta = |dir: &Path| {
dir.join("objects")
.join(ObjectName::new(dep, ObjectType::Commit).loose_path(RepoMode::Archive))
.with_extension("commitmeta")
};
let dst = dest_with_remote(base, &signed_remote()).await;
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_complete(&src, &dst, &base.join("dst"), &dep).await;
assert!(!meta(&base.join("dst")).exists());
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
src.sign_commit(&dep, &Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap())
.await
.unwrap();
let dst = dest_with_remote(base, &signed_remote()).await;
pull_main_with(&dst, &src, origin_pull(PullVerify::default()))
.await
.unwrap();
assert_complete(&src, &dst, &base.join("dst"), &dep).await;
assert_eq!(
std::fs::read(meta(&base.join("dst"))).unwrap(),
std::fs::read(meta(&src_dir)).unwrap()
);
});
}
#[test]
fn a_local_dependency_held_complete_keeps_its_detached_metadata() {
let tmp = TmpDir::new("pull-local-dependency-held-meta");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _tip, dep) = build_dependency_source(base).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap();
assert_eq!(dst.commit_state(&dep).await.unwrap(), CommitState::Normal);
assert_eq!(dst.read_commit_detached_metadata(&dep).await.unwrap(), None);
src.write_commit_detached_metadata(&dep, Some(&two_property_metadata()))
.await
.unwrap();
pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap();
assert_eq!(dst.read_commit_detached_metadata(&dep).await.unwrap(), None);
dst.pull_local(
&src,
PullOptions {
refs: vec!["dep/uki".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(
dst.read_commit_detached_metadata(&dep).await.unwrap(),
Some(two_property_metadata())
);
});
}
#[test]
fn a_local_dependency_that_is_also_a_target_is_checked() {
let tmp = TmpDir::new("pull-local-dependency-target-signature");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
sign_commits(&src, &[tip]).await;
let dst = dest_with_remote(base, &signed_remote()).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned(), "dep/uki".to_owned()],
..origin_pull(PullVerify::default())
},
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains(&format!("commit {dep}"))),
"{err}"
);
assert_left_nothing(&dst).await;
});
}
#[test]
fn a_local_dependency_that_is_also_a_parent_is_checked() {
let tmp = TmpDir::new("pull-local-dependency-parent-signature");
block_on(async {
let base = tmp.path();
for sub in ["p", "t"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let parent = commit_tree(&src, base, "p", "main", None).await;
let tip =
commit_tree_related(&src, base, "t", "main", Some(parent), &[("boot/p", parent)]).await;
sign_commits(&src, &[tip]).await;
for depth in [0, 1] {
let dst = dest_with_remote(base, &signed_remote()).await;
let pulled = pull_main_with(
&dst,
&src,
PullOptions {
depth,
..origin_pull(PullVerify::default())
},
)
.await;
if depth == 0 {
pulled.unwrap();
assert_complete(&src, &dst, &base.join("dst"), &parent).await;
} else {
let err = pulled.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains(&format!("commit {parent}"))),
"depth {depth}: {err}"
);
assert_left_nothing(&dst).await;
}
drop(dst);
std::fs::remove_dir_all(base.join("dst")).unwrap();
}
});
}
#[test]
fn a_missing_local_dependency_fails_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-missing");
block_on(async {
let base = tmp.path();
let (src_dir, src, _tip, dep) = build_dependency_source(base).await;
remove_commit_object(&src_dir, &dep);
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap_err();
assert_commit_not_found(&err, &dep);
assert_left_nothing(&dst).await;
});
}
#[test]
fn a_defective_local_dependency_entry_fails_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-defective");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let short: &[u8] = &dep.as_bytes()[..31];
for (entry, reason) in [
(
("boot/uki", short),
"entry 0 (boot/uki) has a checksum of 31 bytes, not 32",
),
(("", dep.as_bytes()), "entry 0 has an empty name"),
] {
let defective = store_with_field2(&src, &tip, &[entry]).await;
move_ref(&src, "main", &defective).await;
let err = pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap_err();
assert_eq!(dependency_error(err), (Some(defective), reason.to_owned()));
assert_left_nothing(&dst).await;
}
});
}
#[test]
fn a_nested_local_dependency_fails_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-nested");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
build_tree(&base.join("other"), b"other\n");
let other = commit_tree(&src, base, "other", "other", None).await;
let nested = store_with_field2(&src, &other, &[("lib/c", dep.as_bytes())]).await;
let head = store_with_field2(&src, &tip, &[("lib/b", nested.as_bytes())]).await;
move_ref(&src, "other", &nested).await;
move_ref(&src, "main", &head).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let reason =
format!("dependency lib/b names commit {nested}, which has dependencies of its own");
for refs in [&["main"][..], &["main", "other"]] {
let err = dst
.pull_local(
&src,
PullOptions {
refs: refs.iter().map(|r| (*r).to_owned()).collect(),
..PullOptions::default()
},
)
.await
.unwrap_err();
assert_eq!(
dependency_error(err),
(Some(head), reason.clone()),
"{refs:?}"
);
assert_left_nothing(&dst).await;
}
});
}
#[test]
fn the_first_failing_local_dependency_gives_the_error() {
let tmp = TmpDir::new("pull-local-dependency-first-failure");
block_on(async {
let base = tmp.path();
for sub in ["p", "t", "x", "n", "d"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let parent = commit_tree(&src, base, "p", "main", None).await;
let plain = commit_tree(&src, base, "t", "main", Some(parent)).await;
let absent = commit_tree(&src, base, "x", "dep/x", None).await;
remove_commit_object(&src_dir, &absent);
let inner = commit_tree(&src, base, "d", "dep/d", None).await;
let nested = commit_tree_related(&src, base, "n", "dep/n", None, &[("lib/d", inner)]).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let opts = || PullOptions {
depth: 1,
..PullOptions::default()
};
for (first, second) in [(absent, nested), (nested, absent)] {
let tip = store_with_field2(
&src,
&plain,
&[
("a/p", parent.as_bytes()),
("b/x", first.as_bytes()),
("c/y", second.as_bytes()),
],
)
.await;
move_ref(&src, "main", &tip).await;
let err = pull_main_with(&dst, &src, opts()).await.unwrap_err();
if first == absent {
assert_commit_not_found(&err, &absent);
} else {
let reason = format!(
"dependency b/x names commit {nested}, which has dependencies of its own"
);
assert_eq!(dependency_error(err), (Some(tip), reason));
}
assert_left_nothing(&dst).await;
}
});
}
#[test]
fn a_held_nested_dependency_before_a_missing_one_gives_the_nested_error() {
let tmp = TmpDir::new("pull-local-dependency-held-nested");
block_on(async {
let base = tmp.path();
for sub in ["t", "o", "x", "d"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let plain = commit_tree(&src, base, "t", "main", None).await;
let inner = commit_tree(&src, base, "d", "dep/d", None).await;
let other = commit_tree_related(&src, base, "o", "other", None, &[("lib/d", inner)]).await;
let absent = commit_tree(&src, base, "x", "dep/x", None).await;
remove_commit_object(&src_dir, &absent);
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
for (first, second) in [(other, absent), (absent, other)] {
let tip = store_with_field2(
&src,
&plain,
&[("a/x", first.as_bytes()), ("b/y", second.as_bytes())],
)
.await;
move_ref(&src, "main", &tip).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned(), "other".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
if first == other {
let reason = format!(
"dependency a/x names commit {other}, which has dependencies of its own"
);
assert_eq!(dependency_error(err), (Some(tip), reason));
} else {
assert_commit_not_found(&err, &absent);
}
assert_left_nothing(&dst).await;
}
});
}
#[test]
fn an_absent_local_parent_that_is_a_dependency_fails_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-absent-parent");
block_on(async {
let base = tmp.path();
for sub in ["p", "t"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let parent = commit_tree(&src, base, "p", "main", None).await;
let plain = commit_tree(&src, base, "t", "main", Some(parent)).await;
let tip = store_with_field2(&src, &plain, &[("boot/p", parent.as_bytes())]).await;
move_ref(&src, "main", &tip).await;
remove_commit_object(&src_dir, &parent);
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let opts = || PullOptions {
depth: 1,
..PullOptions::default()
};
let err = pull_main_with(&dst, &src, opts()).await.unwrap_err();
assert_commit_not_found(&err, &parent);
assert_left_nothing(&dst).await;
move_ref(&src, "main", &plain).await;
pull_main_with(&dst, &src, opts()).await.unwrap();
assert!(!dst.has_object(ObjectType::Commit, &parent).await.unwrap());
});
}
#[test]
fn a_local_dependency_held_partial_is_completed() {
let tmp = TmpDir::new("pull-local-dependency-partial");
block_on(async {
let base = tmp.path();
let (_src_dir, src, _tip, dep) = build_dependency_source(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(
&src,
PullOptions {
refs: vec!["dep/uki".to_owned()],
flags: PullFlags::COMMIT_ONLY,
..PullOptions::default()
},
)
.await
.unwrap();
assert_eq!(dst.commit_state(&dep).await.unwrap(), CommitState::Partial);
pull_main(&dst, &src, PullFlags::NONE).await;
assert_complete(&src, &dst, &dst_dir, &dep).await;
});
}
#[test]
fn a_local_parent_that_is_a_dependency_is_imported_once() {
let tmp = TmpDir::new("pull-local-dependency-parent-once");
block_on(async {
let base = tmp.path();
for sub in ["g", "p", "t"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let grand = commit_tree(&src, base, "g", "main", None).await;
let parent = commit_tree(&src, base, "p", "main", Some(grand)).await;
src.write_commit_detached_metadata(&parent, Some(&two_property_metadata()))
.await
.unwrap();
commit_tree_related(&src, base, "t", "main", Some(parent), &[("boot/p", parent)]).await;
for depth in [0, 1] {
let (dst_dir, dst) = make_repo(base, &format!("dst-{depth}"), RepoMode::Archive).await;
let stats = dst
.pull_local(
&src,
PullOptions {
depth,
..counted_pull()
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &parent).await;
assert!(!dst.has_object(ObjectType::Commit, &grand).await.unwrap());
assert_eq!(
stats.metadata_fetched,
stats.metadata_imported + 1,
"depth {depth}"
);
}
});
}
#[test]
fn a_failure_in_the_import_of_a_dependency_clears_its_marker() {
let tmp = TmpDir::new("pull-local-dependency-import-fails");
block_on(async {
let base = tmp.path();
let (src_dir, src, tip, dep) = build_dependency_source(base).await;
let own = src.traverse_commit(&tip, 0).await.unwrap();
let only_dep: Vec<ObjectName> = src
.traverse_commit(&dep, 0)
.await
.unwrap()
.into_iter()
.filter(|name| name.ty == ObjectType::File && !own.contains(name))
.collect();
assert!(!only_dep.is_empty());
std::fs::remove_file(object_path(&src_dir, &only_dep[0], RepoMode::Archive)).unwrap();
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap_err();
assert!(matches!(err, Error::ObjectNotFound { .. }), "{err:?}");
assert_left_nothing(&dst).await;
});
}
#[test]
fn a_dependency_comes_from_a_localcache_or_the_destination() {
let tmp = TmpDir::new("pull-local-dependency-localcache");
block_on(async {
let base = tmp.path();
let (src_dir, src, tip, dep) = build_dependency_source(base).await;
let (_cache_dir, cache) = make_repo(base, "cache", RepoMode::Archive).await;
hold_commit(&cache, &src, &dep).await;
let (held_dir, held) = make_repo(base, "held", RepoMode::Archive).await;
hold_commit(&held, &src, &dep).await;
remove_commit_object(&src_dir, &dep);
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
pull_main_with(
&dst,
&src,
PullOptions {
localcache_repos: vec![cache],
..PullOptions::default()
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_eq!(dst.commit_state(&dep).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &dep));
pull_main_with(&held, &src, PullOptions::default())
.await
.unwrap();
assert_complete(&src, &held, &held_dir, &tip).await;
assert_eq!(held.commit_state(&dep).await.unwrap(), CommitState::Normal);
assert!(held.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_local_pull_reads_each_dependency_from_the_repository_that_holds_it() {
let tmp = TmpDir::new("pull-local-dependency-holders");
block_on(async {
let base = tmp.path();
for sub in ["s", "c", "d", "main"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let in_src = commit_tree(&src, base, "s", "dep/s", None).await;
let in_cache = commit_tree(&src, base, "c", "dep/c", None).await;
let in_dst = commit_tree(&src, base, "d", "dep/d", None).await;
let tip = commit_tree_related(
&src,
base,
"main",
"main",
None,
&[("a/s", in_src), ("b/c", in_cache), ("c/d", in_dst)],
)
.await;
let (_cache_dir, cache) = make_repo(base, "cache", RepoMode::Archive).await;
hold_commit(&cache, &src, &in_cache).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
hold_commit(&dst, &src, &in_dst).await;
remove_commit_object(&src_dir, &in_cache);
remove_commit_object(&src_dir, &in_dst);
pull_main_with(
&dst,
&src,
PullOptions {
localcache_repos: vec![cache],
..PullOptions::default()
},
)
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &in_src).await;
for dep in [in_cache, in_dst] {
assert_eq!(dst.commit_state(&dep).await.unwrap(), CommitState::Normal);
assert!(!has_partial_marker(&dst_dir, &dep));
}
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
assert_eq!(
dst.list_refs(None).await.unwrap(),
[("main".to_owned(), tip)]
);
});
}
#[test]
fn a_local_pull_reads_a_dependency_from_its_first_holder() {
let tmp = TmpDir::new("pull-local-dependency-holder-order");
block_on(async {
let base = tmp.path();
for sub in ["t", "d", "c", "e"] {
build_tree(&base.join(sub), sub.as_bytes());
}
let (src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let plain = commit_tree(&src, base, "t", "main", None).await;
let in_dst = commit_tree(&src, base, "d", "dep/d", None).await;
let in_cache = commit_tree(&src, base, "c", "dep/c", None).await;
let past_cache = commit_tree(&src, base, "e", "dep/e", None).await;
let (cache_dir, cache) = make_repo(base, "cache", RepoMode::Archive).await;
hold_commit(&cache, &src, &in_cache).await;
hold_commit(&cache, &src, &past_cache).await;
spoil_commit_object(&cache_dir, &past_cache);
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
hold_commit(&dst, &src, &in_dst).await;
hold_commit(&dst, &src, &past_cache).await;
remove_commit_object(&src_dir, &in_dst);
remove_commit_object(&src_dir, &past_cache);
spoil_commit_object(&src_dir, &in_cache);
for second in [in_cache, past_cache] {
let tip = store_with_field2(
&src,
&plain,
&[("a/d", in_dst.as_bytes()), ("b/x", second.as_bytes())],
)
.await;
move_ref(&src, "main", &tip).await;
let err = pull_main_with(
&dst,
&src,
PullOptions {
localcache_repos: vec![cache.clone()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Io(e) if e.kind() == std::io::ErrorKind::InvalidData)
&& err.to_string().contains("not a regular file"),
"{second}: {err:?}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
}
});
}
#[test]
fn the_switch_drops_the_related_key_of_a_dependency() {
let tmp = TmpDir::new("pull-local-dependency-switch");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
src.write_commit_detached_metadata(&dep, Some(&two_property_metadata()))
.await
.unwrap();
src.add_detached_related(&dep, "layer/base", &tip)
.await
.unwrap();
assert_eq!(
detached_keys(&src, &dep).await,
["ostree.gpgsigs", "build.gc-roots", "ostrya.related"]
);
let (dst_dir, _dst) = make_repo(base, "dst", RepoMode::Archive).await;
let dst = with_keep_related(&dst_dir, "false").await;
pull_main_with(&dst, &src, PullOptions::default())
.await
.unwrap();
assert_eq!(
dst.read_commit_detached_metadata(&dep).await.unwrap(),
Some(two_property_metadata())
);
});
}
#[test]
fn a_collection_pull_imports_a_dependency() {
let tmp = TmpDir::new("pull-local-dependency-collection");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
set_collection_ref(&src, COLLECTION, "main", &tip).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, collection_pull(&["main"]))
.await
.unwrap();
assert_complete(&src, &dst, &dst_dir, &tip).await;
assert_complete(&src, &dst, &dst_dir, &dep).await;
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_remote_refs().await.unwrap().is_empty());
});
}
#[test]
fn a_dependency_of_an_intermediate_commit_is_imported() {
let tmp = TmpDir::new("pull-local-dependency-chain");
block_on(async {
let base = tmp.path();
for sub in ["a", "b", "c", "uki"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let a = commit_tree(&src, base, "a", "main", None).await;
let dep = commit_tree(&src, base, "uki", "dep/uki", None).await;
let b = commit_tree_related(&src, base, "b", "main", Some(a), &[("boot/uki", dep)]).await;
let c = commit_tree(&src, base, "c", "main", Some(b)).await;
let naming = store_with_field2(&src, &c, &[("lib/b", b.as_bytes())]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c), (b, naming)]).await;
move_ref(&src, "main", &c).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
dst.pull_local(&src, chain_pull(list.clone()))
.await
.unwrap();
for commit in [b, c, dep] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
move_ref(&src, "main", &naming).await;
let (nested_dir, nested) = dst_holding(base, "nested", &src, &a).await;
let held = nested.list_objects().await.unwrap();
let err = nested.pull_local(&src, chain_pull(list)).await.unwrap_err();
assert_eq!(
dependency_error(err),
(
Some(naming),
format!("dependency lib/b names commit {b}, which has dependencies of its own")
)
);
assert_eq!(nested.list_objects().await.unwrap(), held);
assert!(nested.list_refs(None).await.unwrap().is_empty());
assert_no_markers(&nested_dir);
});
}
#[test]
fn an_intermediate_commit_that_is_a_dependency_comes_from_its_delta() {
let tmp = TmpDir::new("pull-local-dependency-chain-level");
block_on(async {
let base = tmp.path();
for sub in ["a", "b", "c"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let a = commit_tree(&src, base, "a", "main", None).await;
let b = commit_tree(&src, base, "b", "main", Some(a)).await;
let c = commit_tree_related(&src, base, "c", "main", Some(b), &[("lib/b", b)]).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
remove_commit_object(&src_dir, &b);
dst.pull_local(&src, chain_pull(list)).await.unwrap();
for commit in [b, c] {
assert_eq!(
dst.commit_state(&commit).await.unwrap(),
CommitState::Normal
);
}
assert_no_markers(&dst_dir);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
});
}
#[test]
fn a_defective_entry_of_an_intermediate_commit_fails_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-chain-defective");
block_on(async {
let base = tmp.path();
for sub in ["a", "b", "c"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let a = commit_tree(&src, base, "a", "main", None).await;
let plain = commit_tree(&src, base, "b", "main", Some(a)).await;
let short: &[u8] = &a.as_bytes()[..31];
let b = store_with_field2(&src, &plain, &[("boot/a", short)]).await;
let c = commit_tree(&src, base, "c", "main", Some(b)).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let held = dst.list_objects().await.unwrap();
let err = dst.pull_local(&src, chain_pull(list)).await.unwrap_err();
assert_eq!(
dependency_error(err),
(
Some(b),
"entry 0 (boot/a) has a checksum of 31 bytes, not 32".to_owned()
)
);
assert_eq!(dst.list_objects().await.unwrap(), held);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert_no_markers(&dst_dir);
});
}
#[test]
fn a_required_delta_pull_refuses_a_dependency_with_no_delta() {
let tmp = TmpDir::new("pull-local-dependency-required");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
delta_with(&src, None, &tip, DeltaOptions::default()).await;
src.reindex_static_deltas().await.unwrap();
summarize(&src).await;
let (_dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let err = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap_err();
match err {
Error::Pull(message) => assert_eq!(
message,
format!("Static deltas required, but none found for boot/uki of main to {dep}")
),
other => panic!("{other:?}"),
}
assert_left_nothing(&dst).await;
});
}
#[test]
fn a_dependency_of_an_intermediate_commit_that_the_depth_reaches_is_imported_once() {
let tmp = TmpDir::new("pull-local-dependency-chain-depth");
block_on(async {
let base = tmp.path();
for sub in ["a", "b", "c", "uki"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let a = commit_tree(&src, base, "a", "main", None).await;
let dep = commit_tree(&src, base, "uki", "dep/uki", None).await;
let b = commit_tree_related(&src, base, "b", "main", Some(a), &[("boot/uki", dep)]).await;
let c = commit_tree(&src, base, "c", "main", Some(b)).await;
let (list, _dirs) = chain_list(&src, &[(a, b), (b, c)]).await;
let (dst_dir, dst) = dst_holding(base, "dst", &src, &a).await;
let before = dst.list_objects().await.unwrap();
let stats = dst
.pull_local(
&src,
PullOptions {
depth: 1,
..chain_pull(list)
},
)
.await
.unwrap();
for commit in [b, c, dep] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
let after = dst.list_objects().await.unwrap();
let mut expected = before.clone();
for commit in [b, c, dep] {
expected.extend(src.traverse_commit(&commit, 0).await.unwrap());
}
assert_eq!(after, expected);
assert_eq!(
(stats.metadata_imported + stats.content_imported) as usize,
after.len() - before.len()
);
});
}
async fn build_dependency_generations(base: &Path) -> (Repo, [Checksum; 4]) {
for sub in ["uki1", "uki2", "main1", "main2"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (_path, src) = make_repo(base, "src", RepoMode::Archive).await;
let d1 = commit_tree(&src, base, "uki1", "dep/uki", None).await;
let d2 = commit_tree(&src, base, "uki2", "dep/uki", Some(d1)).await;
let t1 = commit_tree_related(&src, base, "main1", "main", None, &[("boot/uki", d1)]).await;
let t2 = commit_tree_related(&src, base, "main2", "main", Some(t1), &[("boot/uki", d2)]).await;
move_ref(&src, "main", &t1).await;
(src, [t1, d1, t2, d2])
}
async fn publish_deltas(src: &Repo, steps: &[(Option<Checksum>, Checksum)]) -> Vec<PathBuf> {
let mut dirs = Vec::new();
for (from, to) in steps {
dirs.push(delta_with(src, from.as_ref(), to, DeltaOptions::default()).await);
}
src.reindex_static_deltas().await.unwrap();
summarize(src).await;
dirs
}
fn spoil_superblock(dir: &Path) {
std::fs::write(dir.join("superblock"), b"not a superblock").unwrap();
}
fn pull_refs(refs: &[&str]) -> PullOptions {
PullOptions {
refs: refs.iter().map(|name| (*name).to_owned()).collect(),
..PullOptions::default()
}
}
fn required_refs(refs: &[&str]) -> PullOptions {
PullOptions {
require_static_deltas: true,
..pull_refs(refs)
}
}
#[test]
fn a_local_dependency_delta_from_its_paired_entry_is_taken() {
let tmp = TmpDir::new("pull-local-dependency-delta-paired");
block_on(async {
let base = tmp.path();
let (src, [t1, d1, t2, d2]) = build_dependency_generations(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, pull_refs(&["main"])).await.unwrap();
move_ref(&src, "main", &t2).await;
let dirs = publish_deltas(&src, &[(Some(t1), t2), (Some(d1), d2), (None, d2)]).await;
spoil_superblock(&dirs[2]);
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.delta_parts, 2);
for commit in [t2, d2] {
assert_complete(&src, &dst, &dst_dir, &commit).await;
}
assert_no_markers(&dst_dir);
assert!(dst.fsck(&FsckOptions::default()).await.unwrap().is_ok());
assert_eq!(
dst.list_refs(None).await.unwrap(),
[("main".to_owned(), t2)]
);
});
}
#[test]
fn a_local_dependency_delta_from_another_held_commit_is_taken() {
let tmp = TmpDir::new("pull-local-dependency-delta-held");
block_on(async {
let base = tmp.path();
let (src, [_, d1, t2, d2]) = build_dependency_generations(base).await;
move_ref(&src, "main", &t2).await;
let dirs = publish_deltas(&src, &[(None, t2), (Some(d1), d2), (None, d2)]).await;
spoil_superblock(&dirs[2]);
let (dst_dir, dst) = dst_holding(base, "dst", &src, &d1).await;
let stats = dst
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
assert_complete(&src, &dst, &dst_dir, &d2).await;
assert_no_markers(&dst_dir);
});
}
#[test]
fn the_from_scratch_delta_of_a_local_dependency_needs_no_paired_entry_held() {
let tmp = TmpDir::new("pull-local-dependency-delta-scratch");
block_on(async {
let base = tmp.path();
let (src, [t1, _, t2, d2]) = build_dependency_generations(base).await;
let (paired_dir, paired) = make_repo(base, "paired", RepoMode::Archive).await;
paired.pull_local(&src, pull_refs(&["main"])).await.unwrap();
move_ref(&src, "main", &t2).await;
publish_deltas(&src, &[(None, t2), (Some(t1), t2), (None, d2)]).await;
let own = src.traverse_commit(&t2, 0).await.unwrap();
let only_dep = src
.traverse_commit(&d2, 0)
.await
.unwrap()
.into_iter()
.filter(|name| name.ty == ObjectType::File && !own.contains(name))
.count();
assert!(only_dep > 0);
let (fresh_dir, fresh) = make_repo(base, "fresh", RepoMode::Archive).await;
let stats = fresh
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.delta_parts, 2);
assert_complete(&src, &fresh, &fresh_dir, &d2).await;
let stats = paired
.pull_local(&src, required(PullFlags::empty()))
.await
.unwrap();
assert_eq!(stats.delta_parts, 1);
assert_eq!(stats.content_fetched as usize, only_dep);
assert_complete(&src, &paired, &paired_dir, &d2).await;
assert_no_markers(&paired_dir);
});
}
#[test]
fn the_first_local_target_gives_the_from_of_a_dependency() {
let tmp = TmpDir::new("pull-local-dependency-delta-targets");
block_on(async {
let base = tmp.path();
for sub in ["da", "db", "d", "a1", "b1", "a2", "b2"] {
build_tree(&base.join(sub), format!("{sub}\n").as_bytes());
}
let (_src_dir, src) = make_repo(base, "src", RepoMode::Archive).await;
let da = commit_tree(&src, base, "da", "dep/a", None).await;
let db = commit_tree(&src, base, "db", "dep/b", None).await;
let d = commit_tree(&src, base, "d", "dep/d", None).await;
let a1 = commit_tree_related(&src, base, "a1", "left", None, &[("boot/uki", da)]).await;
let b1 = commit_tree_related(&src, base, "b1", "right", None, &[("boot/uki", db)]).await;
let mut dsts = Vec::new();
for name in ["one", "two", "three"] {
let (dir, dst) = make_repo(base, name, RepoMode::Archive).await;
dst.pull_local(&src, pull_refs(&["left", "right"]))
.await
.unwrap();
dsts.push((dir, dst));
}
let a2 = commit_tree_related(&src, base, "a2", "left", Some(a1), &[("boot/uki", d)]).await;
let b2 = commit_tree_related(&src, base, "b2", "right", Some(b1), &[("boot/uki", d)]).await;
let dirs = publish_deltas(&src, &[(Some(a1), a2), (Some(b1), b2), (Some(db), d)]).await;
let stats = dsts[0]
.1
.pull_local(&src, required_refs(&["left", "right"]))
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.delta_parts, 3);
publish_deltas(&src, &[(Some(da), d)]).await;
spoil_superblock(&dirs[2]);
let stats = dsts[1]
.1
.pull_local(&src, required_refs(&["left", "right"]))
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
let err = dsts[2]
.1
.pull_local(&src, required_refs(&["right", "left"]))
.await
.unwrap_err();
assert!(matches!(err, Error::ChecksumMismatch { .. }), "{err:?}");
for (dir, dst) in &dsts[..2] {
for commit in [a2, b2, d] {
assert_complete(&src, dst, dir, &commit).await;
}
}
});
}
#[test]
fn a_local_pull_by_checksum_takes_the_from_scratch_delta_of_a_dependency() {
let tmp = TmpDir::new("pull-local-dependency-delta-checksum");
block_on(async {
let base = tmp.path();
let (src, [_, _, t2, d2]) = build_dependency_generations(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, pull_refs(&["main"])).await.unwrap();
move_ref(&src, "main", &t2).await;
publish_deltas(&src, &[(None, t2), (None, d2)]).await;
let stats = dst
.pull_local(
&src,
PullOptions {
flags: PullFlags::DISABLE_VERIFY_BINDINGS,
..required_refs(&[&t2.to_hex()])
},
)
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.delta_parts, 2);
assert_complete(&src, &dst, &dst_dir, &d2).await;
});
}
#[test]
fn a_local_pull_with_disabled_deltas_reads_no_dependency_delta() {
let tmp = TmpDir::new("pull-local-dependency-delta-disabled");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
publish_deltas(&src, &[(None, tip), (None, dep)]).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
let stats = dst
.pull_local(
&src,
PullOptions {
disable_static_deltas: true,
..required(PullFlags::empty())
},
)
.await
.unwrap();
assert_eq!(stats.delta_parts, 0);
assert_complete(&src, &dst, &dst_dir, &dep).await;
});
}
#[test]
fn a_local_list_pull_takes_the_listed_delta_of_a_dependency() {
let tmp = TmpDir::new("pull-local-dependency-delta-list");
block_on(async {
let base = tmp.path();
let (src, [t1, d1, t2, d2]) = build_dependency_generations(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, pull_refs(&["main"])).await.unwrap();
let (refused_dir, refused) = make_repo(base, "refused", RepoMode::Archive).await;
refused
.pull_local(&src, pull_refs(&["main"]))
.await
.unwrap();
move_ref(&src, "main", &t2).await;
let (list, _dirs) = chain_list(&src, &[(t1, t2), (d1, d2)]).await;
let stats = dst
.pull_local(&src, chain_pull(list.clone()))
.await
.unwrap();
assert_eq!(stats.content_fetched, 0);
assert_eq!(stats.delta_parts, 2);
assert_complete(&src, &dst, &dst_dir, &d2).await;
assert_no_markers(&dst_dir);
let held = refused.list_objects().await.unwrap();
let err = refused
.pull_local(
&src,
PullOptions {
require_static_deltas: true,
..chain_pull(list[..1].to_vec())
},
)
.await
.unwrap_err();
match err {
Error::Pull(message) => assert_eq!(
message,
format!("Static deltas required, but none found for boot/uki of main to {d2}")
),
other => panic!("{other:?}"),
}
assert_eq!(refused.list_objects().await.unwrap(), held);
assert_eq!(
refused.list_refs(None).await.unwrap(),
[("main".to_owned(), t1)]
);
assert_no_markers(&refused_dir);
});
}
#[test]
fn a_local_list_pull_imports_a_dependency_with_no_listed_delta_loose() {
let tmp = TmpDir::new("pull-local-dependency-delta-list-loose");
block_on(async {
let base = tmp.path();
let (src, [t1, _, t2, d2]) = build_dependency_generations(base).await;
let (dst_dir, dst) = make_repo(base, "dst", RepoMode::Archive).await;
dst.pull_local(&src, pull_refs(&["main"])).await.unwrap();
move_ref(&src, "main", &t2).await;
let (list, _dirs) = chain_list(&src, &[(t1, t2)]).await;
let stats = dst.pull_local(&src, chain_pull(list)).await.unwrap();
assert_eq!(stats.delta_parts, 1);
assert!(stats.content_fetched > 0, "{stats:?}");
assert_complete(&src, &dst, &dst_dir, &t2).await;
assert_complete(&src, &dst, &dst_dir, &d2).await;
assert_no_markers(&dst_dir);
assert_eq!(
dst.list_refs(None).await.unwrap(),
[("main".to_owned(), t2)]
);
});
}
const SUPERBLOCK_SIG: &str = "(a{sv}tayay(a{sv}aya(say)sstayay)aya(uayttay)a(yaytt))";
#[test]
fn a_local_dependency_delta_that_gives_another_commit_fails_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-delta-other-commit");
block_on(async {
let base = tmp.path();
let (src_dir, src, tip, dep) = build_dependency_source(base).await;
sign_commits(&src, &[tip]).await;
build_tree(&base.join("other"), b"other\n");
let donor = commit_tree(&src, base, "other", "other/x", None).await;
let dir = delta_with(&src, None, &dep, DeltaOptions::default()).await;
let donor_dir = delta_with(&src, None, &donor, DeltaOptions::default()).await;
let ty = Type::parse(SUPERBLOCK_SIG).unwrap();
let Value::Tuple(mut fields) =
ostrya::from_bytes(&ty, &std::fs::read(dir.join("superblock")).unwrap()).unwrap()
else {
panic!("a superblock is a tuple");
};
fields[4] = ostrya::from_bytes(
&Type::parse("(a{sv}aya(say)sstayay)").unwrap(),
&std::fs::read(object_path(
&src_dir,
&ObjectName::new(donor, ObjectType::Commit),
RepoMode::Archive,
))
.unwrap(),
)
.unwrap();
let embedded = ostrya_core::to_bytes(&ty, &Value::Tuple(fields)).unwrap();
let other = std::fs::read(donor_dir.join("superblock")).unwrap();
for (case, bytes) in [("embedded", embedded), ("other", other)] {
std::fs::write(dir.join("superblock"), &bytes).unwrap();
let list = vec![AdvertisedDelta {
from: None,
to: dep,
superblock: Checksum::sha256(&bytes),
}];
for (tag, extra) in [("unverified", None), ("verified", Some(signed_remote()))] {
let case_base = base.join(format!("{case}-{tag}"));
std::fs::create_dir(&case_base).unwrap();
let (dst, opts) = match &extra {
None => (
make_repo(&case_base, "dst", RepoMode::Archive).await.1,
chain_pull(list.clone()),
),
Some(extra) => (
dest_with_remote(&case_base, extra).await,
PullOptions {
static_deltas: Some(list.clone()),
..origin_pull(PullVerify::default())
},
),
};
let err = dst.pull_local(&src, opts).await.unwrap_err();
match (case, &err) {
("embedded", Error::InvalidFormat(m)) => {
assert!(m.contains("embedded commit"), "{case} {tag}: {err}");
}
("other", Error::Pull(m)) => {
assert!(m.contains(&donor.to_hex()), "{case} {tag}: {err}");
}
_ => panic!("{case} {tag}: {err:?}"),
}
assert_left_nothing(&dst).await;
}
}
});
}
#[test]
fn a_local_dependency_delta_signed_by_an_untrusted_key_passes_the_pull() {
let tmp = TmpDir::new("pull-local-dependency-delta-untrusted");
block_on(async {
let base = tmp.path();
let (_src_dir, src, tip, dep) = build_dependency_source(base).await;
sign_commits(&src, &[tip]).await;
let dir = delta_with(&src, None, &dep, DeltaOptions::default()).await;
src.sign_static_delta(&dir, &Ed25519Signer::from_base64(OTHER_SECRET_B64).unwrap())
.await
.unwrap();
delta_with(&src, None, &tip, DeltaOptions::default()).await;
src.reindex_static_deltas().await.unwrap();
summarize(&src).await;
let dependency = base.join("dependency");
std::fs::create_dir(&dependency).unwrap();
let dst = dest_with_remote(&dependency, &signed_remote()).await;
let stats = dst
.pull_local(
&src,
PullOptions {
require_static_deltas: true,
..origin_pull(PullVerify::default())
},
)
.await
.unwrap();
assert_eq!(stats.delta_parts, 2);
assert_complete(&src, &dst, &dependency.join("dst"), &dep).await;
assert_no_markers(&dependency.join("dst"));
let target = base.join("target");
std::fs::create_dir(&target).unwrap();
let dst = dest_with_remote(&target, &signed_remote()).await;
let err = dst
.pull_local(
&src,
PullOptions {
refs: vec!["main".to_owned(), "dep/uki".to_owned()],
require_static_deltas: true,
..origin_pull(PullVerify::default())
},
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("static delta")),
"{err}"
);
assert_left_nothing(&dst).await;
});
}