use ostrya_core::{KeyFile, Value};
use crate::config::{Remote, SignVerify};
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::verify::{KeySource, TrustedKeys, Verifiers, build_policy};
impl TrustedKeys {
pub async fn for_remote(repo: &Repo, remote: &str) -> Result<TrustedKeys> {
TrustedKeys::for_remote_in(repo, repo.config().keyfile(), remote, true).await
}
pub(crate) async fn for_remote_in(
repo: &Repo,
keyfile: &KeyFile,
remote: &str,
repo_keyring: bool,
) -> Result<TrustedKeys> {
let Some(section) = Remote::in_keyfile(keyfile, remote) else {
return Err(Error::InvalidFormat(format!(
"remote:{remote} names no [remote \"{remote}\"] section"
)));
};
let gpg = section.gpg_verify()?;
let sign = section.sign_verify()?;
if !gpg && sign == SignVerify::Off {
return Err(Error::InvalidFormat(format!(
"remote:{remote} turns on no signature check: the remote sets \
gpg-verify=false and no sign-verify; write verify=off for no check"
)));
}
let source = KeySource::Remote {
name: remote,
section: Some(§ion),
repo_keyring,
};
let policy = build_policy(repo, &source, &mut Verifiers::default(), gpg, &sign).await?;
Ok(TrustedKeys::from_policy(policy))
}
pub(crate) async fn for_trust_group(
repo: &Repo,
keyfile: &KeyFile,
name: &str,
group: &str,
) -> Result<TrustedKeys> {
let section = Remote::view(keyfile, group.to_owned());
let gpg = keyfile.get_bool(group, "gpg-verify")?.unwrap_or(false);
let sign = section.sign_verify()?;
let source = KeySource::Trust {
name,
section: §ion,
};
let policy = build_policy(repo, &source, &mut Verifiers::default(), gpg, &sign).await?;
Ok(TrustedKeys::from_policy(policy))
}
pub(crate) async fn check(
&self,
subject: &str,
payload: &[u8],
detached: Option<&Value>,
) -> Result<()> {
self.policy().check(subject, payload, detached).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sign::{Ed25519Signer, Signer, append_signature};
use crate::{CreateOptions, RepoMode};
const SECRET_B64: &str =
"o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
const OTHER_SECRET_B64: &str =
"5ILWxT+l9G/u3h0BptRpmSi35C9uog7YDdD+Fp1Xk+Hz52p0NlYh6xBA73kJEJKhKbbnjcE0rsWA5XA/K5Sq5Q==";
const PAYLOAD: &[u8] = b"the commit bytes";
struct Scratch {
dir: std::path::PathBuf,
}
impl Scratch {
fn new(label: &str) -> Scratch {
let dir = std::env::temp_dir().join(format!(
"ostrya-trust-{label}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
Scratch { dir }
}
fn repo(&self) -> Repo {
ostrya_rt::block_on(Repo::create(
&self.dir.join("repo"),
CreateOptions::new(RepoMode::Archive),
))
.unwrap()
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn dict_with(key: &str, blob: Vec<u8>) -> Value {
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, key, blob).unwrap();
dict
}
fn ed25519_signed(secret: &str) -> Value {
let signer = Ed25519Signer::from_base64(secret).unwrap();
let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
dict_with(signer.metadata_key(), blob)
}
#[test]
fn a_trust_group_checks_a_commit() {
let scratch = Scratch::new("group");
let repo = scratch.repo();
let group = "ex-ostrya trust \"t\"";
let keyfile = KeyFile::parse(&format!(
"[{group}]\nsign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
))
.unwrap();
let keys =
ostrya_rt::block_on(TrustedKeys::for_trust_group(&repo, &keyfile, "t", group)).unwrap();
let own = ed25519_signed(SECRET_B64);
let other = ed25519_signed(OTHER_SECRET_B64);
let (valid, unsigned, untrusted) = ostrya_rt::block_on(async {
(
keys.check("commit", PAYLOAD, Some(&own)).await,
keys.check("commit", PAYLOAD, None).await,
keys.check("commit", PAYLOAD, Some(&other)).await,
)
});
valid.expect("a signature from the named key passes");
let err = unsigned.unwrap_err();
assert!(err.to_string().contains("carries no signature"), "{err}");
let err = untrusted.unwrap_err();
assert!(
err.to_string()
.contains("no sign-api signature is from a trusted key"),
"{err}"
);
}
#[test]
fn a_trust_group_engine_needs_a_key() {
let scratch = Scratch::new("nokey");
let repo = scratch.repo();
let group = "ex-ostrya trust \"t\"";
let keyfile = KeyFile::parse(&format!("[{group}]\nsign-verify=ed25519\n")).unwrap();
let Err(err) =
ostrya_rt::block_on(TrustedKeys::for_trust_group(&repo, &keyfile, "t", group))
else {
panic!("an engine with no key is refused");
};
assert!(
matches!(&err, Error::Signature(m) if m.contains("no trusted key for signature engine 'ed25519'")),
"{err}"
);
}
#[test]
fn the_pull_trust_of_a_remote() {
let scratch = Scratch::new("remote");
let repo = scratch.repo();
let keyfile = KeyFile::parse(&format!(
"[remote \"origin\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n\
[remote \"plain\"]\nurl=http://localhost/\ngpg-verify=false\n"
))
.unwrap();
let keys = ostrya_rt::block_on(TrustedKeys::for_remote_in(&repo, &keyfile, "origin", true))
.unwrap();
ostrya_rt::block_on(keys.check("commit", PAYLOAD, Some(&ed25519_signed(SECRET_B64))))
.expect("a signature from the remote's key passes");
for remote in ["plain", "absent"] {
let Err(err) =
ostrya_rt::block_on(TrustedKeys::for_remote_in(&repo, &keyfile, remote, true))
else {
panic!("{remote} is refused");
};
assert!(matches!(err, Error::InvalidFormat(_)), "{remote}: {err}");
}
}
#[cfg(feature = "verify-gpg")]
fn gpg_or_skip() -> bool {
if crate::gpg::tests::gpg_available() {
return true;
}
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");
false
}
#[cfg(feature = "verify-gpg")]
#[test]
fn the_repository_keyring_takes_part_on_request() {
use crate::gpg::tests::KeyFixture;
if !gpg_or_skip() {
return;
}
let key = KeyFixture::new("Central <central@example.org>");
let signed = dict_with("ostree.gpgsigs", key.sign(PAYLOAD));
let scratch = Scratch::new("keyring");
let repo = scratch.repo();
std::fs::write(
scratch.dir.join("repo").join("origin.trustedkeys.gpg"),
key.export(false),
)
.unwrap();
let keyfile = KeyFile::parse("[remote \"origin\"]\nurl=http://localhost/\n").unwrap();
let check = |repo_keyring: bool| {
ostrya_rt::block_on(async {
TrustedKeys::for_remote_in(&repo, &keyfile, "origin", repo_keyring)
.await
.unwrap()
.check("commit", PAYLOAD, Some(&signed))
.await
})
};
check(true).expect("the repository keyring holds the key");
let err = check(false).expect_err("the repository keyring does not take part");
assert!(matches!(err, Error::Signature(_)), "{err}");
}
#[cfg(feature = "verify-gpg")]
#[test]
fn a_policy_file_leaves_out_the_repository_keyring() {
use crate::gpg::tests::KeyFixture;
use crate::receive::{ReceivePolicy, ReceiveVerify};
if !gpg_or_skip() {
return;
}
let key = KeyFixture::new("Central <central@example.org>");
let signed = dict_with("ostree.gpgsigs", key.sign(PAYLOAD));
let scratch = Scratch::new("policy-keyring");
scratch.repo();
let root = scratch.dir.join("repo");
std::fs::write(root.join("central.trustedkeys.gpg"), key.export(false)).unwrap();
let groups = "[remote \"central\"]\nurl=http://localhost/\n\
[ex-ostrya receive]\nverify=remote:central\n";
let mut config = std::fs::read_to_string(root.join("config")).unwrap();
config.push('\n');
config.push_str(groups);
std::fs::write(root.join("config"), config).unwrap();
let file = scratch.dir.join("receive.conf");
std::fs::write(&file, groups).unwrap();
let repo = ostrya_rt::block_on(Repo::open(&root)).unwrap();
let check = |policy: ReceivePolicy| {
let ReceiveVerify::Keys(keys) = &policy.default_rule.verify else {
panic!("the default rule checks signatures");
};
ostrya_rt::block_on(keys.check("commit", PAYLOAD, Some(&signed)))
};
check(ostrya_rt::block_on(ReceivePolicy::from_config(&repo)).unwrap())
.expect("the repository config trusts the repository keyring");
let err = check(ostrya_rt::block_on(ReceivePolicy::from_file(&repo, &file)).unwrap())
.expect_err("a policy file reads no keyring inside the repository");
assert!(matches!(err, Error::Signature(_)), "{err}");
}
#[cfg(feature = "verify-gpg")]
const FIXTURE_ENV: &str = "OSTRYA_TRUST_TEST_FIXTURES";
#[cfg(feature = "verify-gpg")]
#[test]
fn the_global_gpg_directory_reaches_remotes_alone() {
use crate::gpg::tests::KeyFixture;
if !gpg_or_skip() {
return;
}
let key = KeyFixture::new("Global <global@example.org>");
let stranger = KeyFixture::new("Stranger <stranger@example.org>");
let scratch = Scratch::new("global");
let global = scratch.dir.join("global");
std::fs::create_dir(&global).unwrap();
std::fs::write(global.join("global.gpg"), key.export(false)).unwrap();
std::fs::write(scratch.dir.join("stranger.gpg"), stranger.export(false)).unwrap();
std::fs::write(scratch.dir.join("signature"), key.sign(PAYLOAD)).unwrap();
let child = std::process::Command::new(std::env::current_exe().unwrap())
.args([
"receive::trust::tests::global_gpg_directory_subprocess",
"--exact",
"--ignored",
"--nocapture",
])
.env("OSTREE_GPG_HOME", &global)
.env(FIXTURE_ENV, &scratch.dir)
.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),
);
}
#[cfg(feature = "verify-gpg")]
#[test]
#[ignore = "helper process for the_global_gpg_directory_reaches_remotes_alone"]
fn global_gpg_directory_subprocess() {
let Some(fixtures) = std::env::var_os(FIXTURE_ENV).map(std::path::PathBuf::from) else {
return;
};
let signed = dict_with(
"ostree.gpgsigs",
std::fs::read(fixtures.join("signature")).unwrap(),
);
let scratch = Scratch::new("global-child");
let repo = scratch.repo();
let group = "ex-ostrya trust \"t\"";
let keyfile = KeyFile::parse(&format!(
"[remote \"origin\"]\nurl=http://localhost/\n\
[{group}]\ngpg-verify=true\ngpgkeypath={}\n",
fixtures.join("stranger.gpg").display()
))
.unwrap();
ostrya_rt::block_on(async {
TrustedKeys::for_remote_in(&repo, &keyfile, "origin", true)
.await
.unwrap()
.check("commit", PAYLOAD, Some(&signed))
.await
.expect("the global directory holds the key");
let err = TrustedKeys::for_trust_group(&repo, &keyfile, "t", group)
.await
.unwrap()
.check("commit", PAYLOAD, Some(&signed))
.await
.expect_err("a trust group reads no global directory");
assert!(matches!(err, Error::Signature(_)), "{err}");
});
}
}