diff --git a/pkgs/id/crates/id-core/src/graph/cross_signing.rs b/pkgs/id/crates/id-core/src/graph/cross_signing.rs new file mode 100644 index 0000000000..8aac0a1b08 --- /dev/null +++ b/pkgs/id/crates/id-core/src/graph/cross_signing.rs @@ -0,0 +1,445 @@ +//! Mutual cross-signed key links (slice A-GRAPH-9132-02, #10240; design +//! part A §11, statements S5.58, S5.59, S5.60, S5.63). +//! +//! A [`LinkChallenge`] is one statement that two keys may both sign: the +//! ordered key pair, a purpose, an exact [`Scope`], a nonce and an expiry. +//! Its canonical bytes are the challenge. Each key signs an envelope over +//! exactly those bytes, so two statements pair only when every field is +//! identical: a different purpose, scope, nonce or expiry is a different +//! challenge, and unrelated one-sided statements never combine. +//! +//! [`KeyLinks`] collects verified statements and revocations and reports a +//! [`LinkStatus`] per challenge: `Pending` until both keys have signed, +//! `Mutual` once both have, and `Expired` or `Revoked` after that ends. +//! Either key may revoke. A mutual link proves only that both keys +//! approved that statement. It is not evidence that the keys belong to one +//! person, and this module offers no way to merge accounts, identities or +//! authority from it: a status is the only output. Authorization stays +//! with delegation grants (`graph/delegation.rs`), which never consult it. +//! +//! Module wiring into `graph/mod.rs` belongs to slice 9110-09; until then +//! the integration test includes this file by path. + +use std::collections::{HashMap, HashSet}; +use std::fmt; + +use ed25519_dalek::SigningKey; + +use super::delegation::{DELEGATION_PROFILE, Profile, Scope}; +use super::term::{ObjectRef, Term}; +use crate::canonical_cbor::{Value, decode_canonical, encode_canonical}; +use crate::hash_profile::ProfileDispatch; +use crate::id_shape::{ContentId, HashProfile}; +use crate::signed_envelope::{Body, Envelope, EnvelopeError, PayloadId, SUITE_ED25519}; + +/// Signing domain of a link statement. +pub const LINK_DOMAIN: &str = "id/key-link"; +/// Signing domain of a link revocation. +pub const LINK_REVOCATION_DOMAIN: &str = "id/key-link-revocation"; +/// Signing context (record profile) of both record types. +pub const LINK_PROFILE: &str = DELEGATION_PROFILE; +/// Payload version. +pub const LINK_VERSION: u64 = 1; +/// Longest purpose label, in bytes. +pub const MAX_PURPOSE_BYTES: usize = 64; +/// Longest nonce, in bytes. +pub const MAX_NONCE_BYTES: usize = 64; + +/// Profile that names challenges and payloads. +pub const ID_PROFILE: HashProfile = HashProfile::RawBlake3_256; + +/// The statement both keys sign. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LinkChallenge { + first_key: [u8; 32], + second_key: [u8; 32], + /// What the link is for, such as `"same-owner"`. + pub purpose: String, + /// Where the link applies. + pub scope: Scope, + /// A nonce both parties saw. + pub nonce: Vec, + /// Latest valid time, UTC Unix seconds. + pub expires: u64, +} + +/// The identity of a challenge: the hash of its canonical bytes. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct ChallengeId(ContentId); + +/// Where one challenge stands. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LinkStatus { + /// No statement for this challenge is known. + Unknown, + /// Only this key has signed. + Pending { + /// The key that signed. + signed_by: [u8; 32], + }, + /// Both keys signed the identical challenge. + Mutual, + /// The challenge expired. + Expired, + /// One of the keys revoked the challenge. + Revoked, +} + +/// Why a record was refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum LinkError { + /// The record is not well formed. + Malformed(&'static str), + /// The envelope does not verify. + Envelope(EnvelopeError), + /// The record was signed for another purpose or profile. + WrongDomain(String), + /// The signer is not one of the challenge's two keys. + WrongSigner, + /// Both keys of the pair are the same. + SameKey, + /// A revocation names a challenge that is not known. + UnknownChallenge, +} + +impl LinkError { + /// A stable failure class name. + #[must_use] + pub const fn class(&self) -> &'static str { + match self { + Self::Malformed(_) => "malformed", + Self::Envelope(_) => "bad_signature", + Self::WrongDomain(_) => "wrong_domain", + Self::WrongSigner => "wrong_signer", + Self::SameKey => "same_key", + Self::UnknownChallenge => "unknown_challenge", + } + } +} + +impl fmt::Display for LinkError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Malformed(why) => write!(f, "malformed key-link record: {why}"), + Self::Envelope(error) => write!(f, "key-link record: {error}"), + Self::WrongDomain(domain) => write!(f, "record domain {domain:?} is not expected here"), + other => f.write_str(other.class()), + } + } +} + +impl std::error::Error for LinkError {} + +impl From for LinkError { + fn from(error: EnvelopeError) -> Self { + Self::Envelope(error) + } +} + +fn key_from(value: &Value) -> Result<[u8; 32], LinkError> { + match value { + Value::Bytes(bytes) => { + <[u8; 32]>::try_from(bytes.as_slice()).map_err(|_error| LinkError::Malformed("key")) + } + _ => Err(LinkError::Malformed("key")), + } +} + +fn require_canonical(payload: &[u8], value: &Value) -> Result<(), LinkError> { + match encode_canonical(value) { + Ok(bytes) if bytes == payload => Ok(()), + _ => Err(LinkError::Malformed("payload is not canonical")), + } +} + +impl LinkChallenge { + /// A challenge for two keys, stored in ascending key order so both + /// parties build the same bytes. + /// + /// # Errors + /// + /// [`LinkError::SameKey`] for one key twice, or + /// [`LinkError::Malformed`] for an empty or long purpose or nonce. + pub fn new( + a: [u8; 32], + b: [u8; 32], + purpose: &str, + scope: Scope, + nonce: Vec, + expires: u64, + ) -> Result { + if a == b { + return Err(LinkError::SameKey); + } + if purpose.is_empty() || purpose.len() > MAX_PURPOSE_BYTES { + return Err(LinkError::Malformed("purpose must be 1 to 64 bytes")); + } + if nonce.is_empty() || nonce.len() > MAX_NONCE_BYTES { + return Err(LinkError::Malformed("nonce must be 1 to 64 bytes")); + } + Ok(Self { + first_key: a.min(b), + second_key: a.max(b), + purpose: purpose.to_owned(), + scope, + nonce, + expires, + }) + } + + /// The two keys, in ascending order. + #[must_use] + pub const fn keys(&self) -> (&[u8; 32], &[u8; 32]) { + (&self.first_key, &self.second_key) + } + + fn to_value(&self) -> Result { + Ok(Value::Array(vec![ + Value::UInt(LINK_VERSION), + Value::Text(LINK_DOMAIN.to_owned()), + Value::Bytes(self.first_key.to_vec()), + Value::Bytes(self.second_key.to_vec()), + Value::Text(self.purpose.clone()), + self.scope + .to_value() + .map_err(|_error| LinkError::Malformed("scope"))?, + Value::Bytes(self.nonce.clone()), + Value::UInt(self.expires), + ])) + } + + /// The canonical challenge bytes both keys sign. + /// + /// # Errors + /// + /// [`LinkError::Malformed`] when a field cannot be encoded. + pub fn challenge_bytes(&self) -> Result, LinkError> { + encode_canonical(&self.to_value()?).map_err(|_error| LinkError::Malformed("encoding")) + } + + /// The challenge's identity. + /// + /// # Errors + /// + /// As [`Self::challenge_bytes`]. + pub fn id(&self) -> Result { + let bytes = self.challenge_bytes()?; + let payload_id = PayloadId::of(ID_PROFILE, &bytes).map_err(EnvelopeError::from)?; + Ok(ChallengeId(*payload_id.content_id())) + } + + /// Decodes a challenge from its canonical bytes. + /// + /// # Errors + /// + /// [`LinkError`] for any other shape, keys out of order or equal, or + /// a non-canonical encoding (which also covers another version or + /// domain label). + pub fn from_bytes(bytes: &[u8]) -> Result { + let Ok(Value::Array(items)) = decode_canonical(bytes) else { + return Err(LinkError::Malformed("challenge must be an array")); + }; + let [ + _, + _, + first, + second, + Value::Text(purpose), + scope, + Value::Bytes(nonce), + Value::UInt(expires), + ] = items.as_slice() + else { + return Err(LinkError::Malformed("challenge shape")); + }; + let (first, second) = (key_from(first)?, key_from(second)?); + if first >= second { + return Err(LinkError::Malformed("keys must be in ascending order")); + } + let scope = Scope::from_value(scope).map_err(|_error| LinkError::Malformed("scope"))?; + let challenge = Self::new(first, second, purpose, scope, nonce.clone(), *expires)?; + require_canonical(bytes, &challenge.to_value()?)?; + Ok(challenge) + } + + /// One key's signed statement of this challenge. + /// + /// # Errors + /// + /// [`LinkError::WrongSigner`] when `key` is neither of the pair, or + /// an encoding or signing error. + pub fn sign(&self, signer_id: &str, key: &SigningKey) -> Result { + let public = key.verifying_key().to_bytes(); + if public != self.first_key && public != self.second_key { + return Err(LinkError::WrongSigner); + } + sign_record(LINK_DOMAIN, self.challenge_bytes()?, signer_id, key) + } + + const fn expired(&self, utc: u64, skew: u64) -> bool { + self.expires.saturating_add(skew) < utc + } +} + +fn sign_record( + domain: &str, + payload: Vec, + signer_id: &str, + key: &SigningKey, +) -> Result { + let body = Body { + domain: domain.to_owned(), + context: LINK_PROFILE.to_owned(), + subject: None, + graph: None, + predecessor: None, + signer_id: signer_id.to_owned(), + key: key.verifying_key().to_bytes(), + suite: SUITE_ED25519.to_owned(), + payload_id: PayloadId::of(ID_PROFILE, &payload).map_err(EnvelopeError::from)?, + payload_length: payload.len() as u64, + }; + Ok(Envelope::sign(body, payload, key)?) +} + +fn check_record( + envelope: &Envelope, + domain: &str, + dispatch: &ProfileDispatch, +) -> Result<(), LinkError> { + if envelope.body.domain != domain { + return Err(LinkError::WrongDomain(envelope.body.domain.clone())); + } + if envelope.body.context != LINK_PROFILE { + return Err(LinkError::WrongDomain(envelope.body.context.clone())); + } + envelope.verify(dispatch)?; + Ok(()) +} + +fn revocation_value(id: ChallengeId) -> Value { + Value::Array(vec![ + Value::UInt(LINK_VERSION), + Term::Object(ObjectRef::Content(id.0)) + .to_value() + .unwrap_or(Value::Null), + ]) +} + +/// A key's signed withdrawal of a challenge. +/// +/// # Errors +/// +/// An encoding or signing error. +pub fn sign_link_revocation( + id: ChallengeId, + signer_id: &str, + key: &SigningKey, +) -> Result { + let payload = encode_canonical(&revocation_value(id)) + .map_err(|_error| LinkError::Malformed("revocation encoding"))?; + sign_record(LINK_REVOCATION_DOMAIN, payload, signer_id, key) +} + +/// Verified link statements and revocations. +#[derive(Debug, Default, Clone)] +pub struct KeyLinks { + challenges: HashMap, + signed: HashMap>, + revoked: HashSet, +} + +impl KeyLinks { + /// An empty set. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Verifies and records one key's statement, returning its challenge. + /// + /// # Errors + /// + /// [`LinkError`] for a bad record or a signer outside the pair. + pub fn admit_statement( + &mut self, + envelope: &Envelope, + dispatch: &ProfileDispatch, + ) -> Result { + check_record(envelope, LINK_DOMAIN, dispatch)?; + let challenge = LinkChallenge::from_bytes(&envelope.payload)?; + let signer = envelope.body.key; + if signer != challenge.first_key && signer != challenge.second_key { + return Err(LinkError::WrongSigner); + } + let id = ChallengeId(*envelope.body.payload_id.content_id()); + self.signed.entry(id).or_default().insert(signer); + self.challenges.insert(id, challenge); + Ok(id) + } + + /// Verifies and records a revocation by either key of a challenge. + /// + /// # Errors + /// + /// [`LinkError`] for a bad record, an unknown challenge, or a signer + /// outside the pair. + pub fn admit_revocation( + &mut self, + envelope: &Envelope, + dispatch: &ProfileDispatch, + ) -> Result { + check_record(envelope, LINK_REVOCATION_DOMAIN, dispatch)?; + let Ok(Value::Array(items)) = decode_canonical(&envelope.payload) else { + return Err(LinkError::Malformed("revocation must be an array")); + }; + let [_, target] = items.as_slice() else { + return Err(LinkError::Malformed("revocation shape")); + }; + let Ok(Term::Object(ObjectRef::Content(content))) = Term::from_value(target) else { + return Err(LinkError::Malformed("revocation target")); + }; + let id = ChallengeId(content); + require_canonical(&envelope.payload, &revocation_value(id))?; + let challenge = self + .challenges + .get(&id) + .ok_or(LinkError::UnknownChallenge)?; + let signer = envelope.body.key; + if signer != challenge.first_key && signer != challenge.second_key { + return Err(LinkError::WrongSigner); + } + self.revoked.insert(id); + Ok(id) + } + + /// The challenge recorded under `id`. + #[must_use] + pub fn challenge(&self, id: &ChallengeId) -> Option<&LinkChallenge> { + self.challenges.get(id) + } + + /// Where the challenge stands at verifier time `utc`. + #[must_use] + pub fn status(&self, id: &ChallengeId, utc: u64, profile: &Profile) -> LinkStatus { + let Some(challenge) = self.challenges.get(id) else { + return LinkStatus::Unknown; + }; + if self.revoked.contains(id) { + return LinkStatus::Revoked; + } + if challenge.expired(utc, profile.clock_skew_secs) { + return LinkStatus::Expired; + } + let signed = &self.signed[id]; + if signed.contains(&challenge.first_key) && signed.contains(&challenge.second_key) { + return LinkStatus::Mutual; + } + signed + .iter() + .next() + .map_or(LinkStatus::Unknown, |signer| LinkStatus::Pending { + signed_by: *signer, + }) + } +} diff --git a/pkgs/id/crates/id-core/src/graph/delegation.rs b/pkgs/id/crates/id-core/src/graph/delegation.rs index 346c74622e..6e0270659c 100644 --- a/pkgs/id/crates/id-core/src/graph/delegation.rs +++ b/pkgs/id/crates/id-core/src/graph/delegation.rs @@ -240,7 +240,8 @@ impl Scope { other.prefixes.iter().all(|p| self.covers_path(p)) } - fn to_value(&self) -> Result { + /// The scope as a canonical CBOR array of prefix arrays. + pub(crate) fn to_value(&self) -> Result { self.prefixes .iter() .map(|p| prefix_value(p)) @@ -248,7 +249,8 @@ impl Scope { .map(Value::Array) } - fn from_value(value: &Value) -> Result { + /// Reads a scope written by [`Self::to_value`]. + pub(crate) fn from_value(value: &Value) -> Result { let Value::Array(prefixes) = value else { return Err(DelegationError::Malformed("scope must be an array")); }; diff --git a/pkgs/id/crates/id-core/tests/cross_signing_challenge.rs b/pkgs/id/crates/id-core/tests/cross_signing_challenge.rs new file mode 100644 index 0000000000..cf72865b9d --- /dev/null +++ b/pkgs/id/crates/id-core/tests/cross_signing_challenge.rs @@ -0,0 +1,673 @@ +//! Mutual cross-signed key links (slice A-GRAPH-9132-02, issue #10240; +//! design part A §11, statements S5.58, S5.59, S5.60, S5.63). +//! +//! Oracle: **invariant**. This file carries its own signature check +//! (`ed25519-dalek` directly over the signed-body preimage) and its own +//! exact field-equality checker for challenge bytes. The module must +//! agree with them: only both valid signatures over identical challenge +//! bytes become mutual; one-sided, unrelated, mismatched or revoked +//! claims stay pending or end; and a mutual link changes no +//! authorization state. +//! +//! `graph/mod.rs` does not export these modules yet (slice 9110-09 wires +//! them), so this test includes them, and the modules they build on, by +//! path. + +#![allow( + clippy::unwrap_used, + clippy::expect_used, + clippy::panic, + clippy::type_complexity +)] + +#[path = "../src/canonical_cbor.rs"] +#[allow(dead_code)] +mod canonical_cbor; + +#[path = "../src/id_shape.rs"] +#[allow(dead_code)] +mod id_shape; + +#[path = "../src/hash_profile.rs"] +#[allow(dead_code)] +mod hash_profile; + +#[path = "../src/signed_envelope.rs"] +#[allow(dead_code)] +mod signed_envelope; + +#[path = "../src/graph/term.rs"] +#[allow(dead_code)] +mod term; + +#[path = "../src/graph/space_binding.rs"] +#[allow(dead_code)] +mod space_binding; + +#[path = "../src/graph/delegation.rs"] +#[allow(dead_code)] +mod delegation; + +#[path = "../src/graph/cross_signing.rs"] +mod cross_signing; + +use std::collections::{HashMap, HashSet}; + +use canonical_cbor::{Value, decode_canonical, encode_canonical}; +use cross_signing::{ + ChallengeId, KeyLinks, LINK_DOMAIN, LINK_REVOCATION_DOMAIN, LinkChallenge, LinkError, + LinkStatus, sign_link_revocation, +}; +use delegation::{DelegationError, DelegationSet, Permission, Profile, Request, Scope}; +use ed25519_dalek::{Signature, SigningKey, VerifyingKey}; +use hash_profile::ProfileDispatch; +use id_shape::HashProfile; +use proptest::prelude::*; +use signed_envelope::{Body, Envelope, PayloadId, SUITE_ED25519, signature_preimage}; +use space_binding::SpaceAddress; +use term::Term; + +const SIGNER: &str = "tester"; +const PROFILE: Profile = Profile::INITIAL; + +fn key(seed: u8) -> SigningKey { + SigningKey::from_bytes(&[seed; 32]) +} + +fn public(seed: u8) -> [u8; 32] { + key(seed).verifying_key().to_bytes() +} + +fn dispatch() -> ProfileDispatch { + ProfileDispatch::default() +} + +fn scope(prefixes: &[&[u8]]) -> Scope { + Scope::new( + prefixes + .iter() + .map(|p| p.iter().map(|b| Term::typed(1, vec![*b])).collect()) + .collect(), + ) + .unwrap() +} + +fn challenge(a: u8, b: u8) -> LinkChallenge { + LinkChallenge::new( + public(a), + public(b), + "same-owner", + scope(&[&[]]), + vec![7], + 1_000, + ) + .unwrap() +} + +/// Signs any payload under any domain and context, so tests can build +/// records the module would never make. +fn record(domain: &str, context: &str, payload: Vec, signer: &SigningKey) -> Envelope { + let body = Body { + domain: domain.to_owned(), + context: context.to_owned(), + subject: None, + graph: None, + predecessor: None, + signer_id: SIGNER.to_owned(), + key: signer.verifying_key().to_bytes(), + suite: SUITE_ED25519.to_owned(), + payload_id: PayloadId::of(HashProfile::RawBlake3_256, &payload).unwrap(), + payload_length: payload.len() as u64, + }; + Envelope::sign(body, payload, signer).unwrap() +} + +// --------------------------------------------------------------------- +// Independent reference: signature check and challenge field checker. + +/// The challenge fields, read straight from the canonical array. +#[derive(Debug, Clone, PartialEq, Eq)] +struct RefChallenge { + first: [u8; 32], + second: [u8; 32], + purpose: String, + scope: Value, + nonce: Vec, + expires: u64, +} + +fn ref_challenge(bytes: &[u8]) -> Option { + let Value::Array(items) = decode_canonical(bytes).ok()? else { + return None; + }; + let [ + Value::UInt(1), + Value::Text(label), + Value::Bytes(first), + Value::Bytes(second), + Value::Text(purpose), + scope @ Value::Array(_), + Value::Bytes(nonce), + Value::UInt(expires), + ] = items.as_slice() + else { + return None; + }; + let first: [u8; 32] = first.as_slice().try_into().ok()?; + let second: [u8; 32] = second.as_slice().try_into().ok()?; + let ok = label == "id/key-link" + && first < second + && (1..=64).contains(&purpose.len()) + && (1..=64).contains(&nonce.len()) + && encode_canonical(&Value::Array(items.clone())).ok()? == bytes; + ok.then(|| RefChallenge { + first, + second, + purpose: purpose.clone(), + scope: scope.clone(), + nonce: nonce.clone(), + expires: *expires, + }) +} + +fn ref_signature_ok(envelope: &Envelope, domain: &str) -> bool { + let body = &envelope.body; + let Ok(verifier) = VerifyingKey::from_bytes(&body.key) else { + return false; + }; + body.domain == domain + && body.context == "delegation/v1" + && body.payload_id == PayloadId::of(HashProfile::RawBlake3_256, &envelope.payload).unwrap() + && body.payload_length == envelope.payload.len() as u64 + && verifier + .verify_strict( + &signature_preimage(body).unwrap(), + &Signature::from_bytes(&envelope.signature), + ) + .is_ok() +} + +/// A statement the reference accepts, as its challenge and signer. +fn ref_statement(envelope: &Envelope) -> Option<(RefChallenge, [u8; 32])> { + if !ref_signature_ok(envelope, LINK_DOMAIN) { + return None; + } + let fields = ref_challenge(&envelope.payload)?; + let signer = envelope.body.key; + (signer == fields.first || signer == fields.second).then_some((fields, signer)) +} + +// --------------------------------------------------------------------- +// Targeted cases. + +#[test] +fn both_keys_over_identical_bytes_become_mutual() { + let c = challenge(1, 2); + let mut links = KeyLinks::new(); + let id = links + .admit_statement(&c.sign(SIGNER, &key(1)).unwrap(), &dispatch()) + .unwrap(); + assert_eq!(id, c.id().unwrap()); + assert_eq!( + links.status(&id, 900, &PROFILE), + LinkStatus::Pending { + signed_by: public(1) + } + ); + // The same statement again changes nothing. + links + .admit_statement(&c.sign(SIGNER, &key(1)).unwrap(), &dispatch()) + .unwrap(); + assert!(matches!( + links.status(&id, 900, &PROFILE), + LinkStatus::Pending { .. } + )); + assert_eq!( + links.admit_statement(&c.sign(SIGNER, &key(2)).unwrap(), &dispatch()), + Ok(id) + ); + assert_eq!(links.status(&id, 900, &PROFILE), LinkStatus::Mutual); + assert_eq!(links.challenge(&id), Some(&c)); + // Key order does not matter to the challenge. + assert_eq!(challenge(2, 1), c); +} + +#[test] +fn any_differing_field_is_a_different_challenge() { + let base = challenge(1, 2); + let variants = [ + LinkChallenge::new( + public(1), + public(3), + "same-owner", + scope(&[&[]]), + vec![7], + 1_000, + ), + LinkChallenge::new( + public(1), + public(2), + "backup-key", + scope(&[&[]]), + vec![7], + 1_000, + ), + LinkChallenge::new( + public(1), + public(2), + "same-owner", + scope(&[&[1]]), + vec![7], + 1_000, + ), + LinkChallenge::new( + public(1), + public(2), + "same-owner", + scope(&[&[]]), + vec![8], + 1_000, + ), + LinkChallenge::new( + public(1), + public(2), + "same-owner", + scope(&[&[]]), + vec![7], + 1_001, + ), + ]; + for variant in variants { + let variant = variant.unwrap(); + let mut links = KeyLinks::new(); + let a = links + .admit_statement(&base.sign(SIGNER, &key(1)).unwrap(), &dispatch()) + .unwrap(); + let second_signer = if variant.keys().1 == &public(3) { 3 } else { 2 }; + let b = links + .admit_statement( + &variant.sign(SIGNER, &key(second_signer)).unwrap(), + &dispatch(), + ) + .unwrap(); + assert_ne!(a, b); + assert!(matches!( + links.status(&a, 900, &PROFILE), + LinkStatus::Pending { .. } + )); + assert!(matches!( + links.status(&b, 900, &PROFILE), + LinkStatus::Pending { .. } + )); + } +} + +#[test] +fn outsiders_tampering_and_other_domains_are_refused() { + let c = challenge(1, 2); + assert_eq!(c.sign(SIGNER, &key(3)), Err(LinkError::WrongSigner)); + let bytes = c.challenge_bytes().unwrap(); + let mut links = KeyLinks::new(); + let outsider = record(LINK_DOMAIN, "delegation/v1", bytes.clone(), &key(3)); + assert_eq!( + links.admit_statement(&outsider, &dispatch()), + Err(LinkError::WrongSigner) + ); + let other_domain = record("id/other", "delegation/v1", bytes.clone(), &key(1)); + assert_eq!( + links + .admit_statement(&other_domain, &dispatch()) + .map_err(|e| e.class()), + Err("wrong_domain") + ); + let other_profile = record(LINK_DOMAIN, "delegation/v2", bytes.clone(), &key(1)); + assert_eq!( + links + .admit_statement(&other_profile, &dispatch()) + .map_err(|e| e.class()), + Err("wrong_domain") + ); + let revocation_as_statement = record(LINK_REVOCATION_DOMAIN, "delegation/v1", bytes, &key(1)); + assert_eq!( + links + .admit_statement(&revocation_as_statement, &dispatch()) + .map_err(|e| e.class()), + Err("wrong_domain") + ); + let mut tampered = c.sign(SIGNER, &key(1)).unwrap(); + tampered.payload[5] ^= 1; + assert_eq!( + links + .admit_statement(&tampered, &dispatch()) + .map_err(|e| e.class()), + Err("bad_signature") + ); + assert_eq!( + links.status(&c.id().unwrap(), 900, &PROFILE), + LinkStatus::Unknown + ); +} + +#[test] +fn challenge_bytes_are_canonical_and_bounded() { + assert_eq!( + LinkChallenge::new(public(1), public(1), "x", scope(&[&[]]), vec![1], 1), + Err(LinkError::SameKey) + ); + for (purpose, nonce) in [ + ("", vec![1]), + (&*"p".repeat(65), vec![1]), + ("x", vec![]), + ("x", vec![0; 65]), + ] { + assert_eq!( + LinkChallenge::new(public(1), public(2), purpose, scope(&[&[]]), nonce, 1) + .map_err(|e| e.class()), + Err("malformed") + ); + } + let longest = LinkChallenge::new( + public(1), + public(2), + &"p".repeat(64), + scope(&[&[]]), + vec![0; 64], + 1, + ) + .unwrap(); + let bytes = longest.challenge_bytes().unwrap(); + assert_eq!(LinkChallenge::from_bytes(&bytes), Ok(longest)); + + let c = challenge(1, 2); + let Value::Array(items) = decode_canonical(&c.challenge_bytes().unwrap()).unwrap() else { + panic!("challenge is an array"); + }; + let decode = |items: Vec| { + LinkChallenge::from_bytes(&encode_canonical(&Value::Array(items)).unwrap()) + .map_err(|e| e.class()) + }; + assert!(decode(items.clone()).is_ok()); + let mut swapped = items.clone(); + swapped.swap(2, 3); + assert_eq!(decode(swapped), Err("malformed")); + let mut same = items.clone(); + same[3] = same[2].clone(); + assert_eq!(decode(same), Err("malformed")); + let mut version = items.clone(); + version[0] = Value::UInt(2); + assert_eq!(decode(version), Err("malformed")); + let mut label = items.clone(); + label[1] = Value::Text("id/other".to_owned()); + assert_eq!(decode(label), Err("malformed")); + let mut short_key = items.clone(); + short_key[2] = Value::Bytes(vec![0; 31]); + assert_eq!(decode(short_key), Err("malformed")); + let mut bad_scope = items; + bad_scope[5] = Value::UInt(0); + assert_eq!(decode(bad_scope), Err("malformed")); + let mut unsorted_scope = c; + unsorted_scope.scope = scope(&[&[1], &[0]]); + let Value::Array(mut items) = + decode_canonical(&unsorted_scope.challenge_bytes().unwrap()).unwrap() + else { + panic!("challenge is an array"); + }; + let Value::Array(prefixes) = &mut items[5] else { + panic!("scope is an array"); + }; + prefixes.reverse(); + assert_eq!(decode(items.clone()), Err("malformed")); + items.pop(); + assert_eq!(decode(items), Err("malformed")); + assert_eq!( + LinkChallenge::from_bytes(&[0xff]).map_err(|e| e.class()), + Err("malformed") + ); +} + +#[test] +fn expiry_and_revocation_end_a_link() { + let c = challenge(1, 2); + let mut links = KeyLinks::new(); + let id = links + .admit_statement(&c.sign(SIGNER, &key(1)).unwrap(), &dispatch()) + .unwrap(); + links + .admit_statement(&c.sign(SIGNER, &key(2)).unwrap(), &dispatch()) + .unwrap(); + // Expiry honours the skew allowance exactly. + assert_eq!(links.status(&id, 1_300, &PROFILE), LinkStatus::Mutual); + assert_eq!(links.status(&id, 1_301, &PROFILE), LinkStatus::Expired); + + let by_outsider = sign_link_revocation(id, SIGNER, &key(3)).unwrap(); + assert_eq!( + links.admit_revocation(&by_outsider, &dispatch()), + Err(LinkError::WrongSigner) + ); + let unknown = sign_link_revocation(challenge(1, 3).id().unwrap(), SIGNER, &key(1)).unwrap(); + assert_eq!( + links.admit_revocation(&unknown, &dispatch()), + Err(LinkError::UnknownChallenge) + ); + let as_statement = record( + LINK_DOMAIN, + "delegation/v1", + by_outsider.payload.clone(), + &key(2), + ); + assert_eq!( + links + .admit_revocation(&as_statement, &dispatch()) + .map_err(|e| e.class()), + Err("wrong_domain") + ); + for payload in [ + encode_canonical(&Value::UInt(1)).unwrap(), + encode_canonical(&Value::Array(vec![Value::UInt(1)])).unwrap(), + encode_canonical(&Value::Array(vec![ + Value::UInt(1), + Value::Bytes(vec![1; 4]), + ])) + .unwrap(), + encode_canonical(&Value::Array(vec![Value::UInt(2), { + let Value::Array(items) = decode_canonical(&by_outsider.payload).unwrap() else { + panic!("revocation is an array"); + }; + items[1].clone() + }])) + .unwrap(), + ] { + let bad = record(LINK_REVOCATION_DOMAIN, "delegation/v1", payload, &key(2)); + assert_eq!( + links + .admit_revocation(&bad, &dispatch()) + .map_err(|e| e.class()), + Err("malformed") + ); + } + assert_eq!(links.status(&id, 900, &PROFILE), LinkStatus::Mutual); + + // Either key may withdraw, and a revoked link stays revoked even if + // its statements arrive again. + let by_second = sign_link_revocation(id, SIGNER, &key(2)).unwrap(); + assert_eq!(links.admit_revocation(&by_second, &dispatch()), Ok(id)); + assert_eq!(links.status(&id, 900, &PROFILE), LinkStatus::Revoked); + links + .admit_statement(&c.sign(SIGNER, &key(1)).unwrap(), &dispatch()) + .unwrap(); + assert_eq!(links.status(&id, 900, &PROFILE), LinkStatus::Revoked); + assert_eq!(links.status(&id, 5_000, &PROFILE), LinkStatus::Revoked); +} + +#[test] +fn a_mutual_link_grants_no_authority() { + let owner = 0; + let c = challenge(owner, 1); + let mut links = KeyLinks::new(); + for seed in [owner, 1] { + links + .admit_statement(&c.sign(SIGNER, &key(seed)).unwrap(), &dispatch()) + .unwrap(); + } + assert_eq!( + links.status(&c.id().unwrap(), 900, &PROFILE), + LinkStatus::Mutual + ); + let grants = DelegationSet::new(); + let request = Request { + space: SpaceAddress::for_key(public(owner)).unwrap(), + key: public(1), + path: vec![], + permission: Permission::Read, + }; + assert_eq!( + grants.authorize( + &request, + None, + delegation::Clock { + verifier_utc: 900, + frontier_age_secs: 0 + }, + &PROFILE + ), + Err(DelegationError::NotAuthorized("no grant presented")) + ); +} + +#[test] +fn error_classes_are_stable() { + let all = [ + (LinkError::Malformed("x"), "malformed"), + (LinkError::WrongDomain(String::new()), "wrong_domain"), + (LinkError::WrongSigner, "wrong_signer"), + (LinkError::SameKey, "same_key"), + (LinkError::UnknownChallenge, "unknown_challenge"), + ]; + let mut seen = HashSet::new(); + for (error, class) in all { + assert_eq!(error.class(), class); + assert!(seen.insert(class)); + assert!(!error.to_string().is_empty()); + } +} + +// --------------------------------------------------------------------- +// Property: the module's status matches the reference on random sets of +// statements over a base challenge and its near-miss variants. + +const KEYS: u8 = 4; + +#[derive(Debug, Clone)] +struct Statement { + /// 0 = the base challenge; 1..=5 change one field. + variant: u8, + signer: u8, + /// 0 = honest; 1 = flip a payload byte; 2 = wrong domain. + damage: u8, +} + +fn variant(base: (u8, u8), which: u8) -> LinkChallenge { + let (a, b) = base; + let mut c = challenge(a, b); + match which { + 0 => {} + 1 => c = challenge(a, (0..KEYS).find(|k| *k != a && *k != b).unwrap()), + 2 => "backup-key".clone_into(&mut c.purpose), + 3 => c.scope = scope(&[&[1]]), + 4 => c.nonce = vec![8], + _ => c.expires += 50, + } + c +} + +fn make(c: &LinkChallenge, s: &Statement) -> Envelope { + let bytes = c.challenge_bytes().unwrap(); + let domain = if s.damage == 2 { + LINK_REVOCATION_DOMAIN + } else { + LINK_DOMAIN + }; + let mut envelope = record(domain, "delegation/v1", bytes, &key(s.signer)); + if s.damage == 1 { + envelope.payload[3] ^= 1; + } + envelope +} + +fn statement() -> impl Strategy { + ( + prop_oneof![3 => Just(0u8), 2 => 1..6u8], + 0..KEYS, + prop_oneof![8 => Just(0u8), 1 => Just(1u8), 1 => Just(2u8)], + ) + .prop_map(|(variant, signer, damage)| Statement { + variant, + signer, + damage, + }) +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(512))] + + #[test] + fn status_agrees_with_the_reference( + pair in (0..KEYS, 1..KEYS).prop_map(|(a, d)| (a, (a + d) % KEYS)), + statements in prop::collection::vec(statement(), 0..7), + revokers in prop::collection::vec((0..6u8, 0..KEYS), 0..2), + utc in prop_oneof![Just(900u64), 1_250..1_400u64], + ) { + let mut links = KeyLinks::new(); + // Reference state: exact challenge bytes -> signers. + let mut ref_signed: HashMap, HashSet<[u8; 32]>> = HashMap::new(); + for s in &statements { + let c = variant(pair, s.variant); + let envelope = make(&c, s); + let accepted = links.admit_statement(&envelope, &dispatch()).is_ok(); + let reference = ref_statement(&envelope); + prop_assert_eq!(accepted, reference.is_some(), "statement {:?}", s); + if let Some((_, signer)) = reference { + ref_signed.entry(envelope.payload.clone()).or_default().insert(signer); + } + } + let mut ref_revoked: HashSet> = HashSet::new(); + for (which, seed) in &revokers { + let c = variant(pair, *which); + let bytes = c.challenge_bytes().unwrap(); + let revocation = sign_link_revocation(c.id().unwrap(), SIGNER, &key(*seed)).unwrap(); + let accepted = links.admit_revocation(&revocation, &dispatch()).is_ok(); + let fields = ref_challenge(&bytes).unwrap(); + let expected = ref_signed.contains_key(&bytes) + && (public(*seed) == fields.first || public(*seed) == fields.second); + prop_assert_eq!(accepted, expected); + if expected { + ref_revoked.insert(bytes); + } + } + for which in 0..6 { + let c = variant(pair, which); + let bytes = c.challenge_bytes().unwrap(); + let fields = ref_challenge(&bytes).unwrap(); + let id: ChallengeId = c.id().unwrap(); + let got = links.status(&id, utc, &PROFILE); + let expected = match ref_signed.get(&bytes) { + None => "unknown", + Some(_) if ref_revoked.contains(&bytes) => "revoked", + Some(_) if fields.expires + PROFILE.clock_skew_secs < utc => "expired", + Some(signers) if signers.contains(&fields.first) && signers.contains(&fields.second) => "mutual", + Some(_) => "pending", + }; + let got_class = match &got { + LinkStatus::Unknown => "unknown", + LinkStatus::Revoked => "revoked", + LinkStatus::Expired => "expired", + LinkStatus::Mutual => "mutual", + LinkStatus::Pending { signed_by } => { + prop_assert!(ref_signed[&bytes].contains(signed_by)); + "pending" + } + }; + prop_assert_eq!(got_class, expected, "variant {}", which); + } + } +}