@@ -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 < u8 > ,
/// Sorted ascending and unique.
pub apps : Vec < String > ,
}
/// 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 < String > ,
}
/// 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 < u8 > {
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 < u64 > {
let digits = ! s . is_empty ( ) & & s . len ( ) < = 16 & & s . bytes ( ) . all ( | b | b . is_ascii_digit ( ) ) & & ! s . starts_with ( '0' ) ;
digits . then ( | | s . parse ::< u64 > ( ) . 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 < i64 > {
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 < i64 > {
let part = & b [ from .. to ] ;
part . iter ( ) . all ( u8 ::is_ascii_digit ) . then ( | | part . iter ( ) . fold ( 0 i64 , | 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 < Vec < String > , 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 ( ) )
}
/// `<name>: <value>`: 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 < Licence , LicenceRefusal > {
let mut v : [ Option < & str > ; 7 ] = [ None ; 7 ] ;
let mut last : Option < usize > = 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 < Revocations , LicenceRefusal > {
let ( mut seq_v , mut issued ) = ( None , None ) ;
let mut revoked : Vec < String > = Vec ::new ( ) ;
let mut last : Option < usize > = 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 < Payload , LicenceRefusal > {
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 < String > ,
/// 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 < i64 > ,
#[ 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 < String > ,
#[ serde(default, skip_serializing_if = " Vec::is_empty " ) ]
pub apps : Vec < String > ,
#[ serde(default, skip_serializing_if = " Option::is_none " ) ]
pub seq : Option < u64 > ,
#[ serde(default, skip_serializing_if = " Option::is_none " ) ]
pub revoked : Option < u64 > ,
}
/// 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 < LicenceGrant > ,
#[ serde(default, skip_serializing_if = " Vec::is_empty " ) ]
pub log : Vec < LicenceEntry > ,
}
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 < String > } ,
/// 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 < CardReason > ,
}
/// 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 < LicenceGrant > {
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 < LicenceGrant , Error > {
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 < String > = 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 < LicenceAsk , LicenceRefusal > {
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 < String > = 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 < String , LicenceRefusal > {
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 < u8 > {
format! (
" domi-licence-v1 \n id: {id} \n issued: 2026-11-28T20:15:07Z \n nickname: Novak family \n bundle: household-all \n \
scope: household \n apps: {apps} \n "
)
. into_bytes ( )
}
fn revocations ( seq : u64 , ids : & [ & str ] ) -> Vec < u8 > {
let mut s = format! ( " domi-revocations-v1 \n seq: {seq} \n issued: 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 \t ak " ) ) , " 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 \n bundle: " ) ) , " unknown_field " ) ;
assert_eq! ( code ( & with ( " bundle: " , " id: k3Jx0Qm1T9yZpW2bA7cD4f \n bundle: " ) ) , " duplicate_field " ) ;
assert_eq! ( code ( & with ( " nickname: Novak family \n bundle: household-all " , " bundle: household-all \n nickname: 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 \n seats: 51 " ) ) , " bad_seats " ) ;
assert_eq! ( code ( & with ( " scope: household " , " scope: household \n seats: 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 < String > = ( 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 \n sig: 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 \n seats: 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 \n issued: 2026-11-28T20:15:07Z \n " ) , " missing_field " ) ;
let reordered = b " domi-revocations-v1 \n seq: 3 \n revoked: AAAAAAAAAAAAAAAAAAAAAA \n issued: 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 ( ) ) ;
}
}