use std::os::fd::BorrowedFd;
use std::path::Path;
use std::sync::Arc;
use ostrya_core::{Type, Value, base64};
use crate::config::{
ConfigPath, DottedOid, Group, Key, KeyPath, Section, SectionExt as _, SignVerify,
X509Identities, io_of, remote, valid_remote_name,
};
use crate::error::{Error, Result};
use crate::pull::PullVerify;
use crate::repo::Repo;
use crate::repo_fs::{FsError, Named, Reason, open_named};
use crate::sign::{
Ed25519Verifier, MAX_KEY_FILE, SYSTEM_KEY_ROOTS, SignKeys, Verifier, X509Check,
capped_signatures, key_text, load_sign_keys_from, read_key_source,
};
pub(crate) mod trust;
const DUMMY_METADATA_KEY: &str = "ostree.sign.dummy";
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
const SPKI_METADATA_KEY: &str = "ostree.sign.spki";
#[derive(Clone)]
pub struct TrustedKeys {
policy: Policy,
}
impl TrustedKeys {
pub fn new(sign: Vec<Arc<dyn Verifier>>) -> Result<TrustedKeys> {
if sign.is_empty() {
return Err(Error::InvalidFormat(
"the trusted keys name no verifier".into(),
));
}
refuse_dummy(&sign)?;
Ok(TrustedKeys {
policy: Policy::from_axes(None, Some(sign)),
})
}
#[cfg(feature = "verify-gpg")]
pub fn with_gpg(
gpg: crate::gpg::GpgVerifier,
sign: Vec<Arc<dyn Verifier>>,
) -> Result<TrustedKeys> {
refuse_dummy(&sign)?;
let sign = (!sign.is_empty()).then_some(sign);
Ok(TrustedKeys {
policy: Policy::from_axes(Some(Arc::new(gpg)), sign),
})
}
pub(crate) fn from_policy(policy: Policy) -> TrustedKeys {
debug_assert!(policy.applies(), "trusted keys need at least one axis");
TrustedKeys { policy }
}
#[cfg(any(feature = "receive", feature = "s3"))]
pub(crate) fn policy(&self) -> &Policy {
&self.policy
}
pub(crate) fn into_policy(self) -> Policy {
self.policy
}
}
fn refuse_dummy(sign: &[Arc<dyn Verifier>]) -> Result<()> {
if sign.iter().any(|v| v.metadata_key() == DUMMY_METADATA_KEY) {
return Err(Error::InvalidFormat(
"the trusted keys name a dummy verifier, whose signature is its key".into(),
));
}
Ok(())
}
impl std::fmt::Debug for TrustedKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let sign: Option<Vec<&str>> = self
.policy
.sign_axis()
.map(|engines| engines.iter().map(|v| v.metadata_key()).collect());
f.debug_struct("TrustedKeys")
.field("gpg", &self.policy.gpg_axis())
.field("sign", &sign)
.finish()
}
}
#[derive(Clone, Debug)]
pub struct PullTrust {
commit: Option<TrustedKeys>,
summary: Option<TrustedKeys>,
}
impl PullTrust {
pub fn unverified() -> PullTrust {
PullTrust {
commit: None,
summary: None,
}
}
pub fn commits(keys: TrustedKeys) -> PullTrust {
PullTrust {
commit: Some(keys),
summary: None,
}
}
pub fn with_summary(self, keys: TrustedKeys) -> PullTrust {
PullTrust {
summary: Some(keys),
..self
}
}
pub fn summary_keys(&self) -> Option<&TrustedKeys> {
self.summary.as_ref()
}
pub(crate) fn checks_signatures(&self) -> bool {
self.commit.is_some() || self.summary.is_some()
}
pub async fn from_remote(repo: &Repo, remote: &str, verify: &PullVerify) -> Result<PullTrust> {
PullTrust::for_pull(repo, remote, verify, None).await
}
pub(crate) async fn for_pull(
repo: &Repo,
remote: &str,
verify: &PullVerify,
group: Option<&mut trust::FieldGroup<'_>>,
) -> Result<PullTrust> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
PullTrust::resolve(repo, Some(remote), verify, group, Defaults::Config, false).await
}
pub(crate) async fn for_media(
repo: &Repo,
remote: &str,
verify: &PullVerify,
) -> Result<PullTrust> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
PullTrust::resolve(repo, Some(remote), verify, None, Defaults::Config, true).await
}
pub(crate) async fn for_summary(repo: &Repo, remote: &str) -> Result<PullTrust> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let section = repo.config().section::<remote::Group>(remote);
let verify = PullVerify {
gpg: Some(false),
sign: Some(false),
..PullVerify::default()
};
PullTrust::from_section(
repo,
Some(remote),
section.as_ref(),
&verify,
Defaults::Config,
false,
)
.await
}
pub(crate) async fn resolve(
repo: &Repo,
remote: Option<&str>,
verify: &PullVerify,
group: Option<&mut trust::FieldGroup<'_>>,
defaults: Defaults,
best_effort: bool,
) -> Result<PullTrust> {
let section = remote.and_then(|name| repo.config().section::<remote::Group>(name));
if let Some(group) = group {
let name = trust::GroupName::Field(group.name);
return trust::pull_trust(
repo,
remote,
section.as_ref(),
name,
verify,
&mut group.commit,
best_effort,
)
.await;
}
if let (Some(remote), Some(section)) = (remote, §ion)
&& let Some(value) = section.get::<remote::Trust>()?
{
let name = trust::GroupName::Key {
remote,
value: value.group().name(),
};
return trust::pull_trust(
repo,
Some(remote),
Some(section),
name,
verify,
&mut None,
best_effort,
)
.await;
}
PullTrust::from_section(
repo,
remote,
section.as_ref(),
verify,
defaults,
best_effort,
)
.await
}
async fn from_section(
repo: &Repo,
remote: Option<&str>,
section: Option<&Section<'_, remote::Group>>,
verify: &PullVerify,
defaults: Defaults,
best_effort: bool,
) -> Result<PullTrust> {
let gpg_commit = switch(verify.gpg, || match section {
Some(section) => Ok(section.get::<remote::GpgVerify>()?),
None => Ok(defaults == Defaults::Config),
})?;
let sign_commit = engines(verify.sign, || match section {
Some(section) => Ok(section.get::<remote::SignVerify>()?),
None => Ok(SignVerify::Off),
})?;
let (gpg_summary, sign_summary) = summary_switches(section, verify)?;
let asks_for_a_check = gpg_commit
|| gpg_summary
|| sign_commit != SignVerify::Off
|| sign_summary != SignVerify::Off;
let Some(name) = remote else {
if asks_for_a_check {
return Err(no_remote());
}
return Ok(PullTrust::unverified());
};
let source = KeySource::Remote {
name,
section,
repo_keyring: true,
system_keys: true,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort,
};
let mut cache = Verifiers::default();
let commit = build_policy(repo, &source, &mut cache, gpg_commit, &sign_commit).await?;
let summary = build_policy(repo, &source, &mut cache, gpg_summary, &sign_summary).await?;
Ok(PullTrust {
commit: commit.applies().then(|| TrustedKeys::from_policy(commit)),
summary: summary.applies().then(|| TrustedKeys::from_policy(summary)),
})
}
pub(crate) fn into_policies(self) -> (Policy, Policy) {
(
self.commit
.map(TrustedKeys::into_policy)
.unwrap_or_default(),
self.summary
.map(TrustedKeys::into_policy)
.unwrap_or_default(),
)
}
}
#[derive(Clone)]
pub struct RemoteKeys {
gpg: Option<Arc<dyn Verifier>>,
sign: Vec<Arc<dyn Verifier>>,
}
impl RemoteKeys {
pub async fn commits(
repo: &Repo,
remote: &str,
engines: Option<&[&str]>,
) -> Result<RemoteKeys> {
RemoteKeys::read(repo, remote, true, engines).await
}
pub async fn summary(
repo: &Repo,
remote: &str,
engines: Option<&[&str]>,
) -> Result<RemoteKeys> {
RemoteKeys::read(repo, remote, false, engines).await
}
pub fn gpg(&self) -> Option<&Arc<dyn Verifier>> {
self.gpg.as_ref()
}
pub fn sign(&self) -> &[Arc<dyn Verifier>] {
&self.sign
}
async fn read(
repo: &Repo,
remote: &str,
commits: bool,
engines: Option<&[&str]>,
) -> Result<RemoteKeys> {
RemoteKeys::read_at(repo, remote, commits, engines, &SYSTEM_KEY_ROOTS).await
}
async fn read_at(
repo: &Repo,
remote: &str,
commits: bool,
engines: Option<&[&str]>,
roots: &[&str],
) -> Result<RemoteKeys> {
if !valid_remote_name(remote) {
return Err(Error::InvalidInput(format!(
"invalid remote name: {remote}"
)));
}
let Some(section) = repo.config().section::<remote::Group>(remote) else {
return Err(Error::RemoteNotFound(remote.to_owned()));
};
let value = section.get::<remote::Trust>()?;
let group = match &value {
Some(value) => {
let name = value.group().name();
let group = trust::check_remote_group(repo, remote, §ion, name)?;
Some((name, group))
}
None => None,
};
let target = if commits { "commits" } else { "summary" };
let (gpg, sign) = match &group {
Some((_, group)) if commits => trust::trust_group_switches(group)?,
_ if commits => (
section.get::<remote::GpgVerify>()?,
section.get::<remote::SignVerify>()?,
),
_ => (
section.get::<remote::GpgVerifySummary>()?,
section.get::<remote::SignVerifySummary>()?,
),
};
let (gpg, sign) = match engines {
Some(names) => select_engines(remote, target, gpg, &sign, names)?,
None => (gpg, sign),
};
if !gpg && sign == SignVerify::Off {
return Err(no_check(remote, target));
}
let policy = match &group {
Some((name, group)) if commits => {
trust::trust_group_build(repo, name, group, gpg, &sign, X509Check::Existing, false)
.await?
}
_ => {
let source = KeySource::Remote {
name: remote,
section: Some(§ion),
repo_keyring: true,
system_keys: false,
roots,
check: X509Check::Existing,
best_effort: false,
};
build_policy(repo, &source, &mut Verifiers::default(), gpg, &sign).await?
}
};
if !policy.applies() {
return Err(no_check(remote, target));
}
Ok(RemoteKeys {
gpg: policy.gpg,
sign: policy.sign.unwrap_or_default(),
})
}
}
fn select_engines(
remote: &str,
target: &str,
gpg: bool,
sign: &SignVerify,
names: &[&str],
) -> Result<(bool, SignVerify)> {
let mut gpg_selected = false;
let mut selected: Vec<String> = Vec::with_capacity(names.len());
for name in names {
let on = match (*name, sign) {
("gpg", _) => gpg,
(_, SignVerify::Off) => false,
(_, SignVerify::All) => ALL_ENGINES.contains(name),
(_, SignVerify::Engines(held)) => held.iter().any(|held| held == name),
};
if !on {
return Err(Error::Signature(format!(
"remote '{remote}' turns on no {name} check of its {target}"
)));
}
if *name == "gpg" {
gpg_selected = true;
} else if !selected.iter().any(|held| held == name) {
selected.push((*name).to_owned());
}
}
let sign = if selected.is_empty() {
SignVerify::Off
} else {
SignVerify::Engines(selected)
};
Ok((gpg_selected, sign))
}
fn no_check(remote: &str, target: &str) -> Error {
Error::Signature(format!(
"remote '{remote}' turns on no signature check of its {target}"
))
}
impl std::fmt::Debug for RemoteKeys {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let sign: Vec<&str> = self.sign.iter().map(|v| v.metadata_key()).collect();
f.debug_struct("RemoteKeys")
.field("gpg", &self.gpg.is_some())
.field("sign", &sign)
.finish()
}
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<TrustedKeys>();
assert_send_sync::<PullTrust>();
assert_send_sync::<RemoteKeys>();
};
fn no_remote() -> Error {
Error::Pull(
"a signature check takes its keys from a remote's configuration, so the pull \
has to name a remote"
.into(),
)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Defaults {
Config,
Section,
}
fn summary_switches(
section: Option<&Section<'_, remote::Group>>,
verify: &PullVerify,
) -> Result<(bool, SignVerify)> {
let gpg = switch(verify.gpg_summary, || match section {
Some(section) => Ok(section.get::<remote::GpgVerifySummary>()?),
None => Ok(false),
})?;
let sign = engines(verify.sign_summary, || match section {
Some(section) => Ok(section.get::<remote::SignVerifySummary>()?),
None => Ok(SignVerify::Off),
})?;
Ok((gpg, sign))
}
fn switch(override_: Option<bool>, configured: impl FnOnce() -> Result<bool>) -> Result<bool> {
match override_ {
Some(value) => Ok(value),
None => configured(),
}
}
fn engines(
override_: Option<bool>,
configured: impl FnOnce() -> Result<SignVerify>,
) -> Result<SignVerify> {
match override_ {
Some(true) => Ok(SignVerify::All),
Some(false) => Ok(SignVerify::Off),
None => configured(),
}
}
pub(crate) const ALL_ENGINES: &[&str] = &[
"ed25519",
#[cfg(feature = "sign-spki")]
"spki",
];
#[derive(Clone, Default)]
pub(crate) struct Policy {
gpg: Option<Arc<dyn Verifier>>,
sign: Option<Vec<Arc<dyn Verifier>>>,
}
impl Policy {
pub(crate) fn applies(&self) -> bool {
self.gpg.is_some() || self.sign.is_some()
}
pub(crate) fn sign_axis(&self) -> Option<&[Arc<dyn Verifier>]> {
self.sign.as_deref()
}
pub(crate) fn from_axes(
gpg: Option<Arc<dyn Verifier>>,
sign: Option<Vec<Arc<dyn Verifier>>>,
) -> Policy {
Policy { gpg, sign }
}
pub(crate) fn gpg_axis(&self) -> bool {
self.gpg.is_some()
}
#[cfg(feature = "s3")]
pub(crate) fn check_signature_count(&self, signatures: Option<&Value>) -> Result<()> {
let Some(dict) = signatures else {
return Ok(());
};
for verifier in self.gpg.iter().chain(self.sign.iter().flatten()) {
capped_signatures(dict, verifier.metadata_key())?;
}
Ok(())
}
pub(crate) async fn check<'p>(
&self,
subject: &str,
payload: impl Into<Payload<'p>>,
signatures: Option<&Value>,
crls: &CrlScope,
) -> Result<()> {
let mut payload = PoolCopy::new(payload.into());
if let Some(gpg) = &self.gpg {
check_axis(
subject,
"GPG",
std::slice::from_ref(gpg),
&mut payload,
signatures,
crls,
)
.await?;
}
if let Some(engines) = &self.sign {
check_axis(subject, "sign-api", engines, &mut payload, signatures, crls).await?;
}
Ok(())
}
}
#[derive(Clone, Default)]
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
pub(crate) struct CrlScope {
repo: Option<Repo>,
write: bool,
context: Vec<Arc<Value>>,
}
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
impl CrlScope {
pub(crate) fn reading(repo: &Repo) -> CrlScope {
CrlScope {
repo: Some(repo.clone()),
..CrlScope::default()
}
}
pub(crate) fn caching(repo: &Repo) -> CrlScope {
CrlScope {
repo: Some(repo.clone()),
write: true,
context: Vec::new(),
}
}
pub(crate) fn with_context(mut self, dict: Arc<Value>) -> CrlScope {
self.context.push(dict);
self
}
fn run(&self, jobs: &[Arc<dyn Verifier>], payload: &[u8], dict: &Value) -> Result<Found> {
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
let cache = match &self.repo {
Some(repo) => {
let dirs = crate::sign::crl_cache::cache_dirs(
jobs.iter().map(|job| -> &dyn Verifier { job.as_ref() }),
Some(dict),
);
crate::sign::crl_cache::read(repo.root_dir(), &dirs)
.map(crate::sign::crl_cache::dicts)?
}
None => Vec::new(),
};
#[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
let cache: Vec<Value> = Vec::new();
let context: Vec<&Value> = cache
.iter()
.chain(self.context.iter().map(|dict| dict.as_ref()))
.collect();
let (found, crls) = first_valid(jobs, payload, dict, &context)?;
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
if self.write
&& !crls.is_empty()
&& let Some(repo) = &self.repo
{
let fsync = repo.config().get::<crate::config::repo::Fsync>()?;
crate::sign::crl_cache::write(repo.root_dir(), &crls, fsync)?;
}
#[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
let _ = crls;
Ok(found)
}
}
#[derive(Clone, Copy)]
pub(crate) enum Payload<'a> {
Borrowed(&'a [u8]),
Shared(&'a Arc<Vec<u8>>),
}
impl<'a> Payload<'a> {
#[cfg_attr(not(feature = "receive"), allow(dead_code))]
pub(crate) fn bytes(self) -> &'a [u8] {
match self {
Payload::Borrowed(bytes) => bytes,
Payload::Shared(bytes) => bytes,
}
}
pub(crate) fn to_shared(self) -> Arc<Vec<u8>> {
match self {
Payload::Borrowed(bytes) => Arc::new(bytes.to_vec()),
Payload::Shared(bytes) => Arc::clone(bytes),
}
}
}
impl<'a> From<&'a [u8]> for Payload<'a> {
fn from(bytes: &'a [u8]) -> Payload<'a> {
Payload::Borrowed(bytes)
}
}
impl<'a> From<&'a Arc<Vec<u8>>> for Payload<'a> {
fn from(bytes: &'a Arc<Vec<u8>>) -> Payload<'a> {
Payload::Shared(bytes)
}
}
struct PoolCopy<'a> {
payload: Payload<'a>,
copy: Option<Arc<Vec<u8>>>,
}
impl<'a> PoolCopy<'a> {
fn new(payload: Payload<'a>) -> PoolCopy<'a> {
PoolCopy {
payload,
copy: None,
}
}
fn shared(&mut self) -> Arc<Vec<u8>> {
match self.payload {
Payload::Shared(bytes) => Arc::clone(bytes),
Payload::Borrowed(_) => {
Arc::clone(self.copy.get_or_insert_with(|| self.payload.to_shared()))
}
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Found {
Valid,
Untrusted(Vec<String>),
Nothing,
}
pub(crate) async fn examine<'p>(
verifiers: &[Arc<dyn Verifier>],
payload: impl Into<Payload<'p>>,
signatures: Option<&Value>,
crls: &CrlScope,
) -> Result<Found> {
examine_pooled(
verifiers,
&mut PoolCopy::new(payload.into()),
signatures,
crls,
)
.await
}
async fn examine_pooled(
verifiers: &[Arc<dyn Verifier>],
payload: &mut PoolCopy<'_>,
signatures: Option<&Value>,
crls: &CrlScope,
) -> Result<Found> {
let Some(dict) = signatures else {
return Ok(Found::Nothing);
};
let capped = verifiers
.iter()
.map(|verifier| capped_signatures(dict, verifier.metadata_key()))
.collect::<Result<Vec<_>>>()?;
let mut jobs: Vec<Arc<dyn Verifier>> = Vec::new();
let mut entries: Vec<Value> = Vec::new();
for (verifier, blobs) in verifiers.iter().zip(capped) {
if blobs.is_empty() {
continue;
}
jobs.push(Arc::clone(verifier));
let key = verifier.metadata_key();
if !jobs[..jobs.len() - 1]
.iter()
.any(|job| job.metadata_key() == key)
{
let blobs = blobs
.iter()
.map(|blob| Value::Bytes(blob.to_vec()))
.collect();
let ty = Type::array(Type::array(Type::Byte));
entries.push(entry(key, ty, Value::Array(blobs)));
}
}
if jobs.is_empty() {
return Ok(Found::Nothing);
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
let mut chained = false;
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
if jobs
.iter()
.any(|job| job.metadata_key() == SPKI_METADATA_KEY)
{
let chains: Vec<Value> = ostrya_sign::x509_chains_in(dict)
.into_iter()
.map(|chain| {
Value::Array(
chain
.into_iter()
.map(|der| Value::Bytes(der.to_vec()))
.collect(),
)
})
.collect();
if !chains.is_empty() {
let ty = Type::array(Type::array(Type::array(Type::Byte)));
entries.push(entry(
crate::sign::X509_CHAINS_KEY,
ty,
Value::Array(chains),
));
if let Some((ty, crls)) = dict
.dict_get(crate::sign::X509_CRLS_KEY)
.and_then(Value::as_variant)
&& ty.signature() == "aay"
&& crls.as_array().is_some_and(|crls| {
!crls.is_empty() && crls.len() <= crate::sign::MAX_X509_CRLS
})
{
entries.push(entry(crate::sign::X509_CRLS_KEY, ty.clone(), crls.clone()));
}
chained = true;
}
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
let scope = if chained {
crls.clone()
} else {
CrlScope::default()
};
#[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
let scope = {
let _ = crls;
CrlScope::default()
};
let dict = Value::Array(entries);
let payload = payload.shared();
ostrya_rt::unblock(move || scope.run(&jobs, &payload, &dict)).await
}
pub(crate) const MAX_DETAILS: usize = 4;
fn entry(key: &str, ty: Type, value: Value) -> Value {
Value::Tuple(vec![Value::Str(key.to_owned()), Value::variant(ty, value)])
}
fn first_valid(
jobs: &[Arc<dyn Verifier>],
payload: &[u8],
dict: &Value,
context: &[&Value],
) -> ostrya_sign::Result<(Found, Vec<crate::sign::X509KeptCrl>)> {
let mut details = Vec::new();
let mut crls: Vec<crate::sign::X509KeptCrl> = Vec::new();
for verifier in jobs {
let outcome = verifier.verify_metadata(payload, Some(dict), context)?;
for crl in outcome.crls {
if !crls.contains(&crl) {
crls.push(crl);
}
}
if outcome.valid {
return Ok((Found::Valid, crls));
}
for info in outcome.signatures {
if details.len() < MAX_DETAILS
&& let Some(detail) = info.detail
{
details.push(detail);
}
}
}
Ok((Found::Untrusted(details), crls))
}
pub(crate) fn with_details(head: String, details: &[String]) -> String {
if details.is_empty() {
head
} else {
format!("{head}: {}", details.join("; "))
}
}
async fn check_axis(
subject: &str,
axis: &str,
verifiers: &[Arc<dyn Verifier>],
payload: &mut PoolCopy<'_>,
signatures: Option<&Value>,
crls: &CrlScope,
) -> Result<()> {
match examine_pooled(verifiers, payload, signatures, crls).await? {
Found::Valid => Ok(()),
Found::Untrusted(details) => Err(Error::Signature(with_details(
format!("{subject}: no {axis} signature is from a trusted key"),
&details,
))),
Found::Nothing => Err(Error::Signature(format!(
"{subject}: {axis} verification is enabled, but it carries no signature"
))),
}
}
pub(crate) enum KeySource<'a> {
Remote {
name: &'a str,
section: Option<&'a Section<'a, remote::Group>>,
#[cfg_attr(not(feature = "verify-gpg"), allow(dead_code))]
repo_keyring: bool,
system_keys: bool,
roots: &'a [&'a str],
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
check: X509Check,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
best_effort: bool,
},
Trust {
name: &'a str,
section: &'a Section<'a, crate::config::trust::Group>,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
check: X509Check,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
best_effort: bool,
},
}
impl KeySource<'_> {
fn verification_key(&self, engine: &str) -> Result<Option<String>> {
match self {
KeySource::Remote { section, .. } => match section {
Some(section) => section.verification_key(engine),
None => Ok(None),
},
KeySource::Trust { section, .. } => section.verification_key(engine),
}
}
fn verification_file(&self, engine: &str) -> Result<Option<KeyPath>> {
match self {
KeySource::Remote { section, .. } => match section {
Some(section) => section.verification_file(engine),
None => Ok(None),
},
KeySource::Trust { section, .. } => section.verification_file(engine),
}
}
fn system_store(&self) -> bool {
match self {
KeySource::Remote { system_keys, .. } => *system_keys,
KeySource::Trust { .. } => false,
}
}
fn roots(&self) -> Vec<String> {
match self {
KeySource::Remote { roots, .. } => roots.iter().map(|r| (*r).to_owned()).collect(),
KeySource::Trust { .. } => Vec::new(),
}
}
fn x509_source(&self) -> Result<Option<X509Source>> {
match self {
KeySource::Remote {
name,
section: Some(section),
check,
best_effort,
..
} => x509_source_of(section, format!("remote '{name}'"), *check, *best_effort),
KeySource::Remote { section: None, .. } => Ok(None),
KeySource::Trust {
section,
check,
best_effort,
..
} => x509_source_of(
section,
format!("[{}]", section.header()),
*check,
*best_effort,
),
}
}
}
fn x509_source_of<G: Group>(
section: &Section<'_, G>,
subject: String,
check: X509Check,
best_effort: bool,
) -> Result<Option<X509Source>>
where
remote::VerificationSpkiCaFile: Key<G, Value = ConfigPath>,
remote::VerificationSpkiIntermediatesFile: Key<G, Value = ConfigPath>,
remote::VerificationSpkiEku: Key<G, Output = Option<DottedOid>>,
remote::VerificationSpkiIdentity: Key<G, Output = Option<X509Identities>>,
remote::VerificationSpkiCrlFile: Key<G, Value = ConfigPath>,
remote::VerificationSpkiRevocation: Key<G, Output = crate::sign::X509Revocation>,
{
section.check_x509()?;
let revocation = match best_effort {
true => crate::sign::X509Revocation::BestEffort,
false => section.get::<remote::VerificationSpkiRevocation>()?,
};
let source = X509Source {
subject,
ca_file: section.key_path::<remote::VerificationSpkiCaFile>()?,
intermediates_file: section.key_path::<remote::VerificationSpkiIntermediatesFile>()?,
eku: section
.get::<remote::VerificationSpkiEku>()?
.map(|oid| oid.as_str().to_owned()),
identities: section
.get::<remote::VerificationSpkiIdentity>()?
.map(X509Identities::into_items),
crl_file: section.key_path::<remote::VerificationSpkiCrlFile>()?,
revocation,
check,
};
if source.ca_file.is_none() && source.identities.is_none() {
return Ok(None);
}
Ok(Some(source))
}
struct X509Source {
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
subject: String,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
ca_file: Option<KeyPath>,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
intermediates_file: Option<KeyPath>,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
eku: Option<String>,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
identities: Option<Vec<String>>,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
crl_file: Option<KeyPath>,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
revocation: crate::sign::X509Revocation,
#[cfg_attr(
not(all(feature = "sign-spki", feature = "sign-x509")),
allow(dead_code)
)]
check: X509Check,
}
#[derive(Default)]
pub(crate) struct Verifiers {
gpg: Option<Arc<dyn Verifier>>,
sign: Vec<(String, Option<Arc<dyn Verifier>>)>,
}
impl Verifiers {
async fn gpg(&mut self, repo: &Repo, source: &KeySource<'_>) -> Result<Arc<dyn Verifier>> {
match &self.gpg {
Some(verifier) => Ok(Arc::clone(verifier)),
None => {
let verifier = gpg_verifier(repo, source).await?;
self.gpg = Some(Arc::clone(&verifier));
Ok(verifier)
}
}
}
async fn sign(
&mut self,
repo: &Repo,
engine: &str,
source: &KeySource<'_>,
) -> Result<Option<Arc<dyn Verifier>>> {
if let Some((_, verifier)) = self.sign.iter().find(|(name, _)| name == engine) {
return Ok(verifier.clone());
}
let verifier = sign_verifier(repo, engine, source).await?;
self.sign.push((engine.to_owned(), verifier.clone()));
Ok(verifier)
}
}
pub(crate) async fn build_policy(
repo: &Repo,
source: &KeySource<'_>,
cache: &mut Verifiers,
gpg: bool,
sign: &SignVerify,
) -> Result<Policy> {
let mut policy = Policy::default();
if gpg {
policy.gpg = Some(cache.gpg(repo, source).await?);
}
let (names, required): (Vec<String>, bool) = match sign {
SignVerify::Off => (Vec::new(), false),
SignVerify::All => (
ALL_ENGINES.iter().map(|name| (*name).to_owned()).collect(),
false,
),
SignVerify::Engines(names) => (each_engine_once(names), true),
};
if !names.is_empty() {
let mut verifiers: Vec<Arc<dyn Verifier>> = Vec::with_capacity(names.len());
for name in &names {
match cache.sign(repo, name, source).await? {
Some(verifier) => verifiers.push(verifier),
None if required => {
return Err(Error::Signature(format!(
"no trusted key for signature engine '{name}'"
)));
}
None => {}
}
}
if verifiers.is_empty() {
return Err(Error::Signature(
"signature verification is enabled, but no engine of this build \
has a trusted key"
.into(),
));
}
policy.sign = Some(verifiers);
}
Ok(policy)
}
fn each_engine_once(names: &[String]) -> Vec<String> {
let mut kept: Vec<String> = Vec::with_capacity(names.len());
for name in names {
if !kept.iter().any(|held| held == name) {
kept.push(name.clone());
}
}
kept
}
#[cfg(feature = "verify-gpg")]
async fn gpg_verifier(repo: &Repo, source: &KeySource<'_>) -> Result<Arc<dyn Verifier>> {
let verifier = match source {
KeySource::Remote {
name,
section,
repo_keyring,
system_keys,
..
} => {
let keypath = match section {
Some(section) => section.gpgkeypath_paths()?,
None => Vec::new(),
};
let repo = repo.clone();
let remote = (*name).to_owned();
let read_keyring = *repo_keyring;
let global = *system_keys;
let verifier = ostrya_rt::unblock(move || {
let keyring = if read_keyring {
crate::gpg::read_remote_keyring(repo.root_dir(), repo.remotes_dir(), &remote)?
} else {
None
};
crate::gpg::remote_keyrings(keyring, &remote, Some(&repo), &keypath, global)
})
.await?;
if !global && verifier.is_empty() {
return Err(Error::Signature(format!(
"remote '{name}' asks for GPG verification, and its keyrings hold no \
certificate"
)));
}
verifier
}
KeySource::Trust { name, section, .. } => {
let keypath = section.gpgkeypath_paths()?;
let key = format!("[ex-ostrya trust \"{name}\"] gpgkeypath");
let repo = repo.clone();
ostrya_rt::unblock(move || crate::gpg::from_keypath(&key, &repo, &keypath)).await?
}
};
Ok(Arc::new(verifier))
}
#[cfg(not(feature = "verify-gpg"))]
async fn gpg_verifier(_repo: &Repo, source: &KeySource<'_>) -> Result<Arc<dyn Verifier>> {
match source {
KeySource::Remote { name, .. } => Err(Error::Unsupported(format!(
"remote '{name}' asks for GPG verification, which this build has no \
engine for; build with the verify-gpg feature or set gpg-verify=false"
))),
KeySource::Trust { name, .. } => Err(Error::Unsupported(format!(
"[ex-ostrya trust \"{name}\"] asks for GPG verification, which this \
build has no engine for; build with the verify-gpg feature"
))),
}
}
enum Engine {
Ed25519,
#[cfg(feature = "sign-spki")]
Spki,
}
async fn sign_verifier(
repo: &Repo,
engine: &str,
source: &KeySource<'_>,
) -> Result<Option<Arc<dyn Verifier>>> {
let kind = match engine {
"ed25519" => Engine::Ed25519,
#[cfg(feature = "sign-spki")]
"spki" => Engine::Spki,
_ => {
return Err(Error::Unsupported(format!(
"signature engine '{engine}' is not one this build verifies with"
)));
}
};
let Some(keys) = sign_keys(repo, engine, source).await? else {
return Ok(None);
};
build_verifier(kind, keys)
}
struct EngineKeys {
keys: SignKeys,
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
x509: Option<(crate::spki::X509Trust, X509Check)>,
}
fn build_verifier(kind: Engine, keys: EngineKeys) -> Result<Option<Arc<dyn Verifier>>> {
Ok(match kind {
Engine::Ed25519 => {
let verifier = Ed25519Verifier::from_sign_keys(keys.keys)?;
(!verifier.is_empty()).then(|| Arc::new(verifier) as Arc<dyn Verifier>)
}
#[cfg(feature = "sign-spki")]
Engine::Spki => {
let verifier = crate::spki::SpkiVerifier::from_sign_keys(keys.keys)?;
#[cfg(feature = "sign-x509")]
let verifier = match keys.x509 {
Some((trust, check)) => verifier.with_x509(trust, check),
None => verifier,
};
(!verifier.is_empty()).then(|| Arc::new(verifier) as Arc<dyn Verifier>)
}
})
}
async fn sign_keys(
repo: &Repo,
engine: &str,
source: &KeySource<'_>,
) -> Result<Option<EngineKeys>> {
let inline = source.verification_key(engine)?;
let path = source.verification_file(engine)?;
let system = source.system_store();
let x509 = if engine == "spki" {
source.x509_source()?
} else {
None
};
let roots = source.roots();
let engine = engine.to_owned();
let repo = repo.clone();
ostrya_rt::unblock(move || {
let roots: Vec<&Path> = roots.iter().map(Path::new).collect();
let keys = read_raw_keys(&engine, inline, path, Some(&repo), system, &roots)?;
let x509 = x509
.map(|x509| read_x509(x509, &repo, &roots, system))
.transpose()?;
if keys.trusted.is_empty() && x509.is_none() {
return Ok(None);
}
Ok(Some(engine_keys(keys, x509)))
})
.await
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
type ReadTrust = (crate::spki::X509Trust, X509Check);
#[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
type ReadTrust = std::convert::Infallible;
fn engine_keys(keys: SignKeys, x509: Option<ReadTrust>) -> EngineKeys {
#[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
let _ = x509;
EngineKeys {
keys,
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
x509,
}
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn read_x509(source: X509Source, repo: &Repo, roots: &[&Path], system: bool) -> Result<ReadTrust> {
let read = |path: KeyPath, what: &str| -> Result<Vec<Vec<u8>>> {
let (base, at, shown) = path.locate(Some(repo));
let subject = format!("the 'spki' {what} file '{}'", shown.display());
let bytes = read_key_file_at(base, &at, &subject)?;
Ok(crate::spki::x509_certificates(&bytes, &subject)?)
};
let mut anchors = match source.ca_file {
Some(path) => read(path, "CA")?,
None => Vec::new(),
};
if source.identities.is_some() {
anchors.extend(crate::sign::load_x509_anchors_from(roots)?);
}
let identities = source.identities.unwrap_or_default();
if anchors.is_empty() {
return Err(Error::Signature(format!(
"{} sets verification-spki-identity, and no anchor source holds an anchor: \
verification-spki-ca-file and the trusted.x509 files of the system key store \
hold none",
source.subject
)));
}
let mut trust = crate::spki::X509Trust::new(anchors, identities)?;
if let Some(path) = source.intermediates_file {
trust = trust.with_intermediates(read(path, "intermediates")?)?;
}
if let Some(eku) = &source.eku {
trust = trust.with_eku(eku)?;
}
if let Some(path) = source.crl_file {
let (base, at, shown) = path.locate(Some(repo));
let subject = format!("the 'spki' CRL file '{}'", shown.display());
let bytes = read_capped_file_at(base, &at, &subject, crate::sign::MAX_X509_CRL_FILE)?;
let crls = crate::spki::x509_crls(&bytes, &subject)?;
trust = crate::sign::with_file_crls(trust, crls, &subject)?;
}
trust = crate::sign::load_x509_crls_from(trust, roots)?.with_revocation(source.revocation);
if !system {
trust = trust.with_revoked(crate::sign::load_revoked_keys_from(roots, "spki")?)?;
}
Ok((trust, source.check))
}
#[cfg(not(all(feature = "sign-spki", feature = "sign-x509")))]
fn read_x509(
source: X509Source,
_repo: &Repo,
_roots: &[&Path],
_system: bool,
) -> Result<ReadTrust> {
Err(Error::Unsupported(format!(
"{} sets an X.509 trust of the spki engine, which this build has no path check \
for; build with the sign-x509 feature",
source.subject
)))
}
#[cfg(test)]
fn read_sign_keys(
engine: &str,
inline: Option<String>,
path: Option<KeyPath>,
repo: Option<&Repo>,
system: bool,
) -> Result<Option<SignKeys>> {
let roots: Vec<&Path> = SYSTEM_KEY_ROOTS.iter().map(Path::new).collect();
let keys = read_raw_keys(engine, inline, path, repo, system, &roots)?;
Ok((!keys.trusted.is_empty()).then_some(keys))
}
fn read_raw_keys(
engine: &str,
inline: Option<String>,
path: Option<KeyPath>,
repo: Option<&Repo>,
system: bool,
roots: &[&Path],
) -> Result<SignKeys> {
let mut keys = SignKeys::default();
if let Some(mut inline) = inline {
if engine == "spki" {
inline.retain(|c| !c.is_ascii_whitespace());
}
keys.trusted.push(base64::decode(inline.trim())?);
}
if let Some(path) = path {
let (base, at, shown) = path.locate(repo);
keys.trusted
.extend(read_verification_file(engine, base, &at, &shown)?);
}
if system {
let store = load_sign_keys_from(roots, engine)?;
keys.trusted.extend(store.trusted);
keys.revoked.extend(store.revoked);
}
Ok(keys)
}
pub(crate) fn read_key_file_at(base: BorrowedFd<'_>, at: &Path, subject: &str) -> Result<Vec<u8>> {
read_capped_file_at(base, at, subject, MAX_KEY_FILE)
}
pub(crate) fn read_capped_file_at(
base: BorrowedFd<'_>,
at: &Path,
subject: &str,
ceiling: u64,
) -> Result<Vec<u8>> {
let refuse = |what: String| Err(Error::Signature(format!("{subject} {what}")));
let fd = match open_named(base, at, Named::File) {
Ok(fd) => fd,
Err(FsError::Absent { .. }) => return refuse("does not exist".into()),
Err(FsError::Invalid {
reason: Reason::NotRegular(_),
..
}) => return refuse("is not a regular file".into()),
Err(
err @ (FsError::Io(_)
| FsError::Invalid {
reason: Reason::NotDirectory,
..
}),
) => return refuse(format!("cannot be opened: {}", io_of(err))),
Err(other) => return Err(other.into()),
};
Ok(read_key_source(std::fs::File::from(fd), subject, ceiling)?)
}
fn read_verification_file(
engine: &str,
base: BorrowedFd<'_>,
at: &Path,
shown: &Path,
) -> Result<Vec<Vec<u8>>> {
let subject = format!("the '{engine}' key file '{}'", shown.display());
let bytes = read_key_file_at(base, at, &subject)?;
#[cfg(feature = "sign-spki")]
if engine == "spki" {
return Ok(crate::spki::spki_public_keys(&bytes, &subject)?);
}
let mut keys = Vec::new();
for line in key_text(bytes, &subject)?.lines() {
let line = line.trim();
if !line.is_empty() {
keys.push(base64::decode(line)?);
}
}
Ok(keys)
}
#[cfg(test)]
mod tests {
use rustix::fs::{FileType, Mode};
use super::*;
fn with_repo<T>(f: impl AsyncFnOnce(&Repo) -> T) -> T {
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-repo-{}-{}",
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, crate::CreateOptions::new(crate::RepoMode::Archive))
.await
.unwrap();
f(&repo).await
});
std::fs::remove_dir_all(&dir).unwrap();
outcome
}
fn key_file(engine: &str, path: &Path) -> Result<Vec<Vec<u8>>> {
read_verification_file(engine, rustix::fs::CWD, path, path)
}
const NO_SECTION: KeySource<'static> = KeySource::Remote {
name: "origin",
section: None,
repo_keyring: true,
system_keys: true,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort: false,
};
const SECRET_B64: &str =
"o74ME/dmhvDeYf64dDJQY8kX2piK0M/nyIRWVi30i6DCOzRsHVcvgYToz6zOb5OvK/v8nH6KfLR3dfdsn6ZSyQ==";
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
const PAYLOAD: &[u8] = b"the commit bytes";
#[cfg(feature = "sign-spki")]
const SPKI_SECRET_A: &str = concat!(
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg2L708EsnnzHER0SYasMNIUcG",
"v63QapC/3kVsoPerzKGhRANCAATxfzfHKUPeJtyLTGMUoxHhvBS1NT9guWhUQPGiZRLZIcB8Wc3",
"csdVU1iOiTRmbZGKJTtekOdEAbVRrx5HxIpst",
);
#[cfg(feature = "sign-spki")]
const SPKI_SECRET_B: &str = concat!(
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgU5tYPz/hTTxfsSTPOxD/H9U+",
"IkBj5qWV4/H3D1NBfRChRANCAAQPyTr9rh2d6WiYOi3oxNiE3ppTP2g5JP2xX9D7rEKnzixp",
"MqVuqA9XnzQr5GlCYd71m/D7BnYIqS4MytNawYrR",
);
fn ed25519_signed(secret: &str) -> Value {
use crate::sign::{Ed25519Signer, Signer, append_signature};
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
}
#[test]
fn switches_resolve_the_override_first() {
assert!(switch(Some(true), || Ok(false)).unwrap());
assert!(!switch(Some(false), || Ok(true)).unwrap());
assert!(switch(None, || Ok(true)).unwrap());
assert_eq!(
engines(Some(true), || Ok(SignVerify::Off)).unwrap(),
SignVerify::All
);
assert_eq!(
engines(Some(false), || Ok(SignVerify::All)).unwrap(),
SignVerify::Off
);
assert_eq!(
engines(None, || Ok(SignVerify::Engines(vec!["ed25519".to_owned()]))).unwrap(),
SignVerify::Engines(vec!["ed25519".to_owned()])
);
}
#[test]
fn explicit_keys_need_a_verifier() {
let err = TrustedKeys::new(Vec::new()).unwrap_err();
assert!(matches!(err, Error::InvalidFormat(_)), "{err}");
let verifier =
Ed25519Verifier::new([base64::decode(PUBLIC_B64).unwrap()], Vec::<Vec<u8>>::new())
.unwrap();
let keys = TrustedKeys::new(vec![Arc::new(verifier)]).unwrap();
ostrya_rt::block_on(keys.policy.check(
"commit",
PAYLOAD,
Some(&ed25519_signed(SECRET_B64)),
&CrlScope::default(),
))
.unwrap();
}
#[test]
fn a_trust_with_keys_checks_signatures() {
let keys = || {
let verifier =
Ed25519Verifier::new([base64::decode(PUBLIC_B64).unwrap()], Vec::<Vec<u8>>::new())
.unwrap();
TrustedKeys::new(vec![Arc::new(verifier)]).unwrap()
};
assert!(!PullTrust::unverified().checks_signatures());
assert!(PullTrust::commits(keys()).checks_signatures());
assert!(
PullTrust::unverified()
.with_summary(keys())
.checks_signatures()
);
assert!(
PullTrust::commits(keys())
.with_summary(keys())
.checks_signatures()
);
}
#[test]
fn each_axis_verifies_on_the_blocking_pool() {
use crate::sign::append_signature;
use crate::verify::trust::tests::ThreadRecorder;
let gpg = ThreadRecorder::new("ostree.gpgsigs");
let sign = ThreadRecorder::new("ostree.sign.ed25519");
let policy = Policy::from_axes(
Some(Arc::new(gpg.clone())),
Some(vec![Arc::new(sign.clone())]),
);
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, "ostree.gpgsigs", vec![1; 8]).unwrap();
append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict), &CrlScope::default()))
.unwrap();
gpg.assert_one_foreign_call();
sign.assert_one_foreign_call();
let (gpg, sign) = (gpg.payloads(), sign.payloads());
assert_eq!(gpg, sign);
assert_eq!(gpg[0].1, PAYLOAD);
assert_ne!(gpg[0].0, PAYLOAD.as_ptr() as usize);
}
#[test]
fn a_shared_payload_reaches_each_axis_with_no_copy() {
use crate::sign::append_signature;
use crate::verify::trust::tests::ThreadRecorder;
let gpg = ThreadRecorder::new("ostree.gpgsigs");
let sign = ThreadRecorder::new("ostree.sign.ed25519");
let policy = Policy::from_axes(
Some(Arc::new(gpg.clone())),
Some(vec![Arc::new(sign.clone())]),
);
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, "ostree.gpgsigs", vec![1; 8]).unwrap();
append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
let payload = Arc::new(PAYLOAD.to_vec());
ostrya_rt::block_on(policy.check("commit", &payload, Some(&dict), &CrlScope::default()))
.unwrap();
gpg.assert_no_copy_of(&payload);
sign.assert_no_copy_of(&payload);
}
#[test]
fn an_axis_stops_at_the_first_valid_signature() {
use crate::sign::append_signature;
use crate::verify::trust::tests::ThreadRecorder;
let first = ThreadRecorder::new("ostree.sign.ed25519");
let second = ThreadRecorder::new("ostree.sign.spki");
let policy = Policy::from_axes(
None,
Some(vec![Arc::new(first.clone()), Arc::new(second.clone())]),
);
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
append_signature(&mut dict, "ostree.sign.spki", vec![9; 64]).unwrap();
ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict), &CrlScope::default()))
.unwrap();
first.assert_one_foreign_call();
assert!(second.threads().is_empty());
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[derive(Default)]
struct Keeping {
dict: std::sync::Mutex<Option<Value>>,
context: std::sync::Mutex<Vec<Value>>,
crls: Vec<crate::sign::X509KeptCrl>,
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
impl Verifier for Keeping {
fn metadata_key(&self) -> &str {
SPKI_METADATA_KEY
}
fn verify(
&self,
_data: &[u8],
_signatures: &[Vec<u8>],
) -> ostrya_sign::Result<crate::sign::VerifyOutcome> {
unreachable!("the check calls verify_metadata")
}
fn verify_metadata(
&self,
_data: &[u8],
metadata: Option<&Value>,
context: &[&Value],
) -> ostrya_sign::Result<crate::sign::VerifyOutcome> {
*self.dict.lock().unwrap() = metadata.cloned();
*self.context.lock().unwrap() = context.iter().map(|d| (*d).clone()).collect();
let mut outcome = crate::sign::VerifyOutcome::default();
outcome.crls = self.crls.clone();
Ok(outcome)
}
fn x509_crl_cache_dirs(&self, _metadata: Option<&Value>) -> Vec<String> {
self.crls
.iter()
.filter_map(|crl| Some(ostrya_sign::x509_crl_cache_name(crl)?.0))
.collect()
}
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn chained_dict(chains: Vec<Value>, crls: Vec<Vec<u8>>) -> Value {
use crate::sign::{X509_CHAINS_KEY, X509_CRLS_KEY, append_signature};
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, SPKI_METADATA_KEY, vec![9; 64]).unwrap();
append_signature(&mut dict, SPKI_METADATA_KEY, vec![8; 64]).unwrap();
let Value::Array(entries) = &mut dict else {
unreachable!()
};
if !chains.is_empty() {
entries.push(Value::Tuple(vec![
Value::Str(X509_CHAINS_KEY.into()),
Value::variant(
Type::array(Type::array(Type::array(Type::Byte))),
Value::Array(chains),
),
]));
}
entries.push(Value::Tuple(vec![
Value::Str(X509_CRLS_KEY.into()),
Value::variant(
Type::array(Type::array(Type::Byte)),
Value::Array(crls.into_iter().map(Value::Bytes).collect()),
),
]));
dict
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
fn fixture_crl(name: &str) -> Vec<u8> {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/x509")
.join(name);
crate::spki::x509_crls(&std::fs::read(path).unwrap(), name)
.unwrap()
.remove(0)
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn the_pool_job_reads_and_writes_the_crl_cache_for_a_chain() {
let newer = crate::sign::X509KeptCrl {
der: fixture_crl("intermediate-2.crl.pem"),
signer: b"the key of the intermediate".to_vec(),
};
let dirs = [ostrya_sign::x509_crl_cache_name(&newer).unwrap().0];
let newer_der = newer.der.clone();
let older = fixture_crl("intermediate.crl.pem");
let root = fixture_crl("root.crl.pem");
with_repo(async |repo| {
let keeping = Arc::new(Keeping {
crls: vec![newer.clone()],
..Keeping::default()
});
let policy = Policy::from_axes(None, Some(vec![keeping.clone()]));
let chain = Value::Array(vec![Value::Bytes(vec![1, 2])]);
let dict = chained_dict(vec![chain], vec![older.clone()]);
let context = Arc::new(crate::sign::crl_cache::dicts(vec![root.clone()]).remove(0));
let reading = CrlScope::reading(repo).with_context(Arc::clone(&context));
let _ = policy.check("commit", PAYLOAD, Some(&dict), &reading).await;
let kept = keeping.dict.lock().unwrap().take().unwrap();
assert_eq!(ostrya_sign::x509_crls_in(&kept), [&older[..]]);
assert_eq!(*keeping.context.lock().unwrap(), [(*context).clone()]);
assert!(
crate::sign::crl_cache::read(repo.root_dir(), &dirs)
.unwrap()
.is_empty()
);
let err = policy
.check("commit", PAYLOAD, Some(&dict), &CrlScope::caching(repo))
.await
.unwrap_err();
assert!(matches!(err, Error::Signature(_)), "{err}");
assert_eq!(
crate::sign::crl_cache::read(repo.root_dir(), &dirs).unwrap(),
std::slice::from_ref(&newer_der)
);
let _ = policy.check("commit", PAYLOAD, Some(&dict), &reading).await;
assert_eq!(
*keeping.context.lock().unwrap(),
[
crate::sign::crl_cache::dicts(vec![newer_der.clone()]).remove(0),
(*context).clone()
]
);
let unnamed = Arc::new(Keeping::default());
let unnamed_policy = Policy::from_axes(None, Some(vec![unnamed.clone()]));
let _ = unnamed_policy
.check("commit", PAYLOAD, Some(&dict), &reading)
.await;
assert_eq!(*unnamed.context.lock().unwrap(), [(*context).clone()]);
let plain = chained_dict(Vec::new(), vec![older.clone()]);
let _ = policy
.check("commit", PAYLOAD, Some(&plain), &reading)
.await;
let kept = keeping.dict.lock().unwrap().take().unwrap();
assert!(ostrya_sign::x509_crls_in(&kept).is_empty());
assert!(keeping.context.lock().unwrap().is_empty());
});
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
#[test]
fn the_dict_of_the_pool_job_holds_the_blobs_and_the_chains_it_reads() {
use crate::sign::{X509_CHAINS_KEY, append_signature};
let keeping = Arc::new(Keeping::default());
let policy = Policy::from_axes(None, Some(vec![keeping.clone()]));
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, SPKI_METADATA_KEY, vec![9; 64]).unwrap();
append_signature(&mut dict, SPKI_METADATA_KEY, vec![8; 64]).unwrap();
append_signature(&mut dict, "ostree.sign.other", vec![7; 64]).unwrap();
let chain = |n: usize| Value::Array(vec![Value::Bytes(vec![1, 2]); n]);
let Value::Array(entries) = &mut dict else {
unreachable!()
};
entries.push(Value::Tuple(vec![
Value::Str(X509_CHAINS_KEY.into()),
Value::variant(
Type::array(Type::array(Type::array(Type::Byte))),
Value::Array(vec![chain(1), chain(9), chain(2)]),
),
]));
let _ =
ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict), &CrlScope::default()));
let kept = keeping.dict.lock().unwrap().take().unwrap();
assert_eq!(
ostrya_sign::signatures_in(&kept, SPKI_METADATA_KEY).unwrap(),
[&[9; 64][..], &[8; 64][..]]
);
assert!(kept.dict_get("ostree.sign.other").is_none());
let (ty, _) = kept
.dict_get(SPKI_METADATA_KEY)
.unwrap()
.as_variant()
.unwrap();
assert_eq!(ty.signature(), "aay");
let chains = ostrya_sign::x509_chains_in(&kept);
assert_eq!(chains.len(), 2);
assert_eq!(chains, ostrya_sign::x509_chains_in(&dict));
}
struct Detailing {
key: &'static str,
}
impl Verifier for Detailing {
fn metadata_key(&self) -> &str {
self.key
}
fn verify(
&self,
_data: &[u8],
signatures: &[Vec<u8>],
) -> ostrya_sign::Result<crate::sign::VerifyOutcome> {
let mut outcome = crate::sign::VerifyOutcome::default();
for n in 0..signatures.len() {
let mut info = crate::sign::SignatureInfo::default();
info.key_missing = true;
info.detail = Some(format!("{} {n}", self.key));
outcome.signatures.push(info);
}
Ok(outcome)
}
}
#[test]
fn the_refusal_of_an_axis_holds_at_most_four_details() {
use crate::sign::append_signature;
let policy = Policy::from_axes(
None,
Some(vec![
Arc::new(Detailing {
key: "ostree.sign.ed25519",
}),
Arc::new(Detailing {
key: "ostree.sign.spki",
}),
]),
);
let mut dict = Value::Array(Vec::new());
for blob in 0..3 {
append_signature(&mut dict, "ostree.sign.ed25519", vec![blob]).unwrap();
append_signature(&mut dict, "ostree.sign.spki", vec![blob]).unwrap();
}
let err = ostrya_rt::block_on(policy.check(
"commit c",
PAYLOAD,
Some(&dict),
&CrlScope::default(),
))
.unwrap_err();
assert_eq!(
err.to_string(),
"signature: commit c: no sign-api signature is from a trusted key: \
ostree.sign.ed25519 0; ostree.sign.ed25519 1; ostree.sign.ed25519 2; \
ostree.sign.spki 0"
);
let policy = Policy::from_axes(
None,
Some(vec![Arc::new(
Ed25519Verifier::new([base64::decode(PUBLIC_B64).unwrap()], Vec::<&[u8]>::new())
.unwrap(),
)]),
);
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
let err = ostrya_rt::block_on(policy.check(
"commit c",
PAYLOAD,
Some(&dict),
&CrlScope::default(),
))
.unwrap_err();
assert_eq!(
err.to_string(),
"signature: commit c: no sign-api signature is from a trusted key"
);
}
#[test]
fn an_axis_with_no_blob_calls_no_verifier() {
use crate::verify::trust::tests::{ThreadRecorder, dict_with};
let first = ThreadRecorder::new("ostree.sign.ed25519");
let second = ThreadRecorder::new("ostree.sign.spki");
let policy = Policy::from_axes(
None,
Some(vec![Arc::new(first.clone()), Arc::new(second.clone())]),
);
let dict = dict_with("ostree.sign.other", vec![7; 64]);
let err =
ostrya_rt::block_on(policy.check("commit", PAYLOAD, Some(&dict), &CrlScope::default()))
.unwrap_err();
assert!(
err.to_string()
.contains("sign-api verification is enabled, but it carries no signature"),
"{err}"
);
assert!(first.threads().is_empty());
assert!(second.threads().is_empty());
}
#[test]
fn the_verifiers_of_an_axis_run_in_one_call() {
use std::task::Poll;
use std::time::{Duration, Instant};
use crate::sign::append_signature;
use crate::verify::trust::tests::ThreadRecorder;
let rejecting = ThreadRecorder::rejecting("ostree.sign.ed25519");
let accepting = ThreadRecorder::new("ostree.sign.spki");
let policy = Policy::from_axes(
None,
Some(vec![
Arc::new(rejecting.clone()),
Arc::new(accepting.clone()),
]),
);
let mut dict = Value::Array(Vec::new());
append_signature(&mut dict, "ostree.sign.ed25519", vec![7; 64]).unwrap();
append_signature(&mut dict, "ostree.sign.spki", vec![9; 64]).unwrap();
let crls = CrlScope::default();
ostrya_rt::block_on(async {
let mut check = std::pin::pin!(policy.check("commit", PAYLOAD, Some(&dict), &crls));
let first = std::future::poll_fn(|cx| Poll::Ready(check.as_mut().poll(cx))).await;
match first {
Poll::Ready(result) => {
result.unwrap();
assert_eq!(accepting.threads().len(), 1);
}
Poll::Pending => {
let deadline = Instant::now() + Duration::from_secs(5);
while accepting.threads().is_empty() && Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(1));
}
assert_eq!(accepting.threads().len(), 1);
check.await.unwrap();
}
}
});
rejecting.assert_one_foreign_call();
accepting.assert_one_foreign_call();
}
#[test]
fn explicit_keys_refuse_the_dummy_engine() {
let dummy = || -> Arc<dyn Verifier> { Arc::new(crate::sign::DummyVerifier::new([b"k"])) };
let ed25519: Arc<dyn Verifier> = Arc::new(
Ed25519Verifier::new([base64::decode(PUBLIC_B64).unwrap()], Vec::<Vec<u8>>::new())
.unwrap(),
);
for sign in [vec![dummy()], vec![ed25519, dummy()]] {
let err = TrustedKeys::new(sign).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m.contains("dummy verifier")),
"{err}"
);
}
}
#[test]
fn all_engines_excludes_the_dummy_engine() {
assert!(ALL_ENGINES.contains(&"ed25519"));
assert!(!ALL_ENGINES.contains(&"dummy"));
}
#[test]
fn unknown_engines_and_empty_key_sets_are_told_apart() {
with_repo(async |repo| {
let Err(err) = sign_verifier(repo, "nosuchengine", &NO_SECTION).await else {
panic!("an engine this build has no verifier for is refused");
};
assert!(
err.to_string().contains("not one this build verifies with"),
"{err}"
);
if crate::sign::load_sign_keys("ed25519")
.unwrap()
.trusted
.is_empty()
{
assert!(
sign_verifier(repo, "ed25519", &NO_SECTION)
.await
.unwrap()
.is_none()
);
}
});
}
#[test]
fn the_dummy_engine_is_refused_by_name() {
with_repo(async |repo| {
let Err(err) = sign_verifier(repo, "dummy", &NO_SECTION).await else {
panic!("a configuration naming the dummy engine is refused");
};
assert!(
err.to_string().contains("not one this build verifies with"),
"{err}"
);
});
}
#[test]
fn a_revoked_key_leaves_the_engine_without_a_key() {
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
let key = base64::decode(PUBLIC_B64).unwrap();
let held = SignKeys {
trusted: vec![key.clone()],
revoked: Vec::new(),
};
assert!(
build_verifier(Engine::Ed25519, engine_keys(held, None))
.unwrap()
.is_some(),
"a key no source revokes builds a verifier"
);
let revoked = SignKeys {
trusted: vec![key.clone()],
revoked: vec![key],
};
assert!(
build_verifier(Engine::Ed25519, engine_keys(revoked, None))
.unwrap()
.is_none(),
"the engine's only key is revoked, so the engine has no key"
);
}
#[cfg(feature = "sign-spki")]
#[test]
fn the_x509_keys_of_a_remote_need_the_path_check() {
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-x509-build-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let ca = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/fixtures/x509/root.pem");
let config = crate::config::RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=archive\n\
[remote \"origin\"]\nurl=http://localhost/\nsign-verify=spki\n\
verification-spki-ca-file={}\nverification-spki-identity=*\n",
ca.display()
))
.unwrap();
let section = config.section::<remote::Group>("origin");
let roots = [dir.to_str().unwrap()];
let result = ostrya_rt::block_on(async {
let repo = Repo::create(
&dir.join("repo"),
crate::CreateOptions::new(crate::RepoMode::Archive),
)
.await
.unwrap();
let source = KeySource::Remote {
name: "origin",
section: section.as_ref(),
repo_keyring: true,
system_keys: true,
roots: &roots,
check: X509Check::Admission,
best_effort: false,
};
let sign = SignVerify::Engines(vec!["spki".to_owned()]);
build_policy(&repo, &source, &mut Verifiers::default(), false, &sign)
.await
.map(|policy| policy.sign_axis().map(<[_]>::len))
});
std::fs::remove_dir_all(&dir).unwrap();
#[cfg(feature = "sign-x509")]
assert_eq!(result.unwrap(), Some(1));
#[cfg(not(feature = "sign-x509"))]
assert!(
matches!(&result, Err(Error::Unsupported(m))
if m == "remote 'origin' sets an X.509 trust of the spki engine, which this \
build has no path check for; build with the sign-x509 feature"),
"{result:?}"
);
}
#[test]
fn a_repeated_engine_name_builds_one_verifier() {
use crate::{CreateOptions, RepoMode};
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
let config = crate::config::RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=archive\n\
[remote \"origin\"]\nurl=http://localhost/\n\
sign-verify=ed25519,ed25519\nverification-ed25519-key={PUBLIC_B64}\n"
))
.unwrap();
let section = config.section::<remote::Group>("origin");
let sign = section
.as_ref()
.unwrap()
.get::<remote::SignVerify>()
.unwrap();
assert_eq!(
sign,
SignVerify::Engines(vec!["ed25519".to_owned(), "ed25519".to_owned()]),
"the configured value names the engine twice"
);
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-repeat-{}-{}",
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 cache = Verifiers::default();
let source = KeySource::Remote {
name: "origin",
section: section.as_ref(),
repo_keyring: true,
system_keys: true,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort: false,
};
build_policy(&repo, &source, &mut cache, false, &sign).await
});
std::fs::remove_dir_all(&dir).unwrap();
let policy = outcome.expect("the configured key builds a policy");
let verifiers = policy.sign.expect("the sign-api axis applies");
assert_eq!(verifiers.len(), 1, "the repeated name holds one verifier");
}
#[test]
fn an_engine_is_read_once_for_both_targets() {
const PUBLIC_B64: &str = "wjs0bB1XL4GE6M+szm+Tryv7/Jx+iny0d3X3bJ+mUsk=";
let config = crate::config::RepoConfig::parse(&format!(
"[core]\nrepo_version=1\nmode=archive\n\
[remote \"origin\"]\nurl=http://localhost/\n\
verification-ed25519-key={PUBLIC_B64}\n"
))
.unwrap();
let section = config.section::<remote::Group>("origin");
with_repo(async |repo| {
let source = KeySource::Remote {
name: "origin",
section: section.as_ref(),
repo_keyring: true,
system_keys: true,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort: false,
};
let mut cache = Verifiers::default();
let first = cache.sign(repo, "ed25519", &source).await.unwrap();
let second = cache.sign(repo, "ed25519", &source).await.unwrap();
let (Some(first), Some(second)) = (first, second) else {
panic!("the configured key builds a verifier");
};
assert!(Arc::ptr_eq(&first, &second));
assert_eq!(cache.sign.len(), 1);
});
}
#[test]
fn a_trust_group_and_the_remote_share_no_verifier() {
use crate::{CreateOptions, RepoMode};
const OTHER_SECRET_B64: &str = "5ILWxT+l9G/u3h0BptRpmSi35C9uog7YDdD+Fp1Xk+Hz52p0NlYh6xBA73kJEJKhKbbnjcE0rsWA5XA/K5Sq5Q==";
const OTHER_PUBLIC_B64: &str = "8+dqdDZWIesQQO95CRCSoSm2543BNK7FgOVwPyuUquU=";
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-trust-split-{}-{}",
std::process::id(),
crate::write::unique()
));
let root = dir.join("repo");
std::fs::create_dir_all(&dir).unwrap();
let group_key = ed25519_signed(SECRET_B64);
let remote_key = ed25519_signed(OTHER_SECRET_B64);
let outcome = ostrya_rt::block_on(async {
drop(
Repo::create(&root, CreateOptions::new(RepoMode::Archive))
.await
.unwrap(),
);
let config = root.join("config");
let mut text = std::fs::read_to_string(&config).unwrap();
text.push_str(&format!(
"\n[remote \"origin\"]\nurl=http://localhost/\ngpg-verify=false\ntrust=t\n\
sign-verify-summary=ed25519\nverification-ed25519-key={OTHER_PUBLIC_B64}\n\
[ex-ostrya trust \"t\"]\nsign-verify=ed25519\n\
verification-ed25519-key={PUBLIC_B64}\n"
));
std::fs::write(&config, text).unwrap();
let repo = Repo::open(&root).await.unwrap();
let trust = PullTrust::from_remote(&repo, "origin", &PullVerify::default())
.await
.unwrap();
let (commit, summary) = trust.into_policies();
(
commit
.check("commit", PAYLOAD, Some(&group_key), &CrlScope::default())
.await,
commit
.check("commit", PAYLOAD, Some(&remote_key), &CrlScope::default())
.await,
summary
.check("summary", PAYLOAD, Some(&remote_key), &CrlScope::default())
.await,
summary
.check("summary", PAYLOAD, Some(&group_key), &CrlScope::default())
.await,
)
});
std::fs::remove_dir_all(&dir).unwrap();
let (commit_a, commit_b, summary_b, summary_a) = outcome;
commit_a.expect("the commit policy trusts the key of the group");
let err = commit_b.expect_err("the commit policy does not trust the remote key");
assert!(err.to_string().contains("is from a trusted key"), "{err}");
summary_b.expect("the summary policy trusts the key of the remote");
let err = summary_a.expect_err("the summary policy does not trust the group key");
assert!(err.to_string().contains("is from a trusted key"), "{err}");
}
#[test]
fn a_relative_key_file_is_relative_to_the_repository_root() {
let keyfile = ostrya_core::KeyFile::parse(
"[remote \"o\"]\nverification-ed25519-file=keys/o.ed25519\n",
)
.unwrap();
let section = Section::<remote::Group>::from_parts(&keyfile, "remote \"o\"", None);
let source = KeySource::Remote {
name: "o",
section: Some(§ion),
repo_keyring: false,
system_keys: false,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort: false,
};
let (absent, present) = with_repo(async |repo| {
let absent = sign_keys(repo, "ed25519", &source).await;
std::fs::create_dir(repo.path().join("keys")).unwrap();
std::fs::write(
repo.path().join("keys/o.ed25519"),
format!("{PUBLIC_B64}\n"),
)
.unwrap();
(absent, sign_keys(repo, "ed25519", &source).await)
});
assert!(
matches!(&absent, Err(Error::Signature(m))
if m.starts_with("the 'ed25519' key file 'keys/o.ed25519' does not exist")),
"{:?}",
absent.err()
);
let keys = present.unwrap().expect("the key file holds a key");
assert_eq!(keys.keys.trusted, [base64::decode(PUBLIC_B64).unwrap()]);
}
#[test]
fn an_oversized_key_file_is_refused_by_name() {
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyfile-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("keys.ed25519");
std::fs::File::create(&path)
.unwrap()
.set_len(MAX_KEY_FILE + 1)
.unwrap();
let outcome = key_file("ed25519", &path);
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a key file over the ceiling has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("keys.ed25519") && m.contains("ceiling")),
"{err}"
);
}
#[cfg(feature = "verify-gpg")]
#[test]
fn an_oversized_repository_keyring_is_refused_by_name() {
use crate::{CreateOptions, RepoMode};
use ostrya_sign::MAX_KEYRING;
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyring-{}-{}",
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();
std::fs::File::create(root.join("origin.trustedkeys.gpg"))
.unwrap()
.set_len(MAX_KEYRING + 1)
.unwrap();
gpg_verifier(&repo, &NO_SECTION).await.map(|_| ())
});
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a keyring over the ceiling has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")
&& m.contains("ceiling")),
"{err}"
);
}
#[cfg(feature = "verify-gpg")]
#[test]
fn a_fifo_repository_keyring_is_refused_by_name() {
use crate::{CreateOptions, RepoMode};
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyfifo-repo-{}-{}",
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();
rustix::fs::mknodat(
rustix::fs::CWD,
root.join("origin.trustedkeys.gpg"),
FileType::Fifo,
Mode::from_raw_mode(0o600),
0,
)
.unwrap();
gpg_verifier(&repo, &NO_SECTION).await.map(|_| ())
});
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a fifo at a keyring's name has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")
&& m.contains("regular file")),
"{err}"
);
}
#[test]
fn a_fifo_key_file_is_refused_by_name() {
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-keyfifo-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("keys.ed25519");
rustix::fs::mknodat(
rustix::fs::CWD,
&path,
FileType::Fifo,
Mode::from_raw_mode(0o600),
0,
)
.unwrap();
let outcome = key_file("ed25519", &path);
std::fs::remove_dir_all(&dir).unwrap();
let err = outcome.expect_err("a fifo at a key file's name has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("keys.ed25519")
&& m.contains("regular file")),
"{err}"
);
}
#[test]
fn an_empty_key_file_of_a_remotes_file_is_absent_as_in_config() {
use crate::config::tests::repos_with_remotes_file;
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-emptyfile-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let section = |name: &str| {
format!("[remote \"{name}\"]\nurl=http://h/\nverification-ed25519-file=\n")
};
let repos = repos_with_remotes_file(&dir.join("repo"), §ion("c"), §ion("o"));
let mut results = Vec::new();
for repo in &repos {
let read = |name: &str| {
let remote = repo.config().section::<remote::Group>(name).unwrap();
let path = remote
.key_path::<remote::VerificationEd25519File>()
.unwrap();
read_sign_keys("ed25519", None, path, Some(repo), false).map(|_| ())
};
results.push((read("c"), read("o"), repo.remotes_dir().cloned()));
}
drop(repos);
std::fs::remove_dir_all(&dir).unwrap();
let expected = "the 'ed25519' key file '' does not exist";
for (in_config, in_file, remotes_dir) in results {
assert!(
matches!(&in_config, Err(Error::Signature(m)) if m.starts_with(expected)),
"{in_config:?}"
);
assert_eq!(
in_file.map_err(|e| e.to_string()),
in_config.map_err(|e| e.to_string()),
"{remotes_dir:?}"
);
}
}
#[cfg(feature = "sign-spki")]
#[test]
fn an_spki_key_file_holds_pem_blocks() {
const SPKI_B64: &str = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE8X83xylD3ibci0xjFKMR4bwUtTU/\
YLloVEDxomUS2SHAfFnN3LHVVNYjok0Zm2RiiU7XpDnRAG1Ua8eR8SKbLQ==";
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-spkifile-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let write = |name: &str, text: &str| {
let path = dir.join(name);
std::fs::write(&path, text).unwrap();
path.display().to_string()
};
let pem = write(
"pem",
&format!(
"-----BEGIN PUBLIC KEY-----\n{}\n{}\n-----END PUBLIC KEY-----\n",
&SPKI_B64[..64],
&SPKI_B64[64..]
),
);
let lines = write("lines", &format!("{SPKI_B64}\n"));
let empty = write("empty", "");
let read =
|path: &str| read_sign_keys("spki", None, Some(KeyPath::caller(path)), None, false);
let by_pem = read(&pem);
let by_lines = read(&lines);
let by_empty = read(&empty);
std::fs::remove_dir_all(&dir).unwrap();
let keys = by_pem.unwrap().expect("the PEM file holds a key");
assert_eq!(keys.trusted, [base64::decode(SPKI_B64).unwrap()]);
let err = by_lines.expect_err("a file of base64 lines has to be refused");
assert!(
matches!(&err, Error::Signature(m) if m.ends_with(&format!(
"the 'spki' key file '{lines}' holds no PEM PUBLIC KEY block"
))),
"{err}"
);
assert!(by_empty.unwrap().is_none());
}
#[cfg(feature = "sign-spki")]
#[test]
fn an_spki_inline_key_and_key_file_are_both_trusted() {
use crate::sign::Signer;
use crate::spki::SpkiSigner;
let inline = SpkiSigner::from_base64(SPKI_SECRET_A).unwrap();
let in_file = SpkiSigner::from_base64(SPKI_SECRET_B).unwrap();
let b64 = base64::encode(&in_file.public_key_der());
let lines: Vec<&str> = b64
.as_bytes()
.chunks(64)
.map(|c| std::str::from_utf8(c).unwrap())
.collect();
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-spkiboth-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("pem");
std::fs::write(
&path,
format!(
"-----BEGIN PUBLIC KEY-----\n{}\n-----END PUBLIC KEY-----\n",
lines.join("\n")
),
)
.unwrap();
let read = read_sign_keys(
"spki",
Some(base64::encode(&inline.public_key_der())),
Some(KeyPath::caller(&path)),
None,
false,
);
std::fs::remove_dir_all(&dir).unwrap();
let keys = read.unwrap().expect("both sources hold a key");
assert_eq!(
keys.trusted,
[inline.public_key_der(), in_file.public_key_der()]
);
let verifier = build_verifier(Engine::Spki, engine_keys(keys, None))
.unwrap()
.unwrap();
for signer in [&inline, &in_file] {
let signature = ostrya_rt::block_on(signer.sign(PAYLOAD)).unwrap();
let outcome = verifier.verify(PAYLOAD, &[signature]).unwrap();
assert!(outcome.valid);
}
}
#[cfg(feature = "sign-spki")]
#[test]
fn an_spki_inline_key_is_a_subject_public_key_info() {
use crate::spki::SpkiSigner;
let der = SpkiSigner::from_base64(SPKI_SECRET_A)
.unwrap()
.public_key_der();
let b64 = base64::encode(&der);
let (head, tail) = b64.split_at(64);
for inline in [
b64.clone(),
format!("{head}\n{tail}\n"),
format!("{head}\r\n{tail}\r\n"),
format!(" {head}\t{tail} "),
] {
let keys = read_sign_keys("spki", Some(inline), None, None, false)
.unwrap()
.expect("the inline key is a key");
assert_eq!(keys.trusted, std::slice::from_ref(&der));
assert!(
build_verifier(Engine::Spki, engine_keys(keys, None))
.unwrap()
.is_some()
);
}
let pem = format!("-----BEGIN PUBLIC KEY-----\n{head}\n{tail}\n-----END PUBLIC KEY-----\n");
let point = der[der.len() - 65..].to_vec();
let secret = base64::decode(SPKI_SECRET_A).unwrap();
for bytes in [point, pem.into_bytes(), secret] {
let keys = read_sign_keys("spki", Some(base64::encode(&bytes)), None, None, false)
.unwrap()
.expect("the inline key decodes");
match build_verifier(Engine::Spki, engine_keys(keys, None)) {
Err(Error::Signature(m)) => {
assert_eq!(m, "spki public key: expected SubjectPublicKeyInfo DER");
}
Err(other) => panic!("not a signature error: {other}"),
Ok(_) => panic!("the key has to be refused"),
}
}
let (a, b) = PUBLIC_B64.split_at(20);
assert!(read_sign_keys("ed25519", Some(format!("{a}\n{b}")), None, None, false).is_err());
}
#[test]
fn trust_source_reads_its_own_group() {
let keyfile = ostrya_core::KeyFile::parse(
"[remote \"t\"]\nverification-ed25519-key=REMOTE\n\
[ex-ostrya trust \"t\"]\nverification-ed25519-key=INLINE\n\
verification-ed25519-file=/keys.ed25519\n",
)
.unwrap();
let section = Section::<crate::config::trust::Group>::from_parts(
&keyfile,
"ex-ostrya trust \"t\"",
None,
);
assert_eq!(section.name(), "t");
let source = KeySource::Trust {
name: "t",
section: §ion,
check: X509Check::Admission,
best_effort: false,
};
assert_eq!(
source.verification_key("ed25519").unwrap().as_deref(),
Some("INLINE")
);
assert_eq!(
source.verification_file("ed25519").unwrap(),
Some(KeyPath {
value: "/keys.ed25519".into(),
origin: crate::config::KeyOrigin::Config,
})
);
assert_eq!(source.verification_key("spki").unwrap(), None);
assert!(source.x509_source().unwrap().is_none());
assert!(!source.system_store());
assert!(source.roots().is_empty());
assert!(NO_SECTION.system_store());
}
#[cfg(feature = "verify-gpg")]
#[test]
fn a_source_without_the_repository_keyring_does_not_read_it() {
use crate::{CreateOptions, RepoMode};
use ostrya_sign::MAX_KEYRING;
let dir = std::env::temp_dir().join(format!(
"ostrya-verify-nokeyring-{}-{}",
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();
std::fs::File::create(root.join("origin.trustedkeys.gpg"))
.unwrap()
.set_len(MAX_KEYRING + 1)
.unwrap();
let without = KeySource::Remote {
name: "origin",
section: None,
repo_keyring: false,
system_keys: true,
roots: &SYSTEM_KEY_ROOTS,
check: X509Check::Admission,
best_effort: false,
};
(
gpg_verifier(&repo, &without).await.map(|_| ()),
gpg_verifier(&repo, &NO_SECTION).await.map(|_| ()),
)
});
std::fs::remove_dir_all(&dir).unwrap();
let (without, with) = outcome;
without.expect("the repository keyring is not read");
let err = with.expect_err("the repository keyring is read, and refused");
assert!(
matches!(&err, Error::Signature(m) if m.contains("origin.trustedkeys.gpg")),
"{err}"
);
}
}