use ostrya_core::{Checksum, Value};
use crate::error::{Error, Result};
use crate::verify::{Found, Policy, PullTrust, examine};
pub(crate) struct Verification {
commit: Policy,
summary: Policy,
}
impl Verification {
pub(crate) fn from_trust(trust: PullTrust) -> Verification {
let (commit, summary) = trust.into_policies();
Verification { commit, summary }
}
pub(crate) fn checks_commits(&self) -> bool {
self.commit.applies()
}
pub(crate) fn checks_summary(&self) -> bool {
self.summary.applies()
}
pub(crate) async fn check_commit(
&self,
checksum: &Checksum,
bytes: &[u8],
detached: Option<&Value>,
) -> Result<()> {
if !self.commit.applies() {
return Ok(());
}
self.commit
.check(&format!("commit {checksum}"), bytes, detached)
.await
}
pub(crate) async fn check_summary(
&self,
summary: Option<&[u8]>,
signature: Option<Vec<u8>>,
) -> Result<Option<Vec<u8>>> {
if !self.summary.applies() {
return Ok(signature);
}
let Some(summary) = summary else {
return Err(Error::Signature(
"summary verification is enabled, but no summary is published".into(),
));
};
let Some(signature) = signature else {
return Err(Error::Signature(
"summary verification is enabled, but no summary.sig is published".into(),
));
};
let (dict, signature) = super::parse_detached(signature).await;
self.summary
.check("the summary", summary, dict?.as_ref())
.await?;
Ok(Some(signature))
}
pub(crate) async fn check_delta(
&self,
name: &str,
superblock: &[u8],
signatures: Option<&Value>,
) -> Result<()> {
let Some(engines) = self.commit.sign_axis() else {
return Ok(());
};
match examine(engines, superblock, signatures).await? {
Found::Valid | Found::Nothing => Ok(()),
Found::Untrusted => Err(Error::Signature(format!(
"static delta {name}: no signature is from a trusted key"
))),
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
use crate::pull::PullVerify;
use crate::repo::Repo;
use crate::sign::{Ed25519Signer, Ed25519Verifier, Signer, Verifier, append_signature};
use crate::verify::TrustedKeys;
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 OTHER_PUBLIC_B64: &str = "8+dqdDZWIesQQO95CRCSoSm2543BNK7FgOVwPyuUquU=";
const PAYLOAD: &[u8] = b"the signed bytes";
fn checksum() -> Checksum {
Checksum::from_bytes([0x5a; 32])
}
fn keys(public: &str) -> TrustedKeys {
let verifier = Ed25519Verifier::new(
[ostrya_core::base64::decode(public).unwrap()],
Vec::<Vec<u8>>::new(),
)
.unwrap();
TrustedKeys::new(vec![Arc::new(verifier) as Arc<dyn Verifier>]).unwrap()
}
fn signed(secret: &str) -> Value {
let signer = Ed25519Signer::from_base64(secret).unwrap();
let blob = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, signer.metadata_key(), blob).unwrap();
dict
}
fn summary_sig(secret: &str) -> Vec<u8> {
crate::summary::serialize_signature_dict(&signed(secret)).unwrap()
}
#[test]
fn explicit_keys_are_the_whole_trusted_set() {
let verification = Verification::from_trust(PullTrust::commits(keys(PUBLIC_B64)));
assert!(verification.checks_commits());
assert!(!verification.checks_summary());
let (own, other) = (signed(SECRET_B64), signed(OTHER_SECRET_B64));
let (own, other, unsigned, summary) = ostrya_rt::block_on(async {
(
verification
.check_commit(&checksum(), PAYLOAD, Some(&own))
.await,
verification
.check_commit(&checksum(), PAYLOAD, Some(&other))
.await,
verification.check_commit(&checksum(), PAYLOAD, None).await,
verification.check_summary(None, None).await.map(drop),
)
});
own.expect("a commit signed with the trusted key passes");
let err = other.expect_err("a commit signed with another key fails");
assert!(
matches!(&err, Error::Signature(m)
if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
let err = unsigned.expect_err("an unsigned commit fails");
assert!(
matches!(&err, Error::Signature(m) if m.contains("carries no signature")),
"{err}"
);
summary.expect("the summary is not checked");
}
#[test]
fn a_summary_trust_checks_the_summary_alone() {
let verification = Verification::from_trust(
PullTrust::unverified()
.with_summary(keys(OTHER_PUBLIC_B64))
.with_summary(keys(PUBLIC_B64)),
);
assert!(!verification.checks_commits());
assert!(verification.checks_summary());
let other = signed(OTHER_SECRET_B64);
let (unsigned, other, delta) = ostrya_rt::block_on(async {
(
verification.check_commit(&checksum(), PAYLOAD, None).await,
verification
.check_commit(&checksum(), PAYLOAD, Some(&other))
.await,
verification
.check_delta("delta", PAYLOAD, Some(&other))
.await,
)
});
unsigned.expect("an unsigned commit passes");
other.expect("a commit signed with another key passes");
delta.expect("a delta signed with another key passes");
let own_sig = summary_sig(SECRET_B64);
let other = summary_sig(OTHER_SECRET_B64);
let (own, other, missing) = ostrya_rt::block_on(async {
(
verification
.check_summary(Some(PAYLOAD), Some(own_sig.clone()))
.await,
verification.check_summary(Some(PAYLOAD), Some(other)).await,
verification.check_summary(Some(PAYLOAD), None).await,
)
});
assert_eq!(
own.expect("a summary signed with the last summary key passes"),
Some(own_sig),
"the check gives back the summary.sig bytes"
);
let err = other.expect_err("a summary signed with a replaced key fails");
assert!(
matches!(&err, Error::Signature(m)
if m.contains("no sign-api signature is from a trusted key")),
"{err}"
);
let err = missing.expect_err("a summary with no summary.sig fails");
assert!(
matches!(&err, Error::Signature(m)
if m == "summary verification is enabled, but no summary.sig is published"),
"{err}"
);
}
#[test]
fn from_remote_reads_the_remote_section() {
let dir = std::env::temp_dir().join(format!(
"ostrya-pull-trust-{}-{}",
std::process::id(),
crate::write::unique()
));
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let mut config = std::fs::read_to_string(root.join("config")).unwrap();
config.push_str(&format!(
"\n[remote \"origin\"]\nurl=http://localhost/\ngpg-verify=false\n\
sign-verify=ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
));
std::fs::write(root.join("config"), config).unwrap();
let repo = Repo::open(&root).await.unwrap();
let plain = PullTrust::from_remote(&repo, "origin", &PullVerify::default()).await;
let summary = PullVerify {
sign_summary: Some(true),
..PullVerify::default()
};
let summary = PullTrust::from_remote(&repo, "origin", &summary).await;
(plain, summary)
});
std::fs::remove_dir_all(&dir).unwrap();
let (plain, summary) = outcome;
let verification = Verification::from_trust(plain.unwrap());
assert!(verification.checks_commits());
assert!(!verification.checks_summary());
let (own, other) = (signed(SECRET_B64), signed(OTHER_SECRET_B64));
let (own, unsigned, other) = ostrya_rt::block_on(async {
(
verification
.check_commit(&checksum(), PAYLOAD, Some(&own))
.await,
verification.check_commit(&checksum(), PAYLOAD, None).await,
verification
.check_commit(&checksum(), PAYLOAD, Some(&other))
.await,
)
});
own.expect("a commit signed with the key of the section passes");
unsigned.expect_err("an unsigned commit fails");
if other.is_ok() {
assert!(
crate::sign::load_sign_keys("ed25519").is_ok_and(|store| !store.trusted.is_empty()),
"a commit signed with another key passes, and the system key \
store holds no ed25519 key"
);
}
let verification = Verification::from_trust(summary.unwrap());
assert!(verification.checks_commits());
assert!(verification.checks_summary());
let own = summary_sig(SECRET_B64);
ostrya_rt::block_on(verification.check_summary(Some(PAYLOAD), Some(own)))
.expect("a summary signed with the key of the section passes");
}
#[test]
fn from_remote_refuses_an_invalid_remote_name() {
let dir = std::env::temp_dir().join(format!(
"ostrya-pull-trust-name-{}-{}",
std::process::id(),
crate::write::unique()
));
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let outcome = ostrya_rt::block_on(async {
let repo = Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap();
let mut refused = Vec::new();
for name in ["../../x", ""] {
let result = PullTrust::from_remote(&repo, name, &PullVerify::default()).await;
refused.push((name, result));
}
refused
});
std::fs::remove_dir_all(&dir).unwrap();
for (name, result) in outcome {
let err = result.expect_err("an invalid remote name is refused");
assert!(
matches!(&err, Error::InvalidInput(m) if m.contains("invalid remote name")),
"{name:?}: {err}"
);
}
}
}