use std::os::fd::{AsFd, BorrowedFd};
use std::path::Path;
use crate::config::{Key, Section, SectionExt as _, SigningKeyType, key};
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::sign::key_text;
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
use crate::verify::read_capped_file_at;
use crate::verify::read_key_file_at;
use crate::verify::trust::valid_group_name;
use super::SigningKey;
const KEY_PREFIX: &str = "ex-ostrya key \"";
pub(crate) enum KeySpec {
Ed25519 {
file: String,
},
#[cfg(feature = "sign-spki")]
Spki {
file: String,
chain: Option<String>,
crl: Option<String>,
},
#[cfg(feature = "sign-gpg")]
Gpg {
key: String,
homedir: Option<String>,
},
}
impl SigningKey {
pub async fn from_key_group(repo: &Repo, name: &str) -> Result<Vec<SigningKey>> {
if !valid_group_name(name) {
return Err(Error::InvalidInput(format!(
"malformed key group name '{name}': the name is not empty, and holds no '\"' \
and no control character"
)));
}
let Some(section) = repo.config().section::<key::Group>(name) else {
return Err(Error::InvalidInput(format!(
"the config has no [{KEY_PREFIX}{name}\"] group"
)));
};
let spec = parse_key(§ion)?;
build_signers(repo, name, &spec).await
}
}
pub(crate) fn parse_key(section: &Section<'_, key::Group>) -> Result<KeySpec> {
section.refuse_unknown_keys()?;
let group = section.header();
let Some(kind) = section.file_value::<key::Type>()? else {
return Err(Error::InvalidFormat(format!(
"[{group}] needs type: ed25519, spki, or gpg"
)));
};
let foreign = |held: Option<&str>| -> Result<()> {
match held {
Some(name) => Err(Error::InvalidFormat(format!(
"[{group}] holds '{name}', which a key of type {} does not take",
kind.as_str()
))),
None => Ok(()),
}
};
let needs = |name: &str| Error::InvalidFormat(format!("[{group}] needs {name}"));
let key_file = || -> Result<String> {
match section.file_value::<key::SecretKeyFile>()? {
Some(path) if !path.as_str().is_empty() => Ok(path.into_string()),
_ => Err(needs(<key::SecretKeyFile as Key<key::Group>>::NAME)),
}
};
let gpg_keys = || held::<key::GpgKey>(section).or_else(|| held::<key::GpgHomedir>(section));
let x509_keys =
|| held::<key::CertificateChainFile>(section).or_else(|| held::<key::CrlFile>(section));
let x509_file = |path: Option<crate::config::ConfigPath>, name: &str| -> Result<_> {
match path {
Some(path) if path.as_str().is_empty() => {
Err(Error::InvalidFormat(format!("[{group}] {name} is empty")))
}
other => Ok(other.map(crate::config::ConfigPath::into_string)),
}
};
match kind {
SigningKeyType::Ed25519 => {
foreign(x509_keys().or_else(gpg_keys))?;
Ok(KeySpec::Ed25519 { file: key_file()? })
}
SigningKeyType::Spki => {
foreign(gpg_keys())?;
let file = key_file()?;
let chain = x509_file(
section.file_value::<key::CertificateChainFile>()?,
<key::CertificateChainFile as Key<key::Group>>::NAME,
)?;
let crl = x509_file(
section.file_value::<key::CrlFile>()?,
<key::CrlFile as Key<key::Group>>::NAME,
)?;
spki_key(group, file, chain, crl)
}
SigningKeyType::Gpg => {
foreign(held::<key::SecretKeyFile>(section).or_else(x509_keys))?;
let selector = match section.file_value::<key::GpgKey>()? {
Some(value) if !value.is_empty() => value,
_ => return Err(needs(<key::GpgKey as Key<key::Group>>::NAME)),
};
gpg_key(group, selector, section.file_value::<key::GpgHomedir>()?)
}
}
}
fn held<K: Key<key::Group>>(section: &Section<'_, key::Group>) -> Option<&'static str> {
section.contains::<K>().then_some(K::NAME)
}
#[cfg(feature = "sign-spki")]
fn spki_key(
group: &str,
file: String,
chain: Option<String>,
crl: Option<String>,
) -> Result<KeySpec> {
#[cfg(not(feature = "sign-x509"))]
if chain.is_some() || crl.is_some() {
let name = if chain.is_some() {
"certificate-chain-file"
} else {
"crl-file"
};
return Err(Error::Unsupported(format!(
"[{group}] holds '{name}', which this build cannot read; build with the sign-x509 \
feature"
)));
}
#[cfg(feature = "sign-x509")]
let _ = group;
Ok(KeySpec::Spki { file, chain, crl })
}
#[cfg(not(feature = "sign-spki"))]
fn spki_key(
group: &str,
_file: String,
_chain: Option<String>,
_crl: Option<String>,
) -> Result<KeySpec> {
Err(Error::Unsupported(format!(
"[{group}] is an spki key, which this build cannot sign with; build with \
the sign-spki feature"
)))
}
#[cfg(feature = "sign-gpg")]
fn gpg_key(_group: &str, key: String, homedir: Option<String>) -> Result<KeySpec> {
Ok(KeySpec::Gpg { key, homedir })
}
#[cfg(not(feature = "sign-gpg"))]
fn gpg_key(group: &str, _key: String, _homedir: Option<String>) -> Result<KeySpec> {
Err(Error::Unsupported(format!(
"[{group}] is a GPG key, which this build cannot sign with; build with the \
sign-gpg feature"
)))
}
pub(crate) async fn build_signers(
repo: &Repo,
name: &str,
spec: &KeySpec,
) -> Result<Vec<SigningKey>> {
let label = format!("[{KEY_PREFIX}{name}\"]");
let in_group = |e: Error| match e {
Error::Signature(message) => Error::Signature(format!("{label}: {message}")),
other => other,
};
match spec {
KeySpec::Ed25519 { file } => {
let line = secret_key_line(repo, file).await.map_err(in_group)?;
let signer =
SigningKey::ed25519(&ostrya_core::base64::decode(&line)?).map_err(in_group)?;
Ok(vec![signer])
}
#[cfg(feature = "sign-spki")]
KeySpec::Spki { file, chain, crl } => {
let signers = secret_key_blocks(repo, file).await.map_err(in_group)?;
#[cfg(feature = "sign-x509")]
if chain.is_some() || crl.is_some() {
return x509_signers(repo, signers, chain.as_deref(), crl.as_deref())
.await
.map_err(in_group);
}
#[cfg(not(feature = "sign-x509"))]
let _ = (chain, crl);
signers
.into_iter()
.map(|signer| SigningKey::spki(signer).map_err(in_group))
.collect()
}
#[cfg(feature = "sign-gpg")]
KeySpec::Gpg { key, homedir } => {
let mut signer = crate::gpg::GpgSigner::new(key.as_str());
if let Some(dir) = homedir {
signer = signer.with_homedir(dir);
}
Ok(vec![SigningKey::gpg(signer).await.map_err(in_group)?])
}
}
}
async fn secret_key_line(repo: &Repo, path: &str) -> Result<String> {
let repo = repo.clone();
let path = path.to_owned();
ostrya_rt::unblock(move || read_secret_key_line(repo.root_dir().as_fd(), &path)).await
}
fn read_secret_key_line(root: BorrowedFd<'_>, path: &str) -> Result<String> {
let subject = format!("the secret key file '{path}'");
let bytes = read_key_file_at(root, Path::new(path), &subject)?;
let text = key_text(bytes, &subject)?;
let mut lines = text.lines().map(str::trim).filter(|line| !line.is_empty());
match (lines.next(), lines.next()) {
(Some(line), None) => Ok(line.to_owned()),
(None, _) => Err(Error::Signature(format!("{subject} holds no key"))),
(Some(_), Some(_)) => Err(Error::Signature(format!(
"{subject} holds more than one key"
))),
}
}
#[cfg(all(feature = "sign-spki", feature = "sign-x509"))]
async fn x509_signers(
repo: &Repo,
signers: Vec<crate::spki::SpkiSigner>,
chain: Option<&str>,
crl: Option<&str>,
) -> Result<Vec<SigningKey>> {
use crate::spki::{X509Chain, x509_crls};
let repo = repo.clone();
let (chain, crl) = (chain.map(str::to_owned), crl.map(str::to_owned));
let (chain, crls) = ostrya_rt::unblock(move || -> Result<_> {
let root = repo.root_dir().as_fd();
let chain = match &chain {
Some(path) => {
let subject = format!("the certificate chain file '{path}'");
let bytes = read_key_file_at(root, Path::new(path), &subject)?;
let chain = X509Chain::from_pem(&bytes, &subject)?;
Some((chain, subject))
}
None => None,
};
let crls = match &crl {
Some(path) => {
let subject = format!("the CRL file '{path}'");
let bytes = read_capped_file_at(
root,
Path::new(path),
&subject,
crate::sign::MAX_X509_CRL_FILE,
)?;
x509_crls(&bytes, &subject)?
}
None => Vec::new(),
};
Ok((chain, crls))
})
.await?;
if let Some((chain, subject)) = &chain
&& !signers.iter().any(|signer| chain.is_key_of(signer))
{
return Err(Error::Signature(format!(
"{subject}: the key of the first certificate is not the key of a PRIVATE KEY block \
of the group"
)));
}
signers
.into_iter()
.map(|signer| {
let chains = chain
.iter()
.filter(|(chain, _)| chain.is_key_of(&signer))
.map(|(chain, _)| chain.clone())
.collect();
SigningKey::spki_x509(signer.with_x509(chains, crls.clone())?)
})
.collect()
}
#[cfg(feature = "sign-spki")]
async fn secret_key_blocks(repo: &Repo, path: &str) -> Result<Vec<crate::spki::SpkiSigner>> {
let repo = repo.clone();
let path = path.to_owned();
ostrya_rt::unblock(move || read_secret_key_blocks(repo.root_dir().as_fd(), &path)).await
}
#[cfg(feature = "sign-spki")]
fn read_secret_key_blocks(
root: BorrowedFd<'_>,
path: &str,
) -> Result<Vec<crate::spki::SpkiSigner>> {
let subject = format!("the secret key file '{path}'");
let bytes = read_key_file_at(root, Path::new(path), &subject)?;
Ok(crate::spki::spki_secret_keys(bytes, &subject)?)
}