[vault] Android: the android key kind (RSA-4096, self-signed, 100 years) and the apk sign kind (1-4 SHA-512 digests, PKCS#1 v1.5), never unattended; v0.14.0

This commit is contained in:
2026-11-08 00:27:47 +01:00
parent 82698bd9e5
commit 045f1f5d00
12 changed files with 564 additions and 27 deletions
+107 -5
View File
@@ -49,6 +49,8 @@ pub enum KeyKind {
Ed25519,
RootCa,
CodeSigning,
/// An Android app's signing key (core 0.14.0): RSA-4096 and a self-signed certificate; signs `apk` only.
Android,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -59,6 +61,9 @@ pub enum SignKind {
Authenticode,
/// A deploy approval's canonical JSON, signed as minisign by `domi-approve` only (core 0.12.0).
Approval,
/// APK Signature Scheme v2/v3: 1 to 4 SHA-512 digests, signed with RSA PKCS#1 v1.5, by an Android key only
/// (core 0.14.0).
Apk,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -92,7 +97,8 @@ pub struct Context {
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.
/// BLAKE2b-512 of the file (minisign), signtool's 32-byte digest (authenticode), or 1 to 4 SHA-512 digests of
/// an APK's signed data, concatenated (apk). Empty for a manifest or an approval.
pub digest: Vec<u8>,
/// The `SHA256SUMS` text, for a manifest.
pub manifest: Option<String>,
@@ -148,7 +154,8 @@ pub struct AuditEntry {
/// 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).
/// The `.minisig` text (minisign, manifest, approval), the raw RSA signature (authenticode) or the raw RSA
/// signatures, concatenated in the order of the digests (apk).
pub bytes: Vec<u8>,
pub sha256: String,
}
@@ -170,7 +177,7 @@ pub struct KeyView {
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.
/// The certificate (DER), for root, code-signing and Android keys.
pub cert: Option<Vec<u8>>,
pub issuer: Option<String>,
}
@@ -275,7 +282,7 @@ impl Store {
let seed: [u8; 32] = k.secret.expose().try_into().ok()?;
Secret::Ed25519(Ed25519Secret::from_bytes(seed))
}
KeyKind::RootCa | KeyKind::CodeSigning => {
KeyKind::RootCa | KeyKind::CodeSigning | KeyKind::Android => {
Secret::Rsa(RsaSecret::from_pkcs8_der(k.secret.expose().to_vec()).ok()?)
}
};
@@ -297,6 +304,10 @@ impl Store {
Some(c) => Some(unb64(c)?),
None => None,
};
// An Android key is nothing without its certificate: the app is identified by it forever.
if k.kind == KeyKind::Android && cert.is_none() {
return None;
}
keys.push(Key {
id: k.id,
kind: k.kind,
@@ -372,6 +383,22 @@ fn approve_key(pipelines: &[String], repos: &[String], now: i64) -> Key {
}
}
/// What [`Vault::signing_create_android`] makes: the key's id and name, the certificate's subject, its role and
/// who may ask. The key is RSA-4096 and the certificate is valid [`custos_sign::ANDROID_YEARS`] years.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AndroidKey {
/// `[a-z0-9-]{1,64}`, e.g. `postea-android`; not the id of a key the vault has.
pub id: String,
pub name: String,
/// The certificate's subject: common name, organisation, two-letter country code.
pub cn: String,
pub o: String,
pub c: String,
pub role: Role,
pub pipelines: Vec<String>,
pub repos: Vec<String>,
}
fn in_scope(list: &[String], what: &str) -> bool {
list.iter().any(|x| x == "*" || x == what)
}
@@ -484,6 +511,49 @@ impl Vault {
Ok(APPROVE_KEY.into())
}
/// Creates an Android app signing key (core 0.14.0): RSA-4096 and a self-signed certificate. A release key
/// always asks; a test key signs without asking, never for a `tag`. The caller saves. Slow: one RSA-4096 key.
pub fn signing_create_android(&mut self, spec: &AndroidKey, now: i64) -> Result<String, Error> {
let id = spec.id.as_str();
if id.is_empty()
|| id.len() > 64
|| !id.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
{
return Err(Error::Signing("a key id is 1 to 64 of a-z, 0-9 and -".into()));
}
if self.signing.get(id).is_some() {
return Err(Error::Signing(format!("there is a key `{id}` already")));
}
let name = spec.name.trim();
if name.is_empty() || name.len() > 100 || name.chars().any(char::is_control) {
return Err(Error::Signing("the key's name is not usable".into()));
}
let (pipelines, repos) = (clean_list(&spec.pipelines)?, clean_list(&spec.repos)?);
let made = custos_sign::new_android(&spec.cn, &spec.o, &spec.c).map_err(|e| match e {
custos_sign::Error::Certificate => Error::Signing(
"the certificate's name is not usable (1-64 characters without , + = \" \\ < > ; # and no space at \
either end, and a two-letter country code)"
.into(),
),
e => Error::Signing(e.to_string()),
})?;
self.signing.keys.push(Key {
id: id.into(),
kind: KeyKind::Android,
role: spec.role,
name: name.into(),
secret: Secret::Rsa(made.secret),
public: None,
key_id: None,
cert: Some(made.cert_der),
issuer: None,
created: now,
pipelines,
repos,
});
Ok(id.into())
}
/// Every signing key, public parts only.
pub fn signing_keys(&self) -> Vec<KeyView> {
self.signing
@@ -553,6 +623,7 @@ impl Vault {
(KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY,
(KeyKind::Ed25519, SignKind::Approval) => approver,
(KeyKind::CodeSigning, SignKind::Authenticode) => true,
(KeyKind::Android, SignKind::Apk) => true,
_ => false,
};
if k.kind == KeyKind::RootCa {
@@ -579,6 +650,13 @@ impl Vault {
SignKind::Authenticode if req.digest.len() != 32 => {
return Err(Refusal::Invalid("an Authenticode digest is SHA-256: 32 bytes".into()));
}
SignKind::Apk
if req.digest.is_empty()
|| req.digest.len() % 64 != 0
|| req.digest.len() > 64 * custos_sign::MAX_APK_DIGESTS =>
{
return Err(Refusal::Invalid("an APK request is 1 to 4 SHA-512 digests: 64 bytes each".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()))?;
@@ -670,6 +748,7 @@ impl Vault {
)
.map(String::into_bytes),
(Secret::Rsa(s), SignKind::Authenticode) => custos_sign::authenticode(s, &req.digest),
(Secret::Rsa(s), SignKind::Apk) => custos_sign::apk(s, &req.digest),
_ => unreachable!("signing_check matched the key to the kind"),
};
let bytes = match bytes {
@@ -805,6 +884,19 @@ mod tests {
Vault::create(&SecretString::from("pw"), KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap();
v.signing_create(Role::Release, &s(&["*"]), &s(&["*"]), 1).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), 1).unwrap();
for (id, role) in [("postea-android", Role::Release), ("domi-test-android", Role::Test)] {
let spec = AndroidKey {
id: id.into(),
name: id.into(),
cn: "Postea".into(),
o: "Marek Novak".into(),
c: "CZ".into(),
role,
pipelines: s(&["*"]),
repos: s(&["*"]),
};
v.signing_create_android(&spec, 1).unwrap();
}
let secrets: Vec<Vec<u8>> = v
.signing
.keys
@@ -814,7 +906,7 @@ mod tests {
Secret::Rsa(s) => s.expose().to_vec(),
})
.collect();
assert_eq!(secrets.len(), 7, "the release set with domi-approve, and the test set");
assert_eq!(secrets.len(), 9, "the release set with domi-approve, the test set, two Android keys");
// Every public way out: views (serialised and printed), certificates, minisign public keys, checks,
// signatures of every kind, refusals, the audit log, errors, and the Debug of the vault's own store.
@@ -839,6 +931,10 @@ mod tests {
));
reqs.push(approve);
reqs.push(req("domi-approve", SignKind::Minisign, 64));
reqs.push(req("postea-android", SignKind::Apk, 128));
reqs.push(req("domi-test-android", SignKind::Apk, 64));
reqs.push(req("postea-android", SignKind::Authenticode, 32));
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] {
@@ -852,6 +948,12 @@ mod tests {
v.signing_audit().iter().any(|e| e.kind == SignKind::Approval && e.outcome == Outcome::Approved),
"an approval was signed too"
);
assert!(
v.signing_audit()
.iter()
.any(|e| e.kind == SignKind::Apk && e.key == "postea-android" && e.outcome == Outcome::Approved),
"and an APK"
);
out += &serde_json::to_string(v.signing_audit()).unwrap();
out += &format!("{:?}", v.signing_audit());
out += &format!("{:?}", v.signing_create(Role::Release, &[], &[], 3));
+248
View File
@@ -0,0 +1,248 @@
//! Android APK signing keys (core 0.14.0, docs/SIGNING.md "apk"): the key and its certificate, the `apk` kind and
//! nothing else, scope, the test-key rules, malformed requests, the audit through a reopen, and never unattended.
//! That no API path returns an Android key's private half is part of the unit test in src/signing.rs.
use std::collections::BTreeSet;
use std::sync::OnceLock;
use custos_vault::security::{self, Level};
use custos_vault::signing::{AndroidKey, Approval, Context, KeyKind, Outcome, Refusal, Request, Role, SignKind, Via};
use custos_vault::{Error, KdfParams, SecretString, Vault};
use rsa::pkcs1v15::{Signature, VerifyingKey};
use rsa::pkcs8::DecodePublicKey;
use rsa::signature::hazmat::PrehashVerifier;
use x509_cert::der::{Decode, Encode};
const FAST: KdfParams = KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 };
const NOW: i64 = 1_793_750_000_000;
const REPO: &str = "mnovak/Postea";
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
fn spec(id: &str, role: Role, pipelines: &[&str], repos: &[&str]) -> AndroidKey {
AndroidKey {
id: id.into(),
name: if role == Role::Release { "Postea Android".into() } else { "Domi test Android".into() },
cn: if role == Role::Release { "Postea".into() } else { "Domi Test Android".into() },
o: if role == Role::Release { "Marek Novak".into() } else { "Domi".into() },
c: "CZ".into(),
role,
pipelines: s(pipelines),
repos: s(repos),
}
}
/// A vault with the release and test sets, `postea-android` (release, `mnovak/Postea`) and `domi-test-android`
/// (test, any). Two RSA-4096 keys are made once and the vault reopened from its bytes for each test.
fn vault() -> Vault {
static BYTES: OnceLock<Vec<u8>> = OnceLock::new();
let bytes = BYTES.get_or_init(|| {
let mut v = Vault::create(&SecretString::from("pw"), FAST).unwrap();
v.signing_create(Role::Release, &s(&["release"]), &s(&["Arca"]), NOW).unwrap();
v.signing_create(Role::Test, &s(&["*"]), &s(&["*"]), NOW).unwrap();
v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW).unwrap();
v.signing_create_android(&spec("domi-test-android", Role::Test, &["*"], &["*"]), NOW).unwrap();
v.to_bytes().unwrap()
});
Vault::open(bytes, &SecretString::from("pw")).unwrap()
}
fn ctx(pipeline: &str, repo: &str, trigger: &str) -> Context {
Context {
repo: repo.into(),
commit: "6925d0cb08b9e0c5c3a4a7a2c37b7f2a9f7ed3b1".into(),
pipeline: pipeline.into(),
step: "sign".into(),
trigger: trigger.into(),
file: "Postea-1.0.0.apk".into(),
size: 9_876_543,
sha256: "c4995c6e2e0c20fec7e8dcb05d70144da58f42d379c6705df66edb42abafb8a3".into(),
version: "1.0.0".into(),
}
}
fn apk_req(key: &str, digests: usize, c: Context) -> Request {
Request {
key: key.into(),
kind: SignKind::Apk,
digest: (0..digests * 64).map(|i| (i % 251) as u8).collect(),
manifest: None,
approval: None,
run: Some("r-7".into()),
context: c,
via: Via::Local,
}
}
fn release() -> Context {
ctx("release", REPO, "tag")
}
#[test]
fn an_android_key_has_its_certificate_and_no_secret_in_its_view() {
let v = vault();
let keys = v.signing_keys();
let k = keys.iter().find(|k| k.id == "postea-android").unwrap();
assert_eq!((k.kind, k.role, k.auto_approve), (KeyKind::Android, Role::Release, false));
assert_eq!((k.pipelines.clone(), k.repos.clone()), (s(&["release"]), s(&[REPO])));
assert_eq!((k.issuer.clone(), k.key_id.clone(), k.minisign_public.clone()), (None, None, None));
let cert = v.signing_export_cert("postea-android").unwrap();
assert_eq!(k.cert.as_deref(), Some(cert.as_slice()));
let c = x509_cert::Certificate::from_der(&cert).unwrap();
assert_eq!(c.tbs_certificate.subject.to_string(), "CN=Postea,O=Marek Novak,C=CZ");
assert_eq!(c.tbs_certificate.issuer, c.tbs_certificate.subject);
let t = keys.iter().find(|k| k.id == "domi-test-android").unwrap();
assert_eq!((t.kind, t.role, t.auto_approve), (KeyKind::Android, Role::Test, true));
// Both serialise as the closed value `android`.
assert!(serde_json::to_string(k).unwrap().contains(r#""kind":"android""#));
}
#[test]
fn ids_and_names_are_checked_and_an_id_is_made_once() {
let mut v = vault();
let again = v.signing_create_android(&spec("postea-android", Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(again, Err(Error::Signing(m)) if m.contains("already")));
let taken = v.signing_create_android(&spec("domi-release", Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(taken, Err(Error::Signing(_))), "an id of another kind");
for bad in ["", "Postea", "postea android", "postea/android", &"x".repeat(65)] {
let r = v.signing_create_android(&spec(bad, Role::Release, &["release"], &[REPO]), NOW);
assert!(matches!(r, Err(Error::Signing(_))), "{bad:?}");
}
let mut odd = spec("odd-android", Role::Release, &["release"], &[REPO]);
odd.c = "Czechia".into();
assert!(matches!(v.signing_create_android(&odd, NOW), Err(Error::Signing(m)) if m.contains("country")));
assert_eq!(v.signing_keys().len(), 9, "nothing was added");
}
#[test]
fn an_apk_request_signs_every_digest_with_sha512_pkcs1_and_the_certificates_key() {
let mut v = vault();
let req = apk_req("postea-android", 2, release());
assert!(v.signing_check(&req).is_ok());
let signed = v.signing_sign(&req, Approval::Mark, NOW).unwrap();
assert_eq!(signed.bytes.len(), 2 * 512, "two RSA-4096 signatures");
assert_eq!(signed.sha256, custos_sign::sha256_hex(&signed.bytes));
let cert = x509_cert::Certificate::from_der(&v.signing_export_cert("postea-android").unwrap()).unwrap();
let spki = cert.tbs_certificate.subject_public_key_info.to_der().unwrap();
let key = VerifyingKey::<sha2_010::Sha512>::from_public_key_der(&spki).unwrap();
for (d, sig) in req.digest.chunks(64).zip(signed.bytes.chunks(512)) {
key.verify_prehash(d, &Signature::try_from(sig).unwrap()).unwrap();
}
// One request, one audit entry, whatever the number of digests.
let a = v.signing_audit().last().unwrap();
assert_eq!((a.key.as_str(), a.kind, a.outcome), ("postea-android", SignKind::Apk, Outcome::Approved));
assert_eq!((a.context.file.as_str(), a.run.as_deref()), ("Postea-1.0.0.apk", Some("r-7")));
}
#[test]
fn an_android_key_signs_only_apks_and_only_android_keys_sign_apks() {
let mut v = vault();
let mut exe = apk_req("postea-android", 0, release());
exe.kind = SignKind::Authenticode;
exe.digest = vec![9; 32];
let mut minisign = exe.clone();
minisign.kind = SignKind::Minisign;
minisign.digest = vec![9; 64];
let leaf = Request {
key: "domi-code-signing".into(),
context: ctx("release", "Arca", "tag"),
..apk_req("", 1, release())
};
let ed =
Request { key: "domi-release".into(), context: ctx("release", "Arca", "tag"), ..apk_req("", 1, release()) };
let root = Request { key: "domi-root".into(), ..apk_req("", 1, release()) };
let test_leaf = Request { key: "domi-test-code-signing".into(), ..apk_req("", 1, ctx("ci", REPO, "push")) };
for r in [&exe, &minisign, &leaf, &ed, &root, &test_leaf] {
assert!(matches!(v.signing_check(r), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
assert!(matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))), "{} {:?}", r.key, r.kind);
}
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
}
#[test]
fn another_repo_or_pipeline_is_out_of_scope_even_when_approved() {
let mut v = vault();
for c in [ctx("release", "mnovak/Arca", "tag"), ctx("release", "Postea", "tag"), ctx("nightly", REPO, "tag")] {
let r = apk_req("postea-android", 2, c);
assert!(matches!(v.signing_check(&r), Err(Refusal::OutOfScope(_))));
assert!(matches!(v.signing_sign(&r, Approval::Mark, NOW), Err(Refusal::OutOfScope(_))));
}
assert_eq!(v.signing_audit().iter().filter(|e| e.outcome == Outcome::OutOfScope).count(), 3);
}
#[test]
fn the_release_key_always_needs_mark_and_the_test_twin_signs_alone_but_never_a_tag() {
let mut v = vault();
let r = v.signing_sign(&apk_req("postea-android", 2, release()), Approval::Auto, NOW);
assert!(matches!(r, Err(Refusal::NeedsApproval(_))));
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Refused);
let t = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "manual")), Approval::Auto, NOW).unwrap();
assert_eq!(t.bytes.len(), 1024);
assert_eq!(v.signing_audit().last().unwrap().outcome, Outcome::Auto);
let tag = v.signing_sign(&apk_req("domi-test-android", 2, ctx("ci", REPO, "tag")), Approval::Auto, NOW);
assert!(matches!(tag, Err(Refusal::OutOfScope(m)) if m.contains("never signs a tag")));
}
#[test]
fn malformed_apk_requests_are_refused() {
let mut v = vault();
let mut cases = Vec::new();
for n in [0usize, 1, 32, 63, 65, 64 * 5] {
let mut r = apk_req("postea-android", 0, release());
r.digest = vec![1; n];
if n != 1 {
cases.push(r);
}
}
let mut no_file = apk_req("postea-android", 2, release());
no_file.context.file = String::new();
let mut path = apk_req("postea-android", 2, release());
path.context.file = "out\\Postea.apk".into();
let mut stray = apk_req("postea-android", 2, release());
stray.approval = Some("{}".into());
let mut bad_run = apk_req("postea-android", 2, release());
bad_run.run = Some("r 7".into());
cases.extend([no_file, path, stray, bad_run]);
for r in &cases {
assert!(
matches!(v.signing_sign(r, Approval::Mark, NOW), Err(Refusal::Invalid(_))),
"{} bytes {:?}",
r.digest.len(),
r.context.file
);
}
assert_eq!(v.signing_audit().len(), cases.len());
assert!(v.signing_audit().iter().all(|e| e.outcome == Outcome::Invalid && e.signature.is_none()));
}
#[test]
fn refused_and_expired_apk_requests_are_recorded_and_everything_survives_a_reopen() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("v.custos");
let mut v = vault();
let req = apk_req("postea-android", 2, release());
v.signing_refuse(&req, Outcome::Refused, Some("Mark refused this signature".into()), NOW);
v.signing_refuse(&req, Outcome::Expired, None, NOW + 1);
let signed = v.signing_sign(&req, Approval::Mark, NOW + 2).unwrap();
v.save(&path).unwrap();
let mut back = Vault::open_file(&path, &SecretString::from("pw")).unwrap();
assert_eq!(back.signing_audit(), v.signing_audit());
let outcomes: Vec<Outcome> = back.signing_audit().iter().map(|e| e.outcome).collect();
assert_eq!(outcomes, [Outcome::Refused, Outcome::Expired, Outcome::Approved]);
assert_eq!(back.signing_audit()[2].signature.as_deref(), Some(signed.sha256.as_str()));
assert_eq!(back.signing_keys(), v.signing_keys());
// The same key: a reopened vault makes the same (deterministic PKCS#1 v1.5) signatures.
assert_eq!(back.signing_sign(&req, Approval::Mark, NOW + 3).unwrap().bytes, signed.bytes);
}
#[test]
fn apk_requests_are_never_signed_unattended_even_on_the_hands_off_vault() {
// `unattended_sign` is a closed list of kinds: `apk` is not on it, so an APK always shows the card.
for level in [Level::Setup, Level::Standard] {
assert!(!security::unattended_sign(level, &BTreeSet::new(), true, "apk", true));
assert!(security::unattended_sign(level, &BTreeSet::new(), true, "authenticode", true));
}
}