[vault] Signing: the Android grant, one answer for every Domi app's release APK and its key on first use; v0.19.0

signing.android: patterns owner/name or owner/*, the certificate's O and C, uses, last used and the keys it
made. A request fits when it is an apk from this PC's pipe with a run, pipeline release, a covered repository,
and that repository's own app key (<name>-android, scoped to exactly it and release, role release), while
card-signing is not ticked; a key's first signature fits. android_grant_make_key makes that key for a covered
repository (android-key-made in the security audit). Granting and revoking write standing-granted and
standing-revoked. A vault whose grant made a key needs core 0.19.0; older cores drop the grant itself.
This commit is contained in:
2026-11-21 08:57:48 +01:00
parent 47146a6ea2
commit e533a38883
7 changed files with 600 additions and 22 deletions
+232 -4
View File
@@ -203,6 +203,35 @@ pub struct StandingRule {
/// At most this many standing approvals in a vault.
pub const STANDING_MAX: usize = 256;
/// The Android grant (core 0.19.0, docs/SIGNING.md "The Android grant"): Mark's one answer for every Domi app's
/// release APK. It signs an app key's APKs from this PC's pipe, its first signature included, and makes the key when
/// the app's first release asks. Nothing in it is secret.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AndroidGrant {
/// `owner/name` or `owner/*`, 1 to [`ANDROID_PATTERNS_MAX`].
pub repos: Vec<String>,
/// The organisation and country in the certificates of the keys it makes.
pub o: String,
pub c: String,
/// Unix milliseconds: when Mark granted it, or last changed it.
pub granted: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub last_used: Option<i64>,
#[serde(default)]
pub uses: u64,
/// The ids of the keys it made, oldest first.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub made: Vec<String>,
}
/// The one pipeline the Android grant covers.
pub const ANDROID_PIPELINE: &str = "release";
/// At most this many repository patterns in the Android grant.
pub const ANDROID_PATTERNS_MAX: usize = 64;
/// At most this many keys the Android grant remembers making.
const ANDROID_MADE_MAX: usize = 256;
/// A signature handed back to the build.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Signed {
@@ -269,6 +298,7 @@ pub(crate) struct Store {
pub(crate) keys: Vec<Key>,
pub(crate) audit: Vec<AuditEntry>,
standing: Vec<StandingRule>,
android: Option<AndroidGrant>,
}
#[derive(Serialize, Deserialize)]
@@ -303,6 +333,9 @@ pub(crate) struct StoreJson {
/// Standing approvals (core 0.16.0); absent while there are none.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
standing: Vec<StandingRule>,
/// The Android grant (core 0.19.0); absent while there is none. Older cores ignore and drop it.
#[serde(default, skip_serializing_if = "Option::is_none")]
android: Option<AndroidGrant>,
}
fn b64(bytes: &[u8]) -> String {
@@ -330,7 +363,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.standing.is_empty()
self.keys.is_empty() && self.audit.is_empty() && self.standing.is_empty() && self.android.is_none()
}
pub(crate) fn from_json(j: StoreJson) -> Option<Store> {
@@ -389,7 +422,10 @@ impl Store {
if j.standing.len() > STANDING_MAX || !j.standing.iter().all(rule_ok) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing })
if j.android.as_ref().is_some_and(|g| !grant_ok(g)) {
return None;
}
Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android })
}
pub(crate) fn json(&self) -> Option<StoreJson> {
@@ -418,7 +454,12 @@ impl Store {
repos: k.repos.clone(),
})
.collect();
Some(StoreJson { keys, audit: self.audit.clone(), standing: self.standing.clone() })
Some(StoreJson {
keys,
audit: self.audit.clone(),
standing: self.standing.clone(),
android: self.android.clone(),
})
}
pub(crate) fn get(&self, id: &str) -> Option<&Key> {
@@ -514,6 +555,64 @@ fn rule_words(r: &StandingRule) -> String {
format!("{} {} {} pipeline {} {}{targets}", r.repo, r.key, kind_word(r.kind), r.pipeline, via_word(r.via))
}
/// `owner/name`, each 1 to 64 of `A-Z a-z 0-9 . _ -`: the owner and the name, or `None`.
fn repo_parts(repo: &str) -> Option<(&str, &str)> {
let part =
|x: &str| (1..=64).contains(&x.len()) && x.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b));
let (owner, name) = repo.split_once('/')?;
(part(owner) && part(name)).then_some((owner, name))
}
/// The app key of a repository (core 0.19.0): `mnovak/Culina` is `culina-android` (the name in lower case, `.` and
/// `_` as `-`); `None` for anything that is not `owner/name` or an id longer than 64.
pub fn android_key_id(repo: &str) -> Option<String> {
let (_, name) = repo_parts(repo)?;
let id: String = name.chars().map(|c| if c == '.' || c == '_' { '-' } else { c.to_ascii_lowercase() }).collect();
let id = format!("{id}-android");
(id.len() <= 64).then_some(id)
}
/// A pattern of the Android grant: `owner/name`, or `owner/*` for every repository of that owner.
fn grant_pattern_ok(p: &str) -> bool {
match p.strip_suffix("/*") {
Some(owner) => repo_parts(&format!("{owner}/x")).is_some(),
None => repo_parts(p).is_some(),
}
}
fn grant_covers(g: &AndroidGrant, repo: &str) -> bool {
let Some((owner, _)) = repo_parts(repo) else { return false };
g.repos.iter().any(|p| p == repo || p.strip_suffix("/*") == Some(owner))
}
/// The certificate's O (1 to 64, no control characters) and C (two ASCII capitals) for the keys the grant makes.
fn grant_subject_ok(o: &str, c: &str) -> bool {
(1..=64).contains(&o.chars().count())
&& !o.chars().any(char::is_control)
&& o.trim() == o
&& c.len() == 2
&& c.bytes().all(|b| b.is_ascii_uppercase())
}
/// A stored grant is what [`Vault::android_grant_set`] could have written; anything else makes the vault refuse to
/// open.
fn grant_ok(g: &AndroidGrant) -> bool {
let id_ok = |id: &String| {
(1..=64).contains(&id.len()) && id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
};
(1..=ANDROID_PATTERNS_MAX).contains(&g.repos.len())
&& g.repos.iter().all(|p| grant_pattern_ok(p))
&& g.repos.iter().enumerate().all(|(i, p)| !g.repos[..i].contains(p))
&& grant_subject_ok(&g.o, &g.c)
&& g.made.len() <= ANDROID_MADE_MAX
&& g.made.iter().all(id_ok)
}
/// What the grant says, for the security audit: names only.
fn grant_words(g: &AndroidGrant) -> String {
format!("Android releases: {} pipeline {ANDROID_PIPELINE}, keys made on first use", g.repos.join(", "))
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
@@ -846,7 +945,9 @@ impl Vault {
return Err(r);
}
let rule = self.standing_rule_for(req, now).map(|r| r.id);
if approval == Approval::Standing && rule.is_none() {
// A standing approval first; the Android grant only where none fits (core 0.19.0).
let by_grant = approval == Approval::Standing && rule.is_none() && self.android_grant_fits(req, now);
if approval == Approval::Standing && rule.is_none() && !by_grant {
let r = Refusal::NeedsApproval(req.key.clone());
self.signing_record(req, Outcome::Refused, Some(r.to_string()), None, now);
return Err(r);
@@ -902,6 +1003,10 @@ impl Vault {
r.uses = r.uses.saturating_add(1);
r.last_used = Some(now);
}
if by_grant && let Some(g) = self.signing.android.as_mut() {
g.uses = g.uses.saturating_add(1);
g.last_used = Some(now);
}
Ok(Signed { bytes, sha256 })
}
@@ -1091,6 +1196,129 @@ impl Vault {
true
}
/// The Android grant, if Mark gave it (core 0.19.0, docs/SIGNING.md "The Android grant").
pub fn android_grant(&self) -> Option<AndroidGrant> {
self.signing.android.clone()
}
/// Stores the Android grant, or replaces its patterns and subject (its counts and the keys it made stay), and
/// writes `standing-granted`. Refused while *Sign only with a card* is ticked. Call it only from Mark's own
/// click. The caller saves.
pub fn android_grant_set(&mut self, repos: &[String], o: &str, c: &str, now: i64) -> Result<AndroidGrant, Error> {
if self.security.is_ticked(crate::security::Item::CardSigning) {
return Err(Error::Signing("Sign only with a card is ticked".into()));
}
let mut patterns: Vec<String> = Vec::new();
for p in repos.iter().map(|p| p.trim()).filter(|p| !p.is_empty()) {
if !grant_pattern_ok(p) {
return Err(Error::Signing(format!(
"`{p}` is not a repository (owner/name) or every repository of an owner (owner/*)"
)));
}
if !patterns.iter().any(|x| x == p) {
patterns.push(p.to_string());
}
}
if patterns.is_empty() || patterns.len() > ANDROID_PATTERNS_MAX {
return Err(Error::Signing(format!("the grant names 1 to {ANDROID_PATTERNS_MAX} repositories")));
}
if !grant_subject_ok(o, c) {
return Err(Error::Signing(
"the certificates need an organisation (1-64 characters) and a two-letter country code".into(),
));
}
let old = self.signing.android.clone();
let grant = AndroidGrant {
repos: patterns,
o: o.into(),
c: c.into(),
granted: now,
last_used: old.as_ref().and_then(|g| g.last_used),
uses: old.as_ref().map_or(0, |g| g.uses),
made: old.map(|g| g.made).unwrap_or_default(),
};
self.security.standing_note(crate::security::Action::StandingGranted, &grant_words(&grant), now);
self.signing.android = Some(grant.clone());
Ok(grant)
}
/// Removes the Android grant (`standing-revoked`); the keys it made stay. False when there is none. The caller
/// saves.
pub fn android_grant_revoke(&mut self, now: i64) -> bool {
let Some(g) = self.signing.android.take() else { return false };
self.security.standing_note(crate::security::Action::StandingRevoked, &grant_words(&g), now);
true
}
/// Whether `req` is signed by the Android grant: an `apk` from this PC's pipe with a run, in the key's scope, for
/// a repository the grant covers and pipeline `release`, by that repository's own app key (scoped to exactly it
/// and `release`, role release), while *Sign only with a card* is not ticked. A key's first signature fits.
pub fn android_grant_fits(&self, req: &Request, now: i64) -> bool {
let Some(g) = &self.signing.android else { return false };
let Ok((view, _)) = self.check(req, now) else { return false };
req.kind == SignKind::Apk
&& req.via == Via::Local
&& req.run.is_some()
&& !self.security.is_ticked(crate::security::Item::CardSigning)
&& view.kind == KeyKind::Android
&& view.role == Role::Release
&& req.context.pipeline == ANDROID_PIPELINE
&& grant_covers(g, &req.context.repo)
&& android_key_id(&req.context.repo).as_deref() == Some(req.key.as_str())
&& view.repos == [req.context.repo.clone()]
&& view.pipelines == [ANDROID_PIPELINE.to_string()]
}
/// Makes `repo`'s app key under the Android grant, when its first release asks (`custos-sign apk`): the grant
/// covers `repo`, `pipeline` is `release`, `via` is local, *Sign only with a card* is not ticked, and there is
/// no key under that id. RSA-4096, `CN=<Name>`, the grant's O and C, scoped to exactly `repo` and `release`.
/// Writes `android-key-made`. The caller saves. Slow: one RSA-4096 key.
pub fn android_grant_make_key(&mut self, repo: &str, pipeline: &str, via: Via, now: i64) -> Result<String, Error> {
let no = |why: String| Err(Error::Signing(why));
let Some(g) = self.signing.android.clone() else { return no("there is no Android grant".into()) };
let (Some((_, name)), Some(id)) = (repo_parts(repo), android_key_id(repo)) else {
return no(format!("`{repo}` is not a repository (owner/name)"));
};
if via != Via::Local {
return no("the server runner never makes a key".into());
}
if pipeline != ANDROID_PIPELINE {
return no(format!("the Android grant makes keys for the pipeline `{ANDROID_PIPELINE}` only"));
}
if self.security.is_ticked(crate::security::Item::CardSigning) {
return no("Sign only with a card is ticked".into());
}
if !grant_covers(&g, repo) {
return no(format!("the Android grant does not cover `{repo}`"));
}
if self.signing.get(&id).is_some() {
return no(format!("there is a key `{id}` already"));
}
let mut cn = name.to_string();
if let Some(first) = cn.get_mut(0..1) {
first.make_ascii_uppercase();
}
let spec = AndroidKey {
id: id.clone(),
name: format!("{cn} Android"),
cn,
o: g.o.clone(),
c: g.c.clone(),
role: Role::Release,
pipelines: vec![ANDROID_PIPELINE.into()],
repos: vec![repo.into()],
};
self.signing_create_android(&spec, now)?;
if let Some(g) = self.signing.android.as_mut()
&& g.made.len() < ANDROID_MADE_MAX
{
g.made.push(id.clone());
}
let words = format!("{id} for {repo} pipeline {ANDROID_PIPELINE}");
self.security.standing_note(crate::security::Action::AndroidKeyMade, &words, now);
Ok(id)
}
/// Every request any key was named in, oldest first.
pub fn signing_audit(&self) -> &[AuditEntry] {
&self.signing.audit