diff --git a/Cargo.lock b/Cargo.lock index da67782..18daaaa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -329,14 +329,14 @@ dependencies = [ [[package]] name = "custos-browser" -version = "0.20.0" +version = "0.21.0" dependencies = [ "zeroize", ] [[package]] name = "custos-gen" -version = "0.20.0" +version = "0.21.0" dependencies = [ "custos-vault", "data-encoding", @@ -348,7 +348,7 @@ dependencies = [ [[package]] name = "custos-kdbx" -version = "0.20.0" +version = "0.21.0" dependencies = [ "aes", "argon2", @@ -369,7 +369,7 @@ dependencies = [ [[package]] name = "custos-keys" -version = "0.20.0" +version = "0.21.0" dependencies = [ "custos-vault", "ed25519-dalek", @@ -382,7 +382,7 @@ dependencies = [ [[package]] name = "custos-native" -version = "0.20.0" +version = "0.21.0" dependencies = [ "custos-browser", "serde_json", @@ -392,11 +392,11 @@ dependencies = [ [[package]] name = "custos-qr" -version = "0.20.0" +version = "0.21.0" [[package]] name = "custos-seal" -version = "0.20.0" +version = "0.21.0" dependencies = [ "chacha20poly1305", "hkdf", @@ -409,7 +409,7 @@ dependencies = [ [[package]] name = "custos-share" -version = "0.20.0" +version = "0.21.0" dependencies = [ "argon2", "chacha20poly1305", @@ -426,7 +426,7 @@ dependencies = [ [[package]] name = "custos-sign" -version = "0.20.0" +version = "0.21.0" dependencies = [ "blake2 0.10.6", "data-encoding", @@ -446,7 +446,7 @@ dependencies = [ [[package]] name = "custos-team" -version = "0.20.0" +version = "0.21.0" dependencies = [ "custos-seal", "custos-sign", @@ -464,7 +464,7 @@ dependencies = [ [[package]] name = "custos-totp" -version = "0.20.0" +version = "0.21.0" dependencies = [ "custos-vault", "data-encoding", @@ -477,7 +477,7 @@ dependencies = [ [[package]] name = "custos-vault" -version = "0.20.0" +version = "0.21.0" dependencies = [ "argon2", "bip39", @@ -503,7 +503,7 @@ dependencies = [ [[package]] name = "custos-wasm" -version = "0.20.0" +version = "0.21.0" dependencies = [ "custos-qr", "custos-seal", diff --git a/Cargo.toml b/Cargo.toml index f0ea2b4..7de456a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.20.0" +version = "0.21.0" edition = "2024" license = "CPAL-1.0" repository = "https://gitea.marek-novak.cz/mnovak/CustosPublic" diff --git a/crates/custos-sign/src/lib.rs b/crates/custos-sign/src/lib.rs index 61fac23..23e2542 100644 --- a/crates/custos-sign/src/lib.rs +++ b/crates/custos-sign/src/lib.rs @@ -195,6 +195,12 @@ pub fn minisign_public(public: &[u8; 32], key_id: &[u8; 8]) -> String { format!("untrusted comment: minisign public key {}\n{}\n", key_id_hex(key_id), BASE64.encode(&raw)) } +/// A plain Ed25519 signature over `message` itself: no prehash, no digest, no wrapping (core 0.21.0, the Domi +/// licence, docs/SIGNING.md "Domi licences"). ed25519-dalek's deterministic RFC 8032 signature. +pub fn ed25519_plain(secret: &Ed25519Secret, message: &[u8]) -> [u8; 64] { + SigningKey::from_bytes(&secret.0).sign(message).to_bytes() +} + /// A prehashed minisign signature file over a file whose BLAKE2b-512 is `digest`. /// The trusted comment is `timestamp:\tfile:\thashed`, as minisign writes it. pub fn minisign( diff --git a/crates/custos-vault/src/lib.rs b/crates/custos-vault/src/lib.rs index 4f93661..0a5677c 100644 --- a/crates/custos-vault/src/lib.rs +++ b/crates/custos-vault/src/lib.rs @@ -20,6 +20,7 @@ mod crypto; mod device; mod format; pub mod identity; +pub mod licence; mod item; pub mod provision; mod recovery; diff --git a/crates/custos-vault/src/licence.rs b/crates/custos-vault/src/licence.rs new file mode 100644 index 0000000..ace7737 --- /dev/null +++ b/crates/custos-vault/src/licence.rs @@ -0,0 +1,843 @@ +//! Domi licences (core 0.21.0, docs/SIGNING.md "Domi licences"; the byte format is Fundamentum's docs/LICENCE.md, +//! licence v1): the key `domi-licence`, the strict parser of what it signs, and Mark's licence grant. +//! +//! The key is an Ed25519 key in the signing store under the reserved id [`LICENCE_KEY`], with no scope: every +//! other signing path refuses it, so it signs only the two payload kinds here (a licence, a revocation list), and +//! no other key signs them. Its secret never leaves this module and `signing.rs`; only its public key does. +//! +//! What it signs is parsed here **before** anything else, byte for byte as the spec's strict parser does (§2.4 +//! steps 1–4 and 7 for a licence, §4.1 for a revocation list): malformed input is refused with the spec's code and +//! never reaches a card. Then the grant decides: a licence from `licence-issue` (its Canalis app id, and a +//! Domi-signed program) whose apps are all on Mark's allowlist, within the cap, is signed at once; anything else +//! that is well formed asks Mark on a card. A revocation list always asks. Refused outright, never a card: a licence +//! whose `issued` is more than a day from this clock, a licence id this key signed before (`replay`), a revocation +//! list whose `seq` is not higher than the highest this key signed (`rollback`), and any caller but `licence-issue`. +//! +//! The grant and the log live in the signing store's `licence` member, which cores before 0.21.0 ignore (and drop if +//! they save the vault: then the grant is gone, which fails closed, and the service's own anti-rollback check still +//! holds, Fundamentum docs/LICENCE.md §4.2). The key itself is an ordinary Ed25519 entry every core reads. + +use serde::{Deserialize, Serialize}; + +use crate::{Error, Vault}; + +/// The reserved id of the licence key. +pub const LICENCE_KEY: &str = "domi-licence"; +/// The one Canalis app that may ask for a licence signature. +pub const LICENCE_ISSUER: &str = "licence-issue"; + +/// The first line of a licence payload, inside the signed bytes. +pub const LICENCE_PREFIX: &str = "domi-licence-v1\n"; +/// The first line of a revocation list payload, inside the signed bytes. +pub const REVOCATIONS_PREFIX: &str = "domi-revocations-v1\n"; + +/// What the `sig:` line adds to a payload to make the file: `sig: ` (5), 86 characters, LF. +const SIG_LINE_LEN: usize = 5 + 86 + 1; +/// The largest licence payload signed: the spec caps the **file** at 4096 bytes, so a payload is at most what still +/// fits with its signature line. Stricter than the spec's payload parser, never looser. +pub const LICENCE_PAYLOAD_MAX: usize = 4096 - SIG_LINE_LEN; +/// The largest revocation list payload signed, for the spec's 61 440-byte file. +pub const REVOCATIONS_PAYLOAD_MAX: usize = 61_440 - SIG_LINE_LEN; + +/// How far a licence's `issued` may be from this clock, either way (seconds). +pub const CLOCK_TOLERANCE_S: i64 = 86_400; +/// At most this many licence signatures in a rolling day; past it, each one asks on a card. +pub const DAY_CAP: usize = 50; +const DAY_MS: i64 = 86_400_000; +/// At most this many app ids on the allowlist. +pub const ALLOW_MAX: usize = 256; +/// At most this many signatures in the log. Every licence id and revocation `seq` signed must stay known (replay, +/// rollback), so a full log refuses to sign more rather than forget (`log_full`). +pub const LOG_MAX: usize = 20_000; + +const MAX_APPS: usize = 64; +const MAX_SEQ: u64 = (1 << 53) - 1; +const LICENCE_FIELDS: [&str; 7] = ["id", "issued", "nickname", "bundle", "scope", "seats", "apps"]; +const REVOCATION_FIELDS: [&str; 3] = ["seq", "issued", "revoked"]; + +/// A licence payload, as parsed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Licence { + pub id: String, + /// Unix seconds. + pub issued: i64, + pub nickname: String, + pub bundle: String, + /// `None` for `scope: household`, the seat count for `scope: seat`. + pub seats: Option, + /// Sorted ascending and unique. + pub apps: Vec, +} + +/// A revocation list payload, as parsed. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Revocations { + pub seq: u64, + /// Unix seconds. + pub issued: i64, + /// Sorted strictly ascending. + pub revoked: Vec, +} + +/// What a payload is. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Payload { + Licence(Licence), + Revocations(Revocations), +} + +/// Why a payload is not signed. [`LicenceRefusal::code`] is the spec's error code (Fundamentum docs/LICENCE.md §8) +/// where the spec has one, else Custos's own. None carries payload or key bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] +pub enum LicenceRefusal { + /// The spec's strict parser refused the payload (§2.4 steps 1–4 and 7, §4.1). + #[error("the payload is malformed: {0}")] + Malformed(&'static str), + /// There is no `domi-licence` key yet. + #[error("there is no licence key in this vault")] + NoKey, + /// Only `licence-issue` may ask. + #[error("only licence-issue may ask for a licence signature")] + NotAllowed, + /// The licence's `issued` is more than a day from this clock. + #[error("the licence is dated more than a day from this PC's clock")] + Clock, + /// This key signed a licence with this id before. + #[error("a licence with this id was signed before")] + Replay, + /// This key signed a revocation list with this `seq` or a higher one before. + #[error("a revocation list with this seq or a higher one was signed before")] + Rollback, + /// The log is full. + #[error("the licence log is full")] + LogFull, + /// Asked to sign without a card where the grant does not cover the request. + #[error("this needs Mark's answer on a card")] + NeedsCard, +} + +impl LicenceRefusal { + pub fn code(self) -> &'static str { + match self { + LicenceRefusal::Malformed(c) => c, + LicenceRefusal::NoKey => "no_key", + LicenceRefusal::NotAllowed => "not_allowed", + LicenceRefusal::Clock => "clock", + LicenceRefusal::Replay => "replay", + LicenceRefusal::Rollback => "rollback", + LicenceRefusal::LogFull => "log_full", + LicenceRefusal::NeedsCard => "needs_card", + } + } +} + +// ---- the strict parser (Fundamentum docs/LICENCE.md §2.4 steps 1–4 and 7, §4.1) ---- + +fn malformed(code: &'static str) -> LicenceRefusal { + LicenceRefusal::Malformed(code) +} + +/// A licence id: 8–64 bytes of `[A-Za-z0-9_-]`. +pub fn licence_id_ok(s: &str) -> bool { + (8..=64).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') +} + +/// A Tessera id (a bundle, an app): 1–32 bytes of `[a-z0-9-]`, not starting or ending with `-`. +pub fn tessera_id_ok(s: &str) -> bool { + (1..=32).contains(&s.len()) + && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !s.starts_with('-') + && !s.ends_with('-') +} + +/// A nickname: 1–32 bytes of `[A-Za-z0-9 ._-]`, no space at either end, never two spaces in a row. +fn nickname_ok(s: &str) -> bool { + (1..=32).contains(&s.len()) + && s.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b' ' | b'.' | b'_' | b'-')) + && !s.starts_with(' ') + && !s.ends_with(' ') + && !s.contains(" ") +} + +/// `[1-9]`, `[1-4][0-9]` or `50`. +fn seats(s: &str) -> Option { + let ok = matches!(s.as_bytes(), [b'1'..=b'9'] | [b'1'..=b'4', b'0'..=b'9'] | [b'5', b'0']); + ok.then(|| s.parse().ok()).flatten() +} + +/// Decimal 1 to 2^53 − 1, no leading zero, no sign. +fn seq(s: &str) -> Option { + let digits = !s.is_empty() && s.len() <= 16 && s.bytes().all(|b| b.is_ascii_digit()) && !s.starts_with('0'); + digits.then(|| s.parse::().ok()).flatten().filter(|n| (1..=MAX_SEQ).contains(n)) +} + +/// `YYYY-MM-DDTHH:MM:SSZ`, year 2000–2999, a real Gregorian date, no leap second: Unix seconds. +pub fn parse_utc(s: &str) -> Option { + let b = s.as_bytes(); + if b.len() != 20 || b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' || b[19] != b'Z' { + return None; + } + let num = |from: usize, to: usize| -> Option { + let part = &b[from..to]; + part.iter().all(u8::is_ascii_digit).then(|| part.iter().fold(0i64, |n, d| n * 10 + i64::from(d - b'0'))) + }; + let (y, mo, d) = (num(0, 4)?, num(5, 7)?, num(8, 10)?); + let (h, mi, sec) = (num(11, 13)?, num(14, 16)?, num(17, 19)?); + let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; + let days_in = match mo { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 if leap => 29, + 2 => 28, + _ => return None, + }; + if !(2000..=2999).contains(&y) || !(1..=days_in).contains(&d) || h > 23 || mi > 59 || sec > 59 { + return None; + } + // Days from the civil date (Howard Hinnant's algorithm). + let (yy, mm) = if mo <= 2 { (y - 1, mo + 9) } else { (y, mo - 3) }; + let era = yy.div_euclid(400); + let yoe = yy - era * 400; + let doy = (153 * mm + 2) / 5 + d - 1; + let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + let days = era * 146_097 + doe - 719_468; + Some(days * 86_400 + h * 3600 + mi * 60 + sec) +} + +/// The apps value: every element a Tessera id, at most 64, then sorted ascending and unique (in that order of checks). +fn apps(s: &str) -> Result, LicenceRefusal> { + let list: Vec<&str> = s.split(',').collect(); + if !list.iter().all(|a| tessera_id_ok(a)) { + return Err(malformed("bad_apps")); + } + if list.len() > MAX_APPS { + return Err(malformed("too_many_apps")); + } + for pair in list.windows(2) { + match pair[0].cmp(pair[1]) { + std::cmp::Ordering::Equal => return Err(malformed("apps_duplicate")), + std::cmp::Ordering::Greater => return Err(malformed("apps_unsorted")), + std::cmp::Ordering::Less => {} + } + } + Ok(list.into_iter().map(String::from).collect()) +} + +/// `: `: a 1–16 byte `[a-z]` name, one space, a non-empty value. +fn field(line: &str) -> Result<(&str, &str), LicenceRefusal> { + let (name, value) = line.split_once(": ").ok_or(malformed("bad_line"))?; + if !(1..=16).contains(&name.len()) || !name.bytes().all(|b| b.is_ascii_lowercase()) || value.is_empty() { + return Err(malformed("bad_line")); + } + Ok((name, value)) +} + +/// Steps 1–4 on a payload, and the lines after the prefix (step 7's input). The prefix says the kind. +fn structure(input: &[u8]) -> Result<(bool, Vec<&str>), LicenceRefusal> { + if input.len() > REVOCATIONS_PAYLOAD_MAX { + return Err(malformed("too_large")); + } + if input.is_empty() { + return Err(malformed("truncated")); + } + if input.contains(&b'\r') { + return Err(malformed("crlf")); + } + if input.iter().any(|&b| b != b'\n' && !(0x20..=0x7e).contains(&b)) { + return Err(malformed("bad_byte")); + } + let licence = input.starts_with(LICENCE_PREFIX.as_bytes()); + let prefix = if licence { + LICENCE_PREFIX + } else if input.starts_with(REVOCATIONS_PREFIX.as_bytes()) { + REVOCATIONS_PREFIX + } else if LICENCE_PREFIX.as_bytes().starts_with(input) || REVOCATIONS_PREFIX.as_bytes().starts_with(input) { + return Err(malformed("truncated")); + } else { + return Err(malformed("bad_prefix")); + }; + if licence && input.len() > LICENCE_PAYLOAD_MAX { + return Err(malformed("too_large")); + } + if input.last() != Some(&b'\n') { + return Err(malformed("truncated")); + } + // Printable ASCII and LF only: valid UTF-8. + let text = std::str::from_utf8(input).map_err(|_| malformed("bad_byte"))?; + let body = &text[prefix.len()..]; + let lines = if body.is_empty() { Vec::new() } else { body[..body.len() - 1].split('\n').collect() }; + Ok((licence, lines)) +} + +fn licence_fields(lines: &[&str]) -> Result { + let mut v: [Option<&str>; 7] = [None; 7]; + let mut last: Option = None; + let (mut issued, mut household, mut seat_count, mut app_list) = (None, None, None, None); + for line in lines { + let (name, value) = field(line)?; + let i = LICENCE_FIELDS.iter().position(|f| *f == name).ok_or(malformed("unknown_field"))?; + if v[i].is_some() { + return Err(malformed("duplicate_field")); + } + if last.is_some_and(|l| i < l) { + return Err(malformed("field_order")); + } + last = Some(i); + v[i] = Some(value); + match i { + 0 if !licence_id_ok(value) => return Err(malformed("bad_id")), + 1 => issued = Some(parse_utc(value).ok_or(malformed("bad_issued"))?), + 2 if !nickname_ok(value) => return Err(malformed("bad_nickname")), + 3 if !tessera_id_ok(value) => return Err(malformed("bad_bundle")), + 4 => { + household = Some(match value { + "household" => true, + "seat" => false, + _ => return Err(malformed("bad_scope")), + }) + } + 5 => seat_count = Some(seats(value).ok_or(malformed("bad_seats"))?), + 6 => app_list = Some(apps(value)?), + _ => {} + } + } + let (Some(id), Some(issued), Some(nickname), Some(bundle), Some(household), Some(apps)) = + (v[0], issued, v[2], v[3], household, app_list) + else { + return Err(malformed("missing_field")); + }; + let seats = match (household, seat_count) { + (true, None) => None, + (true, Some(_)) => return Err(malformed("seats_with_household")), + (false, Some(n)) => Some(n), + (false, None) => return Err(malformed("seats_missing")), + }; + Ok(Licence { id: id.into(), issued, nickname: nickname.into(), bundle: bundle.into(), seats, apps }) +} + +fn revocation_fields(lines: &[&str]) -> Result { + let (mut seq_v, mut issued) = (None, None); + let mut revoked: Vec = Vec::new(); + let mut last: Option = None; + for line in lines { + let (name, value) = field(line)?; + let i = REVOCATION_FIELDS.iter().position(|f| *f == name).ok_or(malformed("unknown_field"))?; + let seen = match i { + 0 => seq_v.is_some(), + 1 => issued.is_some(), + _ => false, + }; + if seen { + return Err(malformed("duplicate_field")); + } + if last.is_some_and(|l| i < l) { + return Err(malformed("field_order")); + } + last = Some(i); + match i { + 0 => seq_v = Some(seq(value).ok_or(malformed("bad_seq"))?), + 1 => issued = Some(parse_utc(value).ok_or(malformed("bad_issued"))?), + _ => { + if !licence_id_ok(value) { + return Err(malformed("bad_id")); + } + if let Some(prev) = revoked.last() { + match prev.as_str().cmp(value) { + std::cmp::Ordering::Equal => return Err(malformed("revoked_duplicate")), + std::cmp::Ordering::Greater => return Err(malformed("revoked_unsorted")), + std::cmp::Ordering::Less => {} + } + } + revoked.push(value.into()); + } + } + } + let (Some(seq), Some(issued)) = (seq_v, issued) else { return Err(malformed("missing_field")) }; + Ok(Revocations { seq, issued, revoked }) +} + +/// The strict parser on a payload: a licence (§2.4 steps 1–4 and 7) or a revocation list (§4.1), by its prefix. +/// Custos never sees a `sig:` line, so steps 5 and 6 do not apply: one in a payload is an `unknown_field`. +pub fn parse_payload(payload: &[u8]) -> Result { + let (licence, lines) = structure(payload)?; + if licence { + licence_fields(&lines).map(Payload::Licence) + } else { + revocation_fields(&lines).map(Payload::Revocations) + } +} + +// ---- the grant, the log, and what Custos does with a request ---- + +/// Mark's licence grant: what `licence-issue` may have signed without a card. Nothing in it is secret. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LicenceGrant { + /// The app ids a licence may name and still be signed without a card (Tessera ids, sorted, unique). + pub allow: Vec, + /// Unix milliseconds: when Mark gave it, or last changed it. + pub granted: i64, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub last_used: Option, + #[serde(default)] + pub uses: u64, +} + +/// How a signature was allowed. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum LicenceBy { + /// Mark's licence grant covered it: no card. + Grant, + /// Mark said yes on a card. + Card, +} + +/// One signature in the log: when, what (a licence's id and apps, or a revocation list's seq and count), and how it +/// was allowed. Never the signature, the payload or the nickname. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LicenceEntry { + pub at: i64, + pub by: LicenceBy, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub licence: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub apps: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub seq: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub revoked: Option, +} + +/// The grant and the log, in the signing store. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct LicenceStore { + #[serde(default, skip_serializing_if = "Option::is_none")] + pub grant: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub log: Vec, +} + +impl LicenceStore { + pub(crate) fn is_empty(&self) -> bool { + self.grant.is_none() && self.log.is_empty() + } + + /// What this core could have written; anything else makes the vault refuse to open. + pub(crate) fn ok(&self) -> bool { + let grant_ok = self.grant.as_ref().is_none_or(|g| allow_ok(&g.allow)); + let entry_ok = |e: &LicenceEntry| match (&e.licence, e.seq) { + (Some(id), None) => { + licence_id_ok(id) + && e.revoked.is_none() + && (1..=MAX_APPS).contains(&e.apps.len()) + && e.apps.iter().all(|a| tessera_id_ok(a)) + } + (None, Some(n)) => (1..=MAX_SEQ).contains(&n) && e.apps.is_empty(), + _ => false, + }; + grant_ok && self.log.len() <= LOG_MAX && self.log.iter().all(entry_ok) + } +} + +fn allow_ok(allow: &[String]) -> bool { + allow.len() <= ALLOW_MAX && allow.iter().all(|a| tessera_id_ok(a)) && allow.windows(2).all(|p| p[0] < p[1]) +} + +/// Why a well-formed request asks Mark on a card instead of being signed at once. Shown on the card. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase", tag = "why")] +pub enum CardReason { + /// A revocation list always asks. + Revocations, + /// There is no licence grant. + NoGrant, + /// The caller is not a program signed with Domi's certificate. + NotDomiSigned, + /// *Sign only with a card* is ticked. + CardSigning, + /// These apps are not on the allowlist. + OffAllowlist { apps: Vec }, + /// The day's cap of licence signatures is reached. + OverCap { signed: usize }, +} + +/// What Custos would do with a well-formed request. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LicenceAsk { + pub payload: Payload, + /// Empty: the grant signs it now. Else the card's reasons. + pub card: Vec, +} + +/// Who asks: the caller's authenticated Canalis app id, and whether its program is signed with one of Domi's +/// code-signing certificates (the desktop's check; docs/25 in Custos). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Caller<'a> { + pub app: &'a str, + pub domi_signed: bool, +} + +impl Vault { + /// Makes the licence key (Ed25519) and returns its 32-byte public key, the one the Atrium Domi service ships. + /// Refused when there is one already. Call it only from Mark's own click. The caller saves. + pub fn licence_key_create(&mut self, now: i64) -> Result<[u8; 32], Error> { + if self.signing.get(LICENCE_KEY).is_some() { + return Err(Error::Signing(format!("there is a key `{LICENCE_KEY}` already"))); + } + let public = self.signing.add_licence_key(now); + let words = format!("licence key {LICENCE_KEY} made"); + self.security.standing_note(crate::security::Action::StandingGranted, &words, now); + Ok(public) + } + + /// The licence key's public key, if there is one. + pub fn licence_public(&self) -> Option<[u8; 32]> { + self.signing.get(LICENCE_KEY).and_then(|k| k.public) + } + + /// The licence grant, if Mark gave it. + pub fn licence_grant(&self) -> Option { + self.signing.licence.grant.clone() + } + + /// Gives the licence grant, or replaces its allowlist (its counts stay), and writes `standing-granted`. Refused + /// while *Sign only with a card* is ticked, and before there is a licence key. Call it only from Mark's own click. + /// The caller saves. + pub fn licence_grant_set(&mut self, allow: &[String], now: i64) -> Result { + if self.security.is_ticked(crate::security::Item::CardSigning) { + return Err(Error::Signing("Sign only with a card is ticked".into())); + } + if self.signing.get(LICENCE_KEY).is_none() { + return Err(Error::Signing("make the licence key first".into())); + } + let mut list: Vec = Vec::new(); + for a in allow.iter().map(|a| a.trim()).filter(|a| !a.is_empty()) { + if !tessera_id_ok(a) { + return Err(Error::Signing(format!("`{a}` is not an app id (a-z, 0-9 and -, up to 32)"))); + } + list.push(a.to_string()); + } + list.sort(); + list.dedup(); + if list.len() > ALLOW_MAX { + return Err(Error::Signing(format!("the allowlist holds at most {ALLOW_MAX} apps"))); + } + let old = self.signing.licence.grant.clone(); + let grant = LicenceGrant { + allow: list, + granted: now, + last_used: old.as_ref().and_then(|g| g.last_used), + uses: old.map_or(0, |g| g.uses), + }; + let words = format!("Domi licences by {LICENCE_ISSUER}: {}", grant.allow.join(", ")); + self.security.standing_note(crate::security::Action::StandingGranted, &words, now); + self.signing.licence.grant = Some(grant.clone()); + Ok(grant) + } + + /// Removes the licence grant (`standing-revoked`): from then on every licence asks on a card. The key and the log + /// stay. False when there is none. The caller saves. + pub fn licence_grant_revoke(&mut self, now: i64) -> bool { + let Some(g) = self.signing.licence.grant.take() else { return false }; + let words = format!("Domi licences by {LICENCE_ISSUER}: {}", g.allow.join(", ")); + self.security.standing_note(crate::security::Action::StandingRevoked, &words, now); + true + } + + /// Every licence signature, oldest first. + pub fn licence_log(&self) -> &[LicenceEntry] { + &self.signing.licence.log + } + + /// What Custos does with `payload` from `caller` at `now` (Unix milliseconds): refused (the code says why, no + /// card), signed by the grant (no reasons), or asked on a card (its reasons). Changes nothing. + pub fn licence_ask(&self, payload: &[u8], caller: Caller<'_>, now: i64) -> Result { + let parsed = parse_payload(payload)?; + if self.signing.get(LICENCE_KEY).is_none() { + return Err(LicenceRefusal::NoKey); + } + if caller.app != LICENCE_ISSUER { + return Err(LicenceRefusal::NotAllowed); + } + if self.signing.licence.log.len() >= LOG_MAX { + return Err(LicenceRefusal::LogFull); + } + let log = &self.signing.licence.log; + let mut card = Vec::new(); + match &parsed { + Payload::Licence(l) => { + if (l.issued - now.div_euclid(1000)).abs() > CLOCK_TOLERANCE_S { + return Err(LicenceRefusal::Clock); + } + if log.iter().any(|e| e.licence.as_deref() == Some(l.id.as_str())) { + return Err(LicenceRefusal::Replay); + } + if !caller.domi_signed { + card.push(CardReason::NotDomiSigned); + } + if self.security.is_ticked(crate::security::Item::CardSigning) { + card.push(CardReason::CardSigning); + } + match &self.signing.licence.grant { + None => card.push(CardReason::NoGrant), + Some(g) => { + let off: Vec = l.apps.iter().filter(|a| !g.allow.contains(a)).cloned().collect(); + if !off.is_empty() { + card.push(CardReason::OffAllowlist { apps: off }); + } + } + } + let today = log.iter().filter(|e| e.licence.is_some() && e.at > now - DAY_MS).count(); + if today >= DAY_CAP { + card.push(CardReason::OverCap { signed: today }); + } + } + Payload::Revocations(r) => { + if log.iter().filter_map(|e| e.seq).any(|s| s >= r.seq) { + return Err(LicenceRefusal::Rollback); + } + card.push(CardReason::Revocations); + } + } + Ok(LicenceAsk { payload: parsed, card }) + } + + /// Checks `payload` again ([`Vault::licence_ask`]) and signs it: by the grant when `by` is [`LicenceBy::Grant`] + /// (refused with `needs_card` when the grant does not cover it), or after Mark's yes on a card. Returns the + /// signature in base64url without padding (86 characters), and logs it. The caller saves. + pub fn licence_sign( + &mut self, + payload: &[u8], + caller: Caller<'_>, + by: LicenceBy, + now: i64, + ) -> Result { + let ask = self.licence_ask(payload, caller, now)?; + if by == LicenceBy::Grant && !ask.card.is_empty() { + return Err(LicenceRefusal::NeedsCard); + } + let signature = self.signing.licence_signature(payload).ok_or(LicenceRefusal::NoKey)?; + let entry = match &ask.payload { + Payload::Licence(l) => LicenceEntry { + at: now, + by, + licence: Some(l.id.clone()), + apps: l.apps.clone(), + seq: None, + revoked: None, + }, + Payload::Revocations(r) => LicenceEntry { + at: now, + by, + licence: None, + apps: Vec::new(), + seq: Some(r.seq), + revoked: Some(r.revoked.len() as u64), + }, + }; + self.signing.licence.log.push(entry); + if by == LicenceBy::Grant + && let Some(g) = self.signing.licence.grant.as_mut() + { + g.uses = g.uses.saturating_add(1); + g.last_used = Some(now); + } + Ok(data_encoding::BASE64URL_NOPAD.encode(&signature)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const NOW_S: i64 = 1_795_896_907; // 2026-11-28T20:15:07Z + const NOW: i64 = NOW_S * 1000; + + fn licence(id: &str, apps: &str) -> Vec { + format!( + "domi-licence-v1\nid: {id}\nissued: 2026-11-28T20:15:07Z\nnickname: Novak family\nbundle: household-all\n\ + scope: household\napps: {apps}\n" + ) + .into_bytes() + } + + fn revocations(seq: u64, ids: &[&str]) -> Vec { + let mut s = format!("domi-revocations-v1\nseq: {seq}\nissued: 2026-11-28T20:15:07Z\n"); + for id in ids { + s.push_str(&format!("revoked: {id}\n")); + } + s.into_bytes() + } + + fn code(p: &[u8]) -> &'static str { + parse_payload(p).unwrap_err().code() + } + + const ISSUER: Caller<'static> = Caller { app: LICENCE_ISSUER, domi_signed: true }; + + fn vault() -> Vault { + let pw = crate::SecretString::from("pw"); + let mut v = Vault::create(&pw, crate::KdfParams { m_cost_kib: 64, t_cost: 1, p_cost: 1 }).unwrap(); + v.licence_key_create(NOW).unwrap(); + v + } + + #[test] + fn the_spec_example_parses_and_its_time_is_utc() { + assert_eq!(parse_utc("2026-11-28T20:15:07Z"), Some(NOW_S)); + assert_eq!(parse_utc("2000-01-01T00:00:00Z"), Some(946_684_800)); + assert_eq!(parse_utc("2024-02-29T00:00:00Z").is_some(), true); + for bad in ["2023-02-29T00:00:00Z", "2100-02-29T00:00:00Z", "1999-12-31T23:59:59Z", "2026-11-28T24:00:00Z", + "2026-11-28T20:15:60Z", "2026-11-28 20:15:07Z", "2026-11-28T20:15:07z", "2026-13-01T00:00:00Z"] { + assert_eq!(parse_utc(bad), None, "{bad}"); + } + let Payload::Licence(l) = parse_payload(&licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,fiscus,medicus,tabula")).unwrap() + else { + panic!("a licence") + }; + assert_eq!((l.issued, l.seats, l.apps.len()), (NOW_S, None, 4)); + } + + #[test] + fn a_malformed_payload_is_refused_with_the_specs_code() { + let ok = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula"); + let with = |from: &str, to: &str| String::from_utf8(ok.clone()).unwrap().replace(from, to).into_bytes(); + assert_eq!(code(b""), "truncated"); + assert_eq!(code(b"domi-lic"), "truncated"); + assert_eq!(code(b"hello\n"), "bad_prefix"); + assert_eq!(code(&with("\n", "\r\n")), "crlf"); + assert_eq!(code(&with("Novak", "Nov\tak")), "bad_byte"); + assert_eq!(code(&ok[..ok.len() - 1]), "truncated"); + assert_eq!(code(&with("id: ", "id:")), "bad_line"); + assert_eq!(code(&with("bundle: ", "colour: blue\nbundle: ")), "unknown_field"); + assert_eq!(code(&with("bundle: ", "id: k3Jx0Qm1T9yZpW2bA7cD4f\nbundle: ")), "duplicate_field"); + assert_eq!(code(&with("nickname: Novak family\nbundle: household-all", "bundle: household-all\nnickname: Novak family")), "field_order"); + assert_eq!(code(&with("scope: household\n", "")), "missing_field"); + assert_eq!(code(&with("k3Jx0Qm1T9yZpW2bA7cD4e", "short")), "bad_id"); + assert_eq!(code(&with("2026-11-28T20:15:07Z", "2026-02-30T20:15:07Z")), "bad_issued"); + assert_eq!(code(&with("Novak family", "Novak family")), "bad_nickname"); + assert_eq!(code(&with("household-all", "-all")), "bad_bundle"); + assert_eq!(code(&with("scope: household", "scope: family")), "bad_scope"); + assert_eq!(code(&with("scope: household", "scope: seat\nseats: 51")), "bad_seats"); + assert_eq!(code(&with("scope: household", "scope: household\nseats: 2")), "seats_with_household"); + assert_eq!(code(&with("scope: household", "scope: seat")), "seats_missing"); + assert_eq!(code(&with("calenda,tabula", "calenda,,tabula")), "bad_apps"); + assert_eq!(code(&with("calenda,tabula", "tabula,calenda")), "apps_unsorted"); + assert_eq!(code(&with("calenda,tabula", "calenda,calenda")), "apps_duplicate"); + let many: Vec = (0..65).map(|i| format!("app{i:03}")).collect(); + assert_eq!(code(&with("calenda,tabula", &many.join(","))), "too_many_apps"); + assert_eq!(code(&with("apps: calenda,tabula\n", "apps: calenda,tabula\nsig: x\n")), "unknown_field"); + let mut big = ok.clone(); + big.truncate(big.len() - 1); + big.extend(std::iter::repeat_n(b'a', LICENCE_PAYLOAD_MAX)); + big.push(b'\n'); + assert_eq!(code(&big), "too_large"); + // A seat licence is fine. + assert!(parse_payload(&with("scope: household", "scope: seat\nseats: 50")).is_ok()); + } + + #[test] + fn a_revocation_list_parses_strictly() { + let a = "AAAAAAAAAAAAAAAAAAAAAA"; + let b = "BBBBBBBBBBBBBBBBBBBBBB"; + assert!(matches!(parse_payload(&revocations(1, &[])).unwrap(), Payload::Revocations(r) if r.revoked.is_empty())); + assert!(matches!(parse_payload(&revocations(7, &[a, b])).unwrap(), Payload::Revocations(r) if r.seq == 7)); + assert_eq!(code(&revocations(7, &[b, a])), "revoked_unsorted"); + assert_eq!(code(&revocations(7, &[a, a])), "revoked_duplicate"); + assert_eq!(code(&revocations(0, &[])), "bad_seq"); + assert_eq!(code(&revocations(MAX_SEQ + 1, &[])), "bad_seq"); + assert_eq!(code(b"domi-revocations-v1\nissued: 2026-11-28T20:15:07Z\n"), "missing_field"); + let reordered = b"domi-revocations-v1\nseq: 3\nrevoked: AAAAAAAAAAAAAAAAAAAAAA\nissued: 2026-11-28T20:15:07Z\n"; + assert_eq!(code(reordered), "field_order"); + } + + #[test] + fn the_grant_signs_an_allowed_licence_and_a_signature_verifies() { + let mut v = vault(); + let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula"); + // No grant yet: a card. + assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap().card, vec![CardReason::NoGrant]); + assert_eq!(v.licence_sign(&p, ISSUER, LicenceBy::Grant, NOW), Err(LicenceRefusal::NeedsCard)); + v.licence_grant_set(&["tabula".into(), "calenda".into()], NOW).unwrap(); + let sig = v.licence_sign(&p, ISSUER, LicenceBy::Grant, NOW).unwrap(); + assert_eq!(sig.len(), 86); + let raw = data_encoding::BASE64URL_NOPAD.decode(sig.as_bytes()).unwrap(); + let key = ed25519_dalek::VerifyingKey::from_bytes(&v.licence_public().unwrap()).unwrap(); + let sig = ed25519_dalek::Signature::from_slice(&raw).unwrap(); + assert!(key.verify_strict(&p, &sig).is_ok(), "plain Ed25519 over the exact payload"); + assert_eq!(v.licence_grant().unwrap().uses, 1); + assert_eq!(v.licence_log()[0].licence.as_deref(), Some("k3Jx0Qm1T9yZpW2bA7cD4e")); + // The same id again is a replay, refused with no card. + assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap_err(), LicenceRefusal::Replay); + } + + #[test] + fn off_the_allowlist_unsigned_programs_and_the_cap_ask_on_a_card() { + let mut v = vault(); + v.licence_grant_set(&["tabula".into()], NOW).unwrap(); + let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "calenda,tabula"); + assert_eq!(v.licence_ask(&p, ISSUER, NOW).unwrap().card, vec![CardReason::OffAllowlist { apps: vec!["calenda".into()] }]); + let unsigned = Caller { app: LICENCE_ISSUER, domi_signed: false }; + let q = licence("k3Jx0Qm1T9yZpW2bA7cD4f", "tabula"); + assert_eq!(v.licence_ask(&q, unsigned, NOW).unwrap().card, vec![CardReason::NotDomiSigned]); + for i in 0..DAY_CAP { + v.licence_sign(&licence(&format!("id-number-{i:03}"), "tabula"), ISSUER, LicenceBy::Grant, NOW).unwrap(); + } + assert_eq!(v.licence_ask(&q, ISSUER, NOW).unwrap().card, vec![CardReason::OverCap { signed: DAY_CAP }]); + // Mark's card signs past the cap; a day later the grant signs again. + assert!(v.licence_sign(&q, ISSUER, LicenceBy::Card, NOW).is_ok()); + let r = licence("k3Jx0Qm1T9yZpW2bA7cD4g", "tabula"); + assert_eq!(v.licence_ask(&r, ISSUER, NOW + DAY_MS).unwrap().card, vec![]); + } + + #[test] + fn refused_without_a_card_another_caller_a_bad_clock_and_a_rollback() { + let mut v = vault(); + v.licence_grant_set(&["tabula".into()], NOW).unwrap(); + let p = licence("k3Jx0Qm1T9yZpW2bA7cD4e", "tabula"); + let other = Caller { app: "atrium", domi_signed: true }; + assert_eq!(v.licence_ask(&p, other, NOW).unwrap_err(), LicenceRefusal::NotAllowed); + assert_eq!(v.licence_ask(&p, ISSUER, NOW + 2 * DAY_MS).unwrap_err(), LicenceRefusal::Clock); + assert_eq!(v.licence_ask(&p, ISSUER, NOW - 2 * DAY_MS).unwrap_err(), LicenceRefusal::Clock); + // A revocation list always asks, and never goes back. + let r5 = revocations(5, &["k3Jx0Qm1T9yZpW2bA7cD4e"]); + assert_eq!(v.licence_ask(&r5, ISSUER, NOW).unwrap().card, vec![CardReason::Revocations]); + assert_eq!(v.licence_sign(&r5, ISSUER, LicenceBy::Grant, NOW), Err(LicenceRefusal::NeedsCard)); + v.licence_sign(&r5, ISSUER, LicenceBy::Card, NOW).unwrap(); + assert_eq!(v.licence_ask(&r5, ISSUER, NOW).unwrap_err(), LicenceRefusal::Rollback); + assert_eq!(v.licence_ask(&revocations(4, &[]), ISSUER, NOW).unwrap_err(), LicenceRefusal::Rollback); + assert!(v.licence_ask(&revocations(6, &[]), ISSUER, NOW).is_ok()); + } + + #[test] + fn the_licence_key_signs_nothing_else_and_its_state_survives_a_save() { + let mut v = vault(); + assert!(v.licence_key_create(NOW).is_err(), "one licence key"); + let req = crate::signing::Request { + key: LICENCE_KEY.into(), + kind: crate::signing::SignKind::Minisign, + digest: vec![1; 64], + manifest: None, + approval: None, + run: Some("r-1".into()), + context: crate::signing::Context { + repo: "mnovak/Custos".into(), + pipeline: "release".into(), + file: "x.exe".into(), + ..Default::default() + }, + via: crate::signing::Via::Local, + }; + assert!(matches!(v.signing_check(&req), Err(crate::signing::Refusal::Invalid(_)))); + assert!(v.signing_set_scope(LICENCE_KEY, &["*".into()], &["*".into()]).is_err()); + v.licence_grant_set(&["tabula".into()], NOW).unwrap(); + v.licence_sign(&licence("k3Jx0Qm1T9yZpW2bA7cD4e", "tabula"), ISSUER, LicenceBy::Grant, NOW).unwrap(); + let again = Vault::open(&v.to_bytes().unwrap(), &crate::SecretString::from("pw")).unwrap(); + assert_eq!(again.licence_public(), v.licence_public()); + assert_eq!(again.licence_grant(), v.licence_grant()); + assert_eq!(again.licence_log(), v.licence_log()); + } +} diff --git a/crates/custos-vault/src/signing.rs b/crates/custos-vault/src/signing.rs index 02b995f..17383d3 100644 --- a/crates/custos-vault/src/signing.rs +++ b/crates/custos-vault/src/signing.rs @@ -299,6 +299,8 @@ pub(crate) struct Store { pub(crate) audit: Vec, standing: Vec, android: Option, + /// The licence grant and log (core 0.21.0, `licence.rs`). + pub(crate) licence: crate::licence::LicenceStore, } #[derive(Serialize, Deserialize)] @@ -336,6 +338,10 @@ pub(crate) struct StoreJson { /// 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, + /// The licence grant and log (core 0.21.0); absent while empty. Older cores ignore and drop it: the grant is then + /// gone (every licence asks on a card), and the key, an ordinary Ed25519 entry, stays. + #[serde(default, skip_serializing_if = "Option::is_none")] + licence: Option, } fn b64(bytes: &[u8]) -> String { @@ -363,7 +369,11 @@ 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.android.is_none() + self.keys.is_empty() + && self.audit.is_empty() + && self.standing.is_empty() + && self.android.is_none() + && self.licence.is_empty() } pub(crate) fn from_json(j: StoreJson) -> Option { @@ -425,7 +435,20 @@ impl Store { 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 }) + let licence = j.licence.unwrap_or_default(); + // The licence key is what `add_licence_key` makes: Ed25519 with its public key, release, no scope. + let licence_key_ok = |k: &Key| { + k.id != crate::licence::LICENCE_KEY + || (k.kind == KeyKind::Ed25519 + && k.role == Role::Release + && k.public.is_some() + && k.pipelines.is_empty() + && k.repos.is_empty()) + }; + if !licence.ok() || !keys.iter().all(licence_key_ok) { + return None; + } + Some(Store { keys, audit: j.audit, standing: j.standing, android: j.android, licence }) } pub(crate) fn json(&self) -> Option { @@ -459,12 +482,42 @@ impl Store { audit: self.audit.clone(), standing: self.standing.clone(), android: self.android.clone(), + licence: (!self.licence.is_empty()).then(|| self.licence.clone()), }) } pub(crate) fn get(&self, id: &str) -> Option<&Key> { self.keys.iter().find(|k| k.id == id) } + + /// Adds the licence key (`licence.rs`): Ed25519, a release key with no scope and no minisign key id, so no + /// pipeline or repository can ever be in its scope. The caller checked there is none. Returns its public key. + pub(crate) fn add_licence_key(&mut self, now: i64) -> [u8; 32] { + let ed = custos_sign::new_ed25519(); + self.keys.push(Key { + id: crate::licence::LICENCE_KEY.into(), + kind: KeyKind::Ed25519, + role: Role::Release, + name: "Domi licence".into(), + secret: Secret::Ed25519(ed.secret), + public: Some(ed.public), + key_id: None, + cert: None, + issuer: None, + created: now, + pipelines: Vec::new(), + repos: Vec::new(), + }); + ed.public + } + + /// The licence key's plain Ed25519 signature over `payload` (`licence.rs` parsed and allowed it). + pub(crate) fn licence_signature(&self, payload: &[u8]) -> Option<[u8; 64]> { + match &self.get(crate::licence::LICENCE_KEY)?.secret { + Secret::Ed25519(s) => Some(custos_sign::ed25519_plain(s, payload)), + _ => None, + } + } } /// Unix seconds from the vault's milliseconds, as minisign and approvals count them. @@ -740,7 +793,7 @@ impl Vault { { 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() { + if self.signing.get(id).is_some() || id == crate::licence::LICENCE_KEY { return Err(Error::Signing(format!("there is a key `{id}` already"))); } let name = spec.name.trim(); @@ -814,6 +867,9 @@ impl Vault { if k.kind == KeyKind::RootCa { return Err(Error::Signing("a root CA signs no requests, so it has no scope".into())); } + if k.id == crate::licence::LICENCE_KEY { + return Err(Error::Signing("the licence key signs Domi licences only, so it has no scope".into())); + } k.pipelines = pipelines; k.repos = repos; Ok(()) @@ -841,6 +897,9 @@ impl Vault { /// The check, and the approval it read (for an approval request). fn check(&self, req: &Request, now: i64) -> Result<(KeyView, Option), Refusal> { let k = self.signing.get(&req.key).ok_or_else(|| Refusal::NoKey(req.key.clone()))?; + if k.id == crate::licence::LICENCE_KEY { + return Err(Refusal::Invalid(format!("`{}` signs Domi licences only (licence.rs)", k.id))); + } let approver = k.id == APPROVE_KEY && k.kind == KeyKind::Ed25519 && k.role == Role::Release; let fits = match (k.kind, req.kind) { (KeyKind::Ed25519, SignKind::Minisign | SignKind::Manifest) => k.id != APPROVE_KEY, diff --git a/docs/SIGNING.md b/docs/SIGNING.md index 74609f3..cce9991 100644 --- a/docs/SIGNING.md +++ b/docs/SIGNING.md @@ -302,6 +302,77 @@ Never covered by the grant: another kind, the server runner, a pipeline other th matches, a key that is not the repository's app key, a request without a run, anything while *Sign only with a card* is ticked. +## Domi licences (core 0.21.0) + +A Domi licence is a small text file the Atrium Domi service checks before it unlocks a paid app. Its byte format, +the paste code, the revocation list and the service's own checks are Fundamentum's `docs/LICENCE.md` (licence v1); +this core is the one that **signs**, and it parses what it signs exactly as that spec's strict parser does. The code +is `crates/custos-vault/src/licence.rs`. + +### The key + +- One key per vault, **`domi-licence`**: Ed25519, made in the vault by Mark's click (`licence_key_create`), never + exported. Only its 32-byte public key leaves (`licence_public`); the service ships it. +- It is stored as an ordinary Ed25519 entry (release, **no scope**, no minisign key id), so every core reads the vault + as before. An empty scope is never in scope, so no older core can sign with it either. +- It signs **only** the two payload kinds below, as a plain Ed25519 signature over the exact payload bytes (no + prehash, no digest; `custos_sign::ed25519_plain`). `signing_check` refuses it for every other kind, its scope + cannot be set, no Android key can take its id, and no other key signs these payloads. + +### What it signs + +| Payload | Starts with | Cap (bytes) | Parser | +| :-- | :-- | :-- | :-- | +| a licence | `domi-licence-v1 +` | 4004 | LICENCE.md §2.4 steps 1–4 and 7 | +| a revocation list | `domi-revocations-v1 +` | 61 348 | LICENCE.md §4.1 | + +The caps are the spec's file caps (4096 and 61 440) less the `sig:` line (92 bytes), so every file signed here also +passes the service's size check. A malformed payload is refused with the spec's error code (§8: `too_large`, +`crlf`, `bad_byte`, `bad_prefix`, `truncated`, `bad_line`, `unknown_field`, `duplicate_field`, `field_order`, +`missing_field`, `bad_id`, `bad_issued`, `bad_nickname`, `bad_bundle`, `bad_scope`, `bad_seats`, +`seats_with_household`, `seats_missing`, `bad_apps`, `apps_unsorted`, `apps_duplicate`, `too_many_apps`, +`bad_seq`, `revoked_unsorted`, `revoked_duplicate`) and **never reaches a card**. A payload never contains a `sig:` +line: one is an `unknown_field`. + +### The licence grant + +One grant per vault, in `signing.licence.grant`, given by Mark's click (`licence_grant_set`, `standing-granted`) and +removed the same way (`licence_grant_revoke`, `standing-revoked`): + +```json +"licence": { "grant": { "allow": ["calenda", "fiscus", "medicus", "tabula"], "granted": 1795896907000, + "lastUsed": 1795896990000, "uses": 4 }, + "log": [ { "at": 1795896990000, "by": "grant", "licence": "k3Jx0Qm1T9yZpW2bA7cD4e", + "apps": ["calenda", "tabula"] }, + { "at": 1795897000000, "by": "card", "seq": 7, "revoked": 3 } ] } +``` + +`licence_ask(payload, caller, now)` decides, and changes nothing: + +| | Result | +| :-- | :-- | +| malformed | refused, the spec's code | +| no `domi-licence` key | refused, `no_key` | +| a caller whose Canalis app id is not `licence-issue` | refused, `not_allowed` | +| the log holds 20 000 signatures | refused, `log_full` (it never forgets what replay and rollback need) | +| a licence whose `issued` is more than 24 h from this clock, either way | refused, `clock` | +| a licence id this key signed before | refused, `replay` | +| a revocation list whose `seq` is not higher than every `seq` this key signed | refused, `rollback` | +| a revocation list | **a card, always** | +| a licence, and any of: no grant; a caller program not signed with Domi's certificate; *Sign only with a card* ticked; an app not on `allow`; 50 licences signed in the last 24 h | a card, with each reason | +| a licence and none of those | signed by the grant, no card | + +`licence_sign(payload, caller, by, now)` checks again, refuses `needs_card` when `by` is `grant` and the grant does +not cover it, signs, returns the signature in base64url without padding (86 characters), logs it (when, how, the +licence id and its apps, or the list's `seq` and how many ids it revokes: never the signature, the payload or the +nickname) and counts the grant's use. + +Cores before 0.21.0 ignore `signing.licence` and drop it if they save the vault: the grant is then gone, so every +licence asks again, and the key stays. Replay and rollback are then only as good as what is left; the service keeps +its own anti-rollback check (LICENCE.md §4.2), which a restored or rewritten vault cannot get past. + ## The audit log `audit` is append-only: there is no function that edits or removes an entry. Every request a key is named in gets @@ -361,6 +432,13 @@ Vault::android_grant_set(repos, o, c, now) -> Result bool Vault::android_grant_fits(req, now) -> bool Vault::android_grant_make_key(repo, pipeline, via, now) -> Result +licence::parse_payload(bytes) -> Payload | LicenceRefusal (core 0.21.0) +Vault::licence_key_create(now) -> [u8; 32] // the public key, never the secret +Vault::licence_public() -> Option<[u8; 32]> +Vault::licence_grant() / licence_grant_set(allow, now) / licence_grant_revoke(now) +Vault::licence_ask(payload, Caller { app, domi_signed }, now) -> LicenceAsk { payload, card: [CardReason] } +Vault::licence_sign(payload, caller, LicenceBy::{Grant, Card}, now) -> base64url signature +Vault::licence_log() -> [LicenceEntry] ``` No function returns a `secret`. The views and the audit entries print and serialise without one; there is a test.