Skip to main content

spoolframe_protocol/portable/
mod.rs

1//! A portable user's identity: the public
2//! half of a root signing key the user owns, not an account any server
3//! hosts; and what that root signs: a credential for
4//! each of the user's devices, and the state that revokes them; and the
5//! proof that ties a local account to the identity.
6//!
7//! Only public things live here. The root's secret, and the recovery
8//! phrase it comes from, are the client SDK's (`spoolframe_client_sdk::
9//! portable`) and never travel: a server checks what the root signed with
10//! [`PortableUserId::verify`] and holds nothing it could sign with.
11
12use std::fmt;
13use std::str::FromStr;
14
15use ed25519_dalek::VerifyingKey;
16use serde::{Deserialize, Deserializer, Serialize, Serializer};
17
18pub use ed25519_dalek::Signature;
19
20use crate::fingerprint;
21
22mod client_data;
23mod roots;
24pub(crate) use roots::handle_hex;
25#[cfg(any(test, feature = "soft-key"))]
26pub mod soft_key;
27
28pub use roots::{
29    AddedRoot, GENESIS_DOMAIN, GenesisError, HANDLE_LEN, IdentityGenesis, MAX_ATTESTATION_OBJECT,
30    MAX_AUTHENTICATOR_DATA, MAX_CLIENT_DATA_JSON, MAX_CREDENTIAL_ID, MAX_DER_SIGNATURE,
31    MAX_ROOT_CHANGES, MAX_ROOTS, P256_PUBLIC_KEY_LEN, PORTABLE_RP, ROOT_ADD_DOMAIN,
32    ROOT_ENDORSE_DOMAIN, RemovedRoot, RootChanges, RootKey, RootRegistration, RootSet,
33    RootSignature, USER_ID_CONTEXT, WebAuthnError, portable_rp_id_hash, root_add_message,
34    root_endorse_message,
35};
36
37/// Bytes in a [`PortableUserId`]: an Ed25519 public key.
38pub const PORTABLE_USER_ID_LEN: usize = 32;
39
40/// Who a portable user is. For an identity begun with one phrase root, its
41/// root's Ed25519 public key; for any other, derived from its
42/// genesis ([`IdentityGenesis::user`]). Written as 64 lowercase hex
43/// digits, as iroh writes an `EndpointId`; serialized the same way.
44#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
45pub struct PortableUserId([u8; PORTABLE_USER_ID_LEN]);
46
47/// Not a portable user id: not 64 hex digits.
48#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
49#[error("not a portable user id: {0}")]
50pub struct InvalidPortableUserId(&'static str);
51
52impl PortableUserId {
53    /// The id `bytes` are. Any 32 bytes: an id derived from a genesis
54    /// is a hash, not a curve point. A phrase identity's is its
55    /// root's public key, and [`Self::verify`] fails for one that is not
56    /// a point.
57    pub fn from_bytes(bytes: [u8; PORTABLE_USER_ID_LEN]) -> Result<Self, InvalidPortableUserId> {
58        Ok(Self(bytes))
59    }
60
61    pub fn as_bytes(&self) -> &[u8; PORTABLE_USER_ID_LEN] {
62        &self.0
63    }
64
65    /// The short code a person compares between two screens, in the same
66    /// format as a server's ([`fingerprint`]): `K7QX-3MPA-9TRD-WF2H`.
67    pub fn fingerprint(&self) -> String {
68        fingerprint::fingerprint(&self.0)
69    }
70
71    /// Whether `signature` is this user's phrase root's over `message`,
72    /// the root a phrase identity's id is. Strict Ed25519 verification: a
73    /// signature another could forge from a valid one, or one under a
74    /// weak key, does not pass. An identity with other roots checks them
75    /// with [`RootKey::verify`].
76    pub fn verify(&self, message: &[u8], signature: &Signature) -> bool {
77        VerifyingKey::from_bytes(&self.0)
78            .is_ok_and(|key| key.verify_strict(message, signature).is_ok())
79    }
80}
81
82impl fmt::Display for PortableUserId {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        write_hex(f, &self.0)
85    }
86}
87
88impl fmt::Debug for PortableUserId {
89    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
90        write!(f, "PortableUserId({self})")
91    }
92}
93
94impl FromStr for PortableUserId {
95    type Err = InvalidPortableUserId;
96
97    /// 64 hex digits, either case.
98    fn from_str(s: &str) -> Result<Self, Self::Err> {
99        Self::from_bytes(parse_hex(s).ok_or(InvalidPortableUserId("not 64 hex digits"))?)
100    }
101}
102
103impl Serialize for PortableUserId {
104    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
105        serializer.collect_str(self)
106    }
107}
108
109impl<'de> Deserialize<'de> for PortableUserId {
110    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
111        let text = String::deserialize(deserializer)?;
112        text.parse().map_err(serde::de::Error::custom)
113    }
114}
115
116/// `bytes` as lowercase hex.
117fn write_hex(f: &mut fmt::Formatter<'_>, bytes: &[u8]) -> fmt::Result {
118    for byte in bytes {
119        write!(f, "{byte:02x}")?;
120    }
121    Ok(())
122}
123
124/// Exactly `2 × N` hex digits, either case, as bytes.
125fn parse_hex<const N: usize>(s: &str) -> Option<[u8; N]> {
126    if s.len() != 2 * N || !s.is_ascii() {
127        return None;
128    }
129    let mut bytes = [0u8; N];
130    for (i, byte) in bytes.iter_mut().enumerate() {
131        *byte = u8::from_str_radix(&s[2 * i..2 * i + 2], 16).ok()?;
132    }
133    Some(bytes)
134}
135
136/// Bytes in a [`DevicePublicKey`]: an Ed25519 public key.
137pub const DEVICE_PUBLIC_KEY_LEN: usize = 32;
138
139/// One device's key for acting as a portable user: its own Ed25519
140/// keypair, apart from both the user's root and the device's Iroh
141/// endpoint key. Written, and serialized, as 64 lowercase hex digits.
142#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
143pub struct DevicePublicKey([u8; DEVICE_PUBLIC_KEY_LEN]);
144
145/// Not a device key: not 64 hex digits, or not an Ed25519 public key.
146#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
147#[error("not a device public key: {0}")]
148pub struct InvalidDevicePublicKey(&'static str);
149
150impl DevicePublicKey {
151    /// The key `bytes` are; an error if they are not a point on the curve.
152    pub fn from_bytes(bytes: [u8; DEVICE_PUBLIC_KEY_LEN]) -> Result<Self, InvalidDevicePublicKey> {
153        VerifyingKey::from_bytes(&bytes)
154            .map_err(|_| InvalidDevicePublicKey("not an Ed25519 public key"))?;
155        Ok(Self(bytes))
156    }
157
158    pub fn as_bytes(&self) -> &[u8; DEVICE_PUBLIC_KEY_LEN] {
159        &self.0
160    }
161
162    /// The short code a person compares between the device and the phone
163    /// that authorizes it, in the same format as an identity's
164    /// ([`PortableUserId::fingerprint`]).
165    pub fn fingerprint(&self) -> String {
166        fingerprint::fingerprint(&self.0)
167    }
168
169    /// Whether `signature` is this device key's over `message`, strictly
170    /// (as [`PortableUserId::verify`]).
171    pub fn verify(&self, message: &[u8], signature: &Signature) -> bool {
172        VerifyingKey::from_bytes(&self.0)
173            .is_ok_and(|key| key.verify_strict(message, signature).is_ok())
174    }
175}
176
177impl fmt::Display for DevicePublicKey {
178    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179        write_hex(f, &self.0)
180    }
181}
182
183impl fmt::Debug for DevicePublicKey {
184    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185        write!(f, "DevicePublicKey({self})")
186    }
187}
188
189impl FromStr for DevicePublicKey {
190    type Err = InvalidDevicePublicKey;
191
192    /// 64 hex digits, either case.
193    fn from_str(s: &str) -> Result<Self, Self::Err> {
194        Self::from_bytes(parse_hex(s).ok_or(InvalidDevicePublicKey("not 64 hex digits"))?)
195    }
196}
197
198impl Serialize for DevicePublicKey {
199    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
200        serializer.collect_str(self)
201    }
202}
203
204impl<'de> Deserialize<'de> for DevicePublicKey {
205    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
206        let text = String::deserialize(deserializer)?;
207        text.parse().map_err(serde::de::Error::custom)
208    }
209}
210
211/// A signature in serde: 128 lowercase hex digits (64 bytes).
212pub(crate) mod signature_hex {
213    use super::*;
214
215    struct Hex<'a>(&'a Signature);
216
217    impl fmt::Display for Hex<'_> {
218        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
219            write_hex(f, &self.0.to_bytes())
220        }
221    }
222
223    pub fn serialize<S: Serializer>(signature: &Signature, s: S) -> Result<S::Ok, S::Error> {
224        s.collect_str(&Hex(signature))
225    }
226
227    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Signature, D::Error> {
228        let text = String::deserialize(d)?;
229        parse_hex::<{ Signature::BYTE_SIZE }>(&text)
230            .map(|bytes| Signature::from_bytes(&bytes))
231            .ok_or_else(|| serde::de::Error::custom("a signature is 128 hex digits"))
232    }
233}
234
235/// Seconds in a day.
236const DAY: i64 = 24 * 60 * 60;
237
238/// The longest a credential may be good for: 90 days from its
239/// `issued_at`. A stale device ages out
240/// within that, even where no revocation ever reaches.
241pub const MAX_CREDENTIAL_VALIDITY: i64 = 90 * DAY;
242
243/// How far ahead of a verifier's clock a credential's `issued_at` may be:
244/// the phone's clock and the server's need not agree to the second.
245pub const CLOCK_SKEW: i64 = 5 * 60;
246
247/// The domain the root's signature over a credential is made in, ahead of
248/// the bytes [`UserDeviceCredential::message`] lays out. Fixed forever: a
249/// new layout takes a new string.
250pub const CREDENTIAL_DOMAIN: &[u8] = b"spoolframe device credential v1\0";
251
252/// The domain of the root's signature over an identity state. v2 added
253/// each key's `revoked_at`; v1 was never sent anywhere.
254pub const STATE_DOMAIN: &[u8] = b"spoolframe identity state v2\0";
255
256/// The domain of a device key's proof of possession to one server.
257pub const DEVICE_PROOF_DOMAIN: &[u8] = b"spoolframe device proof v1\0";
258
259/// The most device keys an identity state may revoke. Revocations older
260/// than [`REVOCATION_WINDOW`] may be dropped, so this bounds the live ones
261/// only.
262pub const MAX_REVOKED: usize = 1024;
263
264/// How long a revocation matters: a key revoked longer ago than this has
265/// no credential left that holds. Every credential expires within
266/// [`MAX_CREDENTIAL_VALIDITY`] of its `issued_at`, which is at most
267/// [`CLOCK_SKEW`] ahead of the clock it was revoked by, and the root
268/// issues none to a key it has revoked.
269pub const REVOCATION_WINDOW: i64 = MAX_CREDENTIAL_VALIDITY + CLOCK_SKEW;
270
271/// Whether a revocation made at `revoked_at` is past [`REVOCATION_WINDOW`]
272/// at `now`, and so may be dropped: it can stop no credential that would
273/// otherwise hold.
274pub fn revocation_lapsed(revoked_at: i64, now: i64) -> bool {
275    revoked_at < now.saturating_sub(REVOCATION_WINDOW)
276}
277
278/// Why a credential, or a device's proof with it, does not authenticate.
279#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
280pub enum CredentialError {
281    /// The root it names did not sign it, as it is: tampered, or signed by
282    /// another identity's root.
283    #[error("the credential is not signed by the identity it names")]
284    BadSignature,
285    /// Issued further ahead of this clock than [`CLOCK_SKEW`].
286    #[error("the credential is not valid yet")]
287    NotYetValid,
288    /// Past its `expires_at`.
289    #[error("the credential has expired")]
290    Expired,
291    /// Good for longer than [`MAX_CREDENTIAL_VALIDITY`]: no root this
292    /// code signs with makes one.
293    #[error("the credential is good for longer than a credential may be")]
294    TooLong,
295    /// The device key did not sign the proof: whoever presents the
296    /// credential does not hold its device's key.
297    #[error("the device key did not sign the proof")]
298    BadDeviceProof,
299}
300
301/// A user's root's word that a device key may act as them, until
302/// `expires_at`. The server checks it alone, with no account server: the
303/// root signed it, it is in date, the device holds its key
304/// ([`verify_device_proof`]) and no state the server has seen revokes the
305/// key ([`PortableIdentityState::revokes`]).
306///
307/// Times are Unix seconds. Renewal is a new credential for the same key,
308/// with a larger serial.
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310pub struct UserDeviceCredential {
311    pub user: PortableUserId,
312    pub device_key: DevicePublicKey,
313    /// Larger for a later credential from one holder of the root, so two
314    /// for one key differ. Only the signature reads it; the SDK gives the
315    /// issue time in milliseconds, or one past its last if that is larger.
316    pub serial: u64,
317    pub issued_at: i64,
318    /// Required: every credential expires.
319    pub expires_at: i64,
320    /// The root's, over [`Self::message`]: Ed25519 from a phrase root; a
321    /// CTAP2 assertion from a security key.
322    pub signature: RootSignature,
323    /// The root that signed it; absent, the phrase root the
324    /// user's id is. Whether it is one
325    /// of the user's roots is the verifier's to check, against the
326    /// identity's [`RootSet`].
327    // Left out when none, not for older peers: a server and a device keep
328    // these as JSON, and older records have no key.
329    #[serde(default, skip_serializing_if = "Option::is_none")]
330    pub root: Option<RootKey>,
331    /// The identity's genesis, carried for a verifier that has not seen
332    /// it: an identity with a security key root cannot be checked
333    /// without it. Not signed: it proves itself, its hash being the id.
334    // Left out when none, not for older peers: a server and a device keep
335    // these as JSON, and older records have no key.
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub genesis: Option<Box<IdentityGenesis>>,
338}
339
340impl UserDeviceCredential {
341    /// A credential `sign` signs with `user`'s phrase root: the client
342    /// SDK's root, which this crate never holds.
343    pub fn new(
344        user: PortableUserId,
345        device_key: DevicePublicKey,
346        serial: u64,
347        issued_at: i64,
348        expires_at: i64,
349        sign: impl FnOnce(&[u8]) -> Signature,
350    ) -> Self {
351        let signature = sign(&Self::message(
352            &user,
353            &device_key,
354            serial,
355            issued_at,
356            expires_at,
357        ));
358        Self {
359            user,
360            device_key,
361            serial,
362            issued_at,
363            expires_at,
364            signature: RootSignature::Ed25519(signature),
365            root: None,
366            genesis: None,
367        }
368    }
369
370    /// A credential `root` signs with `sign`, any kind of root.
371    /// A phrase identity's own phrase root is left unnamed, as before.
372    #[allow(clippy::too_many_arguments)]
373    pub fn signed_by(
374        user: PortableUserId,
375        root: RootKey,
376        device_key: DevicePublicKey,
377        serial: u64,
378        issued_at: i64,
379        expires_at: i64,
380        sign: impl FnOnce(&[u8]) -> RootSignature,
381    ) -> Self {
382        let signature = sign(&Self::message(
383            &user,
384            &device_key,
385            serial,
386            issued_at,
387            expires_at,
388        ));
389        let root = (root != RootKey::phrase_of(&user)).then_some(root);
390        Self {
391            user,
392            device_key,
393            serial,
394            issued_at,
395            expires_at,
396            signature,
397            root,
398            genesis: None,
399        }
400    }
401
402    /// The root it says signed it: the one it names, or the phrase root
403    /// its user's id is.
404    pub fn signer(&self) -> RootKey {
405        self.root
406            .clone()
407            .unwrap_or_else(|| RootKey::phrase_of(&self.user))
408    }
409
410    /// What the root signs: [`CREDENTIAL_DOMAIN`], then user (32 bytes),
411    /// device key (32), serial (u64), issued_at (i64), expires_at (i64),
412    /// the integers big-endian. Fixed width throughout, so there is one
413    /// encoding of each credential and nothing to canonicalise.
414    pub fn message(
415        user: &PortableUserId,
416        device_key: &DevicePublicKey,
417        serial: u64,
418        issued_at: i64,
419        expires_at: i64,
420    ) -> Vec<u8> {
421        let mut message = Vec::with_capacity(CREDENTIAL_DOMAIN.len() + 32 + 32 + 8 * 3);
422        message.extend_from_slice(CREDENTIAL_DOMAIN);
423        message.extend_from_slice(user.as_bytes());
424        message.extend_from_slice(device_key.as_bytes());
425        message.extend_from_slice(&serial.to_be_bytes());
426        message.extend_from_slice(&issued_at.to_be_bytes());
427        message.extend_from_slice(&expires_at.to_be_bytes());
428        message
429    }
430
431    /// Whether it is good at `now` (Unix seconds): signed by the root it
432    /// names ([`Self::signer`]), issued no later than `now` +
433    /// [`CLOCK_SKEW`], not yet expired, and good for no longer than
434    /// [`MAX_CREDENTIAL_VALIDITY`]. Says nothing of whether that root is
435    /// one of the user's ([`RootSet`]) nor of revocation, which are the
436    /// verifier's, from the states it holds.
437    pub fn verify(&self, now: i64) -> Result<(), CredentialError> {
438        let message = Self::message(
439            &self.user,
440            &self.device_key,
441            self.serial,
442            self.issued_at,
443            self.expires_at,
444        );
445        if !self.signer().verify(&message, &self.signature) {
446            return Err(CredentialError::BadSignature);
447        }
448        if self
449            .expires_at
450            .checked_sub(self.issued_at)
451            .is_none_or(|validity| validity > MAX_CREDENTIAL_VALIDITY)
452        {
453            return Err(CredentialError::TooLong);
454        }
455        if self.issued_at > now.saturating_add(CLOCK_SKEW) {
456            return Err(CredentialError::NotYetValid);
457        }
458        if now >= self.expires_at {
459            return Err(CredentialError::Expired);
460        }
461        Ok(())
462    }
463}
464
465/// What a device signs to prove to one server that it holds its key:
466/// [`DEVICE_PROOF_DOMAIN`], the server's endpoint id (32 bytes), then the
467/// server's nonce (32). Naming the server keeps a proof made for one from
468/// being replayed to another; the nonce, one the server just chose, keeps
469/// it from being replayed to the same one.
470pub fn device_proof_message(server: &[u8; 32], nonce: &[u8; 32]) -> Vec<u8> {
471    let mut message = Vec::with_capacity(DEVICE_PROOF_DOMAIN.len() + 64);
472    message.extend_from_slice(DEVICE_PROOF_DOMAIN);
473    message.extend_from_slice(server);
474    message.extend_from_slice(nonce);
475    message
476}
477
478/// Whether `signature` is `credential`'s device key's over
479/// [`device_proof_message`]`(server, nonce)`. Checks the proof only: the
480/// credential itself is [`UserDeviceCredential::verify`]'s.
481pub fn verify_device_proof(
482    credential: &UserDeviceCredential,
483    server: &[u8; 32],
484    nonce: &[u8; 32],
485    signature: &Signature,
486) -> Result<(), CredentialError> {
487    if credential
488        .device_key
489        .verify(&device_proof_message(server, nonce), signature)
490    {
491        Ok(())
492    } else {
493        Err(CredentialError::BadDeviceProof)
494    }
495}
496
497/// Why an identity state is not one.
498#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
499pub enum StateError {
500    /// The root it names (or the phrase root its user's id is) did not
501    /// sign it, as it is.
502    #[error("the identity state is not signed by the identity it names")]
503    BadSignature,
504    /// It lists more than [`MAX_REVOKED`] keys.
505    #[error("the identity state revokes more than {MAX_REVOKED} device keys")]
506    TooManyRevoked,
507    /// It adds or removes more than [`MAX_ROOT_CHANGES`] roots.
508    #[error("the identity state changes more than {MAX_ROOT_CHANGES} roots")]
509    TooManyRootChanges,
510    /// A root it adds is not a valid key, did not sign its addition, or
511    /// its adder did not endorse it.
512    #[error("a root the identity state adds does not prove it is held, or who added it")]
513    BadPossession,
514}
515
516/// One revoked device key, and when the root revoked it (Unix seconds).
517#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
518pub struct RevokedKey {
519    pub key: DevicePublicKey,
520    pub revoked_at: i64,
521}
522
523/// `entries` as a state signs them: sorted by key, one per key, the
524/// earliest `revoked_at` where a key repeats.
525fn canonical(entries: &[RevokedKey]) -> Vec<RevokedKey> {
526    let mut entries = entries.to_vec();
527    entries.sort_unstable_by_key(|entry| (entry.key, entry.revoked_at));
528    entries.dedup_by_key(|entry| entry.key);
529    entries
530}
531
532/// `added` as a state signs it: sorted by root, one per root.
533fn canonical_added(added: &[AddedRoot]) -> Vec<AddedRoot> {
534    let mut added = added.to_vec();
535    added.sort_by(|a, b| a.root.cmp(&b.root));
536    added.dedup_by(|a, b| a.root == b.root);
537    added
538}
539
540/// `removed` as a state signs it: sorted by root, one per root, the
541/// earliest `removed_at` where a root repeats.
542fn canonical_removed(removed: &[RemovedRoot]) -> Vec<RemovedRoot> {
543    let mut removed = removed.to_vec();
544    removed.sort_by(|a, b| (&a.root, a.removed_at).cmp(&(&b.root, b.removed_at)));
545    removed.dedup_by(|a, b| a.root == b.root);
546    removed
547}
548
549/// The domain of a state that names its signer or changes roots.
550/// One that does neither signs [`STATE_DOMAIN`]'s layout, as before.
551pub const STATE_V3_DOMAIN: &[u8] = b"spoolframe identity state v3\0";
552
553/// A user's root's list of revoked device keys, at a revision, and
554/// the roots it has added and removed. Revocation only grows: a
555/// verifier checks credentials against the union of every valid state it
556/// has seen for the user, and keeps the newest (by revision) to hand on.
557/// A credential is good unless that union revokes its device key: adding
558/// a device needs no new state, so it
559/// lists no authorized keys.
560///
561/// Root changes are cumulative too: a state lists every root added and
562/// removed so far, and a verifier works out the roots from all of them
563/// ([`RootSet`]).
564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
565pub struct PortableIdentityState {
566    pub user: PortableUserId,
567    /// Higher is newer; each state the root makes is the last plus one.
568    pub revision: u64,
569    /// Sorted by key, one per key, as [`Self::new`] makes it; the
570    /// signature covers the set, whatever its order here.
571    pub revoked: Vec<RevokedKey>,
572    /// Unix seconds. Not used to order states: the revision is.
573    pub issued_at: i64,
574    /// The signer's, over [`Self::message`].
575    pub signature: RootSignature,
576    /// The root that signed it; absent, the phrase root the
577    /// user's id is.
578    // Left out when none, not for older peers: a server and a device keep
579    // these as JSON, and older records have no key.
580    #[serde(default, skip_serializing_if = "Option::is_none")]
581    pub signer: Option<RootKey>,
582    /// Every root added so far, each with its proof that it is held.
583    // Left out when none, not for older peers: a server and a device keep
584    // these as JSON, and older records have no key.
585    #[serde(default, skip_serializing_if = "Vec::is_empty")]
586    pub roots_added: Vec<AddedRoot>,
587    /// Every root removed so far.
588    // Left out when none, not for older peers: a server and a device keep
589    // these as JSON, and older records have no key.
590    #[serde(default, skip_serializing_if = "Vec::is_empty")]
591    pub roots_removed: Vec<RemovedRoot>,
592}
593
594/// What a state changes, for [`PortableIdentityState::signed_by`]:
595/// revocations and roots, each cumulative.
596#[derive(Debug, Clone, Default, PartialEq, Eq)]
597pub struct StateChanges {
598    pub revoked: Vec<RevokedKey>,
599    pub roots_added: Vec<AddedRoot>,
600    pub roots_removed: Vec<RemovedRoot>,
601}
602
603impl PortableIdentityState {
604    /// A state `sign` signs with `user`'s phrase root. `revoked` is put
605    /// in [`Self::message`]'s order, one entry per key (the earliest);
606    /// more than [`MAX_REVOKED`] is refused. Dropping lapsed entries
607    /// ([`revocation_lapsed`]) is the caller's.
608    pub fn new(
609        user: PortableUserId,
610        revision: u64,
611        revoked: Vec<RevokedKey>,
612        issued_at: i64,
613        sign: impl FnOnce(&[u8]) -> Signature,
614    ) -> Result<Self, StateError> {
615        Self::signed_by(
616            user,
617            RootKey::phrase_of(&user),
618            revision,
619            StateChanges {
620                revoked,
621                ..StateChanges::default()
622            },
623            issued_at,
624            |message| RootSignature::Ed25519(sign(message)),
625        )
626    }
627
628    /// A state `signer` signs with `sign`: any kind of root, and
629    /// any root changes. Lists are put in [`Self::message`]'s order, one
630    /// entry each; over the limits is refused. A phrase identity's own
631    /// phrase root, changing no roots, signs the [`STATE_DOMAIN`] layout.
632    pub fn signed_by(
633        user: PortableUserId,
634        signer: RootKey,
635        revision: u64,
636        changes: StateChanges,
637        issued_at: i64,
638        sign: impl FnOnce(&[u8]) -> RootSignature,
639    ) -> Result<Self, StateError> {
640        let revoked = canonical(&changes.revoked);
641        let roots_added = canonical_added(&changes.roots_added);
642        let roots_removed = canonical_removed(&changes.roots_removed);
643        if revoked.len() > MAX_REVOKED {
644            return Err(StateError::TooManyRevoked);
645        }
646        if roots_added.len() > MAX_ROOT_CHANGES || roots_removed.len() > MAX_ROOT_CHANGES {
647            return Err(StateError::TooManyRootChanges);
648        }
649        let signer = (signer != RootKey::phrase_of(&user)).then_some(signer);
650        let mut state = Self {
651            user,
652            revision,
653            revoked,
654            issued_at,
655            // Replaced below, once the message is laid out.
656            signature: RootSignature::Ed25519(Signature::from_bytes(&[0; 64])),
657            signer,
658            roots_added,
659            roots_removed,
660        };
661        state.signature = sign(&state.signed_message());
662        Ok(state)
663    }
664
665    /// The root it says signed it: the one it names, or the phrase root
666    /// its user's id is.
667    pub fn signer(&self) -> RootKey {
668        self.signer
669            .clone()
670            .unwrap_or_else(|| RootKey::phrase_of(&self.user))
671    }
672
673    /// Its root changes, as [`RootSet`] reads them.
674    pub fn root_changes(&self) -> (RootKey, &[AddedRoot], &[RemovedRoot]) {
675        (self.signer(), &self.roots_added, &self.roots_removed)
676    }
677
678    /// What the root signs: [`STATE_DOMAIN`], then user
679    /// (32 bytes), revision (u64), issued_at (i64), the count of entries
680    /// (u32), then the entries sorted ascending by key, one per key, each
681    /// the key (32 bytes) and its revoked_at (i64); the integers
682    /// big-endian. `revoked` is taken as a set; a key given twice counts
683    /// once, with its earliest `revoked_at`.
684    pub fn message(
685        user: &PortableUserId,
686        revision: u64,
687        revoked: &[RevokedKey],
688        issued_at: i64,
689    ) -> Vec<u8> {
690        let mut message = Vec::new();
691        Self::lay_out(
692            &mut message,
693            STATE_DOMAIN,
694            user,
695            revision,
696            revoked,
697            issued_at,
698        );
699        message
700    }
701
702    fn lay_out(
703        message: &mut Vec<u8>,
704        domain: &[u8],
705        user: &PortableUserId,
706        revision: u64,
707        revoked: &[RevokedKey],
708        issued_at: i64,
709    ) {
710        let entries = canonical(revoked);
711        let count = u32::try_from(entries.len()).expect("fewer than 2^32 keys in memory");
712        message.reserve(domain.len() + 32 + 8 + 8 + 4 + 40 * entries.len());
713        message.extend_from_slice(domain);
714        message.extend_from_slice(user.as_bytes());
715        message.extend_from_slice(&revision.to_be_bytes());
716        message.extend_from_slice(&issued_at.to_be_bytes());
717        message.extend_from_slice(&count.to_be_bytes());
718        for entry in entries {
719            message.extend_from_slice(entry.key.as_bytes());
720            message.extend_from_slice(&entry.revoked_at.to_be_bytes());
721        }
722    }
723
724    /// What its signer signed. [`Self::message`] for a state of
725    /// the phrase root its user's id is that changes no roots; else
726    /// [`STATE_V3_DOMAIN`], the same fields, then the signer
727    /// ([`RootKey::bytes`]), the count of roots added (u8) and each sorted
728    /// ascending by root, as the root, its adder and its added_at (i64),
729    /// and the count of roots removed (u8) and each root sorted ascending
730    /// with its removed_at (i64). The additions' signatures are not in
731    /// it: each is checked against its own message.
732    pub fn signed_message(&self) -> Vec<u8> {
733        if self.signer.is_none() && self.roots_added.is_empty() && self.roots_removed.is_empty() {
734            return Self::message(&self.user, self.revision, &self.revoked, self.issued_at);
735        }
736        let mut message = Vec::new();
737        Self::lay_out(
738            &mut message,
739            STATE_V3_DOMAIN,
740            &self.user,
741            self.revision,
742            &self.revoked,
743            self.issued_at,
744        );
745        message.extend_from_slice(&self.signer().bytes());
746        let added = canonical_added(&self.roots_added);
747        message.push(u8::try_from(added.len()).unwrap_or(u8::MAX));
748        for root in &added {
749            message.extend_from_slice(&root.root.bytes());
750            message.extend_from_slice(&root.added_by.bytes());
751            message.extend_from_slice(&root.added_at.to_be_bytes());
752        }
753        let removed = canonical_removed(&self.roots_removed);
754        message.push(u8::try_from(removed.len()).unwrap_or(u8::MAX));
755        for root in &removed {
756            message.extend_from_slice(&root.root.bytes());
757            message.extend_from_slice(&root.removed_at.to_be_bytes());
758        }
759        message
760    }
761
762    /// Whether the root it names signed it, it is within the limits, and
763    /// every root it adds is valid and signed its addition. The counts
764    /// are checked first, on the lists as given, so an oversized one
765    /// costs no sorting. Whether its signer is one of the user's roots is
766    /// the verifier's ([`RootSet`]).
767    pub fn verify(&self) -> Result<(), StateError> {
768        if self.revoked.len() > MAX_REVOKED {
769            return Err(StateError::TooManyRevoked);
770        }
771        if self.roots_added.len() > MAX_ROOT_CHANGES || self.roots_removed.len() > MAX_ROOT_CHANGES
772        {
773            return Err(StateError::TooManyRootChanges);
774        }
775        if !self
776            .roots_added
777            .iter()
778            .all(|added| added.verify(&self.user))
779        {
780            return Err(StateError::BadPossession);
781        }
782        if self
783            .signer()
784            .verify(&self.signed_message(), &self.signature)
785        {
786            Ok(())
787        } else {
788            Err(StateError::BadSignature)
789        }
790    }
791
792    /// Whether it revokes `key`.
793    pub fn revokes(&self, key: &DevicePublicKey) -> bool {
794        self.revoked.iter().any(|entry| entry.key == *key)
795    }
796
797    /// Whether `other` says the same as this: the same signed bytes and
798    /// signature, whatever order its lists are in.
799    pub fn same_as(&self, other: &PortableIdentityState) -> bool {
800        self.signature == other.signature
801            && self.signer() == other.signer()
802            && self.signed_message() == other.signed_message()
803    }
804
805    /// BLAKE3 of what its signer signed and of its signature as CBOR (the
806    /// wire's codec) writes it: one value for one state, whatever order
807    /// its lists are in. Two states of one revision are ordered by it, the
808    /// lower first ([`newest_first`]), so every verifier picks the same
809    /// one as the newest.
810    pub fn digest(&self) -> [u8; 32] {
811        let mut signature = Vec::new();
812        ciborium::into_writer(&self.signature, &mut signature)
813            .expect("a signature always serializes");
814        let mut digest = blake3::Hasher::new();
815        digest.update(&self.signed_message());
816        digest.update(&signature);
817        digest.finalize().into()
818    }
819
820    /// Whether `others` carry every root change this state makes: each
821    /// root it adds is added in one of them, and each root it removes is
822    /// removed in one of them, no later. A state whose changes others
823    /// carry adds nothing to the root set they make. Its revocations are
824    /// not looked at.
825    pub fn root_changes_covered_by(&self, others: &[PortableIdentityState]) -> bool {
826        self.roots_added.iter().all(|added| {
827            others
828                .iter()
829                .any(|o| o.roots_added.iter().any(|a| a.root == added.root))
830        }) && self.roots_removed.iter().all(|removed| {
831            others.iter().any(|o| {
832                o.roots_removed
833                    .iter()
834                    .any(|r| r.root == removed.root && r.removed_at <= removed.removed_at)
835            })
836        })
837    }
838}
839
840/// Newest first: the higher revision, then the lower
841/// [`PortableIdentityState::digest`]. How a verifier picks the newest of
842/// rival states, the same everywhere.
843pub fn newest_first(a: &PortableIdentityState, b: &PortableIdentityState) -> std::cmp::Ordering {
844    b.revision
845        .cmp(&a.revision)
846        .then_with(|| a.digest().cmp(&b.digest()))
847}
848
849/// The roots of `user`, from its genesis (none for a phrase identity
850/// whose genesis the verifier has not seen: its one root is the phrase
851/// root its id is) and `states`, each already checked
852/// ([`PortableIdentityState::verify`]) and of `user`.
853pub fn root_set(
854    user: &PortableUserId,
855    genesis: Option<&IdentityGenesis>,
856    states: &[PortableIdentityState],
857) -> RootSet {
858    let first = match genesis {
859        Some(genesis) => genesis.roots.clone(),
860        None => vec![RootKey::phrase_of(user)],
861    };
862    let signers: Vec<RootKey> = states.iter().map(PortableIdentityState::signer).collect();
863    let changes: Vec<RootChanges<'_>> = states
864        .iter()
865        .zip(&signers)
866        .map(|(state, signer)| RootChanges {
867            signer,
868            added: &state.roots_added,
869            removed: &state.roots_removed,
870        })
871        .collect();
872    RootSet::of(&first, &changes)
873}
874
875/// What a device or server keeps of an identity to check it, and hands
876/// on so another can: its genesis, absent for a phrase identity
877/// (its one root is its id), and its newest state, if any. Recovery with
878/// a root needs it from anywhere that has it.
879#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
880pub struct IdentityRecord {
881    pub user: PortableUserId,
882    #[serde(default, skip_serializing_if = "Option::is_none")]
883    pub genesis: Option<IdentityGenesis>,
884    #[serde(default, skip_serializing_if = "Option::is_none")]
885    pub state: Option<PortableIdentityState>,
886}
887
888/// The domain of the signature that ties a local account to a portable
889/// identity.
890pub const TIE_DOMAIN: &[u8] = b"spoolframe tie v1\0";
891
892/// What a portable user signs to tie their identity to the local account
893/// `username` on the server whose endpoint id is `server`, answering the
894/// server's `nonce`: [`TIE_DOMAIN`], the server's id (32 bytes),
895/// the nonce (32), the user (32), then the username's length in bytes
896/// (u16, big-endian) and its UTF-8. Each part keeps a proof from being
897/// used elsewhere: on another server, again on this one, for another
898/// identity, or onto another account here.
899///
900/// `None` for a username of more than 65,535 bytes, which no server has
901/// (a username is at most 64 characters).
902pub fn tie_message(
903    server: &[u8; 32],
904    nonce: &[u8; 32],
905    user: &PortableUserId,
906    username: &str,
907) -> Option<Vec<u8>> {
908    let length = u16::try_from(username.len()).ok()?;
909    let mut message = Vec::with_capacity(TIE_DOMAIN.len() + 96 + 2 + username.len());
910    message.extend_from_slice(TIE_DOMAIN);
911    message.extend_from_slice(server);
912    message.extend_from_slice(nonce);
913    message.extend_from_slice(user.as_bytes());
914    message.extend_from_slice(&length.to_be_bytes());
915    message.extend_from_slice(username.as_bytes());
916    Some(message)
917}
918
919/// Who signed a [`tie_message`] for a portable user: their root, on the
920/// phone that holds it, or one of their device keys, with the credential
921/// the root gave it. Either way the root itself never travels.
922#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
923#[serde(tag = "type", rename_all = "snake_case")]
924pub enum TieProof {
925    /// A root's signature: the phrase root the user's id is, or
926    /// the root it names, which the verifier checks is one of the user's.
927    Root {
928        signature: RootSignature,
929        // Left out when none, not for older peers: a server and a device keep
930        // these as JSON, and older records have no key.
931        #[serde(default, skip_serializing_if = "Option::is_none")]
932        root: Option<RootKey>,
933        /// The identity's genesis, for a verifier that has not seen it
934        /// (as [`UserDeviceCredential::genesis`]).
935        // Left out when none, not for older peers: a server and a device keep
936        // these as JSON, and older records have no key.
937        #[serde(default, skip_serializing_if = "Option::is_none")]
938        genesis: Option<Box<IdentityGenesis>>,
939    },
940    /// `credential`'s device key's signature.
941    Device {
942        credential: UserDeviceCredential,
943        #[serde(with = "signature_hex")]
944        signature: Signature,
945    },
946}
947
948/// Why a [`TieProof`] does not prove its user.
949#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
950pub enum TieProofError {
951    /// The key it names did not sign this message: made for another
952    /// server, nonce, identity or account, or not signed at all.
953    #[error("the tie is not signed for this server, challenge, identity and account")]
954    BadSignature,
955    /// A device credential of another identity than the one to tie.
956    #[error("the device credential is another identity's")]
957    OtherIdentity,
958    /// The device credential does not hold.
959    #[error(transparent)]
960    Credential(#[from] CredentialError),
961}
962
963impl TieProof {
964    /// Whether it proves `user` signed `message` (a [`tie_message`]) at
965    /// `now` (Unix seconds): the signature of the root it names, or a
966    /// device key's with a credential for `user` that holds now. Whether
967    /// that root is one of the user's ([`Self::root`]) and revocation are
968    /// the verifier's to check, against every state it has seen.
969    pub fn verify(
970        &self,
971        user: &PortableUserId,
972        message: &[u8],
973        now: i64,
974    ) -> Result<(), TieProofError> {
975        match self {
976            TieProof::Root {
977                signature, root, ..
978            } => root
979                .clone()
980                .unwrap_or_else(|| RootKey::phrase_of(user))
981                .verify(message, signature)
982                .then_some(())
983                .ok_or(TieProofError::BadSignature),
984            TieProof::Device {
985                credential,
986                signature,
987            } => {
988                if credential.user != *user {
989                    return Err(TieProofError::OtherIdentity);
990                }
991                credential.verify(now)?;
992                credential
993                    .device_key
994                    .verify(message, signature)
995                    .then_some(())
996                    .ok_or(TieProofError::BadSignature)
997            }
998        }
999    }
1000
1001    /// The root whose word it is: the one that signed it, or the one that
1002    /// signed the device's credential.
1003    pub fn root(&self, user: &PortableUserId) -> RootKey {
1004        match self {
1005            TieProof::Root { root, .. } => root.clone().unwrap_or_else(|| RootKey::phrase_of(user)),
1006            TieProof::Device { credential, .. } => credential.signer(),
1007        }
1008    }
1009
1010    /// The identity's genesis it carries, if any.
1011    pub fn genesis(&self) -> Option<&IdentityGenesis> {
1012        match self {
1013            TieProof::Root { genesis, .. } => genesis.as_deref(),
1014            TieProof::Device { credential, .. } => credential.genesis.as_deref(),
1015        }
1016    }
1017
1018    /// What kind of proof it is, as the server keeps it: `root` or
1019    /// `device`.
1020    pub fn kind(&self) -> &'static str {
1021        match self {
1022            TieProof::Root { .. } => "root",
1023            TieProof::Device { .. } => "device",
1024        }
1025    }
1026}
1027
1028#[cfg(test)]
1029mod tests {
1030    use super::*;
1031    use ed25519_dalek::{Signer, SigningKey};
1032
1033    fn key() -> SigningKey {
1034        SigningKey::from_bytes(&[7; 32])
1035    }
1036
1037    fn id() -> PortableUserId {
1038        PortableUserId::from_bytes(key().verifying_key().to_bytes()).unwrap()
1039    }
1040
1041    #[test]
1042    fn the_text_form_is_lowercase_hex_and_reads_back() {
1043        let text = id().to_string();
1044        assert_eq!(text.len(), 64);
1045        assert!(text.chars().all(|c| matches!(c, '0'..='9' | 'a'..='f')));
1046        assert_eq!(text.parse::<PortableUserId>(), Ok(id()));
1047        assert_eq!(text.to_uppercase().parse::<PortableUserId>(), Ok(id()));
1048    }
1049
1050    #[test]
1051    fn serde_uses_the_text_form() {
1052        let json = serde_json::to_string(&id()).unwrap();
1053        assert_eq!(json, format!("\"{}\"", id()));
1054        assert_eq!(serde_json::from_str::<PortableUserId>(&json).unwrap(), id());
1055    }
1056
1057    #[test]
1058    fn text_that_is_not_an_id_is_refused() {
1059        assert!("abc".parse::<PortableUserId>().is_err());
1060        assert!("zz".repeat(32).parse::<PortableUserId>().is_err());
1061        assert!("é".repeat(32).parse::<PortableUserId>().is_err());
1062        assert!(serde_json::from_str::<PortableUserId>("\"abc\"").is_err());
1063    }
1064
1065    #[test]
1066    fn an_id_that_is_not_a_curve_point_is_an_id_no_phrase_root_signs_for() {
1067        // An id derived from a genesis (P7-08) is a hash, half of which
1068        // have no point on the curve: such an id reads, but no phrase
1069        // root's signature passes for it.
1070        let point = (0..=255u8)
1071            .map(|y| {
1072                let mut bytes = [0u8; 32];
1073                bytes[0] = y;
1074                bytes
1075            })
1076            .find(|bytes| VerifyingKey::from_bytes(bytes).is_err())
1077            .unwrap();
1078        let id = PortableUserId::from_bytes(point).unwrap();
1079        assert_eq!(id.to_string().parse::<PortableUserId>(), Ok(id));
1080        assert!(!id.verify(b"anything", &key().sign(b"anything")));
1081    }
1082
1083    #[test]
1084    fn the_fingerprint_is_the_server_format() {
1085        let code = id().fingerprint();
1086        assert_eq!(code, fingerprint::fingerprint(id().as_bytes()));
1087        assert_eq!(code.len(), 19);
1088    }
1089
1090    #[test]
1091    fn verify_accepts_the_roots_signature_and_nothing_else() {
1092        let signature = key().sign(b"device credential");
1093        assert!(id().verify(b"device credential", &signature));
1094        assert!(!id().verify(b"another message", &signature));
1095        let other = SigningKey::from_bytes(&[8; 32]).sign(b"device credential");
1096        assert!(!id().verify(b"device credential", &other));
1097    }
1098
1099    // P7-02. The vectors below were computed apart from this code: the
1100    // messages laid out by hand in Python's `struct`, the keys and
1101    // signatures by `openssl pkey` and `openssl pkeyutl -sign -rawin` over
1102    // the raw seeds. Ed25519 signatures are deterministic, so the same
1103    // seed and message give these bytes anywhere.
1104
1105    /// 2026-10-09T00:00:00Z.
1106    const T: i64 = 1_791_504_000;
1107
1108    const ROOT_7: &str = "ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c";
1109    const DEVICE_9: &str = "fd1724385aa0c75b64fb78cd602fa1d991fdebf76b13c58ed702eac835e9f618";
1110    const DEVICE_11: &str = "66be7e332c7a453332bd9d0a7f7db055f5c5ef1a06ada66d98b39fb6810c473a";
1111
1112    /// Root 7's credential for device 9: serial 3, issued at [`T`], for
1113    /// 90 days.
1114    const CREDENTIAL_MESSAGE: &str = "73706f6f6c6672616d65206465766963652063726564656e7469616c20763100\
1115        ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\
1116        fd1724385aa0c75b64fb78cd602fa1d991fdebf76b13c58ed702eac835e9f618\
1117        0000000000000003000000006ac82e80000000006b3ed580";
1118    const CREDENTIAL_SIGNATURE: &str = "91130d366819d59e169d9d744145be3b13bd87badee3f71cb6e4d01007735939\
1119        516ddd13f9bd54ac37c9ab667a5e5c09970248113697abcf166dcb6838351308";
1120
1121    /// Root 7's state at revision 2, issued at [`T`], revoking device 9 a
1122    /// day before and device 11 an hour before (sorted by key: 11's is the
1123    /// lower).
1124    const STATE_MESSAGE: &str = "73706f6f6c6672616d65206964656e7469747920737461746520763200\
1125        ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\
1126        0000000000000002000000006ac82e8000000002\
1127        66be7e332c7a453332bd9d0a7f7db055f5c5ef1a06ada66d98b39fb6810c473a000000006ac82070\
1128        fd1724385aa0c75b64fb78cd602fa1d991fdebf76b13c58ed702eac835e9f618000000006ac6dd00";
1129    const STATE_SIGNATURE: &str = "01853dcafaade8a6780eb0b007ee7a89e79c3d2a21603d3a0231e794b5477901\
1130        03b097d7c5b74e466158c2ead0d1b5b8cadf2a4d95196a5651d9fb3cef59da0d";
1131
1132    /// Device 9's proof to server `[0x5a; 32]` over nonce `[0xa5; 32]`.
1133    const PROOF_MESSAGE: &str = "73706f6f6c6672616d65206465766963652070726f6f6620763100\
1134        5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a\
1135        a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5";
1136    const PROOF_SIGNATURE: &str = "712ca0bb7456d37e02be5b5f24ef61371d864e3cd5d81b0d306df1efea87037e\
1137        3dee370b29920ecd75ba6a72fdfe67bbf9a7bb3609da0ac97c7b1ed29260b503";
1138
1139    const SERVER: [u8; 32] = [0x5a; 32];
1140    const NONCE: [u8; 32] = [0xa5; 32];
1141
1142    fn hex(bytes: &[u8]) -> String {
1143        bytes.iter().map(|b| format!("{b:02x}")).collect()
1144    }
1145
1146    fn signature(text: &str) -> Signature {
1147        Signature::from_bytes(&parse_hex(text).unwrap())
1148    }
1149
1150    fn root() -> SigningKey {
1151        SigningKey::from_bytes(&[7; 32])
1152    }
1153
1154    fn device_secret(seed: u8) -> SigningKey {
1155        SigningKey::from_bytes(&[seed; 32])
1156    }
1157
1158    fn device(seed: u8) -> DevicePublicKey {
1159        DevicePublicKey::from_bytes(device_secret(seed).verifying_key().to_bytes()).unwrap()
1160    }
1161
1162    fn credential_from(
1163        root: &SigningKey,
1164        user: PortableUserId,
1165        issued_at: i64,
1166        expires_at: i64,
1167    ) -> UserDeviceCredential {
1168        UserDeviceCredential::new(user, device(9), 3, issued_at, expires_at, |m| root.sign(m))
1169    }
1170
1171    fn credential() -> UserDeviceCredential {
1172        credential_from(&root(), id(), T, T + MAX_CREDENTIAL_VALIDITY)
1173    }
1174
1175    /// Device `seed`'s key, revoked at `revoked_at`.
1176    fn revoked(seed: u8, revoked_at: i64) -> RevokedKey {
1177        RevokedKey {
1178            key: device(seed),
1179            revoked_at,
1180        }
1181    }
1182
1183    /// The vectors' entries: device 9 a day before [`T`], 11 an hour.
1184    fn nine() -> RevokedKey {
1185        revoked(9, T - DAY)
1186    }
1187
1188    fn eleven() -> RevokedKey {
1189        revoked(11, T - 3600)
1190    }
1191
1192    fn state(revision: u64, revoked: Vec<RevokedKey>) -> PortableIdentityState {
1193        PortableIdentityState::new(id(), revision, revoked, T, |m| root().sign(m)).unwrap()
1194    }
1195
1196    /// A state at `revision` that removes key `seed`'s root at `at`.
1197    fn removing(revision: u64, seed: u8, at: i64) -> PortableIdentityState {
1198        PortableIdentityState::signed_by(
1199            id(),
1200            RootKey::phrase_of(&id()),
1201            revision,
1202            StateChanges {
1203                roots_removed: vec![RemovedRoot {
1204                    root: soft_key::SoftKey::from_seed(seed).root(),
1205                    removed_at: at,
1206                }],
1207                ..StateChanges::default()
1208            },
1209            T,
1210            |m| root().sign(m).into(),
1211        )
1212        .unwrap()
1213    }
1214
1215    /// A rival's removal is covered only by a removal of the same root, no
1216    /// later: a later one would move the time root additions are judged by.
1217    #[test]
1218    fn a_removal_is_covered_by_the_same_removal_no_later() {
1219        let removal = removing(2, 3, T);
1220        assert!(!removal.root_changes_covered_by(&[]));
1221        assert!(!removal.root_changes_covered_by(&[state(5, vec![nine()])]));
1222        assert!(!removal.root_changes_covered_by(&[removing(5, 4, T)]));
1223        assert!(!removal.root_changes_covered_by(&[removing(5, 3, T + 1)]));
1224        assert!(removal.root_changes_covered_by(&[removing(5, 3, T)]));
1225        assert!(removal.root_changes_covered_by(&[state(5, vec![]), removing(1, 3, T - 1)]));
1226        // Revocations alone change no roots: covered by anything.
1227        assert!(state(2, vec![nine()]).root_changes_covered_by(&[]));
1228    }
1229
1230    /// Of two states at one revision, every verifier takes the same one
1231    /// as the newest, whichever it saw first.
1232    #[test]
1233    fn rivals_at_one_revision_are_ordered_the_same_everywhere() {
1234        let (one, other) = (state(3, vec![nine()]), state(3, vec![eleven()]));
1235        assert_ne!(one.digest(), other.digest());
1236        let mut seen = [one.clone(), other.clone()];
1237        seen.sort_by(newest_first);
1238        let mut reversed = [other, one];
1239        reversed.sort_by(newest_first);
1240        assert_eq!(seen, reversed);
1241        let mut by_revision = [state(2, vec![]), state(4, vec![])];
1242        by_revision.sort_by(newest_first);
1243        assert_eq!(by_revision[0].revision, 4);
1244    }
1245
1246    #[test]
1247    fn the_keys_are_the_vectors() {
1248        assert_eq!(id().to_string(), ROOT_7);
1249        assert_eq!(device(9).to_string(), DEVICE_9);
1250        assert_eq!(device(11).to_string(), DEVICE_11);
1251    }
1252
1253    #[test]
1254    fn the_credential_message_is_the_fixed_layout() {
1255        let credential = credential();
1256        let message = UserDeviceCredential::message(
1257            &credential.user,
1258            &credential.device_key,
1259            credential.serial,
1260            credential.issued_at,
1261            credential.expires_at,
1262        );
1263        assert_eq!(hex(&message), CREDENTIAL_MESSAGE);
1264        assert_eq!(
1265            hex(&credential.signature.as_ed25519().unwrap().to_bytes()),
1266            CREDENTIAL_SIGNATURE
1267        );
1268    }
1269
1270    #[test]
1271    fn a_credential_signed_elsewhere_verifies() {
1272        let credential = UserDeviceCredential {
1273            signature: signature(CREDENTIAL_SIGNATURE).into(),
1274            ..credential()
1275        };
1276        assert_eq!(credential.verify(T), Ok(()));
1277    }
1278
1279    #[test]
1280    fn the_state_message_is_the_fixed_layout_whatever_the_order() {
1281        // Given unsorted and with a repeat, it signs the sorted set, the
1282        // repeat at its earliest.
1283        let state = state(2, vec![revoked(9, T), eleven(), nine()]);
1284        assert_eq!(state.revoked, [eleven(), nine()]);
1285        let message = PortableIdentityState::message(&state.user, 2, &state.revoked, T);
1286        assert_eq!(hex(&message), STATE_MESSAGE);
1287        assert_eq!(
1288            hex(&state.signature.as_ed25519().unwrap().to_bytes()),
1289            STATE_SIGNATURE
1290        );
1291        let reordered = PortableIdentityState {
1292            revoked: vec![nine(), eleven(), revoked(9, T)],
1293            signature: signature(STATE_SIGNATURE).into(),
1294            ..state.clone()
1295        };
1296        assert_eq!(reordered.verify(), Ok(()));
1297        assert!(reordered.same_as(&state));
1298    }
1299
1300    #[test]
1301    fn the_proof_message_is_the_fixed_layout() {
1302        let message = device_proof_message(&SERVER, &NONCE);
1303        assert_eq!(hex(&message), PROOF_MESSAGE);
1304        assert_eq!(
1305            verify_device_proof(&credential(), &SERVER, &NONCE, &signature(PROOF_SIGNATURE)),
1306            Ok(())
1307        );
1308    }
1309
1310    #[test]
1311    fn serde_pins_the_credential() {
1312        let json = serde_json::to_string(&credential()).unwrap();
1313        assert_eq!(
1314            json,
1315            format!(
1316                "{{\"user\":\"{ROOT_7}\",\"device_key\":\"{DEVICE_9}\",\"serial\":3,\
1317                 \"issued_at\":{T},\"expires_at\":{},\"signature\":\"{CREDENTIAL_SIGNATURE}\"}}",
1318                T + MAX_CREDENTIAL_VALIDITY
1319            )
1320        );
1321        let back: UserDeviceCredential = serde_json::from_str(&json).unwrap();
1322        assert_eq!(back, credential());
1323    }
1324
1325    #[test]
1326    fn serde_pins_the_state() {
1327        let json = serde_json::to_string(&state(2, vec![nine(), eleven()])).unwrap();
1328        assert_eq!(
1329            json,
1330            format!(
1331                "{{\"user\":\"{ROOT_7}\",\"revision\":2,\"revoked\":[\
1332                 {{\"key\":\"{DEVICE_11}\",\"revoked_at\":{}}},\
1333                 {{\"key\":\"{DEVICE_9}\",\"revoked_at\":{}}}],\
1334                 \"issued_at\":{T},\"signature\":\"{STATE_SIGNATURE}\"}}",
1335                T - 3600,
1336                T - DAY
1337            )
1338        );
1339        let back: PortableIdentityState = serde_json::from_str(&json).unwrap();
1340        assert_eq!(back.verify(), Ok(()));
1341    }
1342
1343    #[test]
1344    fn a_signature_that_is_not_hex_is_refused() {
1345        let json = serde_json::to_string(&credential()).unwrap();
1346        let short = json.replace(CREDENTIAL_SIGNATURE, "abcd");
1347        assert!(serde_json::from_str::<UserDeviceCredential>(&short).is_err());
1348    }
1349
1350    #[test]
1351    fn a_device_key_that_is_not_a_curve_point_is_refused() {
1352        let point = (0..=255u8)
1353            .map(|y| {
1354                let mut bytes = [0u8; 32];
1355                bytes[0] = y;
1356                bytes
1357            })
1358            .find(|bytes| VerifyingKey::from_bytes(bytes).is_err())
1359            .unwrap();
1360        assert!(DevicePublicKey::from_bytes(point).is_err());
1361        assert!(hex(&point).parse::<DevicePublicKey>().is_err());
1362        assert!("abc".parse::<DevicePublicKey>().is_err());
1363        assert_eq!(DEVICE_9.parse::<DevicePublicKey>(), Ok(device(9)));
1364    }
1365
1366    #[test]
1367    fn a_credential_is_good_from_issue_to_expiry() {
1368        let credential = credential();
1369        assert_eq!(credential.verify(T), Ok(()));
1370        assert_eq!(credential.verify(T + MAX_CREDENTIAL_VALIDITY - 1), Ok(()));
1371        assert_eq!(
1372            credential.verify(T + MAX_CREDENTIAL_VALIDITY),
1373            Err(CredentialError::Expired)
1374        );
1375    }
1376
1377    #[test]
1378    fn a_credential_from_the_future_is_good_within_the_skew_only() {
1379        let credential = credential();
1380        assert_eq!(credential.verify(T - CLOCK_SKEW), Ok(()));
1381        assert_eq!(
1382            credential.verify(T - CLOCK_SKEW - 1),
1383            Err(CredentialError::NotYetValid)
1384        );
1385    }
1386
1387    #[test]
1388    fn a_credential_longer_than_ninety_days_is_refused() {
1389        let long = credential_from(&root(), id(), T, T + MAX_CREDENTIAL_VALIDITY + 1);
1390        assert_eq!(long.verify(T), Err(CredentialError::TooLong));
1391        let backwards = credential_from(&root(), id(), i64::MIN, i64::MAX);
1392        assert_eq!(backwards.verify(T), Err(CredentialError::TooLong));
1393    }
1394
1395    #[test]
1396    fn a_tampered_credential_is_refused() {
1397        let good = credential();
1398        let tampered = [
1399            UserDeviceCredential {
1400                device_key: device(11),
1401                ..good.clone()
1402            },
1403            UserDeviceCredential {
1404                serial: 4,
1405                ..good.clone()
1406            },
1407            UserDeviceCredential {
1408                issued_at: T - 1,
1409                ..good.clone()
1410            },
1411            UserDeviceCredential {
1412                expires_at: T + 1,
1413                ..good.clone()
1414            },
1415        ];
1416        for credential in tampered {
1417            assert_eq!(
1418                credential.verify(T),
1419                Err(CredentialError::BadSignature),
1420                "{credential:?}"
1421            );
1422        }
1423    }
1424
1425    #[test]
1426    fn a_credential_another_root_signed_is_refused() {
1427        // Root 8 signs a credential naming root 7's user.
1428        let forged = credential_from(&SigningKey::from_bytes(&[8; 32]), id(), T, T + DAY);
1429        assert_eq!(forged.verify(T), Err(CredentialError::BadSignature));
1430    }
1431
1432    #[test]
1433    fn a_proof_by_another_key_or_for_another_server_is_refused() {
1434        let credential = credential();
1435        let by_other = device_secret(11).sign(&device_proof_message(&SERVER, &NONCE));
1436        assert_eq!(
1437            verify_device_proof(&credential, &SERVER, &NONCE, &by_other),
1438            Err(CredentialError::BadDeviceProof)
1439        );
1440        let good = device_secret(9).sign(&device_proof_message(&SERVER, &NONCE));
1441        assert_eq!(
1442            verify_device_proof(&credential, &[0; 32], &NONCE, &good),
1443            Err(CredentialError::BadDeviceProof)
1444        );
1445        assert_eq!(
1446            verify_device_proof(&credential, &SERVER, &[0; 32], &good),
1447            Err(CredentialError::BadDeviceProof)
1448        );
1449        assert_eq!(
1450            verify_device_proof(&credential, &SERVER, &NONCE, &good),
1451            Ok(())
1452        );
1453    }
1454
1455    #[test]
1456    fn a_state_revokes_what_it_lists() {
1457        let state = state(2, vec![nine()]);
1458        assert_eq!(state.verify(), Ok(()));
1459        assert!(state.revokes(&device(9)));
1460        assert!(!state.revokes(&device(11)));
1461    }
1462
1463    #[test]
1464    fn a_tampered_state_is_refused() {
1465        let good = state(2, vec![nine(), eleven()]);
1466        let tampered = [
1467            PortableIdentityState {
1468                revision: 3,
1469                ..good.clone()
1470            },
1471            PortableIdentityState {
1472                revoked: vec![nine()],
1473                ..good.clone()
1474            },
1475            PortableIdentityState {
1476                revoked: vec![nine(), revoked(11, T)],
1477                ..good.clone()
1478            },
1479            PortableIdentityState {
1480                issued_at: T + 1,
1481                ..good.clone()
1482            },
1483        ];
1484        for state in tampered {
1485            assert_eq!(state.verify(), Err(StateError::BadSignature), "{state:?}");
1486        }
1487        let by_other = PortableIdentityState::new(id(), 2, vec![], T, |m| {
1488            SigningKey::from_bytes(&[8; 32]).sign(m)
1489        })
1490        .unwrap();
1491        assert_eq!(by_other.verify(), Err(StateError::BadSignature));
1492    }
1493
1494    #[test]
1495    fn a_state_revoking_more_than_the_limit_is_refused() {
1496        let keys: Vec<_> = (0u16..)
1497            .map(|n| SigningKey::from_bytes(&blake3::hash(&n.to_be_bytes()).into()))
1498            .map(|key| RevokedKey {
1499                key: DevicePublicKey::from_bytes(key.verifying_key().to_bytes()).unwrap(),
1500                revoked_at: T,
1501            })
1502            .take(MAX_REVOKED + 1)
1503            .collect();
1504        let sign = |m: &[u8]| root().sign(m);
1505        assert!(PortableIdentityState::new(id(), 1, keys[..MAX_REVOKED].to_vec(), T, sign).is_ok());
1506        assert_eq!(
1507            PortableIdentityState::new(id(), 1, keys.clone(), T, sign).unwrap_err(),
1508            StateError::TooManyRevoked
1509        );
1510        // Signed over the full list by a root that ignored the limit.
1511        let oversized = PortableIdentityState {
1512            user: id(),
1513            revision: 1,
1514            signature: root()
1515                .sign(&PortableIdentityState::message(&id(), 1, &keys, T))
1516                .into(),
1517            revoked: keys,
1518            issued_at: T,
1519            signer: None,
1520            roots_added: vec![],
1521            roots_removed: vec![],
1522        };
1523        assert_eq!(oversized.verify(), Err(StateError::TooManyRevoked));
1524    }
1525
1526    #[test]
1527    fn a_revocation_lapses_once_no_credential_it_could_stop_holds() {
1528        // A credential issued at the revocation, up to the skew ahead,
1529        // holds until just before this.
1530        let issued_at = T + CLOCK_SKEW;
1531        let last_good = issued_at + MAX_CREDENTIAL_VALIDITY - 1;
1532        assert!(!revocation_lapsed(T, last_good));
1533        assert!(!revocation_lapsed(T, T + REVOCATION_WINDOW));
1534        assert!(revocation_lapsed(T, T + REVOCATION_WINDOW + 1));
1535        assert!(!revocation_lapsed(i64::MIN, i64::MIN));
1536    }
1537
1538    // P7-04. Computed apart from this code as above: the message laid out
1539    // in Python's `struct` (`>H` for the length), the signatures by
1540    // `openssl pkeyutl -sign -rawin` with the raw seeds 7 (the root) and 9
1541    // (a device).
1542
1543    /// Root 7 tying to account `alice` on server `[0x5a; 32]`, over nonce
1544    /// `[0xa5; 32]`.
1545    const TIE_MESSAGE: &str = "73706f6f6c6672616d6520746965207631\
1546        00\
1547        5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a\
1548        a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5a5\
1549        ea4a6c63e29c520abef5507b132ec5f9954776aebebe7b92421eea691446d22c\
1550        0005616c696365";
1551    const TIE_ROOT_SIGNATURE: &str = "030766ca4d18dba1d29c76d341775a797460d33fd78a0c091ecf09ca4605e59f\
1552        6a4d1504ecbc680e1b41ec9df7c7cfa135ff4afc823fcd25f3761dc2fff7ef02";
1553    const TIE_DEVICE_SIGNATURE: &str = "08a319d99188a15d34259fc193ad36a3024c67e98b336644c362014052b20e85\
1554        0564e5d631d13b20d2212134e7f4a66da90d432c28a043b2819be45029e8f003";
1555
1556    fn tie(username: &str) -> Vec<u8> {
1557        tie_message(&SERVER, &NONCE, &id(), username).unwrap()
1558    }
1559
1560    #[test]
1561    fn the_tie_message_is_the_fixed_layout() {
1562        assert_eq!(hex(&tie("alice")), TIE_MESSAGE);
1563        assert_eq!(
1564            hex(&root().sign(&tie("alice")).to_bytes()),
1565            TIE_ROOT_SIGNATURE
1566        );
1567    }
1568
1569    #[test]
1570    fn a_tie_signed_elsewhere_verifies_by_root_or_device() {
1571        let by_root = TieProof::Root {
1572            signature: signature(TIE_ROOT_SIGNATURE).into(),
1573            root: None,
1574            genesis: None,
1575        };
1576        assert_eq!(by_root.verify(&id(), &tie("alice"), T), Ok(()));
1577        let by_device = TieProof::Device {
1578            credential: credential(),
1579            signature: signature(TIE_DEVICE_SIGNATURE),
1580        };
1581        assert_eq!(by_device.verify(&id(), &tie("alice"), T), Ok(()));
1582    }
1583
1584    #[test]
1585    fn a_tie_for_another_server_nonce_identity_or_account_is_refused() {
1586        let by_root = TieProof::Root {
1587            signature: signature(TIE_ROOT_SIGNATURE).into(),
1588            root: None,
1589            genesis: None,
1590        };
1591        let other_user =
1592            PortableUserId::from_bytes(SigningKey::from_bytes(&[8; 32]).verifying_key().to_bytes())
1593                .unwrap();
1594        let elsewhere = [
1595            tie_message(&[0; 32], &NONCE, &id(), "alice").unwrap(),
1596            tie_message(&SERVER, &[0; 32], &id(), "alice").unwrap(),
1597            tie_message(&SERVER, &NONCE, &other_user, "alice").unwrap(),
1598            tie("bob"),
1599            // A name that starts the same is another account.
1600            tie("alicea"),
1601        ];
1602        for message in elsewhere {
1603            assert_eq!(
1604                by_root.verify(&id(), &message, T),
1605                Err(TieProofError::BadSignature)
1606            );
1607        }
1608        // Signed by the other identity's root for itself: not root 7's.
1609        assert_eq!(
1610            by_root.verify(&other_user, &tie("alice"), T),
1611            Err(TieProofError::BadSignature)
1612        );
1613    }
1614
1615    #[test]
1616    fn a_device_proof_holds_only_with_a_good_credential_for_the_user() {
1617        let signature = device_secret(9).sign(&tie("alice"));
1618        let expired = TieProof::Device {
1619            credential: credential(),
1620            signature,
1621        };
1622        assert_eq!(
1623            expired.verify(&id(), &tie("alice"), T + MAX_CREDENTIAL_VALIDITY),
1624            Err(TieProofError::Credential(CredentialError::Expired))
1625        );
1626        // Device 11 signs, with device 9's credential.
1627        let wrong_key = TieProof::Device {
1628            credential: credential(),
1629            signature: device_secret(11).sign(&tie("alice")),
1630        };
1631        assert_eq!(
1632            wrong_key.verify(&id(), &tie("alice"), T),
1633            Err(TieProofError::BadSignature)
1634        );
1635        let other_root = SigningKey::from_bytes(&[8; 32]);
1636        let other_user = PortableUserId::from_bytes(other_root.verifying_key().to_bytes()).unwrap();
1637        let theirs = TieProof::Device {
1638            credential: credential_from(&other_root, other_user, T, T + DAY),
1639            signature,
1640        };
1641        assert_eq!(
1642            theirs.verify(&id(), &tie("alice"), T),
1643            Err(TieProofError::OtherIdentity)
1644        );
1645    }
1646
1647    #[test]
1648    fn serde_pins_the_tie_proof() {
1649        let json = serde_json::to_value(TieProof::Root {
1650            signature: signature(TIE_ROOT_SIGNATURE).into(),
1651            root: None,
1652            genesis: None,
1653        })
1654        .unwrap();
1655        assert_eq!(
1656            json,
1657            serde_json::json!({"type": "root", "signature": TIE_ROOT_SIGNATURE})
1658        );
1659        let device = TieProof::Device {
1660            credential: credential(),
1661            signature: signature(TIE_DEVICE_SIGNATURE),
1662        };
1663        let back: TieProof =
1664            serde_json::from_value(serde_json::to_value(&device).unwrap()).unwrap();
1665        assert_eq!(back, device);
1666        assert_eq!(device.kind(), "device");
1667    }
1668
1669    #[test]
1670    fn a_username_too_long_to_count_has_no_tie_message() {
1671        assert!(tie_message(&SERVER, &NONCE, &id(), &"a".repeat(65_536)).is_none());
1672        assert!(tie_message(&SERVER, &NONCE, &id(), &"a".repeat(65_535)).is_some());
1673    }
1674}