[vault] Standing approvals: a rule Mark grants from a card (repository, key, kind, pipeline, origin; an approval's targets), signed without asking as outcome standing, counted, revocable, paused by card-signing; never a key's first signature or a mailbox release signature; v0.16.0

This commit is contained in:
2026-11-11 16:02:14 +01:00
parent 1292c09d02
commit 2d04f32f57
7 changed files with 818 additions and 23 deletions
+260 -6
View File
@@ -116,12 +116,16 @@ pub enum Approval {
Mark,
/// Nobody was asked: allowed for test keys only.
Auto,
/// Nobody was asked: a standing approval Mark granted fits the request (core 0.16.0). Refused when none does.
Standing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
Approved,
/// Signed without asking: a standing approval fitted (core 0.16.0).
Standing,
Auto,
Refused,
Expired,
@@ -151,6 +155,34 @@ pub struct AuditEntry {
pub run: Option<String>,
}
/// A standing approval (core 0.16.0, docs/SIGNING.md): what Mark allowed for good, when, and how often it was used.
/// Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StandingRule {
/// 16 hex characters: the SHA-256 of repo, key, kind, pipeline and via, joined by newlines, cut short.
pub id: String,
pub repo: String,
pub key: String,
/// The key's `created`: a key made later under the same id does not inherit the rule.
pub key_created: i64,
pub kind: SignKind,
pub pipeline: String,
pub via: Via,
/// For an approval: the deploy targets the rule was granted for.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub targets: Vec<String>,
/// Unix milliseconds.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
}
/// At most this many standing approvals in a vault.
pub const STANDING_MAX: usize = 256;
/// A signature handed back to the build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signed {
@@ -213,6 +245,7 @@ impl fmt::Debug for Key {
pub(crate) struct Store {
keys: Vec<Key>,
audit: Vec<AuditEntry>,
standing: Vec<StandingRule>,
}
#[derive(Serialize, Deserialize)]
@@ -244,6 +277,9 @@ pub(crate) struct StoreJson {
keys: Vec<KeyJson>,
#[serde(default)]
audit: Vec<AuditEntry>,
/// Standing approvals (core 0.16.0); absent while there are none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
standing: Vec<StandingRule>,
}
fn b64(bytes: &[u8]) -> String {
@@ -271,7 +307,7 @@ fn unhex8(s: &str) -> Option<[u8; 8]> {
impl Store {
pub(crate) fn is_empty(&self) -> bool {
self.keys.is_empty() && self.audit.is_empty()
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
@@ -323,7 +359,10 @@ impl Store {
repos: k.repos,
});
}
Some(Store { keys, audit: j.audit })
if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
@@ -351,7 +390,7 @@ impl Store {
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone() })
Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() })
}
fn get(&self, id: &str) -> Option<&Key> {
@@ -399,6 +438,52 @@ pub struct AndroidKey {
pub repos: Vec<String>,
}
/// A name in a rule: 1 to 100 characters, no control characters (as a key's scope lists hold them).
fn name_ok(x: &str) -> bool {
(1..=100).contains(&x.chars().count()) && !x.chars().any(char::is_control)
}
fn kind_word(kind: SignKind) -> &'static str {
match kind {
SignKind::Minisign => "minisign",
SignKind::Manifest => "manifest",
SignKind::Authenticode => "authenticode",
SignKind::Approval => "approval",
SignKind::Apk => "apk",
}
}
fn via_word(via: Via) -> &'static str {
match via {
Via::Local => "local",
Via::Remote => "remote",
}
}
/// A rule's id: one per repository, key, kind, pipeline and origin.
fn rule_id(repo: &str, key: &str, kind: SignKind, pipeline: &str, via: Via) -> String {
let joined = [repo, key, kind_word(kind), pipeline, via_word(via)].join("\n");
custos_sign::sha256_hex(joined.as_bytes())[..16].to_string()
}
/// A stored rule is what [`Vault::standing_grant`] could have written; anything else makes the vault refuse to open.
fn rule_ok(r: &StandingRule) -> bool {
r.id == rule_id(&r.repo, &r.key, r.kind, &r.pipeline, r.via)
&& name_ok(&r.repo)
&& name_ok(&r.pipeline)
&& (1..=64).contains(&r.key.len())
&& (r.via == Via::Local || r.kind == SignKind::Approval)
&& (r.kind == SignKind::Approval) == !r.targets.is_empty()
&& r.targets.len() <= 64
&& r.targets.iter().all(|t| (1..=80).contains(&t.chars().count()) && !t.chars().any(char::is_control))
}
/// What a rule says, for the security audit: names only.
fn rule_words(r: &StandingRule) -> String {
let targets = if r.targets.is_empty() { String::new() } else { format!(" ({} targets)", r.targets.len()) };
format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via))
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
@@ -726,6 +811,12 @@ impl Vault {
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
}
let rule = self.standing_rule_for(req, now).map(|r| r.id);
if approval == Approval::Standing && rule.is_none() {
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 = seconds(now);
let bytes = match (&k.secret, req.kind) {
@@ -765,15 +856,25 @@ impl Vault {
}
};
let sha256 = custos_sign::sha256_hex(&bytes);
let outcome = if approval == Approval::Auto { Outcome::Auto } else { Outcome::Approved };
let outcome = match approval {
Approval::Auto => Outcome::Auto,
Approval::Mark => Outcome::Approved,
Approval::Standing => Outcome::Standing,
};
self.signing_record(req, outcome, None, Some(sha256.clone()), now);
if let (Approval::Standing, Some(id)) = (approval, rule)
&& let Some(r) = self.signing.standing.iter_mut().find(|r| r.id == id)
{
r.uses += 1;
r.last_used = Some(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,
Outcome::Approved | Outcome::Auto | Outcome::Standing => Outcome::Refused,
o => o,
};
self.signing_record(req, outcome, reason, None, now);
@@ -827,6 +928,131 @@ impl Vault {
});
}
/// What a rule for `req` would name, when `req` could be signed and may be covered by one at all: the key's
/// `created`, the repository and pipeline as the scope check reads them, and an approval's targets.
fn standing_shape(&self, req: &Request, now: i64) -> Result<(i64, String, String, Vec<String>), Error> {
let no = |why: &str| Error::Signing(why.into());
let (view, approval) = self.check(req, now).map_err(|r| Error::Signing(r.to_string()))?;
if req.run.is_none() {
return Err(no("a standing approval is for requests that name a run"));
}
if req.via == Via::Remote && req.kind != SignKind::Approval {
return Err(no("a release signature the server runner asks for always needs a card"));
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(no("Sign only with a card is ticked"));
}
let (repo, pipeline, targets) = match approval {
Some(a) => (a.repo, a.pipeline, a.targets),
None => (req.context.repo.clone(), req.context.pipeline.clone(), Vec::new()),
};
if !name_ok(&repo) || !name_ok(&pipeline) {
return Err(no("the repository or pipeline is not a usable name"));
}
Ok((view.created, repo, pipeline, targets))
}
/// Whether `req`, which Mark is approving on a card, may start a standing approval (docs/SIGNING.md, "Standing
/// approvals"); the error says why not, in words for the card.
pub fn standing_can_grant(&self, req: &Request, now: i64) -> Result<(), Error> {
self.standing_shape(req, now)?;
let k = self.signing.get(&req.key).expect("checked");
if k.role != Role::Release {
return Err(Error::Signing("a test key signs without asking: it needs no standing approval".into()));
}
// A key's first signature is never the one that starts a rule.
let signed = |e: &AuditEntry| {
e.key == k.id && e.at >= k.created && matches!(e.outcome, Outcome::Approved | Outcome::Standing)
};
if !self.signing.audit.iter().any(signed) {
return Err(Error::Signing(format!(
"`{}` has never signed: its first signature needs a card of its own",
k.id
)));
}
Ok(())
}
/// Stores the standing approval for `req` (or adds an approval's targets to the one there is) and writes
/// `standing-granted` to the security audit. Call it before signing the request Mark approved. The caller saves.
pub fn standing_grant(&mut self, req: &Request, now: i64) -> Result<StandingRule, Error> {
self.standing_can_grant(req, now)?;
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now)?;
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
let at = self.signing.standing.iter().position(|r| r.id == id);
// The same combination again keeps its rule (and its count) unless the key under that id is another one.
let mut rule = match at.map(|i| self.signing.standing[i].clone()).filter(|r| r.key_created == key_created) {
Some(r) => r,
None => StandingRule {
id,
repo,
key: req.key.clone(),
key_created,
kind: req.kind,
pipeline,
via: req.via,
targets: Vec::new(),
granted: now,
last_used: None,
uses: 0,
},
};
// Any target Mark sees on this card joins the ones he allowed before.
for t in targets {
if !rule.targets.contains(&t) {
rule.targets.push(t);
}
}
// Never stored in a form this core would refuse to read back; what was there stays as it was.
if !rule_ok(&rule) {
return Err(Error::Signing("this request cannot be written as a standing approval".into()));
}
match at {
Some(i) => self.signing.standing[i] = rule.clone(),
None if self.signing.standing.len() >= STANDING_MAX => {
return Err(Error::Signing("there are 256 standing approvals already: revoke one first".into()));
}
None => self.signing.standing.push(rule.clone()),
}
self.security.standing_note(crate::security::Action::StandingGranted, &rule_words(&rule), now);
Ok(rule)
}
/// The standing approval `req` fits, if one does: the request passes [`Vault::signing_check_at`], names a run,
/// and equals the rule in repository, pipeline, key, kind and origin (an approval: its targets are the rule's).
pub fn standing_rule_for(&self, req: &Request, now: i64) -> Option<StandingRule> {
let (key_created, repo, pipeline, targets) = self.standing_shape(req, now).ok()?;
let id = rule_id(&repo, &req.key, req.kind, &pipeline, req.via);
self.signing
.standing
.iter()
.find(|r| {
r.id == id
&& r.repo == repo
&& r.key == req.key
&& r.key_created == key_created
&& r.kind == req.kind
&& r.pipeline == pipeline
&& r.via == req.via
&& targets.iter().all(|t| r.targets.contains(t))
})
.cloned()
}
/// The standing approvals, oldest first.
pub fn standing_rules(&self) -> Vec<StandingRule> {
self.signing.standing.clone()
}
/// Removes a standing approval, audited `standing-revoked`. False when there is none with this id. The caller
/// saves.
pub fn standing_revoke(&mut self, id: &str, now: i64) -> bool {
let Some(i) = self.signing.standing.iter().position(|r| r.id == id) else { return false };
let rule = self.signing.standing.remove(i);
self.security.standing_note(crate::security::Action::StandingRevoked, &rule_words(&rule), now);
true
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit
@@ -883,6 +1109,27 @@ mod tests {
assert_eq!(back.signing_keys(), views);
}
#[test]
fn a_key_made_again_under_the_same_id_does_not_inherit_the_rule() {
let mut v =
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), 1).unwrap();
let r = Request { run: Some("r-1".into()), ..req("domi-release", SignKind::Minisign, 64) };
v.signing_sign(&r, Approval::Mark, 2).unwrap();
v.standing_grant(&r, 3).unwrap();
assert!(v.standing_rule_for(&r, 4).is_some());
// The same id, made at another time (no API does this; a rule must not depend on that).
v.signing.keys.iter_mut().find(|k| k.id == "domi-release").unwrap().created = 10;
assert!(v.standing_rule_for(&r, 11).is_none(), "the rule names the key it was granted for");
assert!(matches!(v.signing_sign(&r, Approval::Standing, 11), Err(Refusal::NeedsApproval(_))));
// The old key's signatures do not count as the new key's first one either.
assert!(v.standing_grant(&r, 12).is_err());
v.signing_sign(&r, Approval::Mark, 13).unwrap();
let again = v.standing_grant(&r, 14).unwrap();
assert_eq!((again.key_created, again.granted, again.uses), (10, 14, 0));
assert_eq!(v.standing_rules().len(), 1);
}
#[test]
fn no_api_path_returns_a_private_key() {
let mut v =
@@ -942,13 +1189,20 @@ mod tests {
reqs.push(req("domi-code-signing", SignKind::Apk, 64));
for r in &reqs {
out += &format!("{:?}", v.signing_check(r));
for approval in [Approval::Mark, Approval::Auto] {
for approval in [Approval::Mark, Approval::Auto, Approval::Standing] {
match v.signing_sign(r, approval, 2) {
Ok(signed) => out += &format!("{signed:?}{}", data_encoding::HEXLOWER.encode(&signed.bytes)),
Err(e) => out += &format!("{e:?}{e}"),
}
// A standing approval for the same request with a run, once the key has signed (core 0.16.0).
let with_run = Request { run: r.run.clone().or(Some("r-1".into())), ..r.clone() };
out += &format!("{:?}{:?}", v.standing_can_grant(&with_run, 2), v.standing_grant(&with_run, 2));
out += &format!("{:?}", v.standing_rule_for(&with_run, 2));
}
}
assert!(v.standing_rules().len() >= 3, "rules were granted: {:?}", v.standing_rules());
out += &serde_json::to_string(&v.standing_rules()).unwrap();
out += &format!("{:?}{:?}", v.standing_rules(), v.security_view(3).audit);
assert!(
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
"an approval was signed too"