use crate::config::{
RepoConfig, SPKI_X509_KEYS, Section, SectionExt as _, SignVerify, TRUST_ENGINES,
refuse_foreign_keys, remote, trust, verification_engine,
};
use crate::error::{Error, Result};
use crate::pull::PullVerify;
use crate::repo::Repo;
use crate::sign::{SYSTEM_KEY_ROOTS, X509Check};
use super::{
KeySource, Policy, PullTrust, TrustedKeys, Verifiers, build_policy, no_remote, summary_switches,
};
pub(crate) async fn trust_group_policy(
repo: &Repo,
name: &str,
section: &Section<'_, trust::Group>,
gpg_on: bool,
sign_on: bool,
best_effort: bool,
) -> Result<Policy> {
let gpg = gpg_on && section.get::<trust::GpgVerify>()?;
let sign = if sign_on {
section.get::<trust::SignVerify>()?
} else {
SignVerify::Off
};
trust_group_build(
repo,
name,
section,
gpg,
&sign,
X509Check::Admission,
best_effort,
)
.await
}
pub(crate) fn trust_group_switches(
section: &Section<'_, trust::Group>,
) -> Result<(bool, SignVerify)> {
let gpg = section.get::<trust::GpgVerify>()?;
let sign = section.get::<trust::SignVerify>()?;
Ok((gpg, sign))
}
pub(crate) async fn trust_group_build(
repo: &Repo,
name: &str,
section: &Section<'_, trust::Group>,
gpg: bool,
sign: &SignVerify,
check: X509Check,
best_effort: bool,
) -> Result<Policy> {
let source = KeySource::Trust {
name,
section,
check,
best_effort,
};
build_policy(repo, &source, &mut Verifiers::default(), gpg, sign).await
}
impl TrustedKeys {
pub async fn from_trust_group(repo: &Repo, name: &str) -> Result<TrustedKeys> {
let section = named_group(repo.config(), GroupName::Group(name))?;
let policy = trust_group_policy(repo, name, §ion, true, true, false).await?;
Ok(TrustedKeys::from_policy(policy))
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum GroupName<'a> {
Key {
remote: &'a str,
value: &'a str,
},
Field(&'a str),
Group(&'a str),
}
impl GroupName<'_> {
fn value(&self) -> &str {
match self {
GroupName::Key { value, .. } | GroupName::Field(value) | GroupName::Group(value) => {
value
}
}
}
}
pub(crate) struct FieldGroup<'a> {
pub(super) name: &'a str,
pub(super) commit: Option<Policy>,
}
impl<'a> FieldGroup<'a> {
pub(crate) fn new(name: &'a str) -> FieldGroup<'a> {
FieldGroup { name, commit: None }
}
}
pub(crate) async fn pull_trust(
repo: &Repo,
remote: Option<&str>,
section: Option<&Section<'_, remote::Group>>,
name: GroupName<'_>,
verify: &PullVerify,
commit: &mut Option<Policy>,
best_effort: bool,
) -> Result<PullTrust> {
let value = name.value();
let trust = named_group(repo.config(), name)?;
let group = trust.header();
for (field, check) in [
(verify.gpg, "the GPG check"),
(verify.sign, "the sign-api check"),
] {
if field == Some(true) {
return Err(Error::InvalidInput(match name {
GroupName::Key { remote, .. } => format!(
"remote '{remote}' takes its commit keys from [{group}], so a pull \
cannot turn on {check} of the commits"
),
GroupName::Field(_) | GroupName::Group(_) => format!(
"the pull takes its commit keys from [{group}], so it cannot turn on \
{check} of the commits"
),
}));
}
}
if remote.is_none() && (verify.gpg_summary == Some(true) || verify.sign_summary == Some(true)) {
return Err(no_remote());
}
if let (Some(remote), Some(section)) = (remote, section) {
refuse_void_key(remote, section, name, group)?;
}
let (gpg_summary, sign_summary) = summary_switches(section, verify)?;
let commit = match commit.as_ref() {
Some(policy) => policy.clone(),
None => commit
.insert(
trust_group_policy(
repo,
value,
&trust,
verify.gpg != Some(false),
verify.sign != Some(false),
best_effort,
)
.await?,
)
.clone(),
};
let summary = match remote {
Some(remote) => {
let source = KeySource::Remote {
name: remote,
section,
repo_keyring: true,
system_keys: true,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort,
};
build_policy(
repo,
&source,
&mut Verifiers::default(),
gpg_summary,
&sign_summary,
)
.await?
}
None => Policy::default(),
};
Ok(PullTrust {
commit: commit.applies().then(|| TrustedKeys::from_policy(commit)),
summary: summary.applies().then(|| TrustedKeys::from_policy(summary)),
})
}
fn named_group<'a>(
config: &'a RepoConfig,
name: GroupName<'_>,
) -> Result<Section<'a, trust::Group>> {
let value = name.value();
let group = || format!("ex-ostrya trust \"{value}\"");
if !matches!(name, GroupName::Key { .. }) && !valid_group_name(value) {
return Err(Error::InvalidInput(format!(
"malformed trust group name '{value}': the name is not empty, and holds no '\"' \
and no control character"
)));
}
let Some(section) = config.section::<trust::Group>(value) else {
return Err(match name {
GroupName::Key { remote, .. } => Error::InvalidFormat(format!(
"[remote \"{remote}\"] trust={value} names no [{}] group",
group()
)),
GroupName::Field(_) => Error::InvalidInput(format!(
"the pull names the trust group '{value}', and the config has no [{}] group",
group()
)),
GroupName::Group(_) => {
Error::InvalidInput(format!("the config has no [{}] group", group()))
}
});
};
check_trust(§ion)?;
Ok(section)
}
fn refuse_void_key(
remote: &str,
section: &Section<'_, remote::Group>,
name: GroupName<'_>,
group: &str,
) -> Result<()> {
let Some(VoidKey { holds, key, reason }) = void_commit_key(section)? else {
return Ok(());
};
let value = name.value();
Err(Error::InvalidFormat(match name {
GroupName::Key { .. } => {
let verb = if holds { "holds " } else { "" };
format!("[remote \"{remote}\"] sets trust={value} and {verb}{key}{reason}")
}
GroupName::Field(_) | GroupName::Group(_) => {
let verb = if holds { "holds" } else { "sets" };
format!(
"the pull takes its commit keys from [{group}], and [remote \"{remote}\"] \
{verb} {key}{reason}"
)
}
}))
}
pub(crate) fn check_remote_group<'a>(
repo: &'a Repo,
remote: &str,
section: &Section<'_, remote::Group>,
value: &str,
) -> Result<Section<'a, trust::Group>> {
let name = GroupName::Key { remote, value };
let trust = named_group(repo.config(), name)?;
refuse_void_key(remote, section, name, trust.header())?;
Ok(trust)
}
pub(crate) fn valid_group_name(name: &str) -> bool {
!name.is_empty() && !name.contains('"') && !name.contains(char::is_control)
}
struct VoidKey {
holds: bool,
key: String,
reason: String,
}
fn void_commit_key(section: &Section<'_, remote::Group>) -> Result<Option<VoidKey>> {
let sets = |key: String, reason: &str| {
Some(VoidKey {
holds: false,
key,
reason: reason.to_owned(),
})
};
if section.file_value::<remote::GpgVerify>()? == Some(true) {
return Ok(sets(
"gpg-verify=true".to_owned(),
": the trust group sets the commit checks, so set gpg-verify=false or \
remove the key",
));
}
if section.get::<remote::SignVerify>()? != SignVerify::Off {
let raw = section
.raw_value::<remote::SignVerify>()
.unwrap_or_default();
return Ok(sets(
format!("sign-verify={raw}"),
": the trust group sets the commit checks, so remove sign-verify",
));
}
if section.contains::<remote::GpgKeyPath>() && !section.get::<remote::GpgVerifySummary>()? {
return Ok(sets(
"gpgkeypath".to_owned(),
", and gpg-verify-summary is not true, so no check reads it",
));
}
let summary = section.get::<remote::SignVerifySummary>()?;
let engines: Vec<&str> = match &summary {
SignVerify::Off => Vec::new(),
SignVerify::All => TRUST_ENGINES.to_vec(),
SignVerify::Engines(names) => names.iter().map(String::as_str).collect(),
};
for key in section.key_names() {
if let Some(engine) = verification_engine(key)
&& !engines.contains(&engine)
{
return Ok(Some(VoidKey {
holds: true,
key: format!("'{key}'"),
reason: format!(
", and sign-verify-summary does not select {engine}, so no check \
reads it"
),
}));
}
}
Ok(None)
}
pub(crate) fn check_trust(section: &Section<'_, trust::Group>) -> Result<()> {
refuse_foreign_keys(section)?;
let group = section.header();
let engine_keys: Vec<(&str, &str)> = section
.key_names()
.filter_map(|key| verification_engine(key).map(|engine| (key, engine)))
.collect();
let gpg = section.get::<trust::GpgVerify>()?;
let sign = section.get::<trust::SignVerify>()?;
let engines: Vec<&str> = match &sign {
SignVerify::Off => Vec::new(),
SignVerify::All => TRUST_ENGINES.to_vec(),
SignVerify::Engines(names) => names.iter().map(String::as_str).collect(),
};
for engine in &engines {
if !TRUST_ENGINES.contains(engine) {
return Err(Error::InvalidFormat(format!(
"[{group}] sign-verify names '{engine}', which is not ed25519 or spki"
)));
}
}
if !gpg && engines.is_empty() {
return Err(Error::InvalidFormat(format!(
"[{group}] turns on no signature check: set gpg-verify=true or sign-verify"
)));
}
let keypath = section.contains::<trust::GpgKeyPath>();
if keypath && !gpg {
return Err(Error::InvalidFormat(format!(
"[{group}] sets gpgkeypath, and gpg-verify is not true, so no check reads it"
)));
}
let names_spki = matches!(&sign, SignVerify::Engines(names) if names.iter().any(|n| n == "spki"))
|| engine_keys.iter().any(|(_, engine)| *engine == "spki");
if cfg!(not(feature = "sign-spki")) && names_spki {
return Err(Error::Unsupported(format!(
"[{group}] names the spki engine, which this build has no engine for; \
build with the sign-spki feature"
)));
}
section.check_x509()?;
let x509 = engine_keys
.iter()
.any(|(key, _)| SPKI_X509_KEYS.contains(key));
if cfg!(not(feature = "sign-x509")) && x509 {
return Err(Error::Unsupported(format!(
"[{group}] sets an X.509 trust of the spki engine, which this build has no path \
check for; build with the sign-x509 feature"
)));
}
if section.contains::<trust::VerificationSpkiIdentity>()
&& !section.contains::<trust::VerificationSpkiCaFile>()
{
return Err(Error::InvalidFormat(format!(
"[{group}] holds 'verification-spki-identity', and no verification-spki-ca-file: \
a trust group reads no system anchor"
)));
}
for (key, engine) in engine_keys {
if !engines.contains(&engine) {
return Err(Error::InvalidFormat(format!(
"[{group}] holds '{key}', and sign-verify does not select {engine}, so \
no check reads it"
)));
}
if key.ends_with("-file") {
section.verification_file(engine)?;
}
}
if gpg {
if cfg!(not(feature = "verify-gpg")) {
return Err(Error::Unsupported(format!(
"[{group}] asks for GPG verification, which this build has no engine \
for; build with the verify-gpg feature"
)));
}
let keypath = section.get::<trust::GpgKeyPath>()?.into_entries();
if keypath.is_empty() {
return Err(Error::InvalidFormat(format!(
"[{group}] sets gpg-verify=true, and gpgkeypath names no keyring"
)));
}
if keypath.iter().any(String::is_empty) {
return Err(Error::InvalidFormat(format!(
"[{group}] gpgkeypath holds an empty entry"
)));
}
}
Ok(())
}
#[cfg(test)]
pub(crate) mod tests {
use std::sync::{Arc, Mutex};
use std::thread::ThreadId;
use ostrya_core::{KeyFile, Value};
use super::*;
use crate::sign::{Ed25519Signer, Signer, append_signature};
use crate::verify::CrlScope;
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==";
pub(crate) 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);
}
}
pub(crate) fn dict_with(key: &str, blob: Vec<u8>) -> Value {
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, key, blob).unwrap();
dict
}
pub(crate) type SeenPayload = (usize, Vec<u8>);
#[derive(Clone)]
pub(crate) struct ThreadRecorder {
key: &'static str,
valid: bool,
threads: Arc<Mutex<Vec<ThreadId>>>,
payloads: Arc<Mutex<Vec<SeenPayload>>>,
}
impl ThreadRecorder {
pub(crate) fn new(key: &'static str) -> ThreadRecorder {
ThreadRecorder {
key,
valid: true,
threads: Arc::default(),
payloads: Arc::default(),
}
}
pub(crate) fn rejecting(key: &'static str) -> ThreadRecorder {
ThreadRecorder {
valid: false,
..ThreadRecorder::new(key)
}
}
pub(crate) fn threads(&self) -> Vec<ThreadId> {
self.threads.lock().unwrap().clone()
}
pub(crate) fn payloads(&self) -> Vec<SeenPayload> {
self.payloads.lock().unwrap().clone()
}
pub(crate) fn assert_one_foreign_call(&self) {
let threads = self.threads();
assert_eq!(threads.len(), 1, "{threads:?}");
assert_ne!(threads[0], std::thread::current().id());
}
pub(crate) fn assert_no_copy_of(&self, data: &[u8]) {
let payloads = self.payloads();
assert!(!payloads.is_empty());
for (address, bytes) in payloads {
assert_eq!(address, data.as_ptr() as usize);
assert_eq!(bytes, data);
}
}
}
impl crate::sign::Verifier for ThreadRecorder {
fn metadata_key(&self) -> &str {
self.key
}
fn verify(
&self,
data: &[u8],
signatures: &[Vec<u8>],
) -> ostrya_sign::Result<crate::sign::VerifyOutcome> {
self.threads
.lock()
.unwrap()
.push(std::thread::current().id());
self.payloads
.lock()
.unwrap()
.push((data.as_ptr() as usize, data.to_vec()));
let mut outcome = crate::sign::VerifyOutcome::default();
outcome.valid = self.valid && !signatures.is_empty();
Ok(outcome)
}
}
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 policy = ostrya_rt::block_on(trust_group_policy(
&repo,
"t",
&Section::from_parts(&keyfile, group, None),
true,
true,
false,
))
.unwrap();
let own = ed25519_signed(SECRET_B64);
let other = ed25519_signed(OTHER_SECRET_B64);
let (valid, unsigned, untrusted) = ostrya_rt::block_on(async {
(
policy
.check("commit", PAYLOAD, Some(&own), &CrlScope::default())
.await,
policy
.check("commit", PAYLOAD, None, &CrlScope::default())
.await,
policy
.check("commit", PAYLOAD, Some(&other), &CrlScope::default())
.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(trust_group_policy(
&repo,
"t",
&Section::from_parts(&keyfile, group, None),
true,
true,
false,
)) 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 a_trust_group_builds_the_axes_that_stay_on() {
let scratch = Scratch::new("axes");
let repo = scratch.repo();
let group = "ex-ostrya trust \"t\"";
let keyfile = KeyFile::parse(&format!(
"[{group}]\ngpg-verify=true\ngpgkeypath={}\n\
sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n",
scratch.dir.join("absent.gpg").display()
))
.unwrap();
let build = |gpg_on: bool, sign_on: bool| {
ostrya_rt::block_on(trust_group_policy(
&repo,
"t",
&Section::from_parts(&keyfile, group, None),
gpg_on,
sign_on,
false,
))
};
let sign = build(false, true).expect("the GPG axis is off, so no keyring is read");
assert!(!sign.gpg_axis());
assert_eq!(sign.sign_axis().map(<[_]>::len), Some(1));
let own = ed25519_signed(SECRET_B64);
ostrya_rt::block_on(sign.check("commit", PAYLOAD, Some(&own), &CrlScope::default()))
.expect("the sign-api axis reads the key of the group");
let none = build(false, false).unwrap();
assert!(!none.applies());
let Err(err) = build(true, false) else {
panic!("the GPG axis reads the keyring that the group names");
};
#[cfg(feature = "verify-gpg")]
assert!(
matches!(&err, Error::Signature(m) if m.contains("absent.gpg")),
"{err}"
);
#[cfg(not(feature = "verify-gpg"))]
assert!(matches!(&err, Error::Unsupported(_)), "{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")]
const FIXTURE_ENV: &str = "OSTRYA_TRUST_TEST_FIXTURES";
#[cfg(feature = "verify-gpg")]
#[test]
fn the_global_gpg_directory_is_not_part_of_a_trust_group() {
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("own.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([
"verify::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_is_not_part_of_a_trust_group"]
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 check = |keyring: &str| {
let group = "ex-ostrya trust \"t\"";
let keyfile = KeyFile::parse(&format!(
"[{group}]\ngpg-verify=true\ngpgkeypath={}\n",
fixtures.join(keyring).display()
))
.unwrap();
ostrya_rt::block_on(async {
trust_group_policy(
&repo,
"t",
&Section::from_parts(&keyfile, group, None),
true,
true,
false,
)
.await
.unwrap()
.check("commit", PAYLOAD, Some(&signed), &CrlScope::default())
.await
})
};
check("own.gpg").expect("the keyring of the group holds the key");
let err = check("stranger.gpg").expect_err("a trust group reads no global directory");
assert!(matches!(err, Error::Signature(_)), "{err}");
}
fn repo_with_remotes(scratch: &Scratch, remotes: &str) -> Repo {
drop(scratch.repo());
let config = scratch.dir.join("repo/config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(remotes);
std::fs::write(&config, text).unwrap();
ostrya_rt::block_on(Repo::open(&scratch.dir.join("repo"))).unwrap()
}
#[test]
fn remote_keys_follow_the_switches_of_each_target() {
use crate::verify::RemoteKeys;
let scratch = Scratch::new("remote-keys");
let repo = repo_with_remotes(
&scratch,
&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"
),
);
let keys = ostrya_rt::block_on(RemoteKeys::commits(&repo, "origin", None)).unwrap();
assert!(
keys.gpg().is_none(),
"gpg-verify=false gives no GPG verifier"
);
let engines: Vec<&str> = keys.sign().iter().map(|v| v.metadata_key()).collect();
assert_eq!(engines, ["ostree.sign.ed25519"]);
let signer = Ed25519Signer::from_base64(SECRET_B64).unwrap();
let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
assert!(keys.sign()[0].verify(PAYLOAD, &[blob]).unwrap().valid);
for err in [
ostrya_rt::block_on(RemoteKeys::summary(&repo, "origin", None)).unwrap_err(),
ostrya_rt::block_on(RemoteKeys::commits(&repo, "plain", None)).unwrap_err(),
] {
assert!(
matches!(&err, Error::Signature(m) if m.contains("turns on no signature check")),
"{err}"
);
}
let err = ostrya_rt::block_on(RemoteKeys::commits(&repo, "nosuch", None)).unwrap_err();
assert!(matches!(err, Error::RemoteNotFound(_)), "{err}");
let err = ostrya_rt::block_on(RemoteKeys::commits(&repo, "a/b", None)).unwrap_err();
assert!(matches!(err, Error::InvalidInput(_)), "{err}");
}
#[cfg(feature = "verify-gpg")]
#[test]
fn remote_keys_build_the_selected_engines_alone() {
use crate::verify::RemoteKeys;
let scratch = Scratch::new("remote-keys-select");
let missing = scratch.dir.join("missing");
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"both\"]\nurl=http://localhost/\ngpgkeypath={}\n\
sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n\
[remote \"all\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=true\nverification-ed25519-file={}\n",
missing.join("keyring.gpg").display(),
missing.join("ed25519.keys").display(),
),
);
let keys =
ostrya_rt::block_on(RemoteKeys::commits(&repo, "both", Some(&["ed25519"]))).unwrap();
assert!(keys.gpg().is_none(), "gpg is not selected");
let engines: Vec<&str> = keys.sign().iter().map(|v| v.metadata_key()).collect();
assert_eq!(engines, ["ostree.sign.ed25519"]);
for (remote, names, text) in [
(
"both",
&["spki"][..],
"turns on no spki check of its commits",
),
("all", &["gpg"][..], "turns on no gpg check of its commits"),
(
"both",
&["ed25519"][..],
"turns on no ed25519 check of its summary",
),
] {
let summary = text.ends_with("summary");
let err = ostrya_rt::block_on(async {
if summary {
RemoteKeys::summary(&repo, remote, Some(names)).await
} else {
RemoteKeys::commits(&repo, remote, Some(names)).await
}
})
.unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains(text)),
"{remote} {names:?}: {err}"
);
}
let err =
ostrya_rt::block_on(RemoteKeys::commits(&repo, "both", Some(&["gpg"]))).unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("gpgkeypath")),
"the selected GPG engine reads gpgkeypath: {err}"
);
let err =
ostrya_rt::block_on(RemoteKeys::commits(&repo, "all", Some(&["ed25519"]))).unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("ed25519.keys")),
"the selected engine reads its key file: {err}"
);
}
#[test]
fn remote_keys_read_the_trust_group_for_the_commits() {
use crate::verify::RemoteKeys;
let scratch = Scratch::new("remote-keys-trust");
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"t\"]\nurl=http://localhost/\ntrust=g\ngpg-verify=false\n\
[remote \"void\"]\nurl=http://localhost/\ntrust=g\ngpg-verify=true\n\
[ex-ostrya trust \"g\"]\nsign-verify=ed25519\n\
verification-ed25519-key={PUBLIC_B64}\n"
),
);
let keys = ostrya_rt::block_on(RemoteKeys::commits(&repo, "t", None)).unwrap();
assert!(keys.gpg().is_none());
assert_eq!(keys.sign().len(), 1);
let err = ostrya_rt::block_on(RemoteKeys::summary(&repo, "t", None)).unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("of its summary")),
"{err}"
);
for err in [
ostrya_rt::block_on(RemoteKeys::commits(&repo, "void", None)).unwrap_err(),
ostrya_rt::block_on(RemoteKeys::summary(&repo, "void", None)).unwrap_err(),
] {
assert!(
matches!(&err, Error::InvalidFormat(m) if m.contains("gpg-verify=true")),
"{err}"
);
}
}
#[cfg(feature = "verify-gpg")]
#[test]
fn remote_keys_read_no_global_gpg_directory() {
use crate::gpg::tests::KeyFixture;
if !gpg_or_skip() {
return;
}
let key = KeyFixture::new("Global <global@example.org>");
let scratch = Scratch::new("remote-keys-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("own.gpg"), key.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([
"verify::trust::tests::remote_keys_global_gpg_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 remote_keys_read_no_global_gpg_directory"]
fn remote_keys_global_gpg_subprocess() {
use crate::pull::PullVerify;
use crate::verify::RemoteKeys;
let Some(fixtures) = std::env::var_os(FIXTURE_ENV).map(std::path::PathBuf::from) else {
return;
};
let signature = std::fs::read(fixtures.join("signature")).unwrap();
let scratch = Scratch::new("remote-keys-global-child");
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"bare\"]\nurl=http://localhost/\n\
[remote \"own\"]\nurl=http://localhost/\ngpgkeypath={}\n",
fixtures.join("own.gpg").display()
),
);
let err = ostrya_rt::block_on(RemoteKeys::commits(&repo, "bare", None)).unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("hold no certificate")),
"{err}"
);
let signed = dict_with("ostree.gpgsigs", signature.clone());
let pull = ostrya_rt::block_on(PullTrust::from_remote(
&repo,
"bare",
&PullVerify::default(),
))
.unwrap();
ostrya_rt::block_on(pull.into_policies().0.check(
"commit",
PAYLOAD,
Some(&signed),
&CrlScope::default(),
))
.expect("the trust of a pull reads the global directory");
let keys = ostrya_rt::block_on(RemoteKeys::commits(&repo, "own", None)).unwrap();
let gpg = keys.gpg().expect("gpg-verify defaults to true");
assert!(gpg.verify(PAYLOAD, &[signature]).unwrap().valid);
assert!(keys.sign().is_empty());
}
#[test]
fn from_trust_group_verifies_a_commit() {
let scratch = Scratch::new("from-group");
let repo = repo_with_remotes(
&scratch,
&format!(
"[ex-ostrya trust \"t\"]\nsign-verify=ed25519\n\
verification-ed25519-key={PUBLIC_B64}\n"
),
);
let policy = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "t"))
.unwrap()
.into_policy();
let own = ed25519_signed(SECRET_B64);
let other = ed25519_signed(OTHER_SECRET_B64);
let (valid, unsigned, untrusted) = ostrya_rt::block_on(async {
(
policy
.check("commit", PAYLOAD, Some(&own), &CrlScope::default())
.await,
policy
.check("commit", PAYLOAD, None, &CrlScope::default())
.await,
policy
.check("commit", PAYLOAD, Some(&other), &CrlScope::default())
.await,
)
});
valid.expect("a signature from the key of the group 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 from_trust_group_refuses_a_malformed_name() {
let scratch = Scratch::new("from-group-name");
let repo = scratch.repo();
for name in ["", "a\"b", "a\nb"] {
let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, name)).unwrap_err();
let Error::InvalidInput(m) = &err else {
panic!("{name:?}: {err}");
};
assert_eq!(
m,
&format!(
"malformed trust group name '{name}': the name is not empty, and holds \
no '\"' and no control character"
)
);
}
}
#[test]
fn from_trust_group_refuses_an_absent_group() {
let scratch = Scratch::new("from-group-absent");
let repo = repo_with_remotes(
&scratch,
&format!(
"[ex-ostrya trust \"t\"]\nsign-verify=ed25519\n\
verification-ed25519-key={PUBLIC_B64}\n"
),
);
let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "u")).unwrap_err();
let Error::InvalidInput(m) = &err else {
panic!("{err}");
};
assert_eq!(m, "the config has no [ex-ostrya trust \"u\"] group");
assert!(!m.contains("pull"), "{m}");
}
#[test]
fn from_trust_group_refuses_a_malformed_group() {
let scratch = Scratch::new("from-group-malformed");
let repo = repo_with_remotes(
&scratch,
&format!(
"[ex-ostrya trust \"empty\"]\n\
[ex-ostrya trust \"summary\"]\ngpg-verify=true\ngpgkeypath={}\n\
sign-verify=ed25519\nverification-ed25519-file={}\n\
gpg-verify-summary=true\n",
scratch.dir.join("absent.gpg").display(),
scratch.dir.join("absent.keys").display(),
),
);
for (name, text) in [
(
"empty",
"[ex-ostrya trust \"empty\"] turns on no signature check: set \
gpg-verify=true or sign-verify",
),
(
"summary",
"[ex-ostrya trust \"summary\"] holds 'gpg-verify-summary', and a trust \
group sets a commit policy alone",
),
] {
let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, name)).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == text),
"{name}: {err}"
);
}
}
#[test]
fn verification_keys_name_their_engine() {
assert_eq!(
verification_engine("verification-ed25519-key"),
Some("ed25519")
);
assert_eq!(verification_engine("verification-spki-file"), Some("spki"));
assert_eq!(verification_engine("verification-x-y"), None);
assert_eq!(verification_engine("gpgkeypath"), None);
}
const GROUP_T: &str = "ex-ostrya trust \"t\"";
fn check_group(keys: &str) -> Result<()> {
let keyfile = KeyFile::parse(&format!("[{GROUP_T}]\n{keys}")).unwrap();
check_trust(&Section::from_parts(&keyfile, GROUP_T, None))
}
fn switches_of(keys: &str) -> (bool, SignVerify) {
let keyfile = KeyFile::parse(&format!("[{GROUP_T}]\n{keys}")).unwrap();
trust_group_switches(&Section::from_parts(&keyfile, GROUP_T, None)).unwrap()
}
#[test]
fn the_check_keeps_its_texts_and_its_order() {
let key = format!("verification-ed25519-key={PUBLIC_B64}\n");
let invalid = |keys: &str, text: &str| {
let err = check_group(keys).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == text),
"{keys:?}: {err:?}"
);
};
let core = |keys: &str, text: &str| {
let err = check_group(keys).unwrap_err();
assert!(
matches!(&err, Error::Core(_)) && err.to_string() == text,
"{keys:?}: {err:?}"
);
};
invalid(
&format!("sign-verify=ed25519\n{key}zzz=1\n"),
"[ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
);
invalid(
&format!("sign-verify=ed25519\n{key}verification-foo-key=AAAA\n"),
"[ex-ostrya trust \"t\"] holds 'verification-foo-key', and 'foo' is not ed25519 \
or spki",
);
invalid(
&format!("sign-verify=ed25519\n{key}sign-verify-summary=ed25519\n"),
"[ex-ostrya trust \"t\"] holds 'sign-verify-summary', and a trust group sets a \
commit policy alone",
);
invalid(
"zzz=1\ngpg-verify-summary=true\n",
"[ex-ostrya trust \"t\"] holds the unknown key 'zzz'",
);
invalid(
"gpg-verify-summary=true\nzzz=1\n",
"[ex-ostrya trust \"t\"] holds 'gpg-verify-summary', and a trust group sets a \
commit policy alone",
);
core(
"gpg-verify=maybe\n",
"keyfile: value 'maybe' for ex-ostrya trust \"t\".gpg-verify is not a boolean",
);
core(
&format!("sign-verify=ed\\q\n{key}"),
"keyfile: invalid escape '\\q'",
);
invalid(
&format!("sign-verify=dummy\n{key}"),
"[ex-ostrya trust \"t\"] sign-verify names 'dummy', which is not ed25519 or spki",
);
invalid(
&format!("sign-verify=ed25519,spki\n{key}"),
"[ex-ostrya trust \"t\"] sign-verify names 'ed25519,spki', which is not ed25519 \
or spki",
);
invalid(
&format!("sign-verify=;\n{key}"),
"[ex-ostrya trust \"t\"] sign-verify names '', which is not ed25519 or spki",
);
check_group("sign-verify=ed25519\nverification-ed25519-key=\\q\n").unwrap();
invalid(
"gpg-verify=true\ngpgkeypath=/k.gpg\nverification-ed25519-file=../k\n",
"[ex-ostrya trust \"t\"] holds 'verification-ed25519-file', and sign-verify does \
not select ed25519, so no check reads it",
);
let err = check_group("gpg-verify=true\ngpgkeypath=../k.gpg\n").unwrap_err();
#[cfg(feature = "verify-gpg")]
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] gpgkeypath \
../k.gpg has a `..` component, which a relative path in a config cannot have"),
"{err:?}"
);
#[cfg(not(feature = "verify-gpg"))]
assert!(
matches!(&err, Error::Unsupported(m) if m == "[ex-ostrya trust \"t\"] asks for GPG \
verification, which this build has no engine for; build with the verify-gpg \
feature"),
"{err:?}"
);
}
#[test]
fn the_switches_read_the_values_of_the_file() {
let engines = SignVerify::Engines(vec!["ed25519".to_owned()]);
assert_eq!(switches_of("sign-verify=ed25519\n"), (false, engines));
assert_eq!(switches_of("gpg-verify= true\n"), (true, SignVerify::Off));
assert_eq!(
switches_of("gpg-verify=true\ngpg-verify=false\n"),
(false, SignVerify::Off)
);
}
#[test]
fn the_check_refuses_a_key_file_with_a_parent_component() {
let group = "ex-ostrya trust \"t\"";
let keyfile = KeyFile::parse(&format!(
"[{group}]\nsign-verify=ed25519\nverification-ed25519-file=../k.ed25519\n"
))
.unwrap();
let err = check_trust(&Section::from_parts(&keyfile, group, None)).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] \
verification-ed25519-file ../k.ed25519 has a `..` component, which a relative \
path in a config cannot have"),
"{err:?}"
);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn x509_fixture(name: &str) -> Vec<u8> {
let root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
std::fs::read(root.join(name)).unwrap()
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn chain_signed(leaf: &str) -> Value {
file_chain_signed(leaf, &format!("chain-{leaf}.pem"))
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn file_chain_signed(leaf: &str, chain: &str) -> Value {
use crate::spki::{X509Chain, spki_secret_keys};
let signer = spki_secret_keys(x509_fixture(&format!("leaf-{leaf}.key.pem")), "k")
.unwrap()
.remove(0);
let chain = X509Chain::from_pem(&x509_fixture(chain), "c").unwrap();
let signer = signer.with_x509(vec![chain], Vec::new()).unwrap();
let mut dict = Value::Array(Vec::new());
let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
crate::sign::append_signed(
&mut dict,
"ostree.sign.spki",
blob,
signer.x509_attachments(),
)
.unwrap();
dict
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn pem_body(name: &str) -> String {
String::from_utf8(x509_fixture(name))
.unwrap()
.lines()
.filter(|line| !line.starts_with("-----"))
.collect()
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn public_pem(name: &str) -> Vec<u8> {
let der = crate::spki::spki_secret_keys(x509_fixture(name), "k")
.unwrap()
.remove(0)
.public_key_der();
let body = ostrya_core::base64::encode(&der);
let lines: Vec<&str> = body
.as_bytes()
.chunks(64)
.map(|line| std::str::from_utf8(line).unwrap())
.collect();
format!(
"-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
lines.join("\n")
)
.into_bytes()
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn remote_keys_read_the_system_anchors_with_an_identity() {
use crate::verify::RemoteKeys;
let scratch = Scratch::new("remote-keys-x509");
let roots = scratch.dir.join("etc-ostree");
std::fs::create_dir_all(roots.join("trusted.x509.d")).unwrap();
std::fs::write(
roots.join("trusted.x509.d/root.pem"),
x509_fixture("root.pem"),
)
.unwrap();
let p384 = pem_body("leaf-p384.pub.pem");
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"named\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
verification-spki-key={p384}\n\
[remote \"raw\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-key={p384}\n"
),
);
let roots_text = roots.to_str().unwrap();
let read = |remote: &str| {
ostrya_rt::block_on(RemoteKeys::read_at(
&repo,
remote,
true,
None,
&[roots_text],
))
};
let p256 = chain_signed("p256");
let valid = |keys: &RemoteKeys, dict: &Value| {
keys.sign()[0]
.verify_metadata(PAYLOAD, Some(dict), &[])
.unwrap()
.valid
};
let named = read("named").unwrap();
assert!(valid(&named, &p256), "the system anchor admits the chain");
let raw = read("raw").unwrap();
assert!(
!valid(&raw, &p256),
"a remote with no identity reads no anchor"
);
std::fs::write(
roots.join("revoked.spki"),
[
x509_fixture("leaf-p256.pub.pem"),
x509_fixture("leaf-p384.pub.pem"),
]
.concat(),
)
.unwrap();
let named = read("named").unwrap();
let outcome = named.sign()[0]
.verify_metadata(PAYLOAD, Some(&p256), &[])
.unwrap();
assert!(!outcome.valid);
assert_eq!(
outcome.signatures[0].detail.as_deref(),
Some("certificate \"CN=ostrya test leaf p256\" holds a revoked key")
);
assert!(
valid(&named, &chain_signed("p384")),
"the raw key stays trusted"
);
std::fs::remove_file(roots.join("trusted.x509.d/root.pem")).unwrap();
let err = read("named").unwrap_err();
assert!(
matches!(&err, Error::Signature(m) if m.contains("no anchor source holds an anchor")),
"{err}"
);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn remote_keys_read_the_crls_of_the_config_and_of_the_system_store() {
use crate::verify::RemoteKeys;
let scratch = Scratch::new("remote-keys-crl");
let fixtures =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
let roots = scratch.dir.join("etc-ostree");
std::fs::create_dir_all(roots.join("crl.x509.d")).unwrap();
let fixture_path = |name: &str| fixtures.join(name).display().to_string();
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"plain\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=*\n\
verification-spki-ca-file={}\n\
[remote \"crl\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=*\n\
verification-spki-ca-file={}\nverification-spki-crl-file={}\n\
[remote \"bad\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=*\n\
verification-spki-ca-file={}\nverification-spki-crl-file={}\n",
fixture_path("root.pem"),
fixture_path("root.pem"),
fixture_path("intermediate-2.crl.pem"),
fixture_path("root.pem"),
fixture_path("crl-no-number.pem"),
),
);
let roots_text = roots.to_str().unwrap();
let read = |remote: &str| {
ostrya_rt::block_on(RemoteKeys::read_at(
&repo,
remote,
true,
None,
&[roots_text],
))
};
let revoked = chain_signed("revoked");
let detail = |keys: &RemoteKeys| {
let outcome = keys.sign()[0]
.verify_metadata(PAYLOAD, Some(&revoked), &[])
.unwrap();
assert!(!outcome.valid);
assert!(outcome.signatures[0].revoked);
outcome.signatures[0].detail.clone().unwrap()
};
let text = "certificate \"CN=ostrya test leaf revoked\" is revoked by the CRL of \
\"CN=ostrya test intermediate\"";
let plain = read("plain").unwrap();
assert!(
plain.sign()[0]
.verify_metadata(PAYLOAD, Some(&revoked), &[])
.unwrap()
.valid
);
assert_eq!(detail(&read("crl").unwrap()), text);
std::fs::copy(
fixtures.join("intermediate-2.crl.pem"),
roots.join("crl.x509.d/intermediate.pem"),
)
.unwrap();
assert_eq!(detail(&read("plain").unwrap()), text);
let err = read("bad").unwrap_err();
assert_eq!(
err.to_string(),
format!(
"signature: the 'spki' CRL file '{}': x509 CRL 1: it has no \
cRLNumber",
fixture_path("crl-no-number.pem")
)
);
std::fs::copy(fixtures.join("crl-no-number.pem"), roots.join("crl.x509")).unwrap();
let err = read("plain").unwrap_err();
assert_eq!(
err.to_string(),
format!(
"signature: the CRL file '{}': x509 CRL 1: it has no \
cRLNumber",
roots.join("crl.x509").display()
)
);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn a_pull_reads_the_system_anchors_with_an_identity() {
let scratch = Scratch::new("pull-x509");
let roots = scratch.dir.join("etc-ostree");
std::fs::create_dir_all(roots.join("trusted.x509.d")).unwrap();
std::fs::write(
roots.join("trusted.x509.d/root.pem"),
x509_fixture("root.pem"),
)
.unwrap();
let intermediates =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
let p384 = pem_body("leaf-p384.pub.pem");
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"named\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
verification-spki-key={p384}\n\
[remote \"raw\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-key={p384}\n\
[remote \"via-int\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
verification-spki-intermediates-file={}\n",
intermediates.join("intermediate.pem").display()
),
);
let roots_text = roots.to_str().unwrap();
let outcome = |remote: &str, dict: &Value| {
let section = repo.config().section::<remote::Group>(remote);
let source = KeySource::Remote {
name: remote,
section: section.as_ref(),
repo_keyring: true,
system_keys: true,
roots: &[roots_text],
check: X509Check::Admission,
best_effort: false,
};
let sign = SignVerify::Engines(vec!["spki".to_owned()]);
let policy = ostrya_rt::block_on(build_policy(
&repo,
&source,
&mut Verifiers::default(),
false,
&sign,
))
.unwrap();
policy.sign_axis().unwrap()[0]
.verify_metadata(PAYLOAD, Some(dict), &[])
.unwrap()
};
let p256 = chain_signed("p256");
let leaf_alone = file_chain_signed("p256", "leaf-p256.pem");
assert!(
outcome("named", &p256).valid,
"the system anchor admits the chain"
);
assert!(
!outcome("raw", &p256).valid,
"a remote with no identity reads no anchor"
);
assert!(
outcome("via-int", &leaf_alone).valid,
"the intermediate of the config completes the chain"
);
std::fs::write(
roots.join("revoked.spki"),
public_pem("intermediate.key.pem"),
)
.unwrap();
let via_int = outcome("via-int", &leaf_alone);
assert!(!via_int.valid && via_int.signatures[0].key_missing);
assert!(
via_int.signatures[0]
.detail
.as_deref()
.unwrap()
.starts_with(
"certificate \"CN=ostrya test leaf p256\" has no valid path to a trusted \
anchor: "
),
"{via_int:?}"
);
std::fs::write(roots.join("revoked.spki"), public_pem("root.key.pem")).unwrap();
let named = outcome("named", &p256);
assert!(!named.valid && named.signatures[0].key_missing, "{named:?}");
assert!(
outcome("named", &chain_signed("p384")).valid,
"the raw key stays trusted"
);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn remote_keys_read_no_system_raw_key() {
use crate::verify::RemoteKeys;
let scratch = Scratch::new("remote-keys-system");
let roots = scratch.dir.join("etc-ostree");
std::fs::create_dir_all(&roots).unwrap();
std::fs::write(roots.join("trusted.x509"), x509_fixture("root.pem")).unwrap();
std::fs::write(
roots.join("trusted.spki"),
x509_fixture("leaf-p256.pub.pem"),
)
.unwrap();
let p384 = pem_body("leaf-p384.pub.pem");
let repo = repo_with_remotes(
&scratch,
&format!(
"[remote \"named\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-identity=uri:https://example.org/leaf-p256\n\
verification-spki-key={p384}\n\
[remote \"raw\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=spki\nverification-spki-key={p384}\n"
),
);
let roots_text = roots.to_str().unwrap();
let valid = |remote: &str, dict: &Value| {
let keys = ostrya_rt::block_on(RemoteKeys::read_at(
&repo,
remote,
true,
None,
&[roots_text],
))
.unwrap();
keys.sign()[0]
.verify_metadata(PAYLOAD, Some(dict), &[])
.unwrap()
.valid
};
let p256 = chain_signed("p256");
let p384_signed = chain_signed("p384");
assert!(valid("named", &p256), "the system anchor admits the chain");
assert!(
!valid("raw", &p256),
"the raw keys of the system store do not reach the remote"
);
std::fs::write(roots.join("revoked.spki"), public_pem("root.key.pem")).unwrap();
assert!(!valid("named", &p256), "the revoked anchor admits no chain");
assert!(valid("named", &p384_signed), "the raw key stays trusted");
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn a_trust_group_takes_the_x509_keys() {
let anchor = "verification-spki-ca-file=ca.pem\n\
verification-spki-identity=dns:a.example.org\n";
check_group(&format!("sign-verify=spki\n{anchor}")).unwrap();
for key in [
"verification-spki-intermediates-file=i.pem",
"verification-spki-eku=1.3.6.1.5.5.7.3.3",
"verification-spki-crl-file=crl.pem",
"verification-spki-revocation=required",
] {
check_group(&format!("sign-verify=spki\n{anchor}{key}\n")).unwrap();
let name = key.split('=').next().unwrap();
let err = check_group(&format!("sign-verify=spki\n{key}\n")).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if *m == format!(
"[ex-ostrya trust \"t\"] holds '{name}', and no anchor source: set \
verification-spki-ca-file or verification-spki-identity"
)),
"{key}: {err:?}"
);
}
let err = check_group("sign-verify=spki\nverification-spki-ca-file=ca.pem\n").unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
'verification-spki-ca-file', and no verification-spki-identity: an anchor \
needs an identity"),
"{err:?}"
);
let err = check_group("sign-verify=spki\nverification-spki-identity=dns:a.example.org\n")
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
'verification-spki-identity', and no verification-spki-ca-file: a trust group \
reads no system anchor"),
"{err:?}"
);
let err = check_group(&format!(
"sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n{anchor}"
))
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
'verification-spki-ca-file', and sign-verify does not select spki, so no check \
reads it"),
"{err:?}"
);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn x509_group() -> KeyFile {
let root =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/x509");
KeyFile::parse(&format!(
"[{GROUP_T}]\nsign-verify=spki\nverification-spki-ca-file={}\n\
verification-spki-identity=uri:https://example.org/leaf-p256;\
uri:https://example.org/leaf-expired\n",
root.join("root.pem").display()
))
.unwrap()
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn a_trust_group_x509_trust_checks_a_chain_at_admission() {
let scratch = Scratch::new("group-x509-admission");
let repo = scratch.repo();
let keyfile = x509_group();
let section = Section::from_parts(&keyfile, GROUP_T, None);
check_trust(§ion).unwrap();
let policy =
ostrya_rt::block_on(trust_group_policy(&repo, "t", §ion, true, true, false))
.unwrap();
let (p256, expired) = (chain_signed("p256"), chain_signed("expired"));
let (valid, expired) = ostrya_rt::block_on(async {
(
policy
.check("commit", PAYLOAD, Some(&p256), &CrlScope::default())
.await,
policy
.check("commit", PAYLOAD, Some(&expired), &CrlScope::default())
.await,
)
});
valid.expect("a chain to the anchor of the group passes");
let err = expired.unwrap_err();
assert!(
err.to_string().contains(
"no sign-api signature is from a trusted key: certificate \
\"CN=ostrya test leaf expired\" expired at 2001-01-01T00:00:00Z; system time "
),
"{err}"
);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn a_trust_group_x509_trust_follows_the_check_of_its_caller() {
let scratch = Scratch::new("group-x509-existing");
let repo = scratch.repo();
let keyfile = x509_group();
let section = Section::from_parts(&keyfile, GROUP_T, None);
let sign = SignVerify::Engines(vec!["spki".to_owned()]);
let policy = ostrya_rt::block_on(trust_group_build(
&repo,
"t",
§ion,
false,
&sign,
X509Check::Existing,
false,
))
.unwrap();
let outcome = policy.sign_axis().unwrap()[0]
.verify_metadata(PAYLOAD, Some(&chain_signed("expired")), &[])
.unwrap();
assert!(outcome.valid);
let info = &outcome.signatures[0];
assert!(info.expired);
assert_eq!(info.warnings.len(), 1, "{:?}", info.warnings);
assert!(
info.warnings[0].starts_with("certificate \"CN=ostrya test leaf expired\" expired at"),
"{:?}",
info.warnings
);
}
#[cfg(all(feature = "sign-spki", not(feature = "sign-x509")))]
#[test]
fn a_trust_group_needs_the_path_check() {
let scratch = Scratch::new("group-x509-unsupported");
let repo = repo_with_remotes(
&scratch,
"[ex-ostrya trust \"t\"]\nsign-verify=spki\n\
verification-spki-ca-file=/nonexistent/ca.pem\nverification-spki-identity=*\n",
);
let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "t")).unwrap_err();
assert!(
matches!(&err, Error::Unsupported(m) if m == "[ex-ostrya trust \"t\"] sets an X.509 \
trust of the spki engine, which this build has no path check for; build with \
the sign-x509 feature"),
"{err:?}"
);
}
#[cfg(all(feature = "sign-spki", not(feature = "sign-x509")))]
#[test]
fn a_trust_group_checks_the_x509_rules_before_the_path_check() {
let scratch = Scratch::new("group-x509-rules-first");
let repo = repo_with_remotes(
&scratch,
"[ex-ostrya trust \"t\"]\nsign-verify=spki\n\
verification-spki-ca-file=/nonexistent/ca.pem\n",
);
let err = ostrya_rt::block_on(TrustedKeys::from_trust_group(&repo, "t")).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == "[ex-ostrya trust \"t\"] holds \
'verification-spki-ca-file', and no verification-spki-identity: an anchor needs \
an identity"),
"{err:?}"
);
}
}