[vault] Signing: mandatory tests for scope, refusals and the audit log through a reopen

This commit is contained in:
2026-11-04 00:26:11 +01:00
parent 59fdfa26ef
commit cd2963392d
3 changed files with 773 additions and 0 deletions
+560
View File
@@ -0,0 +1,560 @@
//! Signing keys for releases and the audit log of every request (docs/SIGNING.md): the vault body member
//! `signing`. A key's secret is used inside this module and never handed out: the public API returns
//! public keys, certificates, signatures and audit entries only.
use std::fmt;
use custos_sign::{Ed25519Secret, RsaSecret};
use serde::{Deserialize, Serialize};
use crate::{Error, SecretBytes, Vault};
/// What a request may be refused with. Every refusal names why, and none carries key material.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum Refusal {
#[error("there is no signing key `{0}`")]
NoKey(String),
#[error("{0}")]
OutOfScope(String),
#[error("{0}")]
Invalid(String),
#[error("`{0}` is a release key: it signs only after Mark approves")]
NeedsApproval(String),
}
impl Refusal {
/// The audit outcome this refusal is recorded as.
pub fn outcome(&self) -> Outcome {
match self {
Refusal::OutOfScope(_) => Outcome::OutOfScope,
Refusal::NeedsApproval(_) => Outcome::Refused,
Refusal::NoKey(_) | Refusal::Invalid(_) => Outcome::Invalid,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
Release,
Test,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum KeyKind {
Ed25519,
RootCa,
CodeSigning,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SignKind {
Minisign,
Manifest,
Authenticode,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Via {
Local,
Remote,
}
/// What the build says it is signing. Shown on the card and kept in the audit log; Custos cannot check it
/// against the file (docs/SIGNING.md, the wrong-file risk).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Context {
pub repo: String,
pub commit: String,
pub pipeline: String,
pub step: String,
/// `manual`, `push` or `tag`. A test key never signs for `tag`.
pub trigger: String,
pub file: String,
pub size: u64,
pub sha256: String,
}
/// A signing request, from the Domi pipe or the factor service's mailbox.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request {
pub key: String,
pub kind: SignKind,
/// BLAKE2b-512 of the file (minisign) or signtool's 32-byte digest (authenticode). Empty for a manifest.
pub digest: Vec<u8>,
/// The `SHA256SUMS` text, for a manifest.
pub manifest: Option<String>,
pub context: Context,
pub via: Via,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Approval {
/// Mark approved this request on the card.
Mark,
/// Nobody was asked: allowed for test keys only.
Auto,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
Approved,
Auto,
Refused,
Expired,
OutOfScope,
Invalid,
}
/// One audit entry. Append-only: nothing edits or removes one.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AuditEntry {
pub at: i64,
pub key: String,
pub kind: SignKind,
pub outcome: Outcome,
pub via: Via,
#[serde(flatten)]
pub context: Context,
/// SHA-256 (hex) of what was returned, for signed outcomes.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub signature: Option<String>,
/// Why, for refusals the vault decided.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reason: Option<String>,
}
/// A signature handed back to the build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signed {
/// The `.minisig` text (minisign, manifest) or the raw RSA signature (authenticode).
pub bytes: Vec<u8>,
pub sha256: String,
}
/// A key as the app may see it: public parts only.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct KeyView {
pub id: String,
pub kind: KeyKind,
pub role: Role,
pub name: String,
pub created: i64,
pub pipelines: Vec<String>,
pub repos: Vec<String>,
/// Test keys are approved automatically (within scope, never for a `tag` trigger).
pub auto_approve: bool,
/// minisign's key id (hex, as minisign prints it), for Ed25519 keys.
pub key_id: Option<String>,
/// The `minisign.pub` text, for Ed25519 keys.
pub minisign_public: Option<String>,
/// The certificate (DER), for root and code-signing keys.
pub cert: Option<Vec<u8>>,
pub issuer: Option<String>,
}
enum Secret {
Ed25519(Ed25519Secret),
Rsa(RsaSecret),
}
struct Key {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: Secret,
public: Option<[u8; 32]>,
key_id: Option<[u8; 8]>,
cert: Option<Vec<u8>>,
issuer: Option<String>,
created: i64,
pipelines: Vec<String>,
repos: Vec<String>,
}
impl fmt::Debug for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Key").field("id", &self.id).field("kind", &self.kind).field("secret", &"[redacted]").finish()
}
}
/// The keys and the log, in the vault.
#[derive(Debug, Default)]
pub(crate) struct Store {
keys: Vec<Key>,
audit: Vec<AuditEntry>,
}
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
struct KeyJson {
id: String,
kind: KeyKind,
role: Role,
name: String,
secret: SecretBytes,
#[serde(default, skip_serializing_if = "Option::is_none")]
public: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
key_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
cert: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
issuer: Option<String>,
created: i64,
#[serde(default)]
pipelines: Vec<String>,
#[serde(default)]
repos: Vec<String>,
}
#[derive(Serialize, Deserialize)]
pub(crate) struct StoreJson {
#[serde(default)]
keys: Vec<KeyJson>,
#[serde(default)]
audit: Vec<AuditEntry>,
}
fn b64(bytes: &[u8]) -> String {
data_encoding::BASE64.encode(bytes)
}
fn unb64(s: &str) -> Option<Vec<u8>> {
data_encoding::BASE64.decode(s.as_bytes()).ok()
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{b:02x}")).collect()
}
fn unhex8(s: &str) -> Option<[u8; 8]> {
if s.len() != 16 {
return None;
}
let mut out = [0u8; 8];
for (i, o) in out.iter_mut().enumerate() {
*o = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?;
}
Some(out)
}
impl Store {
pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() && self.audit.is_empty()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
let mut keys = Vec::new();
for k in j.keys {
let secret = match k.kind {
KeyKind::Ed25519 => {
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
}
KeyKind::RootCa | KeyKind::CodeSigning => {
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
}
};
let public = match &k.public {
Some(p) => Some(unb64(p)?.try_into().ok()?),
None => None,
};
// The stored public key must be the secret's, as for the identity root.
if let (Secret::Ed25519(s), Some(p)) = (&secret, public) {
if s.public() != p {
return None;
}
}
let key_id = match &k.key_id {
Some(h) => Some(unhex8(h)?),
None => None,
};
let cert = match &k.cert {
Some(c) => Some(unb64(c)?),
None => None,
};
keys.push(Key {
id: k.id,
kind: k.kind,
role: k.role,
name: k.name,
secret,
public,
key_id,
cert,
issuer: k.issuer,
created: k.created,
pipelines: k.pipelines,
repos: k.repos,
});
}
Some(Store { keys, audit: j.audit })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
if self.is_empty() {
return None;
}
let keys = self
.keys
.iter()
.map(|k| KeyJson {
id: k.id.clone(),
kind: k.kind,
role: k.role,
name: k.name.clone(),
secret: SecretBytes::new(match &k.secret {
Secret::Ed25519(s) => s.expose().to_vec(),
Secret::Rsa(s) => s.expose().to_vec(),
}),
public: k.public.map(|p| b64(&p)),
key_id: k.key_id.map(|i| hex(&i)),
cert: k.cert.as_ref().map(|c| b64(c)),
issuer: k.issuer.clone(),
created: k.created,
pipelines: k.pipelines.clone(),
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone() })
}
fn get(&self, id: &str) -> Option<&Key> {
self.keys.iter().find(|k| k.id == id)
}
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
fn clean_list(list: &[String]) -> Result<Vec<String>, Error> {
let mut out: Vec<String> = Vec::new();
for x in list.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) {
if x.len() > 100 || x.chars().any(char::is_control) {
return Err(Error::Signing("a pipeline or repo name is not usable".into()));
}
if !out.iter().any(|o| o == x) {
out.push(x.to_string());
}
}
Ok(out)
}
impl Vault {
/// Creates the release set (`domi-release`, `domi-root`, `domi-code-signing`) or the test set (`domi-test`,
/// `domi-test-root`, `domi-test-code-signing`). The caller saves. Slow: two RSA-3072 keys.
pub fn signing_create(&mut self, role: Role, pipelines: &[String], repos: &[String], now: i64) -> Result<Vec<String>, Error> {
if self.signing.keys.iter().any(|k| k.role == role) {
return Err(Error::SigningExists(match role {
Role::Release => "release",
Role::Test => "test",
}));
}
let pipelines = clean_list(pipelines)?;
let repos = clean_list(repos)?;
let (ed_id, root_id, leaf_id, ed_name, root_name, leaf_name) = match role {
Role::Release => ("domi-release", "domi-root", "domi-code-signing", "Domi release", "Domi Household Root CA", "Domi Code Signing"),
Role::Test => ("domi-test", "domi-test-root", "domi-test-code-signing", "Domi test", "Domi Test Root (never trusted)", "Domi Test Code Signing"),
};
let ed = custos_sign::new_ed25519();
let root = custos_sign::new_root(root_name, 10).map_err(|e| Error::Signing(e.to_string()))?;
let leaf = custos_sign::new_code_signing(leaf_name, 2, &root.secret, &root.cert_der)
.map_err(|e| Error::Signing(e.to_string()))?;
let key = |id: &str, kind, name: &str, secret, cert, issuer: Option<&str>, scoped: bool| Key {
id: id.into(),
kind,
role,
name: name.into(),
secret,
public: None,
key_id: None,
cert,
issuer: issuer.map(String::from),
created: now,
pipelines: if scoped { pipelines.clone() } else { Vec::new() },
repos: if scoped { repos.clone() } else { Vec::new() },
};
let mut ed_key = key(ed_id, KeyKind::Ed25519, ed_name, Secret::Ed25519(ed.secret), None, None, true);
ed_key.public = Some(ed.public);
ed_key.key_id = Some(ed.key_id);
let root_key = key(root_id, KeyKind::RootCa, root_name, Secret::Rsa(root.secret), Some(root.cert_der), None, false);
let leaf_key = key(leaf_id, KeyKind::CodeSigning, leaf_name, Secret::Rsa(leaf.secret), Some(leaf.cert_der), Some(root_id), true);
self.signing.keys.extend([ed_key, root_key, leaf_key]);
Ok(vec![ed_id.into(), root_id.into(), leaf_id.into()])
}
/// Every signing key, public parts only.
pub fn signing_keys(&self) -> Vec<KeyView> {
self.signing
.keys
.iter()
.map(|k| KeyView {
id: k.id.clone(),
kind: k.kind,
role: k.role,
name: k.name.clone(),
created: k.created,
pipelines: k.pipelines.clone(),
repos: k.repos.clone(),
auto_approve: k.role == Role::Test && k.kind != KeyKind::RootCa,
key_id: k.key_id.map(|i| custos_sign::key_id_hex(&i)),
minisign_public: match (k.public, k.key_id) {
(Some(p), Some(i)) => Some(custos_sign::minisign_public(&p, &i)),
_ => None,
},
cert: k.cert.clone(),
issuer: k.issuer.clone(),
})
.collect()
}
/// Changes who may ask for a key. The caller saves.
pub fn signing_set_scope(&mut self, id: &str, pipelines: &[String], repos: &[String]) -> Result<(), Error> {
let (pipelines, repos) = (clean_list(pipelines)?, clean_list(repos)?);
let k = self.signing.keys.iter_mut().find(|k| k.id == id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
if k.kind == KeyKind::RootCa {
return Err(Error::Signing("a root CA signs no requests, so it has no scope".into()));
}
k.pipelines = pipelines;
k.repos = repos;
Ok(())
}
/// A key's certificate (DER): public, for installing the root or giving signtool the leaf.
pub fn signing_export_cert(&self, id: &str) -> Result<Vec<u8>, Error> {
let k = self.signing.get(id).ok_or_else(|| Error::Signing(format!("no key `{id}`")))?;
k.cert.clone().ok_or_else(|| Error::Signing(format!("`{id}` has no certificate")))
}
/// Whether `req` could be signed: the key exists and can do the kind, the input is well formed, the pipeline
/// and repo are in the key's scope, and a test key is not asked for a `tag` build. Shown before any card.
pub fn signing_check(&self, req: &Request) -> Result<KeyView, Refusal> {
let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?;
let fits = matches!(
(k.kind, req.kind),
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) | (KeyKind::CodeSigning, SignKind::Authenticode)
);
if k.kind == KeyKind::RootCa {
return Err(Refusal::Invalid(format!("`{}` is a root CA: it signs only the certificate it issued", k.id)));
}
if !fits {
return Err(Refusal::Invalid(format!("`{}` cannot make {:?} signatures", k.id, req.kind)));
}
match req.kind {
SignKind::Minisign if req.digest.len() != 64 => {
return Err(Refusal::Invalid("a minisign digest is BLAKE2b-512: 64 bytes".into()));
}
SignKind::Authenticode if req.digest.len() != 32 => {
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into()));
}
SignKind::Manifest => {
let text = req.manifest.as_deref().ok_or_else(|| Refusal::Invalid("no manifest text".into()))?;
custos_sign::manifest_check(text).map_err(|e| Refusal::Invalid(e.to_string()))?;
}
_ => {}
}
let file = &req.context.file;
if req.kind != SignKind::Manifest
&& (file.is_empty() || file.len() > 255 || file.contains(['/', '\\']) || file.chars().any(char::is_control))
{
return Err(Refusal::Invalid("the file name is missing or not a plain name".into()));
}
if !in_scope(&k.pipelines, &req.context.pipeline) {
return Err(Refusal::OutOfScope(format!("pipeline `{}` may not use `{}`", req.context.pipeline, k.id)));
}
if !in_scope(&k.repos, &req.context.repo) {
return Err(Refusal::OutOfScope(format!("repo `{}` may not use `{}`", req.context.repo, k.id)));
}
if k.role == Role::Test && req.context.trigger == "tag" {
return Err(Refusal::OutOfScope(format!("`{}` is a test key: it never signs a tag (release) build", k.id)));
}
Ok(self.signing_keys().into_iter().find(|v| v.id == k.id).expect("the key exists"))
}
/// Checks `req` again and signs it, recording the outcome. `Approval::Auto` works for test keys only.
/// A refusal is recorded too. The caller saves.
pub fn signing_sign(&mut self, req: &Request, approval: Approval, now: i64) -> Result<Signed, Refusal> {
let view = match self.signing_check(req) {
Ok(v) => v,
Err(r) => {
self.signing_record(req, r.outcome(), Some(r.to_string()), None, now);
return Err(r);
}
};
if approval == Approval::Auto && !view.auto_approve {
let r = Refusal::NeedsApproval(req.key.clone());
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
}
let k = self.signing.get(&req.key).expect("checked");
let seconds = (now.max(0) / 1000) as u64;
let bytes = match (&k.secret, req.kind) {
(Secret::Ed25519(s), SignKind::Minisign) => {
custos_sign::minisign(s, &k.key_id.expect("ed25519 keys have an id"), &req.digest, &req.context.file, seconds)
.map(String::into_bytes)
}
(Secret::Ed25519(s), SignKind::Manifest) => custos_sign::manifest(
s,
&k.key_id.expect("ed25519 keys have an id"),
req.manifest.as_deref().unwrap_or_default(),
seconds,
)
.map(String::into_bytes),
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
_ => unreachable!("signing_check matched the key to the kind"),
};
let bytes = match bytes {
Ok(b) => b,
Err(e) => {
let r = Refusal::Invalid(e.to_string());
self.signing_record(req, Outcome::Invalid, Some(r.to_string()), None, now);
return Err(r);
}
};
let sha256 = custos_sign::sha256_hex(&bytes);
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
Ok(Signed { bytes, sha256 })
}
/// Records a request that was not signed: Mark refused it, or nobody answered in time. The caller saves.
pub fn signing_refuse(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, now: i64) {
let outcome = match outcome {
Outcome::Approved | Outcome::Auto => Outcome::Refused,
o => o,
};
self.signing_record(req, outcome, reason, None, now);
}
fn signing_record(&mut self, req: &Request, outcome: Outcome, reason: Option<String>, signature: Option<String>, now: i64) {
let mut context = req.context.clone();
if req.kind == SignKind::Manifest {
context.file = "SHA256SUMS".into();
}
self.signing.audit.push(AuditEntry {
at: now,
key: req.key.clone(),
kind: req.kind,
outcome,
via: req.via,
context,
signature,
reason,
});
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit
}
}