use std::os::fd::{AsFd, BorrowedFd};
use std::path::Path;
use ostrya_core::KeyFile;
use crate::config::relative_with_parent;
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::{unknown_key, 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 group = format!("{KEY_PREFIX}{name}\"");
let keyfile = repo.config().keyfile();
if !keyfile.has_group(&group) {
return Err(Error::InvalidInput(format!(
"the config has no [{group}] group"
)));
}
let spec = parse_key(keyfile, &group)?;
build_signers(repo, name, &spec).await
}
}
pub(crate) fn parse_key(keyfile: &KeyFile, group: &str) -> Result<KeySpec> {
for key in keyfile.keys(group) {
if !matches!(key, "type" | "secret-key-file" | "gpg-key" | "gpg-homedir") {
return Err(unknown_key(group, key));
}
}
let foreign = |kind: &str, keys: &[&str]| -> Result<()> {
match keys
.iter()
.find(|key| keyfile.get_value(group, key).is_some())
{
Some(key) => Err(Error::InvalidFormat(format!(
"[{group}] holds '{key}', which a key of type {kind} does not take"
))),
None => Ok(()),
}
};
let required = |key: &str| -> Result<String> {
match keyfile.get_string(group, key)? {
Some(value) if !value.is_empty() => Ok(value),
_ => Err(Error::InvalidFormat(format!("[{group}] needs {key}"))),
}
};
let key_file = || -> Result<String> {
let value = required("secret-key-file")?;
if relative_with_parent(Path::new(&value)) {
return Err(Error::InvalidFormat(format!(
"[{group}] secret-key-file {value} has a `..` component, which a relative \
path in a config cannot have"
)));
}
Ok(value)
};
let Some(kind) = keyfile.get_string(group, "type")? else {
return Err(Error::InvalidFormat(format!(
"[{group}] needs type: ed25519, spki, or gpg"
)));
};
match kind.as_str() {
"ed25519" => {
foreign(&kind, &["gpg-key", "gpg-homedir"])?;
Ok(KeySpec::Ed25519 { file: key_file()? })
}
"spki" => {
foreign(&kind, &["gpg-key", "gpg-homedir"])?;
spki_key(group, key_file()?)
}
"gpg" => {
foreign(&kind, &["secret-key-file"])?;
let key = required("gpg-key")?;
gpg_key(group, key, keyfile.get_string(group, "gpg-homedir")?)
}
"dummy" => Err(Error::InvalidFormat(format!(
"malformed [{group}] type 'dummy': the dummy engine is not a signing key, \
its signature is its key"
))),
other => Err(Error::InvalidFormat(format!(
"malformed [{group}] type '{other}': the type is ed25519, spki, or gpg"
))),
}
}
#[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)?)
}