use std::os::fd::OwnedFd;
use std::path::{Path, PathBuf};
use ostrya_sign::{MAX_KEYRING, gpg_keyring_keys, gpg_merge_keyring, gpg_offered_keys};
use crate::config::{remote_keyring_name, valid_remote_name};
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::sign::{read_key_path, read_key_source};
use crate::summary::{read_root_file_blocking, write_root_file_blocking};
#[cfg(feature = "sign-gpg")]
pub use ostrya_sign::GpgSigner;
pub use ostrya_sign::{GpgKey, GpgVerifier};
const GLOBAL_TRUSTED_GPG_D: &str = "/usr/share/ostree/trusted.gpg.d";
const OSTREE_GPG_HOME_ENV: &str = "OSTREE_GPG_HOME";
const SYSTEM_REMOTES_D: &str = "/etc/ostree/remotes.d";
pub trait FromOstreeKeyrings: Sized {
fn for_remote(repo_path: &Path, remote: &str) -> Result<Self>;
fn for_remote_keypath(repo_path: &Path, remote: &str, keypath: &[String]) -> Result<Self> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let keyring = repo_path.join(format!("{remote}.trustedkeys.gpg"));
let repo_keyring = read_keyring_path(&keyring)?;
Self::for_remote_keyrings(repo_keyring, remote, keypath)
}
fn for_remote_keyrings(
repo_keyring: Option<Vec<u8>>,
remote: &str,
keypath: &[String],
) -> Result<Self>;
fn from_system_trust() -> Result<Self>;
}
impl FromOstreeKeyrings for GpgVerifier {
fn for_remote(repo_path: &Path, remote: &str) -> Result<GpgVerifier> {
GpgVerifier::for_remote_keypath(repo_path, remote, &[])
}
fn for_remote_keyrings(
repo_keyring: Option<Vec<u8>>,
remote: &str,
keypath: &[String],
) -> Result<GpgVerifier> {
remote_keyrings(repo_keyring, remote, keypath, true)
}
fn from_system_trust() -> Result<GpgVerifier> {
let mut verifier = GpgVerifier::default();
verifier.add_binary_keyring_files(keyring_files_in(&global_trusted_dir())?)?;
Ok(verifier)
}
}
pub(crate) fn remote_keyrings(
repo_keyring: Option<Vec<u8>>,
remote: &str,
keypath: &[String],
global: bool,
) -> Result<GpgVerifier> {
let global_dir = global.then(global_trusted_dir);
remote_keyrings_in(
repo_keyring,
remote,
keypath,
Path::new(SYSTEM_REMOTES_D),
global_dir.as_deref(),
)
}
fn remote_keyrings_in(
repo_keyring: Option<Vec<u8>>,
remote: &str,
keypath: &[String],
remotes_d: &Path,
global_dir: Option<&Path>,
) -> Result<GpgVerifier> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let mut verifier = GpgVerifier::default();
let mut own_keyring = repo_keyring.is_some();
if let Some(bytes) = repo_keyring {
verifier.add_binary_keyring(&bytes, &format!("the keyring '{remote}.trustedkeys.gpg'"))?;
}
let system_path = remotes_d.join(remote_keyring_name(remote));
let system_subject = format!("the keyring '{}'", system_path.display());
if let Some(bytes) = read_key_path(&system_path, &system_subject, MAX_KEYRING)? {
own_keyring = true;
verifier.add_binary_keyring(&bytes, &system_subject)?;
}
let global = match global_dir {
Some(dir) if !own_keyring => keyring_files_in(dir)?,
_ => Vec::new(),
};
let keypath = keypath_files("gpgkeypath", keypath)?;
verifier.add_binary_keyring_files(global)?;
verifier.add_keyring_files_skipping(keypath)?;
Ok(verifier)
}
pub(crate) fn from_keypath(key: &str, keypath: &[String]) -> Result<GpgVerifier> {
let mut verifier = GpgVerifier::default();
verifier.add_keyring_files_skipping(keypath_files(key, keypath)?)?;
if verifier.is_empty() {
return Err(Error::Signature(format!(
"{key} names no key: the keyrings it names hold no certificate"
)));
}
Ok(verifier)
}
impl Repo {
pub async fn gpg_import_keys(
&self,
remote: &str,
keys: &[u8],
key_ids: &[String],
) -> Result<usize> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let name = remote_keyring_name(remote);
let fsync = self.config().fsync()?;
let subject = format!("the keyring '{name}'");
let offered = if keys.len() as u64 > MAX_KEYRING {
gpg_offered_keys(keys, key_ids, &subject)
} else {
let offered = keys.to_vec();
let ids = key_ids.to_vec();
let read_subject = subject.clone();
ostrya_rt::unblock(move || gpg_offered_keys(&offered, &ids, &read_subject)).await
};
self.write_locked(move |repo| {
let existing = read_root_file_blocking(repo.repo_fd(), &name)?.unwrap_or_default();
let (imported, keyring) = gpg_merge_keyring(&existing, offered, &subject)?;
write_root_file_blocking(repo.repo_fd(), &name, &keyring, fsync)?;
Ok(imported)
})
.await
}
pub async fn gpg_list_keys(&self, remote: &str) -> Result<Vec<GpgKey>> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let name = remote_keyring_name(remote);
let Some(keyring) = self.read_root_file(&name).await? else {
return Ok(Vec::new());
};
let subject = format!("the keyring '{name}'");
Ok(ostrya_rt::unblock(move || gpg_keyring_keys(&keyring, &subject)).await?)
}
}
fn global_trusted_dir() -> PathBuf {
match std::env::var_os(OSTREE_GPG_HOME_ENV) {
Some(dir) if !dir.is_empty() => PathBuf::from(dir),
_ => PathBuf::from(GLOBAL_TRUSTED_GPG_D),
}
}
fn keyring_files_in(dir: &Path) -> Result<Vec<PathBuf>> {
let refuse = |e: std::io::Error| {
Error::Signature(format!(
"the global trusted directory '{}' cannot be listed: {e}",
dir.display()
))
};
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(refuse(e)),
};
let mut files = Vec::new();
for entry in entries {
let entry = entry.map_err(refuse)?;
if !entry.file_name().as_encoded_bytes().ends_with(b".gpg") {
continue;
}
let file_type = match entry.file_type() {
Ok(file_type) => file_type,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(refuse(e)),
};
if file_type.is_file() {
files.push(entry.path());
}
}
files.sort();
Ok(files)
}
fn keypath_files(key: &str, keypath: &[String]) -> Result<Vec<PathBuf>> {
let mut paths = Vec::new();
for entry in keypath {
let path = Path::new(entry);
let meta = std::fs::metadata(path).map_err(|e| keypath_refusal(key, entry, &e))?;
if meta.is_dir() {
paths.extend(keypath_dir_files(key, entry, path)?);
} else {
paths.push(path.to_owned());
}
}
Ok(paths)
}
fn keypath_dir_files(key: &str, entry: &str, dir: &Path) -> Result<Vec<PathBuf>> {
let refuse = |e: std::io::Error| keypath_refusal(key, entry, &e);
let mut files = Vec::new();
for dirent in std::fs::read_dir(dir).map_err(refuse)? {
let dirent = dirent.map_err(refuse)?;
let file_type = match dirent.file_type() {
Ok(file_type) => file_type,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(refuse(e)),
};
if file_type.is_file() {
files.push(dirent.path());
}
}
files.sort();
Ok(files)
}
fn keypath_refusal(key: &str, entry: &str, e: &std::io::Error) -> Error {
Error::Signature(format!("{key} entry '{entry}' cannot be read: {e}"))
}
#[cfg(all(feature = "receive", feature = "sign-gpg"))]
pub(crate) async fn export_public_key(
homedir: Option<&Path>,
fingerprint: &str,
) -> Result<Vec<u8>> {
use futures_lite::AsyncReadExt;
let mut cmd = ostrya_rt::Command::new("gpg");
if let Some(dir) = homedir {
cmd.arg("--homedir").arg(dir);
}
cmd.arg("--batch")
.arg("--quiet")
.arg("--export")
.arg("--")
.arg(fingerprint);
let mut child = cmd.spawn().map_err(|e| {
if e.kind() == std::io::ErrorKind::NotFound {
Error::Signature("gpg: program not found in PATH".into())
} else {
Error::Signature(format!("gpg: {e}"))
}
})?;
let mut exported = Vec::new();
let read = match child.take_stdout() {
Some(stdout) => stdout
.take(MAX_KEYRING + 1)
.read_to_end(&mut exported)
.await
.map(|_| ()),
None => Ok(()),
};
let status = child.wait().await?;
read?;
if exported.len() as u64 > MAX_KEYRING {
return Err(Error::Signature(format!(
"gpg --export of '{fingerprint}' is over the {MAX_KEYRING}-byte ceiling"
)));
}
if !status.success() || exported.is_empty() {
return Err(Error::Signature(format!(
"gpg --export of '{fingerprint}' gave no certificate: exit status {status}"
)));
}
Ok(exported)
}
fn read_keyring_path(path: &Path) -> Result<Option<Vec<u8>>> {
let subject = format!("the keyring '{}'", path.display());
read_key_path(path, &subject, MAX_KEYRING)
}
pub(crate) fn read_keyring_fd(fd: OwnedFd, name: &str) -> Result<Vec<u8>> {
Ok(read_key_source(
std::fs::File::from(fd),
&format!("the keyring '{name}'"),
MAX_KEYRING,
)?)
}
#[cfg(test)]
fn scratch_dir() -> PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
std::env::temp_dir().join(format!(
"ostrya-gpg-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
))
}
#[cfg(test)]
fn remove_home_sockets(dir: &Path) {
use std::process::{Command, Stdio};
for action in [&["--kill", "all"][..], &["--remove-socketdir"][..]] {
let _ = Command::new("gpgconf")
.arg("--homedir")
.arg(dir)
.args(action)
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
#[cfg(unix)]
#[test]
fn keyring_files_in_selects_gpg_and_sorts() {
use std::os::unix::fs::symlink;
let dir = scratch_dir();
std::fs::create_dir_all(dir.join("d.gpg")).unwrap();
for name in [
"b.gpg",
"a.gpg",
".gpg",
".a.gpg",
"a.GPG",
"a.gpg.bak",
"notes.txt",
"keyring",
"d.gpg/c.gpg",
] {
std::fs::write(dir.join(name), b"").unwrap();
}
symlink(dir.join("b.gpg"), dir.join("link.gpg")).unwrap();
match std::process::Command::new("mkfifo")
.arg(dir.join("fifo.gpg"))
.status()
{
Ok(status) if status.success() => {}
other => eprintln!("skipping the fifo arm: mkfifo did not create a fifo: {other:?}"),
}
let files = keyring_files_in(&dir);
std::fs::remove_dir_all(&dir).unwrap();
let names: Vec<String> = files
.unwrap()
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert_eq!(names, [".a.gpg", ".gpg", "a.gpg", "b.gpg"]);
}
#[test]
fn keyring_files_in_missing_dir_is_empty() {
assert!(keyring_files_in(&scratch_dir()).unwrap().is_empty());
}
#[cfg(unix)]
#[test]
fn a_global_directory_that_cannot_be_listed_is_refused_by_its_path() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch_dir();
let file = dir.join("file");
let locked = dir.join("locked");
std::fs::create_dir_all(&locked).unwrap();
std::fs::write(&file, b"").unwrap();
std::fs::write(locked.join("a.gpg"), b"").unwrap();
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
let listed = std::fs::read_dir(&locked).is_ok();
let from_file = keyring_files_in(&file);
let from_locked = keyring_files_in(&locked);
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
let mut cases = vec![(file, from_file)];
if listed {
eprintln!("skipping the mode 000 arm: the directory lists with mode 000");
} else {
cases.push((locked, from_locked));
}
for (path, result) in cases {
let expected = format!(
"the global trusted directory '{}' cannot be listed: ",
path.display()
);
assert!(
matches!(&result, Err(Error::Signature(m)) if m.starts_with(&expected)),
"{:?}",
result.err()
);
}
}
#[test]
fn a_repository_keyring_stops_the_read_of_the_global_directory() {
let dir = scratch_dir();
std::fs::create_dir_all(&dir).unwrap();
let junk = dir.join("junk.gpg");
std::fs::write(&junk, b"This directory holds the trusted keys.\n").unwrap();
let remotes_d = dir.join("remotes.d");
let remote = "ostrya-global-fallback-test";
let with_keyring =
remote_keyrings_in(Some(Vec::new()), remote, &[], &remotes_d, Some(&dir));
let without = remote_keyrings_in(None, remote, &[], &remotes_d, Some(&dir));
let no_global = remote_keyrings_in(None, remote, &[], &remotes_d, None);
std::fs::remove_dir_all(&dir).unwrap();
assert!(with_keyring.unwrap().is_empty());
assert!(no_global.unwrap().is_empty());
let named = format!("the keyring '{}'", junk.display());
assert!(
matches!(&without, Err(Error::Signature(m)) if m.contains(&named)),
"{:?}",
without.err()
);
}
#[test]
fn the_global_directory_trusts_its_keys_only_with_no_repository_keyring() {
use ostrya_sign::Verifier as _;
if !gpg_available() {
assert!(
std::env::var_os("OSTRYA_REQUIRE_GNUPG").is_none(),
"OSTRYA_REQUIRE_GNUPG is set and `gpg` is not available"
);
eprintln!("skipping: gpg not available");
return;
}
let repo_key = KeyFixture::new("Repository <repository@ostrya.example>");
let global_key = KeyFixture::new("Global <global@ostrya.example>");
let payload = b"global payload";
let signature = global_key.sign(payload);
let dir = scratch_dir();
let global = dir.join("global");
let armored = dir.join("armored");
std::fs::create_dir_all(&global).unwrap();
std::fs::create_dir_all(&armored).unwrap();
std::fs::write(global.join("k.gpg"), global_key.export(false)).unwrap();
std::fs::write(armored.join("k.gpg"), global_key.export(true)).unwrap();
let remotes_d = dir.join("remotes.d");
let remote = "ostrya-global-trust-test";
let load = |repo_keyring: Option<Vec<u8>>, dir: &Path| {
remote_keyrings_in(repo_keyring, remote, &[], &remotes_d, Some(dir))
};
let verdict = |verifier: Result<GpgVerifier>| {
verifier
.unwrap()
.verify(payload, std::slice::from_ref(&signature))
.unwrap()
.valid
};
let fallback = verdict(load(None, &global));
let shadowed = verdict(load(Some(repo_key.export(false)), &global));
let armored_global = load(None, &armored);
let armored_repo = load(Some(repo_key.export(true)), &global);
std::fs::remove_dir_all(&dir).unwrap();
assert!(fallback);
assert!(!shadowed);
let named = format!("the keyring '{}'", armored.join("k.gpg").display());
assert!(
matches!(&armored_global, Err(Error::Signature(m)) if m.contains(&named)
&& m.contains("armor")),
"{:?}",
armored_global.err()
);
let named = format!("the keyring '{remote}.trustedkeys.gpg'");
assert!(
matches!(&armored_repo, Err(Error::Signature(m)) if m.contains(&named)
&& m.contains("armor")),
"{:?}",
armored_repo.err()
);
}
#[test]
fn a_system_keyring_of_the_remote_stops_the_read_of_the_global_directory() {
let dir = scratch_dir();
let global = dir.join("global");
let remotes_d = dir.join("remotes.d");
std::fs::create_dir_all(&global).unwrap();
std::fs::create_dir_all(&remotes_d).unwrap();
let junk = global.join("junk.gpg");
std::fs::write(&junk, b"This directory holds the trusted keys.\n").unwrap();
let remote = "ostrya-system-fallback-test";
std::fs::write(remotes_d.join("other.trustedkeys.gpg"), b"").unwrap();
let without = remote_keyrings_in(None, remote, &[], &remotes_d, Some(&global));
std::fs::write(remotes_d.join(remote_keyring_name(remote)), b"").unwrap();
let with_keyring = remote_keyrings_in(None, remote, &[], &remotes_d, Some(&global));
std::fs::remove_dir_all(&dir).unwrap();
assert!(with_keyring.unwrap().is_empty());
let named = format!("the keyring '{}'", junk.display());
assert!(
matches!(&without, Err(Error::Signature(m)) if m.contains(&named)),
"{:?}",
without.err()
);
}
#[test]
fn the_global_directory_trusts_its_keys_only_with_no_system_keyring() {
use ostrya_sign::Verifier as _;
if !gpg_available() {
assert!(
std::env::var_os("OSTRYA_REQUIRE_GNUPG").is_none(),
"OSTRYA_REQUIRE_GNUPG is set and `gpg` is not available"
);
eprintln!("skipping: gpg not available");
return;
}
let system_key = KeyFixture::new("System <system@ostrya.example>");
let global_key = KeyFixture::new("Global <global@ostrya.example>");
let payload = b"system payload";
let system_signature = system_key.sign(payload);
let global_signature = global_key.sign(payload);
let dir = scratch_dir();
let global = dir.join("global");
let remotes_d = dir.join("remotes.d");
std::fs::create_dir_all(&global).unwrap();
std::fs::create_dir_all(&remotes_d).unwrap();
std::fs::write(global.join("k.gpg"), global_key.export(false)).unwrap();
let remote = "ostrya-system-trust-test";
let system = remotes_d.join(remote_keyring_name(remote));
let load = || remote_keyrings_in(None, remote, &[], &remotes_d, Some(&global));
let verdicts = |verifier: Result<GpgVerifier>| {
let verifier = verifier.unwrap();
[&global_signature, &system_signature].map(|signature| {
verifier
.verify(payload, std::slice::from_ref(signature))
.unwrap()
.valid
})
};
let fallback = verdicts(load());
std::fs::write(&system, system_key.export(false)).unwrap();
let shadowed = verdicts(load());
std::fs::write(&system, system_key.export(true)).unwrap();
let armored = load();
std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(fallback, [true, false]);
assert_eq!(shadowed, [false, true]);
let named = format!("the keyring '{}'", system.display());
assert!(
matches!(&armored, Err(Error::Signature(m)) if m.contains(&named)
&& m.contains("armor")),
"{:?}",
armored.err()
);
}
#[cfg(unix)]
#[test]
fn keypath_dir_files_takes_each_regular_file_and_sorts() {
use std::os::unix::fs::symlink;
let dir = scratch_dir();
std::fs::create_dir_all(dir.join("sub")).unwrap();
for name in [
"z.asc",
"a.keyring",
"README",
".gpg",
".a.gpg",
"sub/b.gpg",
] {
std::fs::write(dir.join(name), b"").unwrap();
}
symlink(dir.join("README"), dir.join("link.gpg")).unwrap();
symlink(dir.join("absent"), dir.join("dangling.gpg")).unwrap();
symlink(dir.join("sub"), dir.join("linkdir")).unwrap();
match std::process::Command::new("mkfifo")
.arg(dir.join("fifo.gpg"))
.status()
{
Ok(status) if status.success() => {}
other => eprintln!("skipping the fifo arm: mkfifo did not create a fifo: {other:?}"),
}
let files = keypath_dir_files("gpgkeypath", "keys", &dir);
std::fs::remove_dir_all(&dir).unwrap();
let names: Vec<String> = files
.unwrap()
.iter()
.map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert_eq!(names, [".a.gpg", ".gpg", "README", "a.keyring", "z.asc"]);
}
#[cfg(unix)]
#[test]
fn a_keypath_directory_that_cannot_be_listed_is_refused_by_the_entry() {
use std::os::unix::fs::PermissionsExt;
let dir = scratch_dir();
let keys = dir.join("keys");
std::fs::create_dir_all(&keys).unwrap();
std::fs::write(keys.join("a.gpg"), b"").unwrap();
std::fs::set_permissions(&keys, std::fs::Permissions::from_mode(0o000)).unwrap();
let entry = keys.to_string_lossy().into_owned();
let listed = std::fs::read_dir(&keys).is_ok();
let result = keypath_files("gpgkeypath", std::slice::from_ref(&entry));
std::fs::set_permissions(&keys, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
if listed {
eprintln!("skipping: the directory lists with mode 000");
return;
}
let expected = format!("gpgkeypath entry '{entry}' cannot be read: ");
assert!(
matches!(&result, Err(Error::Signature(m)) if m.starts_with(&expected)),
"{:?}",
result.err()
);
}
#[test]
fn an_empty_keypath_entry_is_refused() {
let result = keypath_files("gpgkeypath", &[String::new()]);
assert!(
matches!(
&result,
Err(Error::Signature(m)) if m.starts_with("gpgkeypath entry '' cannot be read: ")
),
"{:?}",
result.err()
);
}
#[test]
fn a_remote_keyring_load_refuses_an_invalid_remote_name() {
let dir = scratch_dir();
let root = dir.join("repo");
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir(dir.join("x.trustedkeys.gpg")).unwrap();
let repo = GpgVerifier::for_remote(&root, "../x");
let keypath = GpgVerifier::for_remote_keypath(&root, "../x", &[]);
let keyrings = GpgVerifier::for_remote_keyrings(None, "../x", &[]);
std::fs::remove_dir_all(&dir).unwrap();
for result in [repo, keypath, keyrings] {
assert!(
matches!(
&result,
Err(Error::InvalidInput(m)) if m == "invalid remote name: ../x"
),
"{:?}",
result.err()
);
}
}
#[test]
fn a_keypath_load_refuses_the_repository_keyring_first() {
let dir = scratch_dir();
let keyring = dir.join("keypath-order.trustedkeys.gpg");
std::fs::create_dir_all(&keyring).unwrap();
let entry = dir.join("absent.gpg").to_string_lossy().into_owned();
let result = GpgVerifier::for_remote_keypath(&dir, "keypath-order", &[entry]);
std::fs::remove_dir_all(&dir).unwrap();
let expected = format!("the keyring '{}' is not a regular file", keyring.display());
assert!(
matches!(&result, Err(Error::Signature(m)) if *m == expected),
"{:?}",
result.err()
);
}
#[test]
fn a_keypath_load_trusts_the_keypath_entries() {
use ostrya_sign::Verifier as _;
if !gpg_available() {
assert!(
std::env::var_os("OSTRYA_REQUIRE_GNUPG").is_none(),
"OSTRYA_REQUIRE_GNUPG is set and `gpg` is not available"
);
eprintln!("skipping: gpg not available");
return;
}
let key = KeyFixture::new("Keypath <keypath@ostrya.example>");
let payload = b"keypath payload";
let signature = key.sign(payload);
let dir = scratch_dir();
std::fs::create_dir_all(&dir).unwrap();
let keyring = dir.join("k.gpg");
std::fs::write(&keyring, key.export(false)).unwrap();
let entry = keyring.to_string_lossy().into_owned();
let trusted = GpgVerifier::for_remote_keypath(&dir, "keypath-trust", &[entry])
.unwrap()
.verify(payload, std::slice::from_ref(&signature))
.unwrap();
let untrusted = GpgVerifier::for_remote_keypath(&dir, "keypath-trust", &[])
.unwrap()
.verify(payload, std::slice::from_ref(&signature))
.unwrap();
std::fs::remove_dir_all(&dir).unwrap();
assert!(trusted.valid, "{:?}", trusted.signatures);
assert!(!untrusted.valid, "{:?}", untrusted.signatures);
}
#[test]
fn an_import_over_the_keyring_ceiling_is_refused() {
use crate::{CreateOptions, RepoMode};
let dir = scratch_dir();
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let keyring = root.join("origin.trustedkeys.gpg");
let oversized = vec![0u8; MAX_KEYRING as usize + 1];
let refusals = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let absent = repo.gpg_import_keys("origin", &oversized, &[]).await;
let absent_after = std::fs::exists(&keyring).unwrap();
std::fs::write(&keyring, b"").unwrap();
let empty = repo.gpg_import_keys("origin", &oversized, &[]).await;
let empty_after = std::fs::read(&keyring).unwrap();
(absent, absent_after, empty, empty_after)
});
std::fs::remove_dir_all(&dir).unwrap();
let (absent, absent_after, empty, empty_after) = refusals;
let text = "signature: the keyring to import is over the 4194304-byte ceiling";
assert_eq!(absent.unwrap_err().to_string(), text);
assert!(!absent_after, "the refused import wrote a keyring");
assert_eq!(empty.unwrap_err().to_string(), text);
assert!(
empty_after.is_empty(),
"the refused import changed the keyring"
);
}
#[test]
fn an_import_refuses_an_invalid_remote_name() {
use crate::{CreateOptions, RepoMode};
let dir = scratch_dir();
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let decoy = dir.join("x.trustedkeys.gpg");
std::fs::create_dir(&decoy).unwrap();
let result = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
repo.gpg_import_keys("../x", b"", &[]).await
});
let decoy_stays = decoy.is_dir();
std::fs::remove_dir_all(&dir).unwrap();
assert!(
matches!(&result, Err(Error::InvalidInput(m)) if m == "invalid remote name: ../x"),
"{:?}",
result.err()
);
assert!(decoy_stays, "the refused import changed the decoy");
}
#[test]
fn a_key_listing_refuses_an_invalid_remote_name() {
use crate::{CreateOptions, RepoMode};
let dir = scratch_dir();
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let decoy = dir.join("x.trustedkeys.gpg");
std::fs::create_dir(&decoy).unwrap();
let result = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
repo.gpg_list_keys("../x").await
});
let decoy_stays = decoy.is_dir();
std::fs::remove_dir_all(&dir).unwrap();
assert!(
matches!(&result, Err(Error::InvalidInput(m)) if m == "invalid remote name: ../x"),
"{:?}",
result.err()
);
assert!(decoy_stays, "the refused listing changed the decoy");
}
pub(crate) fn gpg_available() -> bool {
std::process::Command::new("gpg")
.arg("--version")
.output()
.is_ok_and(|out| out.status.success())
}
pub(crate) struct KeyFixture {
pub(crate) dir: PathBuf,
}
impl KeyFixture {
pub(crate) fn new(uid: &str) -> KeyFixture {
let fixture = KeyFixture {
dir: KeyFixture::make_dir(),
};
fixture.add_key(uid);
fixture
}
fn make_dir() -> PathBuf {
use std::os::unix::fs::DirBuilderExt;
let dir = scratch_dir();
std::fs::DirBuilder::new().mode(0o700).create(&dir).unwrap();
dir
}
pub(crate) fn add_key(&self, uid: &str) {
self.generate(uid, "never");
}
fn generate(&self, uid: &str, expiry: &str) {
let status = self
.gpg()
.args(["--pinentry-mode", "loopback", "--passphrase", ""])
.args(["--quick-gen-key", uid, "ed25519", "sign", expiry])
.status()
.unwrap();
assert!(status.success(), "gpg --quick-gen-key failed");
}
pub(crate) fn sign(&self, payload: &[u8]) -> Vec<u8> {
let file = self.dir.join("payload");
std::fs::write(&file, payload).unwrap();
let out = self
.gpg()
.args(["--pinentry-mode", "loopback", "--passphrase", ""])
.args(["--detach-sign", "--output", "-", "--local-user"])
.arg(format!("{}!", self.fingerprint()))
.arg(&file)
.output()
.unwrap();
assert!(out.status.success() && !out.stdout.is_empty());
out.stdout
}
pub(crate) fn fingerprint(&self) -> String {
let out = self
.gpg()
.args(["--with-colons", "--list-keys"])
.output()
.unwrap();
assert!(out.status.success(), "gpg --list-keys failed");
String::from_utf8_lossy(&out.stdout)
.lines()
.filter_map(|line| line.strip_prefix("fpr:"))
.filter_map(|rest| rest.split(':').nth(8).map(str::to_owned))
.next()
.unwrap()
}
fn gpg(&self) -> std::process::Command {
let mut cmd = std::process::Command::new("gpg");
cmd.arg("--homedir").arg(&self.dir).arg("--batch");
cmd
}
pub(crate) fn export(&self, armored: bool) -> Vec<u8> {
let mut cmd = self.gpg();
cmd.arg("--export");
if armored {
cmd.arg("--armor");
}
let out = cmd.output().unwrap();
assert!(out.status.success() && !out.stdout.is_empty());
out.stdout
}
}
impl Drop for KeyFixture {
fn drop(&mut self) {
remove_home_sockets(&self.dir);
let _ = std::fs::remove_dir_all(&self.dir);
}
}
}