Skip to main content

spoolframe_protocol/portable/
mod.rs

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