use std::os::fd::{AsFd, BorrowedFd};
use std::path::Path;
use crate::config::{Key, Section, SigningKeyType, key};
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::sign::key_text;
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,
},
#[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));
match kind {
SigningKeyType::Ed25519 => {
foreign(gpg_keys())?;
Ok(KeySpec::Ed25519 { file: key_file()? })
}
SigningKeyType::Spki => {
foreign(gpg_keys())?;
spki_key(group, key_file()?)
}
SigningKeyType::Gpg => {
foreign(held::<key::SecretKeyFile>(section))?;
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) -> Result<KeySpec> {
Ok(KeySpec::Spki { file })
}
#[cfg(not(feature = "sign-spki"))]
fn spki_key(group: &str, _file: 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 } => secret_key_blocks(repo, file)
.await
.map_err(in_group)?
.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(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)?)
}