#![cfg(feature = "sign-gpg")]
mod common;
#[path = "common/pull.rs"]
mod pull;
use std::os::fd::AsFd;
use std::path::{Path, PathBuf};
use std::process::Command;
use common::TmpDir;
use ostrya::{
AdvertisedDelta, Checksum, CommitModifier, CommitModifierFlags, CommitOptions, CommitState,
CreateOptions, DeltaOptions, Error, GpgSigner, MutableTree, OpenOptions, PullOptions,
PullVerify, Ref, RemotesDir, Repo, RepoMode,
};
use ostrya_rt::block_on;
const FIXED_TS: u64 = 1_700_000_000;
fn gpg_available() -> bool {
common::gnupg_available(&["gpg"])
}
struct GpgHome {
dir: PathBuf,
}
impl GpgHome {
fn create(base: &Path, name: &str, uid: &str) -> GpgHome {
use std::os::unix::fs::DirBuilderExt;
let dir = base.join(name);
std::fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
let home = GpgHome { dir };
let status = home
.gpg()
.args(["--pinentry-mode", "loopback", "--passphrase", ""])
.args(["--quick-gen-key", uid, "ed25519", "sign", "never"])
.status()
.unwrap();
assert!(status.success(), "gpg --quick-gen-key failed");
home
}
fn gpg(&self) -> Command {
let mut cmd = Command::new("gpg");
cmd.arg("--homedir").arg(&self.dir).arg("--batch");
cmd
}
fn fingerprint(&self) -> String {
let out = self
.gpg()
.args(["--with-colons", "--list-keys"])
.output()
.unwrap();
assert!(out.status.success());
let text = String::from_utf8(out.stdout).unwrap();
text.lines()
.find_map(|line| {
let mut fields = line.split(':');
(fields.next() == Some("fpr")).then(|| fields.nth(8).unwrap().to_owned())
})
.expect("a fpr record in the key listing")
}
fn export_to(&self, path: &Path) {
let out = self.gpg().arg("--export").output().unwrap();
assert!(out.status.success() && !out.stdout.is_empty());
std::fs::write(path, out.stdout).unwrap();
}
fn signer(&self) -> GpgSigner {
GpgSigner::new(self.fingerprint()).with_homedir(&self.dir)
}
}
impl Drop for GpgHome {
fn drop(&mut self) {
common::remove_gnupg_sockets(&self.dir);
}
}
async fn source_repo(base: &Path) -> (Repo, Checksum) {
let tree = base.join("tree");
std::fs::create_dir_all(&tree).unwrap();
std::fs::write(tree.join("hello.txt"), b"hello\n").unwrap();
let repo = Repo::create(&base.join("src"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
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("tree"),
&mut mtree,
Some(&mut modifier),
)
.await
.unwrap();
let root = txn.write_mtree(&mut mtree).await.unwrap();
let commit = txn
.write_commit(
CommitOptions {
subject: Some("main".to_owned()),
timestamp: Some(FIXED_TS),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
txn.commit().await.unwrap();
(repo, commit)
}
async fn dest_with_remote(base: &Path, name: &str, extra: &str) -> (PathBuf, Repo) {
let path = base.join(name);
let repo = Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
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();
let repo = Repo::open(&path).await.unwrap();
(path, repo)
}
async fn gpg_pull(dst: &Repo, src: &Repo) -> Result<(), Error> {
dst.pull_local(
src,
PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
verify: PullVerify {
gpg: Some(true),
..PullVerify::default()
},
..PullOptions::default()
},
)
.await
.map(|_| ())
}
async fn commit_marker(repo: &Repo, base: &Path, name: &str, parent: Option<Checksum>) -> Checksum {
let tree = base.join(name);
std::fs::create_dir_all(&tree).unwrap();
std::fs::write(tree.join("marker.txt"), format!("{name}\n")).unwrap();
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(name),
&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(name.to_owned()),
timestamp: Some(FIXED_TS),
..CommitOptions::default()
},
&root,
)
.await
.unwrap();
txn.set_ref(&Ref::local("main"), Some(&commit));
txn.commit().await.unwrap();
commit
}
async fn chain_source(base: &Path) -> (Repo, Checksum, Checksum, Vec<AdvertisedDelta>) {
let repo = Repo::create(&base.join("src"), CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let b = commit_marker(&repo, base, "b", None).await;
let c = commit_marker(&repo, base, "c", Some(b)).await;
let mut list = Vec::new();
for (from, to) in [(None, b), (Some(b), c)] {
let dir = repo
.generate_static_delta(from.as_ref(), &to, &DeltaOptions::default())
.await
.unwrap();
let bytes = std::fs::read(repo.path().join(dir).join("superblock")).unwrap();
list.push(AdvertisedDelta {
from,
to,
superblock: Checksum::sha256(&bytes),
});
}
(repo, b, c, list)
}
async fn gpg_chain_pull(
dst: &Repo,
src: &Repo,
list: Vec<AdvertisedDelta>,
gpg: bool,
) -> Result<(), Error> {
dst.pull_local(
src,
PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
static_deltas: Some(list),
verify: PullVerify {
gpg: Some(gpg),
..PullVerify::default()
},
..PullOptions::default()
},
)
.await
.map(|_| ())
}
fn assert_no_markers(dir: &Path) {
let markers: Vec<String> = std::fs::read_dir(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(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:?}");
}
async fn assert_complete(src: &Repo, dst: &Repo, commit: &Checksum) {
assert_eq!(dst.commit_state(commit).await.unwrap(), CommitState::Normal);
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 an_unsigned_intermediate_commit_fails_gpg_verification() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-chain");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
block_on(async {
let (src, b, c, list) = chain_source(base).await;
let signer = signer_home.signer();
src.sign_commit(&c, &signer).await.unwrap();
let (path, dst) = dest_with_remote(base, "dst-gpg", "").await;
signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
let err = gpg_chain_pull(&dst, &src, list.clone(), true)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.starts_with(&format!("commit {b}: GPG "))),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_objects().await.unwrap().is_empty());
assert_no_markers(&path);
let (off_path, off) = dest_with_remote(base, "dst-off", "").await;
gpg_chain_pull(&off, &src, list.clone(), false)
.await
.unwrap();
assert_eq!(off.resolve_rev("origin:main", true).await.unwrap(), Some(c));
for commit in [b, c] {
assert_complete(&src, &off, &commit).await;
}
assert_no_markers(&off_path);
src.sign_commit(&b, &signer).await.unwrap();
gpg_chain_pull(&dst, &src, list, true).await.unwrap();
assert_eq!(dst.resolve_rev("origin:main", true).await.unwrap(), Some(c));
for commit in [b, c] {
assert_complete(&src, &dst, &commit).await;
}
assert_no_markers(&path);
});
}
#[test]
fn the_repository_keyring_is_what_a_remote_trusts() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-keyring");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
let other_home = GpgHome::create(base, "gnupg-other", "Other <other@example.invalid>");
block_on(async {
let (src, commit) = source_repo(base).await;
let (path, dst) = dest_with_remote(base, "dst-unsigned", "").await;
signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("carries no signature")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let (path, dst) = dest_with_remote(base, "dst-trusted", "").await;
signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
gpg_pull(&dst, &src).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit)
);
let (path, dst) = dest_with_remote(base, "dst-other", "").await;
other_home.export_to(&path.join("origin.trustedkeys.gpg"));
let err = gpg_pull(&dst, &src).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());
});
}
#[test]
fn a_gpg_trust_group_reads_no_repository_keyring() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-trust");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
let other_home = GpgHome::create(base, "gnupg-other", "Other <other@example.invalid>");
let signer_keyring = base.join("signer.gpg");
let other_keyring = base.join("other.gpg");
signer_home.export_to(&signer_keyring);
other_home.export_to(&other_keyring);
let trust = |keyring: &Path, extra: &str| {
format!(
"gpg-verify=false\ntrust=t\n{extra}[ex-ostrya trust \"t\"]\ngpg-verify=true\n\
gpgkeypath={}\n",
keyring.display()
)
};
let opts = PullOptions {
refs: vec!["main".to_owned()],
remote: Some("origin".to_owned()),
..PullOptions::default()
};
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let (path, dst) = dest_with_remote(base, "dst-keyring", &trust(&other_keyring, "")).await;
signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
let err = dst.pull_local(&src, opts.clone()).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());
let (_path, dst) = dest_with_remote(base, "dst-group", &trust(&signer_keyring, "")).await;
dst.pull_local(&src, opts.clone()).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit)
);
src.regenerate_summary(&ostrya::SummaryOptions {
last_modified: Some(FIXED_TS),
..ostrya::SummaryOptions::default()
})
.await
.unwrap();
src.sign_summary(&other_home.signer()).await.unwrap();
let (path, dst) = dest_with_remote(
base,
"dst-summary",
&trust(&signer_keyring, "gpg-verify-summary=true\n"),
)
.await;
signer_home.export_to(&path.join("origin.trustedkeys.gpg"));
let err = dst.pull_local(&src, opts.clone()).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());
other_home.export_to(&path.join("origin.trustedkeys.gpg"));
dst.pull_local(&src, opts.clone()).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit)
);
});
}
#[test]
fn a_symlinked_repository_keyring_is_followed() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-symlink");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let keyring = base.join("elsewhere.gpg");
signer_home.export_to(&keyring);
let (path, dst) = dest_with_remote(base, "dst-symlink", "").await;
std::os::unix::fs::symlink(&keyring, path.join("origin.trustedkeys.gpg")).unwrap();
gpg_pull(&dst, &src).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit)
);
});
}
async fn open_with_dir(path: &Path, dir: RemotesDir) -> Repo {
OpenOptions::new()
.remotes_dir(dir)
.open(path)
.await
.unwrap()
}
#[test]
fn a_keyring_of_the_remotes_directory_is_what_a_remote_trusts() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-dir-keyring");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let mut handles = Vec::new();
let (path, dst) = dest_with_remote(base, "dst-config", "").await;
drop(dst);
let dir = base.join("remotes-config.d");
std::fs::create_dir(&dir).unwrap();
signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
handles.push(("config", open_with_dir(&path, RemotesDir::path(&dir)).await));
let path = base.join("dst-file");
Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let dir = base.join("remotes-file.d");
std::fs::create_dir(&dir).unwrap();
std::fs::write(
dir.join("origin.conf"),
"[remote \"origin\"]\nurl=file:///dev/null\n",
)
.unwrap();
signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
handles.push(("file", open_with_dir(&path, RemotesDir::path(&dir)).await));
let (path, dst) = dest_with_remote(base, "dst-in-repo", "").await;
drop(dst);
std::fs::create_dir(path.join("remotes.d")).unwrap();
signer_home.export_to(&path.join("remotes.d").join("origin.trustedkeys.gpg"));
let in_repo = RemotesDir::InRepo(PathBuf::from("remotes.d"));
handles.push(("in-repo", open_with_dir(&path, in_repo).await));
let (path, dst) = dest_with_remote(base, "dst-fd", "").await;
drop(dst);
let dir = base.join("remotes-fd.d");
std::fs::create_dir(&dir).unwrap();
signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
let fd = std::os::fd::OwnedFd::from(std::fs::File::open(&dir).unwrap());
handles.push(("fd", open_with_dir(&path, RemotesDir::from(fd)).await));
for (label, dst) in handles {
gpg_pull(&dst, &src)
.await
.unwrap_or_else(|e| panic!("{label}: {e}"));
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit),
"{label}"
);
}
});
}
#[test]
fn the_repository_keyring_hides_the_keyring_of_the_remotes_directory() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-dir-hidden");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
let other_home = GpgHome::create(base, "gnupg-other", "Other <other@example.invalid>");
let dir = base.join("remotes.d");
std::fs::create_dir(&dir).unwrap();
signer_home.export_to(&dir.join("origin.trustedkeys.gpg"));
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
for (name, other) in [("dst-other", true), ("dst-empty", false)] {
let (path, dst) = dest_with_remote(base, name, "").await;
drop(dst);
let keyring = path.join("origin.trustedkeys.gpg");
if other {
other_home.export_to(&keyring);
} else {
std::fs::write(&keyring, b"").unwrap();
}
let dst = open_with_dir(&path, RemotesDir::path(&dir)).await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("is from a trusted key")),
"{name}: {err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty(), "{name}");
}
});
}
const NO_DIR_CHILD_ENV: &str = "OSTRYA_NO_REMOTES_DIR_TEST";
#[test]
fn a_handle_with_no_remotes_directory_reads_no_keyring_of_a_directory() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-no-dir");
let global = tmp.path().join("global");
std::fs::create_dir(&global).unwrap();
let child = Command::new(std::env::current_exe().unwrap())
.args([
"no_remotes_directory_subprocess",
"--exact",
"--ignored",
"--nocapture",
])
.env("OSTREE_GPG_HOME", &global)
.env(NO_DIR_CHILD_ENV, tmp.path())
.output()
.expect("re-execute this test binary");
let stdout = String::from_utf8_lossy(&child.stdout);
assert!(
child.status.success() && stdout.contains("1 passed"),
"the child reported {}:\n{stdout}{}",
child.status,
String::from_utf8_lossy(&child.stderr),
);
}
#[test]
#[ignore = "helper process for a_handle_with_no_remotes_directory_reads_no_keyring_of_a_directory"]
fn no_remotes_directory_subprocess() {
let Some(base) = std::env::var_os(NO_DIR_CHILD_ENV).map(PathBuf::from) else {
return;
};
let signer_home = GpgHome::create(&base, "gnupg", "Ostrya Pull <pull@example.invalid>");
block_on(async {
let (src, commit) = source_repo(&base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let (path, dst) = dest_with_remote(&base, "dst", "").await;
std::fs::create_dir(path.join("remotes.d")).unwrap();
signer_home.export_to(&path.join("remotes.d").join("origin.trustedkeys.gpg"));
assert!(dst.remotes_dir().is_none());
let err = gpg_pull(&dst, &src).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());
});
}
#[test]
fn gpgkeypath_adds_keyrings_and_a_missing_entry_fails() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-keypath");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let keyring = base.join("trusted.gpg");
signer_home.export_to(&keyring);
let keydir = base.join("keydir");
std::fs::create_dir(&keydir).unwrap();
signer_home.export_to(&keydir.join("pull.gpg"));
std::fs::write(keydir.join("notes.txt"), b"not a keyring\n").unwrap();
let backslash = base.join(r"k\sspace.gpg");
signer_home.export_to(&backslash);
for (name, entry) in [
("dst-file", keyring.display().to_string()),
("dst-dir", keydir.display().to_string()),
("dst-backslash", backslash.display().to_string()),
("dst-trailing", format!("{};", keyring.display())),
] {
let (_path, dst) = dest_with_remote(base, name, &format!("gpgkeypath={entry}\n")).await;
gpg_pull(&dst, &src).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit),
"gpgkeypath={entry}"
);
}
let (_path, dst) = dest_with_remote(
base,
"dst-missing",
&format!(
"gpgkeypath={}/absent;{}\n",
base.display(),
keyring.display()
),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("cannot be read")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
let (_path, dst) = dest_with_remote(
base,
"dst-empty-entry",
&format!("gpgkeypath=;{}\n", keyring.display()),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m.starts_with("gpgkeypath entry '' cannot be read: ")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}
#[test]
fn a_gpgkeypath_directory_reads_each_regular_file() {
use std::os::unix::fs::PermissionsExt;
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-keypath-files");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
let text = b"This directory holds the trusted keys of the remote.\n";
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let keyring_alone = base.join("keyring-alone");
std::fs::create_dir(&keyring_alone).unwrap();
signer_home.export_to(&keyring_alone.join("a.keyring"));
let junk_first = base.join("junk-first");
std::fs::create_dir(&junk_first).unwrap();
std::fs::write(junk_first.join("junk.gpg"), text).unwrap();
signer_home.export_to(&junk_first.join("b.keyring"));
let junk_file = base.join("junk.txt");
std::fs::write(&junk_file, text).unwrap();
let keyring = base.join("trusted.gpg");
signer_home.export_to(&keyring);
for (name, keypath) in [
("dst-keyring-alone", keyring_alone.display().to_string()),
("dst-junk-first", junk_first.display().to_string()),
(
"dst-junk-file",
format!("{};{}", junk_file.display(), keyring.display()),
),
] {
let (_path, dst) =
dest_with_remote(base, name, &format!("gpgkeypath={keypath}\n")).await;
gpg_pull(&dst, &src).await.unwrap();
assert_eq!(
dst.resolve_rev("origin:main", true).await.unwrap(),
Some(commit),
"gpgkeypath={keypath}"
);
}
let text_alone = base.join("text-alone");
std::fs::create_dir(&text_alone).unwrap();
std::fs::write(text_alone.join("README"), text).unwrap();
let (_path, dst) = dest_with_remote(
base,
"dst-text-alone",
&format!("gpgkeypath={}\n", text_alone.display()),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m.contains("no GPG signature is from a trusted key")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
let unreadable = base.join("unreadable");
std::fs::create_dir(&unreadable).unwrap();
signer_home.export_to(&unreadable.join("a.gpg"));
let locked = unreadable.join("z.gpg");
signer_home.export_to(&locked);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::File::open(&locked).is_ok() {
eprintln!("skipping the unreadable arm: the file opens with mode 000");
return;
}
let (_path, dst) = dest_with_remote(
base,
"dst-unreadable",
&format!("gpgkeypath={}\n", unreadable.display()),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("z.gpg")
&& m.contains("cannot be opened")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}
#[test]
fn a_revocation_in_armor_of_a_gpgkeypath_file_refuses_the_commit() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-keypath-revocation");
let base = tmp.path();
let signer_home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
block_on(async {
let (src, commit) = source_repo(base).await;
src.sign_commit(&commit, &signer_home.signer())
.await
.unwrap();
let keyring = base.join("a.gpg");
signer_home.export_to(&keyring);
let stored = signer_home
.dir
.join("openpgp-revocs.d")
.join(format!("{}.rev", signer_home.fingerprint()));
let certificate = std::fs::read_to_string(stored)
.unwrap()
.replace(":-----BEGIN", "-----BEGIN");
let revocation = base.join("revocation.asc");
std::fs::write(&revocation, certificate).unwrap();
let status = signer_home
.gpg()
.arg("--import")
.arg(&revocation)
.status()
.unwrap();
assert!(status.success(), "gpg --import of the revocation failed");
let out = signer_home
.gpg()
.args(["--armor", "--export"])
.output()
.unwrap();
assert!(out.status.success() && !out.stdout.is_empty());
let revoked = out.stdout;
for (name, text) in [("plain", &b""[..]), ("after-text", &b"Trusted keys\n"[..])] {
let keys = base.join(format!("keys-{name}"));
std::fs::create_dir(&keys).unwrap();
std::fs::copy(&keyring, keys.join("a.gpg")).unwrap();
let armored = keys.join("b.asc");
std::fs::write(&armored, [text, &revoked].concat()).unwrap();
let (_path, dst) = dest_with_remote(
base,
&format!("dst-{name}"),
&format!("gpgkeypath={}\n", keys.display()),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
let message = match &err {
Error::Signature(m) => m.clone(),
other => panic!("{name}: {other}"),
};
if text.is_empty() {
assert!(
message.contains("no GPG signature is from a trusted key"),
"{name}: {message}"
);
} else {
let named = format!("the keyring '{}'", armored.display());
assert!(
message.contains(&named) && message.contains("armor"),
"{name}: {message}"
);
}
assert!(dst.list_refs(None).await.unwrap().is_empty(), "{name}");
}
});
}
#[test]
fn a_fifo_gpgkeypath_entry_is_refused_by_name() {
let tmp = TmpDir::new("pull-verify-gpg-keypath-fifo");
let base = tmp.path();
block_on(async {
let (src, _commit) = source_repo(base).await;
let entry = base.join("fifo.gpg");
rustix::fs::mknodat(
rustix::fs::CWD,
&entry,
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o600),
0,
)
.unwrap();
let (_path, dst) = dest_with_remote(
base,
"dst-fifo",
&format!("gpgkeypath={}\n", entry.display()),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("fifo.gpg")
&& m.contains("regular file")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}
#[test]
fn an_oversized_gpgkeypath_entry_is_refused_by_name() {
const MAX_KEYRING: u64 = 4 * 1024 * 1024;
let tmp = TmpDir::new("pull-verify-gpg-keypath-size");
let base = tmp.path();
block_on(async {
let (src, _commit) = source_repo(base).await;
let entry = base.join("huge.gpg");
std::fs::File::create(&entry)
.unwrap()
.set_len(MAX_KEYRING + 1)
.unwrap();
let (_path, dst) = dest_with_remote(
base,
"dst-huge",
&format!("gpgkeypath={}\n", entry.display()),
)
.await;
let err = gpg_pull(&dst, &src).await.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("huge.gpg")
&& m.contains("ceiling")),
"{err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
});
}
#[test]
fn gpg_verify_summary_refuses_a_403_or_410_for_summary_sig() {
if !gpg_available() {
return;
}
let tmp = TmpDir::new("pull-verify-gpg-absent-sig");
let base = tmp.path();
let home = GpgHome::create(base, "gnupg", "Ostrya Pull <pull@example.invalid>");
let keyring = base.join("signer.gpg");
home.export_to(&keyring);
block_on(async {
let (src, _) = source_repo(base).await;
src.regenerate_summary(&ostrya::SummaryOptions {
last_modified: Some(FIXED_TS),
..ostrya::SummaryOptions::default()
})
.await
.unwrap();
src.sign_summary(&home.signer()).await.unwrap();
assert!(base.join("src/summary.sig").exists());
let server = pull::RepoServer::start(&base.join("src"), false).await;
for status in [403u16, 410] {
server.answer_status("summary.sig", status);
let path = base.join(format!("dst-{status}"));
drop(
Repo::create(&path, CreateOptions::new(RepoMode::Archive))
.await
.unwrap(),
);
let config = path.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!(
"\n[remote \"origin\"]\nurl={}\ngpg-verify=false\ngpg-verify-summary=true\n\
gpgkeypath={}\n",
server.url(),
keyring.display()
));
std::fs::write(&config, text).unwrap();
let dst = Repo::open(&path).await.unwrap();
let err = dst
.pull(
"origin",
PullOptions {
refs: vec!["main".to_owned()],
..PullOptions::default()
},
)
.await
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m)
if m == "summary verification is enabled, but no summary.sig is published"),
"{status}: {err}"
);
assert!(dst.list_refs(None).await.unwrap().is_empty());
assert!(dst.list_remote_refs().await.unwrap().is_empty());
}
});
}